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    /// Builders that create accounts request one unit per new account footprint.
1683    #[test]
1684    fn creating_builders_request_their_account_state_units() {
1685        let (fp, prog, a, b, c, d) = (key(1), key(2), key(3), key(4), key(5), key(6));
1686        let (e, f, g, h) = (key(7), key(8), key(9), key(10));
1687        let proof = vec![0u8; 64];
1688        let fee_payer_proof = StateProof::creation(100, [0u8; 32], [7u8; 32], [8u8; 32], vec![]);
1689        let cases: Vec<(&str, Transaction, u16)> = vec![
1690            (
1691                "build_create_with_fee_payer_proof",
1692                TransactionBuilder::build_create_with_fee_payer_proof(fp, 0, &fee_payer_proof)
1693                    .unwrap(),
1694                1,
1695            ),
1696            (
1697                "build_create_account",
1698                TransactionBuilder::build_create_account(
1699                    fp,
1700                    prog,
1701                    a,
1702                    "5eed",
1703                    Some(&proof),
1704                    1,
1705                    0,
1706                    0,
1707                )
1708                .unwrap(),
1709                1,
1710            ),
1711            (
1712                "build_create_ephemeral_account",
1713                TransactionBuilder::build_create_ephemeral_account(
1714                    fp, prog, a, &[1u8; 32], 1, 0, 0,
1715                )
1716                .unwrap(),
1717                1,
1718            ),
1719            (
1720                "build_token_initialize_mint",
1721                TransactionBuilder::build_token_initialize_mint(
1722                    fp,
1723                    prog,
1724                    a,
1725                    fp,
1726                    fp,
1727                    None,
1728                    6,
1729                    "TKN",
1730                    [1u8; 32],
1731                    proof.clone(),
1732                    1,
1733                    0,
1734                    0,
1735                )
1736                .unwrap(),
1737                1,
1738            ),
1739            (
1740                "build_token_initialize_account",
1741                TransactionBuilder::build_token_initialize_account(
1742                    fp,
1743                    prog,
1744                    a,
1745                    b,
1746                    fp,
1747                    [1u8; 32],
1748                    proof.clone(),
1749                    1,
1750                    0,
1751                    0,
1752                )
1753                .unwrap(),
1754                1,
1755            ),
1756            (
1757                "build_wthru_initialize_mint",
1758                TransactionBuilder::build_wthru_initialize_mint(
1759                    fp,
1760                    prog,
1761                    a,
1762                    b,
1763                    c,
1764                    9,
1765                    [1u8; 32],
1766                    proof.clone(),
1767                    proof.clone(),
1768                    1,
1769                    0,
1770                    0,
1771                )
1772                .unwrap(),
1773                2,
1774            ),
1775            (
1776                "build_name_service_initialize_root",
1777                TransactionBuilder::build_name_service_initialize_root(
1778                    fp,
1779                    prog,
1780                    a,
1781                    fp,
1782                    "thru",
1783                    proof.clone(),
1784                    1,
1785                    0,
1786                    0,
1787                )
1788                .unwrap(),
1789                1,
1790            ),
1791            (
1792                "build_name_service_register_subdomain",
1793                TransactionBuilder::build_name_service_register_subdomain(
1794                    fp,
1795                    prog,
1796                    a,
1797                    b,
1798                    fp,
1799                    fp,
1800                    "name",
1801                    proof.clone(),
1802                    1,
1803                    0,
1804                    0,
1805                )
1806                .unwrap(),
1807                1,
1808            ),
1809            (
1810                "build_thru_registrar_initialize_registry",
1811                TransactionBuilder::build_thru_registrar_initialize_registry(
1812                    fp,
1813                    prog,
1814                    a,
1815                    b,
1816                    c,
1817                    d,
1818                    e,
1819                    f,
1820                    "thru",
1821                    1,
1822                    proof.clone(),
1823                    proof.clone(),
1824                    1,
1825                    0,
1826                    0,
1827                )
1828                .unwrap(),
1829                2,
1830            ),
1831            (
1832                "build_thru_registrar_purchase_domain",
1833                TransactionBuilder::build_thru_registrar_purchase_domain(
1834                    fp,
1835                    prog,
1836                    a,
1837                    b,
1838                    c,
1839                    d,
1840                    e,
1841                    f,
1842                    g,
1843                    h,
1844                    key(11),
1845                    "name",
1846                    1,
1847                    proof.clone(),
1848                    proof.clone(),
1849                    1,
1850                    0,
1851                    0,
1852                )
1853                .unwrap(),
1854                2,
1855            ),
1856            (
1857                "build_bp_create_account",
1858                TransactionBuilder::build_bp_create_account(
1859                    fp,
1860                    prog,
1861                    a,
1862                    b,
1863                    c,
1864                    d,
1865                    e,
1866                    fp,
1867                    false,
1868                    [0u8; 64],
1869                    proof.clone(),
1870                    proof.clone(),
1871                    vec![],
1872                    1,
1873                    0,
1874                    0,
1875                )
1876                .unwrap(),
1877                2,
1878            ),
1879            (
1880                "build_bp_create_account with signer EOA",
1881                TransactionBuilder::build_bp_create_account(
1882                    fp,
1883                    prog,
1884                    a,
1885                    b,
1886                    c,
1887                    d,
1888                    e,
1889                    fp,
1890                    true,
1891                    [0u8; 64],
1892                    proof.clone(),
1893                    proof.clone(),
1894                    proof.clone(),
1895                    1,
1896                    0,
1897                    0,
1898                )
1899                .unwrap(),
1900                3,
1901            ),
1902        ];
1903        for (name, tx, expected) in cases {
1904            assert_eq!(tx.req_state_units, expected, "{name}");
1905        }
1906    }
1907}
1908
1909/// Uploader program instruction discriminants
1910pub const TN_UPLOADER_PROGRAM_INSTRUCTION_CREATE: u32 = 0x00;
1911pub const TN_UPLOADER_PROGRAM_INSTRUCTION_WRITE: u32 = 0x01;
1912pub const TN_UPLOADER_PROGRAM_INSTRUCTION_DESTROY: u32 = 0x02;
1913pub const TN_UPLOADER_PROGRAM_INSTRUCTION_FINALIZE: u32 = 0x03;
1914
1915/// Uploader program CREATE instruction arguments (matches C struct)
1916#[repr(C, packed)]
1917#[derive(Debug, Clone, Copy)]
1918pub struct UploaderCreateArgs {
1919    pub buffer_account_idx: u16,
1920    pub meta_account_idx: u16,
1921    pub authority_account_idx: u16,
1922    pub buffer_account_sz: u32,
1923    pub expected_account_hash: [u8; 32],
1924    pub seed_len: u32,
1925    // seed bytes follow
1926}
1927
1928/// Uploader program WRITE instruction arguments (matches C struct)
1929#[repr(C, packed)]
1930#[derive(Debug, Clone, Copy)]
1931pub struct UploaderWriteArgs {
1932    pub buffer_account_idx: u16,
1933    pub meta_account_idx: u16,
1934    pub data_len: u32,
1935    pub data_offset: u32,
1936    // data bytes follow
1937}
1938
1939/// Uploader program FINALIZE instruction arguments (matches C struct)
1940#[repr(C, packed)]
1941#[derive(Debug, Clone, Copy)]
1942pub struct UploaderFinalizeArgs {
1943    pub buffer_account_idx: u16,
1944    pub meta_account_idx: u16,
1945    pub expected_account_hash: [u8; 32],
1946}
1947
1948/// Uploader program DESTROY instruction arguments (matches C struct)
1949#[repr(C, packed)]
1950#[derive(Debug, Clone, Copy)]
1951pub struct UploaderDestroyArgs {
1952    pub buffer_account_idx: u16,
1953    pub meta_account_idx: u16,
1954}
1955
1956/// Manager program instruction discriminants (matches C defines)
1957pub const MANAGER_INSTRUCTION_CREATE_PERMANENT: u8 = 0x00;
1958pub const MANAGER_INSTRUCTION_CREATE_EPHEMERAL: u8 = 0x01;
1959pub const MANAGER_INSTRUCTION_UPGRADE: u8 = 0x02;
1960pub const MANAGER_INSTRUCTION_SET_PAUSE: u8 = 0x03;
1961pub const MANAGER_INSTRUCTION_DESTROY: u8 = 0x04;
1962pub const MANAGER_INSTRUCTION_FINALIZE: u8 = 0x05;
1963pub const MANAGER_INSTRUCTION_SET_AUTHORITY: u8 = 0x06;
1964pub const MANAGER_INSTRUCTION_CLAIM_AUTHORITY: u8 = 0x07;
1965
1966pub const ABI_MANAGER_INSTRUCTION_CREATE_META_OFFICIAL_PERMANENT: u8 = 0x00;
1967pub const ABI_MANAGER_INSTRUCTION_CREATE_META_OFFICIAL_EPHEMERAL: u8 = 0x01;
1968pub const ABI_MANAGER_INSTRUCTION_CREATE_META_EXTERNAL_PERMANENT: u8 = 0x02;
1969pub const ABI_MANAGER_INSTRUCTION_CREATE_META_EXTERNAL_EPHEMERAL: u8 = 0x03;
1970pub const ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_PERMANENT: u8 = 0x04;
1971pub const ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_EPHEMERAL: u8 = 0x05;
1972pub const ABI_MANAGER_INSTRUCTION_CREATE_ABI_EXTERNAL_PERMANENT: u8 = 0x06;
1973pub const ABI_MANAGER_INSTRUCTION_CREATE_ABI_EXTERNAL_EPHEMERAL: u8 = 0x07;
1974pub const ABI_MANAGER_INSTRUCTION_UPGRADE_ABI_OFFICIAL: u8 = 0x08;
1975pub const ABI_MANAGER_INSTRUCTION_UPGRADE_ABI_EXTERNAL: u8 = 0x09;
1976pub const ABI_MANAGER_INSTRUCTION_CLOSE_ABI_OFFICIAL: u8 = 0x0a;
1977pub const ABI_MANAGER_INSTRUCTION_CLOSE_ABI_EXTERNAL: u8 = 0x0b;
1978pub const ABI_MANAGER_INSTRUCTION_FINALIZE_ABI_OFFICIAL: u8 = 0x0c;
1979pub const ABI_MANAGER_INSTRUCTION_FINALIZE_ABI_EXTERNAL: u8 = 0x0d;
1980
1981/// Manager program header arguments (matches C struct)
1982#[repr(C, packed)]
1983#[derive(Debug, Clone, Copy)]
1984pub struct ManagerHeaderArgs {
1985    pub discriminant: u8,
1986    pub meta_account_idx: u16,
1987    pub program_account_idx: u16,
1988}
1989
1990/// Manager program CREATE instruction arguments (matches C struct)
1991#[repr(C, packed)]
1992#[derive(Debug, Clone, Copy)]
1993pub struct ManagerCreateArgs {
1994    pub discriminant: u8,
1995    pub meta_account_idx: u16,
1996    pub program_account_idx: u16,
1997    pub srcbuf_account_idx: u16,
1998    pub srcbuf_offset: u32,
1999    pub srcbuf_size: u32,
2000    pub authority_account_idx: u16,
2001    pub seed_len: u32,
2002    // seed bytes and proof bytes follow
2003}
2004
2005/// Manager program UPGRADE instruction arguments (matches C struct)
2006#[repr(C, packed)]
2007#[derive(Debug, Clone, Copy)]
2008pub struct ManagerUpgradeArgs {
2009    pub discriminant: u8,
2010    pub meta_account_idx: u16,
2011    pub program_account_idx: u16,
2012    pub srcbuf_account_idx: u16,
2013    pub srcbuf_offset: u32,
2014    pub srcbuf_size: u32,
2015}
2016
2017/// ABI manager program CREATE META (official) instruction arguments (matches C struct)
2018#[repr(C, packed)]
2019#[derive(Debug, Clone, Copy)]
2020pub struct AbiManagerCreateMetaOfficialArgs {
2021    pub abi_meta_account_idx: u16,
2022    pub program_meta_account_idx: u16,
2023    pub authority_account_idx: u16,
2024}
2025
2026/// ABI manager program CREATE META (external) instruction arguments (matches C struct)
2027#[repr(C, packed)]
2028#[derive(Debug, Clone, Copy)]
2029pub struct AbiManagerCreateMetaExternalArgs {
2030    pub abi_meta_account_idx: u16,
2031    pub authority_account_idx: u16,
2032    pub target_program: TnPubkey,
2033    pub seed: [u8; 32],
2034}
2035
2036/// ABI manager program CREATE ABI (official) instruction arguments (matches C struct)
2037#[repr(C, packed)]
2038#[derive(Debug, Clone, Copy)]
2039pub struct AbiManagerCreateAbiOfficialArgs {
2040    pub abi_meta_account_idx: u16,
2041    pub program_meta_account_idx: u16,
2042    pub abi_account_idx: u16,
2043    pub srcbuf_account_idx: u16,
2044    pub srcbuf_offset: u32,
2045    pub srcbuf_size: u32,
2046    pub authority_account_idx: u16,
2047}
2048
2049/// ABI manager program CREATE ABI (external) instruction arguments (matches C struct)
2050#[repr(C, packed)]
2051#[derive(Debug, Clone, Copy)]
2052pub struct AbiManagerCreateAbiExternalArgs {
2053    pub abi_meta_account_idx: u16,
2054    pub abi_account_idx: u16,
2055    pub srcbuf_account_idx: u16,
2056    pub srcbuf_offset: u32,
2057    pub srcbuf_size: u32,
2058    pub authority_account_idx: u16,
2059}
2060
2061/// ABI manager program UPGRADE ABI (official) instruction arguments (matches C struct)
2062#[repr(C, packed)]
2063#[derive(Debug, Clone, Copy)]
2064pub struct AbiManagerUpgradeAbiOfficialArgs {
2065    pub abi_meta_account_idx: u16,
2066    pub program_meta_account_idx: u16,
2067    pub abi_account_idx: u16,
2068    pub srcbuf_account_idx: u16,
2069    pub srcbuf_offset: u32,
2070    pub srcbuf_size: u32,
2071    pub authority_account_idx: u16,
2072}
2073
2074/// ABI manager program UPGRADE ABI (external) instruction arguments (matches C struct)
2075#[repr(C, packed)]
2076#[derive(Debug, Clone, Copy)]
2077pub struct AbiManagerUpgradeAbiExternalArgs {
2078    pub abi_meta_account_idx: u16,
2079    pub abi_account_idx: u16,
2080    pub srcbuf_account_idx: u16,
2081    pub srcbuf_offset: u32,
2082    pub srcbuf_size: u32,
2083    pub authority_account_idx: u16,
2084}
2085
2086/// ABI manager program FINALIZE ABI (official) instruction arguments (matches C struct)
2087#[repr(C, packed)]
2088#[derive(Debug, Clone, Copy)]
2089pub struct AbiManagerFinalizeAbiOfficialArgs {
2090    pub abi_meta_account_idx: u16,
2091    pub program_meta_account_idx: u16,
2092    pub abi_account_idx: u16,
2093    pub authority_account_idx: u16,
2094}
2095
2096/// ABI manager program FINALIZE ABI (external) instruction arguments (matches C struct)
2097#[repr(C, packed)]
2098#[derive(Debug, Clone, Copy)]
2099pub struct AbiManagerFinalizeAbiExternalArgs {
2100    pub abi_meta_account_idx: u16,
2101    pub abi_account_idx: u16,
2102    pub authority_account_idx: u16,
2103}
2104
2105/// ABI manager program CLOSE ABI (official) instruction arguments (matches C struct)
2106#[repr(C, packed)]
2107#[derive(Debug, Clone, Copy)]
2108pub struct AbiManagerCloseAbiOfficialArgs {
2109    pub abi_meta_account_idx: u16,
2110    pub program_meta_account_idx: u16,
2111    pub abi_account_idx: u16,
2112    pub authority_account_idx: u16,
2113}
2114
2115/// ABI manager program CLOSE ABI (external) instruction arguments (matches C struct)
2116#[repr(C, packed)]
2117#[derive(Debug, Clone, Copy)]
2118pub struct AbiManagerCloseAbiExternalArgs {
2119    pub abi_meta_account_idx: u16,
2120    pub abi_account_idx: u16,
2121    pub authority_account_idx: u16,
2122}
2123
2124/// Manager program SET_PAUSE instruction arguments (matches C struct)
2125#[repr(C, packed)]
2126#[derive(Debug, Clone, Copy)]
2127pub struct ManagerSetPauseArgs {
2128    pub discriminant: u8,
2129    pub meta_account_idx: u16,
2130    pub program_account_idx: u16,
2131    pub is_paused: u8,
2132}
2133
2134/// Manager program SET_AUTHORITY instruction arguments (matches C struct)
2135#[repr(C, packed)]
2136#[derive(Debug, Clone, Copy)]
2137pub struct ManagerSetAuthorityArgs {
2138    pub discriminant: u8,
2139    pub meta_account_idx: u16,
2140    pub program_account_idx: u16,
2141    pub authority_candidate: [u8; 32],
2142}
2143
2144/// Test uploader program instruction discriminants (matches C defines)
2145pub const TN_TEST_UPLOADER_PROGRAM_DISCRIMINANT_CREATE: u8 = 0x00;
2146pub const TN_TEST_UPLOADER_PROGRAM_DISCRIMINANT_WRITE: u8 = 0x01;
2147
2148/// Test uploader program CREATE instruction arguments (matches C struct)
2149#[repr(C, packed)]
2150#[derive(Debug, Clone, Copy)]
2151pub struct TestUploaderCreateArgs {
2152    pub account_idx: u16,
2153    pub is_ephemeral: u8,
2154    pub account_sz: u32,
2155    pub seed_len: u32,
2156    // seed bytes follow, then optional state proof
2157}
2158
2159/// Test uploader program WRITE instruction arguments (matches C struct)
2160#[repr(C, packed)]
2161#[derive(Debug, Clone, Copy)]
2162pub struct TestUploaderWriteArgs {
2163    pub target_account_idx: u16,
2164    pub target_offset: u32,
2165    pub data_len: u32,
2166    // data bytes follow
2167}
2168
2169/// System program DECOMPRESS2 instruction arguments (matches C struct)
2170#[repr(C, packed)]
2171#[derive(Debug, Clone, Copy)]
2172pub struct SystemProgramDecompress2Args {
2173    pub target_account_idx: u16,
2174    pub meta_account_idx: u16,
2175    pub data_account_idx: u16,
2176    pub data_offset: u32,
2177}
2178
2179fn uploader_data_has_elf_magic(data: &[u8]) -> bool {
2180    let elf_magic = [0x7f, b'E', b'L', b'F'];
2181    data.starts_with(&elf_magic)
2182}
2183
2184impl TransactionBuilder {
2185    /// Build uploader program CREATE transaction
2186    pub fn build_uploader_create(
2187        fee_payer: TnPubkey,
2188        uploader_program: TnPubkey,
2189        meta_account: TnPubkey,
2190        buffer_account: TnPubkey,
2191        buffer_size: u32,
2192        expected_hash: [u8; 32],
2193        seed: &[u8],
2194        fee: u64,
2195        nonce: u64,
2196        start_slot: u64,
2197    ) -> Result<Transaction> {
2198        // Account layout: [0: fee_payer, 1: uploader_program, 2: meta_account, 3: buffer_account]
2199        let authority_account_idx = 0u16;
2200
2201        let mut tx = Transaction::new(fee_payer, uploader_program, fee, nonce)
2202            .with_start_slot(start_slot)
2203            .with_expiry_after(10)
2204            .with_compute_units(50_000 + 2 * buffer_size as u32)
2205            .with_memory_units(10_000)
2206            .with_state_units(account_state_units(buffer_size as u64 + 4096)?); // Buffer + one-unit uploader metadata.
2207
2208        let mut meta_account_idx = 2u16;
2209        let mut buffer_account_idx = 3u16;
2210        if meta_account > buffer_account {
2211            meta_account_idx = 3u16;
2212            buffer_account_idx = 2u16;
2213            tx = tx
2214                .add_rw_account(buffer_account)
2215                .add_rw_account(meta_account)
2216        } else {
2217            tx = tx
2218                .add_rw_account(meta_account)
2219                .add_rw_account(buffer_account)
2220        }
2221
2222        let instruction_data = build_uploader_create_instruction(
2223            buffer_account_idx,
2224            meta_account_idx,
2225            authority_account_idx,
2226            buffer_size,
2227            expected_hash,
2228            seed,
2229        )?;
2230
2231        tx = tx.with_instructions(instruction_data);
2232
2233        Ok(tx)
2234    }
2235
2236    /// Build uploader program WRITE transaction
2237    pub fn build_uploader_write(
2238        fee_payer: TnPubkey,
2239        uploader_program: TnPubkey,
2240        meta_account: TnPubkey,
2241        buffer_account: TnPubkey,
2242        data: &[u8],
2243        offset: u32,
2244        fee: u64,
2245        nonce: u64,
2246        start_slot: u64,
2247    ) -> Result<Transaction> {
2248        Self::build_uploader_write_with_options(
2249            fee_payer,
2250            uploader_program,
2251            meta_account,
2252            buffer_account,
2253            data,
2254            offset,
2255            fee,
2256            nonce,
2257            start_slot,
2258            UploaderWriteOptions::default(),
2259        )
2260    }
2261
2262    /// Build uploader program WRITE transaction with caller-selected validation options.
2263    pub fn build_uploader_write_with_options(
2264        fee_payer: TnPubkey,
2265        uploader_program: TnPubkey,
2266        meta_account: TnPubkey,
2267        buffer_account: TnPubkey,
2268        data: &[u8],
2269        offset: u32,
2270        fee: u64,
2271        nonce: u64,
2272        start_slot: u64,
2273        options: UploaderWriteOptions,
2274    ) -> Result<Transaction> {
2275        if !options.skip_elf_check && offset == 0 && uploader_data_has_elf_magic(data) {
2276            bail!(
2277                "uploader data begins with ELF magic; upload a Thru program binary, not an ELF executable"
2278            );
2279        }
2280
2281        // Account layout: [0: fee_payer, 1: uploader_program, 2: meta_account, 3: buffer_account]
2282        let mut tx = Transaction::new(fee_payer, uploader_program, fee, nonce)
2283            .with_start_slot(start_slot)
2284            .with_expiry_after(10000)
2285            .with_compute_units(500_000_000)
2286            .with_memory_units(5000)
2287            .with_state_units(0);
2288
2289        let mut meta_account_idx = 2u16;
2290        let mut buffer_account_idx = 3u16;
2291        if meta_account > buffer_account {
2292            meta_account_idx = 3u16;
2293            buffer_account_idx = 2u16;
2294            tx = tx
2295                .add_rw_account(buffer_account)
2296                .add_rw_account(meta_account)
2297        } else {
2298            tx = tx
2299                .add_rw_account(meta_account)
2300                .add_rw_account(buffer_account)
2301        }
2302
2303        let instruction_data =
2304            build_uploader_write_instruction(buffer_account_idx, meta_account_idx, data, offset)?;
2305
2306        tx = tx.with_instructions(instruction_data);
2307
2308        Ok(tx)
2309    }
2310
2311    /// Build uploader program FINALIZE transaction
2312    pub fn build_uploader_finalize(
2313        fee_payer: TnPubkey,
2314        uploader_program: TnPubkey,
2315        meta_account: TnPubkey,
2316        buffer_account: TnPubkey,
2317        buffer_size: u32,
2318        expected_hash: [u8; 32],
2319        fee: u64,
2320        nonce: u64,
2321        start_slot: u64,
2322    ) -> Result<Transaction> {
2323        let mut tx = Transaction::new(fee_payer, uploader_program, fee, nonce)
2324            .with_start_slot(start_slot)
2325            .with_expiry_after(10000)
2326            .with_compute_units(50_000 + 200 * buffer_size as u32)
2327            .with_memory_units(5000)
2328            .with_state_units(0);
2329
2330        // Account layout: [0: fee_payer, 1: uploader_program, 2: meta_account, 3: buffer_account]
2331        let mut meta_account_idx = 2u16;
2332        let mut buffer_account_idx = 3u16;
2333        if meta_account > buffer_account {
2334            meta_account_idx = 3u16;
2335            buffer_account_idx = 2u16;
2336            tx = tx
2337                .add_rw_account(buffer_account)
2338                .add_rw_account(meta_account)
2339        } else {
2340            tx = tx
2341                .add_rw_account(meta_account)
2342                .add_rw_account(buffer_account)
2343        }
2344
2345        let instruction_data = build_uploader_finalize_instruction(
2346            buffer_account_idx,
2347            meta_account_idx,
2348            expected_hash,
2349        )?;
2350
2351        tx = tx.with_instructions(instruction_data);
2352
2353        Ok(tx)
2354    }
2355
2356    /// Build uploader program DESTROY transaction
2357    pub fn build_uploader_destroy(
2358        fee_payer: TnPubkey,
2359        uploader_program: TnPubkey,
2360        meta_account: TnPubkey,
2361        buffer_account: TnPubkey,
2362        fee: u64,
2363        nonce: u64,
2364        start_slot: u64,
2365    ) -> Result<Transaction> {
2366        let mut tx = Transaction::new(fee_payer, uploader_program, fee, nonce)
2367            .with_start_slot(start_slot)
2368            .with_expiry_after(10000)
2369            .with_compute_units(50000)
2370            .with_memory_units(5000)
2371            .with_state_units(0);
2372
2373        // Account layout: [0: fee_payer, 1: uploader_program, 2: meta_account, 3: buffer_account]
2374        let mut meta_account_idx = 2u16;
2375        let mut buffer_account_idx = 3u16;
2376        if meta_account > buffer_account {
2377            meta_account_idx = 3u16;
2378            buffer_account_idx = 2u16;
2379            tx = tx
2380                .add_rw_account(buffer_account)
2381                .add_rw_account(meta_account)
2382        } else {
2383            tx = tx
2384                .add_rw_account(meta_account)
2385                .add_rw_account(buffer_account)
2386        }
2387
2388        let instruction_data =
2389            build_uploader_destroy_instruction(buffer_account_idx, meta_account_idx)?;
2390
2391        tx = tx.with_instructions(instruction_data);
2392        Ok(tx)
2393    }
2394
2395    /// Build manager program CREATE transaction
2396    pub fn build_manager_create(
2397        fee_payer: TnPubkey,
2398        manager_program: TnPubkey,
2399        meta_account: TnPubkey,
2400        program_account: TnPubkey,
2401        srcbuf_account: TnPubkey,
2402        authority_account: TnPubkey,
2403        srcbuf_offset: u32,
2404        srcbuf_size: u32,
2405        seed: &[u8],
2406        is_ephemeral: bool,
2407        meta_proof: Option<&[u8]>,
2408        program_proof: Option<&[u8]>,
2409        fee: u64,
2410        nonce: u64,
2411        start_slot: u64,
2412    ) -> Result<Transaction> {
2413        let mut tx = Transaction::new(fee_payer, manager_program, fee, nonce)
2414            .with_start_slot(start_slot)
2415            .with_expiry_after(10000)
2416            .with_compute_units(500_000_000)
2417            .with_memory_units(5000)
2418            .with_state_units(account_state_units(srcbuf_size as u64 + 4096)?); // Program + one-unit manager metadata.
2419
2420        // Check if authority_account is the same as fee_payer
2421        let authority_is_fee_payer = authority_account == fee_payer;
2422
2423        // Separate accounts by access type and sort each group by pubkey
2424        let mut rw_accounts = vec![(meta_account, "meta"), (program_account, "program")];
2425
2426        let mut r_accounts = vec![(srcbuf_account, "srcbuf")];
2427
2428        // Only add authority_account if it's different from fee_payer
2429        if !authority_is_fee_payer {
2430            r_accounts.push((authority_account, "authority"));
2431        }
2432
2433        // Sort read-write accounts by pubkey
2434        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2435
2436        // Sort read-only accounts by pubkey
2437        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2438
2439        // Combine sorted accounts: read-write first, then read-only
2440        let mut accounts = rw_accounts;
2441        accounts.extend(r_accounts);
2442
2443        let mut meta_account_idx = 0u16;
2444        let mut program_account_idx = 0u16;
2445        let mut srcbuf_account_idx = 0u16;
2446        let mut authority_account_idx = if authority_is_fee_payer {
2447            0u16 // Use fee_payer index (0) when authority is the same as fee_payer
2448        } else {
2449            0u16 // Will be set in the loop below
2450        };
2451
2452        for (i, (account, account_type)) in accounts.iter().enumerate() {
2453            let idx = (i + 2) as u16; // Skip fee_payer (0) and program (1)
2454            match *account_type {
2455                "meta" => {
2456                    meta_account_idx = idx;
2457                    tx = tx.add_rw_account(*account);
2458                }
2459                "program" => {
2460                    program_account_idx = idx;
2461                    tx = tx.add_rw_account(*account);
2462                }
2463                "srcbuf" => {
2464                    srcbuf_account_idx = idx;
2465                    tx = tx.add_r_account(*account);
2466                }
2467                "authority" => {
2468                    authority_account_idx = idx;
2469                    tx = tx.add_r_account(*account);
2470                }
2471                _ => unreachable!(),
2472            }
2473        }
2474
2475        let discriminant = if is_ephemeral {
2476            MANAGER_INSTRUCTION_CREATE_EPHEMERAL
2477        } else {
2478            MANAGER_INSTRUCTION_CREATE_PERMANENT
2479        };
2480
2481        // Concatenate proofs if both are provided (for permanent programs)
2482        let combined_proof = if let (Some(meta), Some(program)) = (meta_proof, program_proof) {
2483            let mut combined = Vec::with_capacity(meta.len() + program.len());
2484            combined.extend_from_slice(meta);
2485            combined.extend_from_slice(program);
2486            Some(combined)
2487        } else {
2488            None
2489        };
2490
2491        let instruction_data = build_manager_create_instruction(
2492            discriminant,
2493            meta_account_idx,
2494            program_account_idx,
2495            srcbuf_account_idx,
2496            authority_account_idx,
2497            srcbuf_offset,
2498            srcbuf_size,
2499            seed,
2500            combined_proof.as_deref(),
2501        )?;
2502
2503        tx = tx.with_instructions(instruction_data);
2504        Ok(tx)
2505    }
2506
2507    /// Build ABI manager program CREATE META (official) transaction
2508    pub fn build_abi_manager_create_meta_official(
2509        fee_payer: TnPubkey,
2510        abi_manager_program: TnPubkey,
2511        program_meta_account: TnPubkey,
2512        abi_meta_account: TnPubkey,
2513        authority_account: TnPubkey,
2514        is_ephemeral: bool,
2515        abi_meta_proof: Option<&[u8]>,
2516        fee: u64,
2517        nonce: u64,
2518        start_slot: u64,
2519    ) -> Result<Transaction> {
2520        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
2521            .with_start_slot(start_slot)
2522            .with_expiry_after(10000)
2523            .with_compute_units(500_000_000)
2524            .with_memory_units(5000)
2525            .with_state_units(1);
2526
2527        let authority_is_fee_payer = authority_account == fee_payer;
2528
2529        let mut rw_accounts = vec![(abi_meta_account, "abi_meta")];
2530        let mut r_accounts = vec![(program_meta_account, "program_meta")];
2531
2532        if !authority_is_fee_payer {
2533            r_accounts.push((authority_account, "authority"));
2534        }
2535
2536        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2537        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2538
2539        let mut accounts = rw_accounts;
2540        accounts.extend(r_accounts);
2541
2542        let mut abi_meta_account_idx = 0u16;
2543        let mut program_meta_account_idx = 0u16;
2544        let mut authority_account_idx = 0u16;
2545
2546        for (i, (account, account_type)) in accounts.iter().enumerate() {
2547            let idx = (i + 2) as u16;
2548            match *account_type {
2549                "abi_meta" => {
2550                    abi_meta_account_idx = idx;
2551                    tx = tx.add_rw_account(*account);
2552                }
2553                "program_meta" => {
2554                    program_meta_account_idx = idx;
2555                    tx = tx.add_r_account(*account);
2556                }
2557                "authority" => {
2558                    authority_account_idx = idx;
2559                    tx = tx.add_r_account(*account);
2560                }
2561                _ => unreachable!(),
2562            }
2563        }
2564
2565        let authority_idx = if authority_is_fee_payer {
2566            0u16
2567        } else {
2568            authority_account_idx
2569        };
2570
2571        let discriminant = if is_ephemeral {
2572            ABI_MANAGER_INSTRUCTION_CREATE_META_OFFICIAL_EPHEMERAL
2573        } else {
2574            ABI_MANAGER_INSTRUCTION_CREATE_META_OFFICIAL_PERMANENT
2575        };
2576
2577        let instruction_data = build_abi_manager_create_meta_official_instruction(
2578            discriminant,
2579            abi_meta_account_idx,
2580            program_meta_account_idx,
2581            authority_idx,
2582            abi_meta_proof,
2583        )?;
2584
2585        tx = tx.with_instructions(instruction_data);
2586        Ok(tx)
2587    }
2588
2589    /// Build ABI manager program CREATE META (external) transaction
2590    pub fn build_abi_manager_create_meta_external(
2591        fee_payer: TnPubkey,
2592        abi_manager_program: TnPubkey,
2593        abi_meta_account: TnPubkey,
2594        authority_account: TnPubkey,
2595        target_program: TnPubkey,
2596        seed: [u8; 32],
2597        is_ephemeral: bool,
2598        abi_meta_proof: Option<&[u8]>,
2599        fee: u64,
2600        nonce: u64,
2601        start_slot: u64,
2602    ) -> Result<Transaction> {
2603        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
2604            .with_start_slot(start_slot)
2605            .with_expiry_after(10000)
2606            .with_compute_units(500_000_000)
2607            .with_memory_units(5000)
2608            .with_state_units(1);
2609
2610        let authority_is_fee_payer = authority_account == fee_payer;
2611
2612        let mut rw_accounts = vec![(abi_meta_account, "abi_meta")];
2613        let mut r_accounts = Vec::new();
2614
2615        if !authority_is_fee_payer {
2616            r_accounts.push((authority_account, "authority"));
2617        }
2618
2619        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2620        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2621
2622        let mut accounts = rw_accounts;
2623        accounts.extend(r_accounts);
2624
2625        let mut abi_meta_account_idx = 0u16;
2626        let mut authority_account_idx = 0u16;
2627
2628        for (i, (account, account_type)) in accounts.iter().enumerate() {
2629            let idx = (i + 2) as u16;
2630            match *account_type {
2631                "abi_meta" => {
2632                    abi_meta_account_idx = idx;
2633                    tx = tx.add_rw_account(*account);
2634                }
2635                "authority" => {
2636                    authority_account_idx = idx;
2637                    tx = tx.add_r_account(*account);
2638                }
2639                _ => unreachable!(),
2640            }
2641        }
2642
2643        let authority_idx = if authority_is_fee_payer {
2644            0u16
2645        } else {
2646            authority_account_idx
2647        };
2648
2649        let discriminant = if is_ephemeral {
2650            ABI_MANAGER_INSTRUCTION_CREATE_META_EXTERNAL_EPHEMERAL
2651        } else {
2652            ABI_MANAGER_INSTRUCTION_CREATE_META_EXTERNAL_PERMANENT
2653        };
2654
2655        let instruction_data = build_abi_manager_create_meta_external_instruction(
2656            discriminant,
2657            abi_meta_account_idx,
2658            authority_idx,
2659            target_program,
2660            seed,
2661            abi_meta_proof,
2662        )?;
2663
2664        tx = tx.with_instructions(instruction_data);
2665        Ok(tx)
2666    }
2667
2668    /// Build ABI manager program CREATE ABI (official) transaction
2669    #[allow(clippy::too_many_arguments)]
2670    pub fn build_abi_manager_create_abi_official(
2671        fee_payer: TnPubkey,
2672        abi_manager_program: TnPubkey,
2673        abi_meta_account: TnPubkey,
2674        program_meta_account: TnPubkey,
2675        abi_account: TnPubkey,
2676        srcbuf_account: TnPubkey,
2677        authority_account: TnPubkey,
2678        srcbuf_offset: u32,
2679        srcbuf_size: u32,
2680        is_ephemeral: bool,
2681        abi_proof: Option<&[u8]>,
2682        fee: u64,
2683        nonce: u64,
2684        start_slot: u64,
2685    ) -> Result<Transaction> {
2686        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
2687            .with_start_slot(start_slot)
2688            .with_expiry_after(10000)
2689            .with_compute_units(500_000_000)
2690            .with_memory_units(5000)
2691            .with_state_units(account_state_units(
2692                srcbuf_size as u64 + ABI_ACCOUNT_HEADER_SIZE,
2693            )?);
2694
2695        let authority_is_fee_payer = authority_account == fee_payer;
2696
2697        let mut rw_accounts = vec![(abi_account, "abi")];
2698        let mut r_accounts = vec![
2699            (abi_meta_account, "abi_meta"),
2700            (program_meta_account, "program_meta"),
2701            (srcbuf_account, "srcbuf"),
2702        ];
2703
2704        if !authority_is_fee_payer {
2705            r_accounts.push((authority_account, "authority"));
2706        }
2707
2708        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2709        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2710
2711        let mut accounts = rw_accounts;
2712        accounts.extend(r_accounts);
2713
2714        let mut abi_meta_account_idx = 0u16;
2715        let mut program_meta_account_idx = 0u16;
2716        let mut abi_account_idx = 0u16;
2717        let mut srcbuf_account_idx = 0u16;
2718        let mut authority_account_idx = 0u16;
2719
2720        for (i, (account, account_type)) in accounts.iter().enumerate() {
2721            let idx = (i + 2) as u16;
2722            match *account_type {
2723                "abi_meta" => {
2724                    abi_meta_account_idx = idx;
2725                    tx = tx.add_r_account(*account);
2726                }
2727                "program_meta" => {
2728                    program_meta_account_idx = idx;
2729                    tx = tx.add_r_account(*account);
2730                }
2731                "abi" => {
2732                    abi_account_idx = idx;
2733                    tx = tx.add_rw_account(*account);
2734                }
2735                "srcbuf" => {
2736                    srcbuf_account_idx = idx;
2737                    tx = tx.add_r_account(*account);
2738                }
2739                "authority" => {
2740                    authority_account_idx = idx;
2741                    tx = tx.add_r_account(*account);
2742                }
2743                _ => unreachable!(),
2744            }
2745        }
2746
2747        let authority_idx = if authority_is_fee_payer {
2748            0u16
2749        } else {
2750            authority_account_idx
2751        };
2752
2753        let discriminant = if is_ephemeral {
2754            ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_EPHEMERAL
2755        } else {
2756            ABI_MANAGER_INSTRUCTION_CREATE_ABI_OFFICIAL_PERMANENT
2757        };
2758
2759        let instruction_data = build_abi_manager_create_abi_official_instruction(
2760            discriminant,
2761            abi_meta_account_idx,
2762            program_meta_account_idx,
2763            abi_account_idx,
2764            srcbuf_account_idx,
2765            srcbuf_offset,
2766            srcbuf_size,
2767            authority_idx,
2768            abi_proof,
2769        )?;
2770
2771        tx = tx.with_instructions(instruction_data);
2772        Ok(tx)
2773    }
2774
2775    /// Build ABI manager program CREATE ABI (external) transaction
2776    #[allow(clippy::too_many_arguments)]
2777    pub fn build_abi_manager_create_abi_external(
2778        fee_payer: TnPubkey,
2779        abi_manager_program: TnPubkey,
2780        abi_meta_account: TnPubkey,
2781        abi_account: TnPubkey,
2782        srcbuf_account: TnPubkey,
2783        authority_account: TnPubkey,
2784        srcbuf_offset: u32,
2785        srcbuf_size: u32,
2786        is_ephemeral: bool,
2787        abi_proof: Option<&[u8]>,
2788        fee: u64,
2789        nonce: u64,
2790        start_slot: u64,
2791    ) -> Result<Transaction> {
2792        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
2793            .with_start_slot(start_slot)
2794            .with_expiry_after(10000)
2795            .with_compute_units(500_000_000)
2796            .with_memory_units(5000)
2797            .with_state_units(account_state_units(
2798                srcbuf_size as u64 + ABI_ACCOUNT_HEADER_SIZE,
2799            )?);
2800
2801        let authority_is_fee_payer = authority_account == fee_payer;
2802
2803        let mut rw_accounts = vec![(abi_account, "abi")];
2804        let mut r_accounts = vec![(abi_meta_account, "abi_meta"), (srcbuf_account, "srcbuf")];
2805
2806        if !authority_is_fee_payer {
2807            r_accounts.push((authority_account, "authority"));
2808        }
2809
2810        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2811        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2812
2813        let mut accounts = rw_accounts;
2814        accounts.extend(r_accounts);
2815
2816        let mut abi_meta_account_idx = 0u16;
2817        let mut abi_account_idx = 0u16;
2818        let mut srcbuf_account_idx = 0u16;
2819        let mut authority_account_idx = 0u16;
2820
2821        for (i, (account, account_type)) in accounts.iter().enumerate() {
2822            let idx = (i + 2) as u16;
2823            match *account_type {
2824                "abi_meta" => {
2825                    abi_meta_account_idx = idx;
2826                    tx = tx.add_r_account(*account);
2827                }
2828                "abi" => {
2829                    abi_account_idx = idx;
2830                    tx = tx.add_rw_account(*account);
2831                }
2832                "srcbuf" => {
2833                    srcbuf_account_idx = idx;
2834                    tx = tx.add_r_account(*account);
2835                }
2836                "authority" => {
2837                    authority_account_idx = idx;
2838                    tx = tx.add_r_account(*account);
2839                }
2840                _ => unreachable!(),
2841            }
2842        }
2843
2844        let authority_idx = if authority_is_fee_payer {
2845            0u16
2846        } else {
2847            authority_account_idx
2848        };
2849
2850        let discriminant = if is_ephemeral {
2851            ABI_MANAGER_INSTRUCTION_CREATE_ABI_EXTERNAL_EPHEMERAL
2852        } else {
2853            ABI_MANAGER_INSTRUCTION_CREATE_ABI_EXTERNAL_PERMANENT
2854        };
2855
2856        let instruction_data = build_abi_manager_create_abi_external_instruction(
2857            discriminant,
2858            abi_meta_account_idx,
2859            abi_account_idx,
2860            srcbuf_account_idx,
2861            srcbuf_offset,
2862            srcbuf_size,
2863            authority_idx,
2864            abi_proof,
2865        )?;
2866
2867        tx = tx.with_instructions(instruction_data);
2868        Ok(tx)
2869    }
2870
2871    /// Build ABI manager program UPGRADE ABI (official) transaction
2872    #[allow(clippy::too_many_arguments)]
2873    pub fn build_abi_manager_upgrade_abi_official(
2874        fee_payer: TnPubkey,
2875        abi_manager_program: TnPubkey,
2876        abi_meta_account: TnPubkey,
2877        program_meta_account: TnPubkey,
2878        abi_account: TnPubkey,
2879        srcbuf_account: TnPubkey,
2880        authority_account: TnPubkey,
2881        srcbuf_offset: u32,
2882        srcbuf_size: u32,
2883        fee: u64,
2884        nonce: u64,
2885        start_slot: u64,
2886    ) -> Result<Transaction> {
2887        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
2888            .with_start_slot(start_slot)
2889            .with_expiry_after(10000)
2890            .with_compute_units(500_000_000)
2891            .with_memory_units(5000)
2892            .with_state_units(
2893                account_state_units(srcbuf_size as u64 + ABI_ACCOUNT_HEADER_SIZE)?
2894                    .saturating_sub(1),
2895            );
2896
2897        let authority_is_fee_payer = authority_account == fee_payer;
2898
2899        let mut rw_accounts = vec![(abi_account, "abi")];
2900        let mut r_accounts = vec![
2901            (abi_meta_account, "abi_meta"),
2902            (program_meta_account, "program_meta"),
2903            (srcbuf_account, "srcbuf"),
2904        ];
2905
2906        if !authority_is_fee_payer {
2907            r_accounts.push((authority_account, "authority"));
2908        }
2909
2910        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2911        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
2912
2913        let mut accounts = rw_accounts;
2914        accounts.extend(r_accounts);
2915
2916        let mut abi_meta_account_idx = 0u16;
2917        let mut program_meta_account_idx = 0u16;
2918        let mut abi_account_idx = 0u16;
2919        let mut srcbuf_account_idx = 0u16;
2920        let mut authority_account_idx = 0u16;
2921
2922        for (i, (account, account_type)) in accounts.iter().enumerate() {
2923            let idx = (i + 2) as u16;
2924            match *account_type {
2925                "abi_meta" => {
2926                    abi_meta_account_idx = idx;
2927                    tx = tx.add_r_account(*account);
2928                }
2929                "program_meta" => {
2930                    program_meta_account_idx = idx;
2931                    tx = tx.add_r_account(*account);
2932                }
2933                "abi" => {
2934                    abi_account_idx = idx;
2935                    tx = tx.add_rw_account(*account);
2936                }
2937                "srcbuf" => {
2938                    srcbuf_account_idx = idx;
2939                    tx = tx.add_r_account(*account);
2940                }
2941                "authority" => {
2942                    authority_account_idx = idx;
2943                    tx = tx.add_r_account(*account);
2944                }
2945                _ => unreachable!(),
2946            }
2947        }
2948
2949        let authority_idx = if authority_is_fee_payer {
2950            0u16
2951        } else {
2952            authority_account_idx
2953        };
2954
2955        let instruction_data = build_abi_manager_upgrade_abi_official_instruction(
2956            abi_meta_account_idx,
2957            program_meta_account_idx,
2958            abi_account_idx,
2959            srcbuf_account_idx,
2960            srcbuf_offset,
2961            srcbuf_size,
2962            authority_idx,
2963        )?;
2964
2965        tx = tx.with_instructions(instruction_data);
2966        Ok(tx)
2967    }
2968
2969    /// Build ABI manager program UPGRADE ABI (external) transaction
2970    #[allow(clippy::too_many_arguments)]
2971    pub fn build_abi_manager_upgrade_abi_external(
2972        fee_payer: TnPubkey,
2973        abi_manager_program: TnPubkey,
2974        abi_meta_account: TnPubkey,
2975        abi_account: TnPubkey,
2976        srcbuf_account: TnPubkey,
2977        authority_account: TnPubkey,
2978        srcbuf_offset: u32,
2979        srcbuf_size: u32,
2980        fee: u64,
2981        nonce: u64,
2982        start_slot: u64,
2983    ) -> Result<Transaction> {
2984        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
2985            .with_start_slot(start_slot)
2986            .with_expiry_after(10000)
2987            .with_compute_units(500_000_000)
2988            .with_memory_units(5000)
2989            .with_state_units(
2990                account_state_units(srcbuf_size as u64 + ABI_ACCOUNT_HEADER_SIZE)?
2991                    .saturating_sub(1),
2992            );
2993
2994        let authority_is_fee_payer = authority_account == fee_payer;
2995
2996        let mut rw_accounts = vec![(abi_account, "abi")];
2997        let mut r_accounts = vec![(abi_meta_account, "abi_meta"), (srcbuf_account, "srcbuf")];
2998
2999        if !authority_is_fee_payer {
3000            r_accounts.push((authority_account, "authority"));
3001        }
3002
3003        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3004        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3005
3006        let mut accounts = rw_accounts;
3007        accounts.extend(r_accounts);
3008
3009        let mut abi_meta_account_idx = 0u16;
3010        let mut abi_account_idx = 0u16;
3011        let mut srcbuf_account_idx = 0u16;
3012        let mut authority_account_idx = 0u16;
3013
3014        for (i, (account, account_type)) in accounts.iter().enumerate() {
3015            let idx = (i + 2) as u16;
3016            match *account_type {
3017                "abi_meta" => {
3018                    abi_meta_account_idx = idx;
3019                    tx = tx.add_r_account(*account);
3020                }
3021                "abi" => {
3022                    abi_account_idx = idx;
3023                    tx = tx.add_rw_account(*account);
3024                }
3025                "srcbuf" => {
3026                    srcbuf_account_idx = idx;
3027                    tx = tx.add_r_account(*account);
3028                }
3029                "authority" => {
3030                    authority_account_idx = idx;
3031                    tx = tx.add_r_account(*account);
3032                }
3033                _ => unreachable!(),
3034            }
3035        }
3036
3037        let authority_idx = if authority_is_fee_payer {
3038            0u16
3039        } else {
3040            authority_account_idx
3041        };
3042
3043        let instruction_data = build_abi_manager_upgrade_abi_external_instruction(
3044            abi_meta_account_idx,
3045            abi_account_idx,
3046            srcbuf_account_idx,
3047            srcbuf_offset,
3048            srcbuf_size,
3049            authority_idx,
3050        )?;
3051
3052        tx = tx.with_instructions(instruction_data);
3053        Ok(tx)
3054    }
3055
3056    /// Build ABI manager program FINALIZE ABI (official) transaction
3057    pub fn build_abi_manager_finalize_abi_official(
3058        fee_payer: TnPubkey,
3059        abi_manager_program: TnPubkey,
3060        abi_meta_account: TnPubkey,
3061        program_meta_account: TnPubkey,
3062        abi_account: TnPubkey,
3063        authority_account: TnPubkey,
3064        fee: u64,
3065        nonce: u64,
3066        start_slot: u64,
3067    ) -> Result<Transaction> {
3068        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
3069            .with_start_slot(start_slot)
3070            .with_expiry_after(10000)
3071            .with_compute_units(500_000_000)
3072            .with_memory_units(5000)
3073            .with_state_units(0);
3074
3075        let authority_is_fee_payer = authority_account == fee_payer;
3076
3077        let mut rw_accounts = vec![(abi_account, "abi")];
3078        let mut r_accounts = vec![
3079            (abi_meta_account, "abi_meta"),
3080            (program_meta_account, "program_meta"),
3081        ];
3082
3083        if !authority_is_fee_payer {
3084            r_accounts.push((authority_account, "authority"));
3085        }
3086
3087        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3088        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3089
3090        let mut accounts = rw_accounts;
3091        accounts.extend(r_accounts);
3092
3093        let mut abi_meta_account_idx = 0u16;
3094        let mut program_meta_account_idx = 0u16;
3095        let mut abi_account_idx = 0u16;
3096        let mut authority_account_idx = 0u16;
3097
3098        for (i, (account, account_type)) in accounts.iter().enumerate() {
3099            let idx = (i + 2) as u16;
3100            match *account_type {
3101                "abi_meta" => {
3102                    abi_meta_account_idx = idx;
3103                    tx = tx.add_r_account(*account);
3104                }
3105                "program_meta" => {
3106                    program_meta_account_idx = idx;
3107                    tx = tx.add_r_account(*account);
3108                }
3109                "abi" => {
3110                    abi_account_idx = idx;
3111                    tx = tx.add_rw_account(*account);
3112                }
3113                "authority" => {
3114                    authority_account_idx = idx;
3115                    tx = tx.add_r_account(*account);
3116                }
3117                _ => unreachable!(),
3118            }
3119        }
3120
3121        let authority_idx = if authority_is_fee_payer {
3122            0u16
3123        } else {
3124            authority_account_idx
3125        };
3126
3127        let instruction_data = build_abi_manager_finalize_abi_official_instruction(
3128            abi_meta_account_idx,
3129            program_meta_account_idx,
3130            abi_account_idx,
3131            authority_idx,
3132        )?;
3133
3134        tx = tx.with_instructions(instruction_data);
3135        Ok(tx)
3136    }
3137
3138    /// Build ABI manager program FINALIZE ABI (external) transaction
3139    pub fn build_abi_manager_finalize_abi_external(
3140        fee_payer: TnPubkey,
3141        abi_manager_program: TnPubkey,
3142        abi_meta_account: TnPubkey,
3143        abi_account: TnPubkey,
3144        authority_account: TnPubkey,
3145        fee: u64,
3146        nonce: u64,
3147        start_slot: u64,
3148    ) -> Result<Transaction> {
3149        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
3150            .with_start_slot(start_slot)
3151            .with_expiry_after(10000)
3152            .with_compute_units(500_000_000)
3153            .with_memory_units(5000)
3154            .with_state_units(0);
3155
3156        let authority_is_fee_payer = authority_account == fee_payer;
3157
3158        let mut rw_accounts = vec![(abi_account, "abi")];
3159        let mut r_accounts = vec![(abi_meta_account, "abi_meta")];
3160
3161        if !authority_is_fee_payer {
3162            r_accounts.push((authority_account, "authority"));
3163        }
3164
3165        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3166        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3167
3168        let mut accounts = rw_accounts;
3169        accounts.extend(r_accounts);
3170
3171        let mut abi_meta_account_idx = 0u16;
3172        let mut abi_account_idx = 0u16;
3173        let mut authority_account_idx = 0u16;
3174
3175        for (i, (account, account_type)) in accounts.iter().enumerate() {
3176            let idx = (i + 2) as u16;
3177            match *account_type {
3178                "abi_meta" => {
3179                    abi_meta_account_idx = idx;
3180                    tx = tx.add_r_account(*account);
3181                }
3182                "abi" => {
3183                    abi_account_idx = idx;
3184                    tx = tx.add_rw_account(*account);
3185                }
3186                "authority" => {
3187                    authority_account_idx = idx;
3188                    tx = tx.add_r_account(*account);
3189                }
3190                _ => unreachable!(),
3191            }
3192        }
3193
3194        let authority_idx = if authority_is_fee_payer {
3195            0u16
3196        } else {
3197            authority_account_idx
3198        };
3199
3200        let instruction_data = build_abi_manager_finalize_abi_external_instruction(
3201            abi_meta_account_idx,
3202            abi_account_idx,
3203            authority_idx,
3204        )?;
3205
3206        tx = tx.with_instructions(instruction_data);
3207        Ok(tx)
3208    }
3209
3210    /// Build ABI manager program CLOSE ABI (official) transaction
3211    pub fn build_abi_manager_close_abi_official(
3212        fee_payer: TnPubkey,
3213        abi_manager_program: TnPubkey,
3214        abi_meta_account: TnPubkey,
3215        program_meta_account: TnPubkey,
3216        abi_account: TnPubkey,
3217        authority_account: TnPubkey,
3218        fee: u64,
3219        nonce: u64,
3220        start_slot: u64,
3221    ) -> Result<Transaction> {
3222        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
3223            .with_start_slot(start_slot)
3224            .with_expiry_after(10000)
3225            .with_compute_units(500_000_000)
3226            .with_memory_units(5000)
3227            .with_state_units(0);
3228
3229        let authority_is_fee_payer = authority_account == fee_payer;
3230
3231        let mut rw_accounts = vec![(abi_account, "abi")];
3232        let mut r_accounts = vec![
3233            (abi_meta_account, "abi_meta"),
3234            (program_meta_account, "program_meta"),
3235        ];
3236
3237        if !authority_is_fee_payer {
3238            r_accounts.push((authority_account, "authority"));
3239        }
3240
3241        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3242        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3243
3244        let mut accounts = rw_accounts;
3245        accounts.extend(r_accounts);
3246
3247        let mut abi_meta_account_idx = 0u16;
3248        let mut program_meta_account_idx = 0u16;
3249        let mut abi_account_idx = 0u16;
3250        let mut authority_account_idx = 0u16;
3251
3252        for (i, (account, account_type)) in accounts.iter().enumerate() {
3253            let idx = (i + 2) as u16;
3254            match *account_type {
3255                "abi_meta" => {
3256                    abi_meta_account_idx = idx;
3257                    tx = tx.add_r_account(*account);
3258                }
3259                "program_meta" => {
3260                    program_meta_account_idx = idx;
3261                    tx = tx.add_r_account(*account);
3262                }
3263                "abi" => {
3264                    abi_account_idx = idx;
3265                    tx = tx.add_rw_account(*account);
3266                }
3267                "authority" => {
3268                    authority_account_idx = idx;
3269                    tx = tx.add_r_account(*account);
3270                }
3271                _ => unreachable!(),
3272            }
3273        }
3274
3275        let authority_idx = if authority_is_fee_payer {
3276            0u16
3277        } else {
3278            authority_account_idx
3279        };
3280
3281        let instruction_data = build_abi_manager_close_abi_official_instruction(
3282            abi_meta_account_idx,
3283            program_meta_account_idx,
3284            abi_account_idx,
3285            authority_idx,
3286        )?;
3287
3288        tx = tx.with_instructions(instruction_data);
3289        Ok(tx)
3290    }
3291
3292    /// Build ABI manager program CLOSE ABI (external) transaction
3293    pub fn build_abi_manager_close_abi_external(
3294        fee_payer: TnPubkey,
3295        abi_manager_program: TnPubkey,
3296        abi_meta_account: TnPubkey,
3297        abi_account: TnPubkey,
3298        authority_account: TnPubkey,
3299        fee: u64,
3300        nonce: u64,
3301        start_slot: u64,
3302    ) -> Result<Transaction> {
3303        let mut tx = Transaction::new(fee_payer, abi_manager_program, fee, nonce)
3304            .with_start_slot(start_slot)
3305            .with_expiry_after(10000)
3306            .with_compute_units(500_000_000)
3307            .with_memory_units(5000)
3308            .with_state_units(0);
3309
3310        let authority_is_fee_payer = authority_account == fee_payer;
3311
3312        let mut rw_accounts = vec![(abi_account, "abi")];
3313        let mut r_accounts = vec![(abi_meta_account, "abi_meta")];
3314
3315        if !authority_is_fee_payer {
3316            r_accounts.push((authority_account, "authority"));
3317        }
3318
3319        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3320        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3321
3322        let mut accounts = rw_accounts;
3323        accounts.extend(r_accounts);
3324
3325        let mut abi_meta_account_idx = 0u16;
3326        let mut abi_account_idx = 0u16;
3327        let mut authority_account_idx = 0u16;
3328
3329        for (i, (account, account_type)) in accounts.iter().enumerate() {
3330            let idx = (i + 2) as u16;
3331            match *account_type {
3332                "abi_meta" => {
3333                    abi_meta_account_idx = idx;
3334                    tx = tx.add_r_account(*account);
3335                }
3336                "abi" => {
3337                    abi_account_idx = idx;
3338                    tx = tx.add_rw_account(*account);
3339                }
3340                "authority" => {
3341                    authority_account_idx = idx;
3342                    tx = tx.add_r_account(*account);
3343                }
3344                _ => unreachable!(),
3345            }
3346        }
3347
3348        let authority_idx = if authority_is_fee_payer {
3349            0u16
3350        } else {
3351            authority_account_idx
3352        };
3353
3354        let instruction_data = build_abi_manager_close_abi_external_instruction(
3355            abi_meta_account_idx,
3356            abi_account_idx,
3357            authority_idx,
3358        )?;
3359
3360        tx = tx.with_instructions(instruction_data);
3361        Ok(tx)
3362    }
3363
3364    /// Build manager program UPGRADE transaction
3365    pub fn build_manager_upgrade(
3366        fee_payer: TnPubkey,
3367        manager_program: TnPubkey,
3368        meta_account: TnPubkey,
3369        program_account: TnPubkey,
3370        srcbuf_account: TnPubkey,
3371        srcbuf_offset: u32,
3372        srcbuf_size: u32,
3373        fee: u64,
3374        nonce: u64,
3375        start_slot: u64,
3376    ) -> Result<Transaction> {
3377        let mut tx = Transaction::new(fee_payer, manager_program, fee, nonce)
3378            .with_start_slot(start_slot)
3379            .with_expiry_after(10000)
3380            .with_compute_units(500_000_000)
3381            .with_memory_units(5000)
3382            .with_state_units(account_state_units(srcbuf_size as u64)?.saturating_sub(1));
3383
3384        // Separate accounts by access type and sort each group by pubkey
3385        let mut rw_accounts = vec![(meta_account, "meta"), (program_account, "program")];
3386
3387        let mut r_accounts = vec![(srcbuf_account, "srcbuf")];
3388
3389        // Sort read-write accounts by pubkey
3390        rw_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3391
3392        // Sort read-only accounts by pubkey
3393        r_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3394
3395        // Combine sorted accounts: read-write first, then read-only
3396        let mut accounts = rw_accounts;
3397        accounts.extend(r_accounts);
3398
3399        let mut meta_account_idx = 0u16;
3400        let mut program_account_idx = 0u16;
3401        let mut srcbuf_account_idx = 0u16;
3402
3403        for (i, (account, account_type)) in accounts.iter().enumerate() {
3404            let idx = (i + 2) as u16; // Skip fee_payer (0) and program (1)
3405            match *account_type {
3406                "meta" => {
3407                    meta_account_idx = idx;
3408                    tx = tx.add_rw_account(*account);
3409                }
3410                "program" => {
3411                    program_account_idx = idx;
3412                    tx = tx.add_rw_account(*account);
3413                }
3414                "srcbuf" => {
3415                    srcbuf_account_idx = idx;
3416                    tx = tx.add_r_account(*account);
3417                }
3418                _ => unreachable!(),
3419            }
3420        }
3421
3422        let instruction_data = build_manager_upgrade_instruction(
3423            meta_account_idx,
3424            program_account_idx,
3425            srcbuf_account_idx,
3426            srcbuf_offset,
3427            srcbuf_size,
3428        )?;
3429
3430        tx = tx.with_instructions(instruction_data);
3431        Ok(tx)
3432    }
3433
3434    /// Build manager program SET_PAUSE transaction
3435    pub fn build_manager_set_pause(
3436        fee_payer: TnPubkey,
3437        manager_program: TnPubkey,
3438        meta_account: TnPubkey,
3439        program_account: TnPubkey,
3440        is_paused: bool,
3441        fee: u64,
3442        nonce: u64,
3443        start_slot: u64,
3444    ) -> Result<Transaction> {
3445        let mut tx = Transaction::new(fee_payer, manager_program, fee, nonce)
3446            .with_start_slot(start_slot)
3447            .with_expiry_after(10000)
3448            .with_compute_units(100_000_000)
3449            .with_memory_units(5000)
3450            .with_state_units(0);
3451
3452        // Add accounts in sorted order
3453        let mut accounts = vec![(meta_account, "meta"), (program_account, "program")];
3454        accounts.sort_by(|a, b| a.0.cmp(&b.0));
3455
3456        let mut meta_account_idx = 0u16;
3457        let mut program_account_idx = 0u16;
3458
3459        for (i, (account, account_type)) in accounts.iter().enumerate() {
3460            let idx = (i + 2) as u16;
3461            match *account_type {
3462                "meta" => {
3463                    meta_account_idx = idx;
3464                    tx = tx.add_rw_account(*account);
3465                }
3466                "program" => {
3467                    program_account_idx = idx;
3468                    tx = tx.add_rw_account(*account);
3469                }
3470                _ => unreachable!(),
3471            }
3472        }
3473
3474        let instruction_data =
3475            build_manager_set_pause_instruction(meta_account_idx, program_account_idx, is_paused)?;
3476
3477        tx = tx.with_instructions(instruction_data);
3478        Ok(tx)
3479    }
3480
3481    /// Build manager program simple transactions (DESTROY, FINALIZE, CLAIM_AUTHORITY)
3482    pub fn build_manager_simple(
3483        fee_payer: TnPubkey,
3484        manager_program: TnPubkey,
3485        meta_account: TnPubkey,
3486        program_account: TnPubkey,
3487        instruction_type: u8,
3488        fee: u64,
3489        nonce: u64,
3490        start_slot: u64,
3491    ) -> Result<Transaction> {
3492        let mut tx = Transaction::new(fee_payer, manager_program, fee, nonce)
3493            .with_start_slot(start_slot)
3494            .with_expiry_after(10000)
3495            .with_compute_units(100_000_000)
3496            .with_memory_units(5000)
3497            .with_state_units(0);
3498
3499        // Add accounts in sorted order
3500        let mut accounts = vec![(meta_account, "meta"), (program_account, "program")];
3501        accounts.sort_by(|a, b| a.0.cmp(&b.0));
3502
3503        let mut meta_account_idx = 0u16;
3504        let mut program_account_idx = 0u16;
3505
3506        for (i, (account, account_type)) in accounts.iter().enumerate() {
3507            let idx = (i + 2) as u16;
3508            match *account_type {
3509                "meta" => {
3510                    meta_account_idx = idx;
3511                    tx = tx.add_rw_account(*account);
3512                }
3513                "program" => {
3514                    program_account_idx = idx;
3515                    tx = tx.add_rw_account(*account);
3516                }
3517                _ => unreachable!(),
3518            }
3519        }
3520
3521        let instruction_data = build_manager_header_instruction(
3522            instruction_type,
3523            meta_account_idx,
3524            program_account_idx,
3525        )?;
3526
3527        tx = tx.with_instructions(instruction_data);
3528        Ok(tx)
3529    }
3530
3531    /// Build manager program SET_AUTHORITY transaction
3532    pub fn build_manager_set_authority(
3533        fee_payer: TnPubkey,
3534        manager_program: TnPubkey,
3535        meta_account: TnPubkey,
3536        program_account: TnPubkey,
3537        authority_candidate: [u8; 32],
3538        fee: u64,
3539        nonce: u64,
3540        start_slot: u64,
3541    ) -> Result<Transaction> {
3542        let mut tx = Transaction::new(fee_payer, manager_program, fee, nonce)
3543            .with_start_slot(start_slot)
3544            .with_expiry_after(10000)
3545            .with_compute_units(100_000_000)
3546            .with_memory_units(5000)
3547            .with_state_units(0);
3548
3549        // Add accounts in sorted order
3550        let mut accounts = vec![(meta_account, "meta"), (program_account, "program")];
3551        accounts.sort_by(|a, b| a.0.cmp(&b.0));
3552
3553        let mut meta_account_idx = 0u16;
3554        let mut program_account_idx = 0u16;
3555
3556        for (i, (account, account_type)) in accounts.iter().enumerate() {
3557            let idx = (i + 2) as u16;
3558            match *account_type {
3559                "meta" => {
3560                    meta_account_idx = idx;
3561                    tx = tx.add_rw_account(*account);
3562                }
3563                "program" => {
3564                    program_account_idx = idx;
3565                    tx = tx.add_rw_account(*account);
3566                }
3567                _ => unreachable!(),
3568            }
3569        }
3570
3571        let instruction_data = build_manager_set_authority_instruction(
3572            meta_account_idx,
3573            program_account_idx,
3574            authority_candidate,
3575        )?;
3576
3577        tx = tx.with_instructions(instruction_data);
3578        Ok(tx)
3579    }
3580
3581    /// Build test uploader program CREATE transaction
3582    pub fn build_test_uploader_create(
3583        fee_payer: TnPubkey,
3584        test_uploader_program: TnPubkey,
3585        target_account: TnPubkey,
3586        account_sz: u32,
3587        seed: &[u8],
3588        is_ephemeral: bool,
3589        state_proof: Option<&[u8]>,
3590        fee: u64,
3591        nonce: u64,
3592        start_slot: u64,
3593    ) -> Result<Transaction> {
3594        // Account layout: [0: fee_payer, 1: test_uploader_program, 2: target_account]
3595        let target_account_idx = 2u16;
3596
3597        let tx = Transaction::new(fee_payer, test_uploader_program, fee, nonce)
3598            .with_start_slot(start_slot)
3599            .with_expiry_after(100)
3600            .with_compute_units(100_000 + account_sz)
3601            .with_memory_units(10_000)
3602            .with_state_units(account_state_units(account_sz as u64)?)
3603            .add_rw_account(target_account);
3604
3605        let instruction_data = build_test_uploader_create_instruction(
3606            target_account_idx,
3607            account_sz,
3608            seed,
3609            is_ephemeral,
3610            state_proof,
3611        )?;
3612
3613        let tx = tx.with_instructions(instruction_data);
3614        Ok(tx)
3615    }
3616
3617    /// Build test uploader program WRITE transaction
3618    pub fn build_test_uploader_write(
3619        fee_payer: TnPubkey,
3620        test_uploader_program: TnPubkey,
3621        target_account: TnPubkey,
3622        offset: u32,
3623        data: &[u8],
3624        fee: u64,
3625        nonce: u64,
3626        start_slot: u64,
3627    ) -> Result<Transaction> {
3628        // Account layout: [0: fee_payer, 1: test_uploader_program, 2: target_account]
3629        let target_account_idx = 2u16;
3630
3631        let tx = Transaction::new(fee_payer, test_uploader_program, fee, nonce)
3632            .with_start_slot(start_slot)
3633            .with_expiry_after(10_000)
3634            .with_compute_units(100_000 + 18 * data.len() as u32)
3635            .with_memory_units(10_000)
3636            .with_state_units(0)
3637            .add_rw_account(target_account);
3638
3639        let instruction_data =
3640            build_test_uploader_write_instruction(target_account_idx, offset, data)?;
3641
3642        let tx = tx.with_instructions(instruction_data);
3643        Ok(tx)
3644    }
3645
3646    /// Build legacy system-test DECOMPRESS2 (separate metadata/data accounts).
3647    /// This instruction format is not compatible with the managed compression program.
3648    pub fn build_decompress2(
3649        fee_payer: TnPubkey,
3650        program: TnPubkey,
3651        target_account: TnPubkey,
3652        meta_account: TnPubkey,
3653        data_account: TnPubkey,
3654        data_offset: u32,
3655        state_proof: &[u8],
3656        fee: u64,
3657        nonce: u64,
3658        start_slot: u64,
3659        data_sz: u32,
3660    ) -> Result<Transaction> {
3661        // Account layout: [0: fee_payer, 1: program, 2: target_account, 3+: meta/data accounts]
3662        let mut tx = Transaction::new(fee_payer, program, fee, nonce)
3663            .with_start_slot(start_slot)
3664            .with_expiry_after(100)
3665            .with_compute_units(10_000 + 2 * data_sz)
3666            .with_memory_units(10_000)
3667            .with_state_units(account_state_units(data_sz as u64)?);
3668
3669        // Add target account (read-write)
3670        let target_account_idx = 2u16;
3671        tx = tx.add_rw_account(target_account);
3672
3673        let mut meta_account_idx = 0u16;
3674        let mut data_account_idx = 0u16;
3675
3676        // Handle meta and data accounts - if they're the same, add only once; if different, add both and sort
3677        if meta_account == data_account {
3678            // Same account for both meta and data
3679            let account_idx = 3u16;
3680            meta_account_idx = account_idx;
3681            data_account_idx = account_idx;
3682            tx = tx.add_r_account(meta_account);
3683        } else {
3684            // Different accounts - add both and sort by pubkey
3685            let mut read_accounts = vec![(meta_account, "meta"), (data_account, "data")];
3686            read_accounts.sort_by(|a, b| a.0.cmp(&b.0));
3687
3688            for (i, (account, account_type)) in read_accounts.iter().enumerate() {
3689                let idx = (3 + i) as u16; // Start from index 3
3690                match *account_type {
3691                    "meta" => {
3692                        meta_account_idx = idx;
3693                        tx = tx.add_r_account(*account);
3694                    }
3695                    "data" => {
3696                        data_account_idx = idx;
3697                        tx = tx.add_r_account(*account);
3698                    }
3699                    _ => unreachable!(),
3700                }
3701            }
3702        }
3703
3704        let instruction_data = build_decompress2_instruction(
3705            target_account_idx,
3706            meta_account_idx,
3707            data_account_idx,
3708            data_offset,
3709            state_proof,
3710        )?;
3711
3712        tx = tx.with_instructions(instruction_data);
3713        Ok(tx)
3714    }
3715}
3716
3717/// Build uploader CREATE instruction data
3718fn build_uploader_create_instruction(
3719    buffer_account_idx: u16,
3720    meta_account_idx: u16,
3721    authority_account_idx: u16,
3722    buffer_size: u32,
3723    expected_hash: [u8; 32],
3724    seed: &[u8],
3725) -> Result<Vec<u8>> {
3726    let mut instruction = Vec::new();
3727
3728    // Discriminant (4 bytes, little-endian)
3729    instruction.extend_from_slice(&TN_UPLOADER_PROGRAM_INSTRUCTION_CREATE.to_le_bytes());
3730
3731    // Create args struct
3732    let args = UploaderCreateArgs {
3733        buffer_account_idx,
3734        meta_account_idx,
3735        authority_account_idx,
3736        buffer_account_sz: buffer_size,
3737        expected_account_hash: expected_hash,
3738        seed_len: seed.len() as u32,
3739    };
3740
3741    // Serialize args (unsafe due to packed struct)
3742    let args_bytes = unsafe {
3743        std::slice::from_raw_parts(
3744            &args as *const _ as *const u8,
3745            std::mem::size_of::<UploaderCreateArgs>(),
3746        )
3747    };
3748    instruction.extend_from_slice(args_bytes);
3749
3750    // Append seed bytes
3751    instruction.extend_from_slice(seed);
3752
3753    Ok(instruction)
3754}
3755
3756/// Build uploader WRITE instruction data
3757fn build_uploader_write_instruction(
3758    buffer_account_idx: u16,
3759    meta_account_idx: u16,
3760    data: &[u8],
3761    offset: u32,
3762) -> Result<Vec<u8>> {
3763    let mut instruction = Vec::new();
3764
3765    // Discriminant (4 bytes, little-endian)
3766    instruction.extend_from_slice(&TN_UPLOADER_PROGRAM_INSTRUCTION_WRITE.to_le_bytes());
3767
3768    // Write args
3769    let args = UploaderWriteArgs {
3770        buffer_account_idx,
3771        meta_account_idx,
3772        data_len: data.len() as u32,
3773        data_offset: offset,
3774    };
3775
3776    // Serialize args
3777    let args_bytes = unsafe {
3778        std::slice::from_raw_parts(
3779            &args as *const _ as *const u8,
3780            std::mem::size_of::<UploaderWriteArgs>(),
3781        )
3782    };
3783    instruction.extend_from_slice(args_bytes);
3784
3785    // Append data
3786    instruction.extend_from_slice(data);
3787
3788    Ok(instruction)
3789}
3790
3791/// Build uploader FINALIZE instruction data
3792fn build_uploader_finalize_instruction(
3793    buffer_account_idx: u16,
3794    meta_account_idx: u16,
3795    expected_hash: [u8; 32],
3796) -> Result<Vec<u8>> {
3797    let mut instruction = Vec::new();
3798
3799    // Discriminant (4 bytes, little-endian)
3800    instruction.extend_from_slice(&TN_UPLOADER_PROGRAM_INSTRUCTION_FINALIZE.to_le_bytes());
3801
3802    // Finalize args
3803    let args = UploaderFinalizeArgs {
3804        buffer_account_idx,
3805        meta_account_idx,
3806        expected_account_hash: expected_hash,
3807    };
3808
3809    // Serialize args
3810    let args_bytes = unsafe {
3811        std::slice::from_raw_parts(
3812            &args as *const _ as *const u8,
3813            std::mem::size_of::<UploaderFinalizeArgs>(),
3814        )
3815    };
3816    instruction.extend_from_slice(args_bytes);
3817
3818    Ok(instruction)
3819}
3820
3821/// Build uploader DESTROY instruction data
3822fn build_uploader_destroy_instruction(
3823    buffer_account_idx: u16,
3824    meta_account_idx: u16,
3825) -> Result<Vec<u8>> {
3826    let mut instruction = Vec::new();
3827
3828    // Discriminant (4 bytes, little-endian)
3829    instruction.extend_from_slice(&TN_UPLOADER_PROGRAM_INSTRUCTION_DESTROY.to_le_bytes());
3830
3831    // Destroy args
3832    let args = UploaderDestroyArgs {
3833        buffer_account_idx,
3834        meta_account_idx,
3835    };
3836
3837    // Serialize args
3838    let args_bytes = unsafe {
3839        std::slice::from_raw_parts(
3840            &args as *const _ as *const u8,
3841            std::mem::size_of::<UploaderDestroyArgs>(),
3842        )
3843    };
3844    instruction.extend_from_slice(args_bytes);
3845
3846    Ok(instruction)
3847}
3848
3849/// Build manager CREATE instruction data
3850fn build_manager_create_instruction(
3851    discriminant: u8,
3852    meta_account_idx: u16,
3853    program_account_idx: u16,
3854    srcbuf_account_idx: u16,
3855    authority_account_idx: u16,
3856    srcbuf_offset: u32,
3857    srcbuf_size: u32,
3858    seed: &[u8],
3859    proof: Option<&[u8]>,
3860) -> Result<Vec<u8>> {
3861    let mut instruction = Vec::new();
3862
3863    // Create args
3864    let args = ManagerCreateArgs {
3865        discriminant,
3866        meta_account_idx,
3867        program_account_idx,
3868        srcbuf_account_idx,
3869        srcbuf_offset,
3870        srcbuf_size,
3871        authority_account_idx,
3872        seed_len: seed.len() as u32,
3873    };
3874
3875    // Serialize args
3876    let args_bytes = unsafe {
3877        std::slice::from_raw_parts(
3878            &args as *const ManagerCreateArgs as *const u8,
3879            std::mem::size_of::<ManagerCreateArgs>(),
3880        )
3881    };
3882    instruction.extend_from_slice(args_bytes);
3883
3884    // Add seed bytes
3885    instruction.extend_from_slice(seed);
3886
3887    // Add proof bytes (only for permanent accounts)
3888    if let Some(proof_bytes) = proof {
3889        instruction.extend_from_slice(proof_bytes);
3890    }
3891
3892    Ok(instruction)
3893}
3894
3895/// Build ABI manager CREATE META (official) instruction data
3896fn build_abi_manager_create_meta_official_instruction(
3897    discriminant: u8,
3898    abi_meta_account_idx: u16,
3899    program_meta_account_idx: u16,
3900    authority_account_idx: u16,
3901    proof: Option<&[u8]>,
3902) -> Result<Vec<u8>> {
3903    let mut instruction = Vec::new();
3904    instruction.push(discriminant);
3905
3906    let args = AbiManagerCreateMetaOfficialArgs {
3907        abi_meta_account_idx,
3908        program_meta_account_idx,
3909        authority_account_idx,
3910    };
3911
3912    let args_bytes = unsafe {
3913        std::slice::from_raw_parts(
3914            &args as *const AbiManagerCreateMetaOfficialArgs as *const u8,
3915            std::mem::size_of::<AbiManagerCreateMetaOfficialArgs>(),
3916        )
3917    };
3918
3919    instruction.extend_from_slice(args_bytes);
3920    if let Some(proof_bytes) = proof {
3921        instruction.extend_from_slice(proof_bytes);
3922    }
3923
3924    Ok(instruction)
3925}
3926
3927/// Build ABI manager CREATE META (external) instruction data
3928fn build_abi_manager_create_meta_external_instruction(
3929    discriminant: u8,
3930    abi_meta_account_idx: u16,
3931    authority_account_idx: u16,
3932    target_program: TnPubkey,
3933    seed: [u8; 32],
3934    proof: Option<&[u8]>,
3935) -> Result<Vec<u8>> {
3936    let mut instruction = Vec::new();
3937    instruction.push(discriminant);
3938
3939    let args = AbiManagerCreateMetaExternalArgs {
3940        abi_meta_account_idx,
3941        authority_account_idx,
3942        target_program,
3943        seed,
3944    };
3945
3946    let args_bytes = unsafe {
3947        std::slice::from_raw_parts(
3948            &args as *const AbiManagerCreateMetaExternalArgs as *const u8,
3949            std::mem::size_of::<AbiManagerCreateMetaExternalArgs>(),
3950        )
3951    };
3952
3953    instruction.extend_from_slice(args_bytes);
3954    if let Some(proof_bytes) = proof {
3955        instruction.extend_from_slice(proof_bytes);
3956    }
3957
3958    Ok(instruction)
3959}
3960
3961/// Build ABI manager CREATE ABI (official) instruction data
3962fn build_abi_manager_create_abi_official_instruction(
3963    discriminant: u8,
3964    abi_meta_account_idx: u16,
3965    program_meta_account_idx: u16,
3966    abi_account_idx: u16,
3967    srcbuf_account_idx: u16,
3968    srcbuf_offset: u32,
3969    srcbuf_size: u32,
3970    authority_account_idx: u16,
3971    proof: Option<&[u8]>,
3972) -> Result<Vec<u8>> {
3973    let mut instruction = Vec::new();
3974    instruction.push(discriminant);
3975
3976    let args = AbiManagerCreateAbiOfficialArgs {
3977        abi_meta_account_idx,
3978        program_meta_account_idx,
3979        abi_account_idx,
3980        srcbuf_account_idx,
3981        srcbuf_offset,
3982        srcbuf_size,
3983        authority_account_idx,
3984    };
3985
3986    let args_bytes = unsafe {
3987        std::slice::from_raw_parts(
3988            &args as *const AbiManagerCreateAbiOfficialArgs as *const u8,
3989            std::mem::size_of::<AbiManagerCreateAbiOfficialArgs>(),
3990        )
3991    };
3992
3993    instruction.extend_from_slice(args_bytes);
3994    if let Some(proof_bytes) = proof {
3995        instruction.extend_from_slice(proof_bytes);
3996    }
3997
3998    Ok(instruction)
3999}
4000
4001/// Build ABI manager CREATE ABI (external) instruction data
4002fn build_abi_manager_create_abi_external_instruction(
4003    discriminant: u8,
4004    abi_meta_account_idx: u16,
4005    abi_account_idx: u16,
4006    srcbuf_account_idx: u16,
4007    srcbuf_offset: u32,
4008    srcbuf_size: u32,
4009    authority_account_idx: u16,
4010    proof: Option<&[u8]>,
4011) -> Result<Vec<u8>> {
4012    let mut instruction = Vec::new();
4013    instruction.push(discriminant);
4014
4015    let args = AbiManagerCreateAbiExternalArgs {
4016        abi_meta_account_idx,
4017        abi_account_idx,
4018        srcbuf_account_idx,
4019        srcbuf_offset,
4020        srcbuf_size,
4021        authority_account_idx,
4022    };
4023
4024    let args_bytes = unsafe {
4025        std::slice::from_raw_parts(
4026            &args as *const AbiManagerCreateAbiExternalArgs as *const u8,
4027            std::mem::size_of::<AbiManagerCreateAbiExternalArgs>(),
4028        )
4029    };
4030
4031    instruction.extend_from_slice(args_bytes);
4032    if let Some(proof_bytes) = proof {
4033        instruction.extend_from_slice(proof_bytes);
4034    }
4035
4036    Ok(instruction)
4037}
4038
4039fn build_abi_manager_upgrade_abi_official_instruction(
4040    abi_meta_account_idx: u16,
4041    program_meta_account_idx: u16,
4042    abi_account_idx: u16,
4043    srcbuf_account_idx: u16,
4044    srcbuf_offset: u32,
4045    srcbuf_size: u32,
4046    authority_account_idx: u16,
4047) -> Result<Vec<u8>> {
4048    let mut instruction = Vec::new();
4049    instruction.push(ABI_MANAGER_INSTRUCTION_UPGRADE_ABI_OFFICIAL);
4050
4051    let args = AbiManagerUpgradeAbiOfficialArgs {
4052        abi_meta_account_idx,
4053        program_meta_account_idx,
4054        abi_account_idx,
4055        srcbuf_account_idx,
4056        srcbuf_offset,
4057        srcbuf_size,
4058        authority_account_idx,
4059    };
4060
4061    let args_bytes = unsafe {
4062        std::slice::from_raw_parts(
4063            &args as *const AbiManagerUpgradeAbiOfficialArgs as *const u8,
4064            std::mem::size_of::<AbiManagerUpgradeAbiOfficialArgs>(),
4065        )
4066    };
4067
4068    instruction.extend_from_slice(args_bytes);
4069    Ok(instruction)
4070}
4071
4072fn build_abi_manager_upgrade_abi_external_instruction(
4073    abi_meta_account_idx: u16,
4074    abi_account_idx: u16,
4075    srcbuf_account_idx: u16,
4076    srcbuf_offset: u32,
4077    srcbuf_size: u32,
4078    authority_account_idx: u16,
4079) -> Result<Vec<u8>> {
4080    let mut instruction = Vec::new();
4081    instruction.push(ABI_MANAGER_INSTRUCTION_UPGRADE_ABI_EXTERNAL);
4082
4083    let args = AbiManagerUpgradeAbiExternalArgs {
4084        abi_meta_account_idx,
4085        abi_account_idx,
4086        srcbuf_account_idx,
4087        srcbuf_offset,
4088        srcbuf_size,
4089        authority_account_idx,
4090    };
4091
4092    let args_bytes = unsafe {
4093        std::slice::from_raw_parts(
4094            &args as *const AbiManagerUpgradeAbiExternalArgs as *const u8,
4095            std::mem::size_of::<AbiManagerUpgradeAbiExternalArgs>(),
4096        )
4097    };
4098
4099    instruction.extend_from_slice(args_bytes);
4100    Ok(instruction)
4101}
4102
4103fn build_abi_manager_finalize_abi_official_instruction(
4104    abi_meta_account_idx: u16,
4105    program_meta_account_idx: u16,
4106    abi_account_idx: u16,
4107    authority_account_idx: u16,
4108) -> Result<Vec<u8>> {
4109    let mut instruction = Vec::new();
4110    instruction.push(ABI_MANAGER_INSTRUCTION_FINALIZE_ABI_OFFICIAL);
4111
4112    let args = AbiManagerFinalizeAbiOfficialArgs {
4113        abi_meta_account_idx,
4114        program_meta_account_idx,
4115        abi_account_idx,
4116        authority_account_idx,
4117    };
4118
4119    let args_bytes = unsafe {
4120        std::slice::from_raw_parts(
4121            &args as *const AbiManagerFinalizeAbiOfficialArgs as *const u8,
4122            std::mem::size_of::<AbiManagerFinalizeAbiOfficialArgs>(),
4123        )
4124    };
4125
4126    instruction.extend_from_slice(args_bytes);
4127    Ok(instruction)
4128}
4129
4130fn build_abi_manager_finalize_abi_external_instruction(
4131    abi_meta_account_idx: u16,
4132    abi_account_idx: u16,
4133    authority_account_idx: u16,
4134) -> Result<Vec<u8>> {
4135    let mut instruction = Vec::new();
4136    instruction.push(ABI_MANAGER_INSTRUCTION_FINALIZE_ABI_EXTERNAL);
4137
4138    let args = AbiManagerFinalizeAbiExternalArgs {
4139        abi_meta_account_idx,
4140        abi_account_idx,
4141        authority_account_idx,
4142    };
4143
4144    let args_bytes = unsafe {
4145        std::slice::from_raw_parts(
4146            &args as *const AbiManagerFinalizeAbiExternalArgs as *const u8,
4147            std::mem::size_of::<AbiManagerFinalizeAbiExternalArgs>(),
4148        )
4149    };
4150
4151    instruction.extend_from_slice(args_bytes);
4152    Ok(instruction)
4153}
4154
4155fn build_abi_manager_close_abi_official_instruction(
4156    abi_meta_account_idx: u16,
4157    program_meta_account_idx: u16,
4158    abi_account_idx: u16,
4159    authority_account_idx: u16,
4160) -> Result<Vec<u8>> {
4161    let mut instruction = Vec::new();
4162    instruction.push(ABI_MANAGER_INSTRUCTION_CLOSE_ABI_OFFICIAL);
4163
4164    let args = AbiManagerCloseAbiOfficialArgs {
4165        abi_meta_account_idx,
4166        program_meta_account_idx,
4167        abi_account_idx,
4168        authority_account_idx,
4169    };
4170
4171    let args_bytes = unsafe {
4172        std::slice::from_raw_parts(
4173            &args as *const AbiManagerCloseAbiOfficialArgs as *const u8,
4174            std::mem::size_of::<AbiManagerCloseAbiOfficialArgs>(),
4175        )
4176    };
4177
4178    instruction.extend_from_slice(args_bytes);
4179    Ok(instruction)
4180}
4181
4182fn build_abi_manager_close_abi_external_instruction(
4183    abi_meta_account_idx: u16,
4184    abi_account_idx: u16,
4185    authority_account_idx: u16,
4186) -> Result<Vec<u8>> {
4187    let mut instruction = Vec::new();
4188    instruction.push(ABI_MANAGER_INSTRUCTION_CLOSE_ABI_EXTERNAL);
4189
4190    let args = AbiManagerCloseAbiExternalArgs {
4191        abi_meta_account_idx,
4192        abi_account_idx,
4193        authority_account_idx,
4194    };
4195
4196    let args_bytes = unsafe {
4197        std::slice::from_raw_parts(
4198            &args as *const AbiManagerCloseAbiExternalArgs as *const u8,
4199            std::mem::size_of::<AbiManagerCloseAbiExternalArgs>(),
4200        )
4201    };
4202
4203    instruction.extend_from_slice(args_bytes);
4204    Ok(instruction)
4205}
4206
4207/// Build manager UPGRADE instruction data
4208fn build_manager_upgrade_instruction(
4209    meta_account_idx: u16,
4210    program_account_idx: u16,
4211    srcbuf_account_idx: u16,
4212    srcbuf_offset: u32,
4213    srcbuf_size: u32,
4214) -> Result<Vec<u8>> {
4215    let mut instruction = Vec::new();
4216
4217    let args = ManagerUpgradeArgs {
4218        discriminant: MANAGER_INSTRUCTION_UPGRADE,
4219        meta_account_idx,
4220        program_account_idx,
4221        srcbuf_account_idx,
4222        srcbuf_offset,
4223        srcbuf_size,
4224    };
4225
4226    let args_bytes = unsafe {
4227        std::slice::from_raw_parts(
4228            &args as *const ManagerUpgradeArgs as *const u8,
4229            std::mem::size_of::<ManagerUpgradeArgs>(),
4230        )
4231    };
4232    instruction.extend_from_slice(args_bytes);
4233
4234    Ok(instruction)
4235}
4236
4237/// Build manager SET_PAUSE instruction data
4238fn build_manager_set_pause_instruction(
4239    meta_account_idx: u16,
4240    program_account_idx: u16,
4241    is_paused: bool,
4242) -> Result<Vec<u8>> {
4243    let mut instruction = Vec::new();
4244
4245    let args = ManagerSetPauseArgs {
4246        discriminant: MANAGER_INSTRUCTION_SET_PAUSE,
4247        meta_account_idx,
4248        program_account_idx,
4249        is_paused: if is_paused { 1 } else { 0 },
4250    };
4251
4252    let args_bytes = unsafe {
4253        std::slice::from_raw_parts(
4254            &args as *const ManagerSetPauseArgs as *const u8,
4255            std::mem::size_of::<ManagerSetPauseArgs>(),
4256        )
4257    };
4258    instruction.extend_from_slice(args_bytes);
4259
4260    Ok(instruction)
4261}
4262
4263/// Build manager header-only instruction data (DESTROY, FINALIZE, CLAIM_AUTHORITY)
4264fn build_manager_header_instruction(
4265    discriminant: u8,
4266    meta_account_idx: u16,
4267    program_account_idx: u16,
4268) -> Result<Vec<u8>> {
4269    let mut instruction = Vec::new();
4270
4271    let args = ManagerHeaderArgs {
4272        discriminant,
4273        meta_account_idx,
4274        program_account_idx,
4275    };
4276
4277    let args_bytes = unsafe {
4278        std::slice::from_raw_parts(
4279            &args as *const ManagerHeaderArgs as *const u8,
4280            std::mem::size_of::<ManagerHeaderArgs>(),
4281        )
4282    };
4283    instruction.extend_from_slice(args_bytes);
4284
4285    Ok(instruction)
4286}
4287
4288/// Build manager SET_AUTHORITY instruction data
4289fn build_manager_set_authority_instruction(
4290    meta_account_idx: u16,
4291    program_account_idx: u16,
4292    authority_candidate: [u8; 32],
4293) -> Result<Vec<u8>> {
4294    let mut instruction = Vec::new();
4295
4296    let args = ManagerSetAuthorityArgs {
4297        discriminant: MANAGER_INSTRUCTION_SET_AUTHORITY,
4298        meta_account_idx,
4299        program_account_idx,
4300        authority_candidate,
4301    };
4302
4303    let args_bytes = unsafe {
4304        std::slice::from_raw_parts(
4305            &args as *const ManagerSetAuthorityArgs as *const u8,
4306            std::mem::size_of::<ManagerSetAuthorityArgs>(),
4307        )
4308    };
4309    instruction.extend_from_slice(args_bytes);
4310
4311    Ok(instruction)
4312}
4313
4314/// Build test uploader CREATE instruction data
4315fn build_test_uploader_create_instruction(
4316    account_idx: u16,
4317    account_sz: u32,
4318    seed: &[u8],
4319    is_ephemeral: bool,
4320    state_proof: Option<&[u8]>,
4321) -> Result<Vec<u8>> {
4322    let mut instruction = Vec::new();
4323
4324    // Discriminant (1 byte)
4325    instruction.push(TN_TEST_UPLOADER_PROGRAM_DISCRIMINANT_CREATE);
4326
4327    // Create args struct
4328    let args = TestUploaderCreateArgs {
4329        account_idx,
4330        is_ephemeral: if is_ephemeral { 1u8 } else { 0u8 },
4331        account_sz,
4332        seed_len: seed.len() as u32,
4333    };
4334
4335    // Serialize args (unsafe due to packed struct)
4336    let args_bytes = unsafe {
4337        std::slice::from_raw_parts(
4338            &args as *const _ as *const u8,
4339            std::mem::size_of::<TestUploaderCreateArgs>(),
4340        )
4341    };
4342    instruction.extend_from_slice(args_bytes);
4343
4344    // Append seed bytes
4345    instruction.extend_from_slice(seed);
4346
4347    // Append state proof if provided (for non-ephemeral accounts)
4348    if let Some(proof) = state_proof {
4349        instruction.extend_from_slice(proof);
4350    }
4351
4352    Ok(instruction)
4353}
4354
4355/// Build test uploader WRITE instruction data
4356fn build_test_uploader_write_instruction(
4357    target_account_idx: u16,
4358    target_offset: u32,
4359    data: &[u8],
4360) -> Result<Vec<u8>> {
4361    let mut instruction = Vec::new();
4362
4363    // Discriminant (1 byte)
4364    instruction.push(TN_TEST_UPLOADER_PROGRAM_DISCRIMINANT_WRITE);
4365
4366    // Write args
4367    let args = TestUploaderWriteArgs {
4368        target_account_idx,
4369        target_offset,
4370        data_len: data.len() as u32,
4371    };
4372
4373    // Serialize args
4374    let args_bytes = unsafe {
4375        std::slice::from_raw_parts(
4376            &args as *const _ as *const u8,
4377            std::mem::size_of::<TestUploaderWriteArgs>(),
4378        )
4379    };
4380    instruction.extend_from_slice(args_bytes);
4381
4382    // Append data
4383    instruction.extend_from_slice(data);
4384
4385    Ok(instruction)
4386}
4387
4388/// Build system program DECOMPRESS2 instruction data
4389pub fn build_decompress2_instruction(
4390    target_account_idx: u16,
4391    meta_account_idx: u16,
4392    data_account_idx: u16,
4393    data_offset: u32,
4394    state_proof: &[u8],
4395) -> Result<Vec<u8>> {
4396    let mut instruction = Vec::new();
4397
4398    // Discriminant (1 byte) - TN_SYS_TEST_PROG_DISCRIMINANT_ACCOUNT_DECOMPRESS2 = 0x08
4399    instruction.push(0x08);
4400
4401    // DECOMPRESS2 args
4402    let args = SystemProgramDecompress2Args {
4403        target_account_idx,
4404        meta_account_idx,
4405        data_account_idx,
4406        data_offset,
4407    };
4408
4409    // Serialize args
4410    let args_bytes = unsafe {
4411        std::slice::from_raw_parts(
4412            &args as *const _ as *const u8,
4413            std::mem::size_of::<SystemProgramDecompress2Args>(),
4414        )
4415    };
4416    instruction.extend_from_slice(args_bytes);
4417
4418    // Append state proof bytes
4419    instruction.extend_from_slice(state_proof);
4420
4421    Ok(instruction)
4422}
4423
4424/// Token program instruction discriminants
4425pub const TOKEN_INSTRUCTION_INITIALIZE_MINT: u8 = 0x00;
4426pub const TOKEN_INSTRUCTION_INITIALIZE_ACCOUNT: u8 = 0x01;
4427pub const TOKEN_INSTRUCTION_TRANSFER: u8 = 0x02;
4428pub const TOKEN_INSTRUCTION_MINT_TO: u8 = 0x03;
4429pub const TOKEN_INSTRUCTION_BURN: u8 = 0x04;
4430pub const TOKEN_INSTRUCTION_CLOSE_ACCOUNT: u8 = 0x05;
4431pub const TOKEN_INSTRUCTION_FREEZE_ACCOUNT: u8 = 0x06;
4432pub const TOKEN_INSTRUCTION_THAW_ACCOUNT: u8 = 0x07;
4433
4434/* WTHRU instruction discriminants */
4435pub const TN_WTHRU_INSTRUCTION_INITIALIZE_MINT: u32 = 0;
4436pub const TN_WTHRU_INSTRUCTION_DEPOSIT: u32 = 1;
4437pub const TN_WTHRU_INSTRUCTION_WITHDRAW: u32 = 2;
4438// lease, resolve (lil library), show lease info,
4439// cost to lease, renew, record management, listing records for domain,
4440// subdomain management
4441
4442/* Name service instruction discriminants */
4443pub const TN_NAME_SERVICE_INSTRUCTION_INITIALIZE_ROOT: u32 = 0;
4444pub const TN_NAME_SERVICE_INSTRUCTION_REGISTER_SUBDOMAIN: u32 = 1;
4445pub const TN_NAME_SERVICE_INSTRUCTION_APPEND_RECORD: u32 = 2;
4446pub const TN_NAME_SERVICE_INSTRUCTION_DELETE_RECORD: u32 = 3;
4447pub const TN_NAME_SERVICE_INSTRUCTION_UNREGISTER: u32 = 4;
4448
4449/* Name service proof discriminants */
4450pub const TN_NAME_SERVICE_PROOF_INLINE: u32 = 0;
4451
4452/* Name service limits */
4453pub const TN_NAME_SERVICE_MAX_DOMAIN_LENGTH: usize = 64;
4454pub const TN_NAME_SERVICE_MAX_KEY_LENGTH: usize = 32;
4455pub const TN_NAME_SERVICE_MAX_VALUE_LENGTH: usize = 256;
4456
4457// Thru registrar instruction types (u32 discriminants)
4458pub const TN_THRU_REGISTRAR_INSTRUCTION_INITIALIZE_REGISTRY: u32 = 0;
4459pub const TN_THRU_REGISTRAR_INSTRUCTION_PURCHASE_DOMAIN: u32 = 1;
4460pub const TN_THRU_REGISTRAR_INSTRUCTION_RENEW_LEASE: u32 = 2;
4461pub const TN_THRU_REGISTRAR_INSTRUCTION_CLAIM_EXPIRED_DOMAIN: u32 = 3;
4462
4463/* Block-producer (BP) bond program instruction discriminants (u32).
4464Mirrors programs/c/examples/tn_block_producer_program.h.  Contiguous 0..7
4465(UNTO-1293 removed ClaimFees and closed the discriminant gaps). */
4466pub const TN_BP_INSTRUCTION_CREATE_ACCOUNT: u32 = 0;
4467pub const TN_BP_INSTRUCTION_SET_BOND_AUTHORITY: u32 = 1;
4468pub const TN_BP_INSTRUCTION_DEPOSIT: u32 = 2;
4469pub const TN_BP_INSTRUCTION_WITHDRAWAL: u32 = 3;
4470pub const TN_BP_INSTRUCTION_UPDATE_BOND: u32 = 4;
4471pub const TN_BP_INSTRUCTION_DELETE_ACCOUNT: u32 = 5;
4472pub const TN_BP_INSTRUCTION_SWEEP: u32 = 6;
4473pub const TN_BP_INSTRUCTION_PAY_OUT_BLOCK: u32 = 7;
4474
4475/* BP bond derivation — single source of truth is
4476programs/c/examples/tn_block_producer_derivation.h.  These mirror it byte
4477for byte (asserted by test_bp_bond_derivation_matches_c). */
4478
4479/// SHA256( prefix || signer ) — the bond / bond-TA seed.
4480fn bp_seed_with_prefix(prefix: &[u8], signer: &[u8; 32]) -> [u8; 32] {
4481    use sha2::{Digest, Sha256};
4482    let mut hasher = Sha256::new();
4483    hasher.update(prefix);
4484    hasher.update(signer);
4485    let hash = hasher.finalize();
4486    let mut out = [0u8; 32];
4487    out.copy_from_slice(&hash[..32]);
4488    out
4489}
4490
4491/// bond = PDA( SHA256("bp_bond" || signer), bp_program ).
4492pub fn bp_bond_account_address(bp_program: &[u8; 32], signer: &[u8; 32]) -> [u8; 32] {
4493    let seed = bp_seed_with_prefix(b"bp_bond", signer);
4494    crate::tn_public_address::create_program_defined_account_address(bp_program, false, &seed)
4495}
4496
4497/// bond_ta = PDA( SHA256(bp_program || wthru_mint || SHA256("bp_bond_ta" ||
4498/// signer)), token_program ).
4499pub fn bp_bond_ta_address(
4500    token_program: &[u8; 32],
4501    bp_program: &[u8; 32],
4502    wthru_mint: &[u8; 32],
4503    signer: &[u8; 32],
4504) -> [u8; 32] {
4505    use sha2::{Digest, Sha256};
4506    let ta_seed = bp_seed_with_prefix(b"bp_bond_ta", signer);
4507    let mut hasher = Sha256::new();
4508    hasher.update(bp_program);
4509    hasher.update(wthru_mint);
4510    hasher.update(&ta_seed);
4511    let hash = hasher.finalize();
4512    let mut token_seed = [0u8; 32];
4513    token_seed.copy_from_slice(&hash[..32]);
4514    crate::tn_public_address::create_program_defined_account_address(
4515        token_program,
4516        false,
4517        &token_seed,
4518    )
4519}
4520
4521/// Ed25519 (RFC 8032, strict) signature over the canonical EOA-create
4522/// authorization message [`build_eoa_create_message`]:
4523/// `"tn_eoa_create_v1" || chain_id LE || fee_payer || signer` (82 bytes),
4524/// proving control of `signer_private_key`.  This is exactly what
4525/// `tsys_account_create_eoa` verifies (`tn_vm_syscall_account_create_eoa`)
4526/// and what the BP CreateAccount Mode 2 path requires as
4527/// `signer_eoa_signature`.  The message binds the chain id and the paying fee
4528/// payer, so a signature is valid for one (chain, fee payer, signer) triple.
4529pub fn bp_sign_eoa_creation(
4530    signer_private_key: &[u8; 32],
4531    chain_id: u16,
4532    fee_payer: &TnPubkey,
4533    signer_pubkey: &TnPubkey,
4534) -> [u8; 64] {
4535    use ed25519_dalek::{Signer, SigningKey};
4536    let signing_key = SigningKey::from_bytes(signer_private_key);
4537    let msg = build_eoa_create_message(chain_id, fee_payer, signer_pubkey);
4538    signing_key.sign(&msg).to_bytes()
4539}
4540
4541/// Helper function to add sorted accounts and return their indices
4542fn add_sorted_accounts(tx: Transaction, accounts: &[(TnPubkey, bool)]) -> (Transaction, Vec<u16>) {
4543    // Separate RW and RO accounts, sort each group separately
4544    let mut rw_accounts: Vec<_> = accounts
4545        .iter()
4546        .enumerate()
4547        .filter(|(_, (_, writable))| *writable)
4548        .collect();
4549    let mut ro_accounts: Vec<_> = accounts
4550        .iter()
4551        .enumerate()
4552        .filter(|(_, (_, writable))| !*writable)
4553        .collect();
4554
4555    // Sort each group by pubkey
4556    rw_accounts.sort_by(|a, b| a.1 .0.cmp(&b.1 .0));
4557    ro_accounts.sort_by(|a, b| a.1 .0.cmp(&b.1 .0));
4558
4559    let mut updated_tx = tx;
4560    let mut indices = vec![0u16; accounts.len()];
4561    let mut seen: HashMap<TnPubkey, u16> = HashMap::new();
4562    seen.insert(updated_tx.fee_payer, 0u16);
4563    seen.insert(updated_tx.program, 1u16);
4564
4565    let mut next_idx = 2u16;
4566
4567    // Process RW accounts first (in sorted order)
4568    for (i, (account, _)) in rw_accounts.iter() {
4569        if let Some(idx) = seen.get(account) {
4570            indices[*i] = *idx;
4571            continue;
4572        }
4573
4574        let account_idx = next_idx;
4575        next_idx = next_idx.saturating_add(1);
4576        seen.insert(*account, account_idx);
4577        indices[*i] = account_idx;
4578
4579        updated_tx = updated_tx.add_rw_account(*account);
4580    }
4581
4582    // Then process RO accounts (in sorted order)
4583    for (i, (account, _)) in ro_accounts.iter() {
4584        if let Some(idx) = seen.get(account) {
4585            indices[*i] = *idx;
4586            continue;
4587        }
4588
4589        let account_idx = next_idx;
4590        next_idx = next_idx.saturating_add(1);
4591        seen.insert(*account, account_idx);
4592        indices[*i] = account_idx;
4593
4594        updated_tx = updated_tx.add_r_account(*account);
4595    }
4596
4597    (updated_tx, indices)
4598}
4599
4600/// Helper function to get authority index (0 if fee_payer, else add as readonly)
4601fn add_sorted_rw_accounts(mut tx: Transaction, accounts: &[TnPubkey]) -> (Transaction, Vec<u16>) {
4602    if accounts.is_empty() {
4603        return (tx, Vec::new());
4604    }
4605
4606    let mut sorted: Vec<(usize, TnPubkey)> = accounts.iter().cloned().enumerate().collect();
4607    sorted.sort_by(|a, b| a.1.cmp(&b.1));
4608
4609    let mut indices = vec![0u16; accounts.len()];
4610    for (pos, (orig_idx, account)) in sorted.into_iter().enumerate() {
4611        let idx = (2 + pos) as u16;
4612        indices[orig_idx] = idx;
4613        tx = tx.add_rw_account(account);
4614    }
4615
4616    (tx, indices)
4617}
4618
4619fn add_sorted_ro_accounts(
4620    mut tx: Transaction,
4621    base_idx: u16,
4622    accounts: &[TnPubkey],
4623) -> (Transaction, Vec<u16>) {
4624    if accounts.is_empty() {
4625        return (tx, Vec::new());
4626    }
4627
4628    let mut sorted: Vec<(usize, TnPubkey)> = accounts.iter().cloned().enumerate().collect();
4629    sorted.sort_by(|a, b| a.1.cmp(&b.1));
4630
4631    let mut indices = vec![0u16; accounts.len()];
4632    for (pos, (orig_idx, account)) in sorted.into_iter().enumerate() {
4633        let idx = base_idx + pos as u16;
4634        indices[orig_idx] = idx;
4635        tx = tx.add_r_account(account);
4636    }
4637
4638    (tx, indices)
4639}
4640
4641impl TransactionBuilder {
4642    /// Build token program InitializeMint transaction
4643    pub fn build_token_initialize_mint(
4644        fee_payer: TnPubkey,
4645        token_program: TnPubkey,
4646        mint_account: TnPubkey,
4647        creator: TnPubkey,
4648        mint_authority: TnPubkey,
4649        freeze_authority: Option<TnPubkey>,
4650        decimals: u8,
4651        ticker: &str,
4652        seed: [u8; 32],
4653        state_proof: Vec<u8>,
4654        fee: u64,
4655        nonce: u64,
4656        start_slot: u64,
4657    ) -> Result<Transaction> {
4658        let base_tx =
4659            Transaction::new(fee_payer, token_program, fee, nonce).with_start_slot(start_slot);
4660        let (tx, indices) = add_sorted_rw_accounts(base_tx, &[mint_account]);
4661        let mint_account_idx = indices[0];
4662
4663        let instruction_data = build_token_initialize_mint_instruction(
4664            mint_account_idx,
4665            decimals,
4666            creator,
4667            mint_authority,
4668            freeze_authority,
4669            ticker,
4670            seed,
4671            state_proof,
4672        )?;
4673
4674        let tx = tx
4675            .with_instructions(instruction_data)
4676            .with_expiry_after(100)
4677            .with_compute_units(300_000)
4678            .with_state_units(1)
4679            .with_memory_units(10_000);
4680
4681        Ok(tx)
4682    }
4683
4684    /// Build token program InitializeAccount transaction
4685    pub fn build_token_initialize_account(
4686        fee_payer: TnPubkey,
4687        token_program: TnPubkey,
4688        token_account: TnPubkey,
4689        mint_account: TnPubkey,
4690        owner: TnPubkey,
4691        seed: [u8; 32],
4692        state_proof: Vec<u8>,
4693        fee: u64,
4694        nonce: u64,
4695        start_slot: u64,
4696    ) -> Result<Transaction> {
4697        let owner_is_fee_payer = owner == fee_payer;
4698
4699        let mut rw_accounts = vec![token_account];
4700        rw_accounts.sort();
4701
4702        let mut ro_accounts = vec![mint_account];
4703        if !owner_is_fee_payer {
4704            ro_accounts.push(owner);
4705            ro_accounts.sort();
4706        }
4707
4708        let mut tx =
4709            Transaction::new(fee_payer, token_program, fee, nonce).with_start_slot(start_slot);
4710
4711        let mut token_account_idx = 0u16;
4712        for (i, account) in rw_accounts.iter().enumerate() {
4713            let idx = (2 + i) as u16;
4714            if *account == token_account {
4715                token_account_idx = idx;
4716            }
4717            tx = tx.add_rw_account(*account);
4718        }
4719
4720        let base_ro_idx = 2 + rw_accounts.len() as u16;
4721        let mut mint_account_idx = 0u16;
4722        let mut owner_account_idx = if owner_is_fee_payer { 0u16 } else { 0u16 };
4723        for (i, account) in ro_accounts.iter().enumerate() {
4724            let idx = base_ro_idx + i as u16;
4725            if *account == mint_account {
4726                mint_account_idx = idx;
4727            } else if !owner_is_fee_payer && *account == owner {
4728                owner_account_idx = idx;
4729            }
4730            tx = tx.add_r_account(*account);
4731        }
4732
4733        let instruction_data = build_token_initialize_account_instruction(
4734            token_account_idx,
4735            mint_account_idx,
4736            owner_account_idx,
4737            seed,
4738            state_proof,
4739        )?;
4740
4741        let tx = tx
4742            .with_instructions(instruction_data)
4743            .with_expiry_after(100)
4744            .with_compute_units(300_000)
4745            .with_state_units(1)
4746            .with_memory_units(10_000);
4747
4748        Ok(tx)
4749    }
4750
4751    /// Build token program Transfer transaction
4752    pub fn build_token_transfer(
4753        fee_payer: TnPubkey,
4754        token_program: TnPubkey,
4755        source_account: TnPubkey,
4756        dest_account: TnPubkey,
4757        _authority: TnPubkey,
4758        amount: u64,
4759        fee: u64,
4760        nonce: u64,
4761        start_slot: u64,
4762    ) -> Result<Transaction> {
4763        let mut tx = Transaction::new(fee_payer, token_program, fee, nonce)
4764            .with_start_slot(start_slot)
4765            .with_expiry_after(100)
4766            .with_compute_units(300_000)
4767            .with_state_units(0)
4768            .with_memory_units(10_000);
4769
4770        let is_self_transfer = source_account == dest_account;
4771        let (source_account_idx, dest_account_idx) = if is_self_transfer {
4772            // For self-transfers, add the account only once and use same index
4773            tx = tx.add_rw_account(source_account);
4774            (2u16, 2u16)
4775        } else {
4776            // Add source and dest accounts in sorted order
4777            let accounts = &[(source_account, true), (dest_account, true)];
4778            let (updated_tx, indices) = add_sorted_accounts(tx, accounts);
4779            tx = updated_tx;
4780            (indices[0], indices[1])
4781        };
4782
4783        // Note: For transfers, the authority (source account owner) must sign the transaction
4784        // The token program will verify the signature matches the source account owner
4785
4786        let instruction_data =
4787            build_token_transfer_instruction(source_account_idx, dest_account_idx, amount)?;
4788
4789        Ok(tx.with_instructions(instruction_data))
4790    }
4791
4792    /// Build token program MintTo transaction
4793    pub fn build_token_mint_to(
4794        fee_payer: TnPubkey,
4795        token_program: TnPubkey,
4796        mint_account: TnPubkey,
4797        dest_account: TnPubkey,
4798        authority: TnPubkey,
4799        amount: u64,
4800        fee: u64,
4801        nonce: u64,
4802        start_slot: u64,
4803    ) -> Result<Transaction> {
4804        let base_tx = Transaction::new(fee_payer, token_program, fee, nonce)
4805            .with_start_slot(start_slot)
4806            .with_expiry_after(100)
4807            .with_compute_units(300_000)
4808            .with_state_units(0)
4809            .with_memory_units(10_000);
4810
4811        let (tx_after_rw, rw_indices) =
4812            add_sorted_rw_accounts(base_tx, &[mint_account, dest_account]);
4813        let mint_account_idx = rw_indices[0];
4814        let dest_account_idx = rw_indices[1];
4815
4816        let mut tx = tx_after_rw;
4817        let authority_account_idx = if authority == fee_payer {
4818            0u16
4819        } else {
4820            let base_ro_idx = 2 + rw_indices.len() as u16;
4821            let (tx_after_ro, ro_indices) = add_sorted_ro_accounts(tx, base_ro_idx, &[authority]);
4822            tx = tx_after_ro;
4823            ro_indices[0]
4824        };
4825
4826        let instruction_data = build_token_mint_to_instruction(
4827            mint_account_idx,
4828            dest_account_idx,
4829            authority_account_idx,
4830            amount,
4831        )?;
4832
4833        Ok(tx.with_instructions(instruction_data))
4834    }
4835
4836    /// Build token program Burn transaction
4837    pub fn build_token_burn(
4838        fee_payer: TnPubkey,
4839        token_program: TnPubkey,
4840        token_account: TnPubkey,
4841        mint_account: TnPubkey,
4842        authority: TnPubkey,
4843        amount: u64,
4844        fee: u64,
4845        nonce: u64,
4846        start_slot: u64,
4847    ) -> Result<Transaction> {
4848        let base_tx = Transaction::new(fee_payer, token_program, fee, nonce)
4849            .with_start_slot(start_slot)
4850            .with_expiry_after(100)
4851            .with_compute_units(300_000)
4852            .with_state_units(0)
4853            .with_memory_units(10_000);
4854
4855        let (tx_after_rw, rw_indices) =
4856            add_sorted_rw_accounts(base_tx, &[token_account, mint_account]);
4857        let token_account_idx = rw_indices[0];
4858        let mint_account_idx = rw_indices[1];
4859
4860        let mut tx = tx_after_rw;
4861        let authority_account_idx = if authority == fee_payer {
4862            0u16
4863        } else {
4864            let base_ro_idx = 2 + rw_indices.len() as u16;
4865            let (tx_after_ro, ro_indices) = add_sorted_ro_accounts(tx, base_ro_idx, &[authority]);
4866            tx = tx_after_ro;
4867            ro_indices[0]
4868        };
4869
4870        let instruction_data = build_token_burn_instruction(
4871            token_account_idx,
4872            mint_account_idx,
4873            authority_account_idx,
4874            amount,
4875        )?;
4876
4877        Ok(tx.with_instructions(instruction_data))
4878    }
4879
4880    /// Build token program FreezeAccount transaction
4881    pub fn build_token_freeze_account(
4882        fee_payer: TnPubkey,
4883        token_program: TnPubkey,
4884        token_account: TnPubkey,
4885        mint_account: TnPubkey,
4886        authority: TnPubkey,
4887        fee: u64,
4888        nonce: u64,
4889        start_slot: u64,
4890    ) -> Result<Transaction> {
4891        let base_tx = Transaction::new(fee_payer, token_program, fee, nonce)
4892            .with_start_slot(start_slot)
4893            .with_expiry_after(100)
4894            .with_compute_units(300_000)
4895            .with_state_units(0)
4896            .with_memory_units(10_000);
4897
4898        let (tx_after_rw, rw_indices) =
4899            add_sorted_rw_accounts(base_tx, &[token_account, mint_account]);
4900        let token_account_idx = rw_indices[0];
4901        let mint_account_idx = rw_indices[1];
4902
4903        let mut tx = tx_after_rw;
4904        let authority_account_idx = if authority == fee_payer {
4905            0u16
4906        } else {
4907            let base_ro_idx = 2 + rw_indices.len() as u16;
4908            let (tx_after_ro, ro_indices) = add_sorted_ro_accounts(tx, base_ro_idx, &[authority]);
4909            tx = tx_after_ro;
4910            ro_indices[0]
4911        };
4912
4913        let instruction_data = build_token_freeze_account_instruction(
4914            token_account_idx,
4915            mint_account_idx,
4916            authority_account_idx,
4917        )?;
4918
4919        Ok(tx.with_instructions(instruction_data))
4920    }
4921
4922    /// Build token program ThawAccount transaction
4923    pub fn build_token_thaw_account(
4924        fee_payer: TnPubkey,
4925        token_program: TnPubkey,
4926        token_account: TnPubkey,
4927        mint_account: TnPubkey,
4928        authority: TnPubkey,
4929        fee: u64,
4930        nonce: u64,
4931        start_slot: u64,
4932    ) -> Result<Transaction> {
4933        let base_tx = Transaction::new(fee_payer, token_program, fee, nonce)
4934            .with_start_slot(start_slot)
4935            .with_expiry_after(100)
4936            .with_compute_units(300_000)
4937            .with_state_units(0)
4938            .with_memory_units(10_000);
4939
4940        let (tx_after_rw, rw_indices) =
4941            add_sorted_rw_accounts(base_tx, &[token_account, mint_account]);
4942        let token_account_idx = rw_indices[0];
4943        let mint_account_idx = rw_indices[1];
4944
4945        let mut tx = tx_after_rw;
4946        let authority_account_idx = if authority == fee_payer {
4947            0u16
4948        } else {
4949            let base_ro_idx = 2 + rw_indices.len() as u16;
4950            let (tx_after_ro, ro_indices) = add_sorted_ro_accounts(tx, base_ro_idx, &[authority]);
4951            tx = tx_after_ro;
4952            ro_indices[0]
4953        };
4954
4955        let instruction_data = build_token_thaw_account_instruction(
4956            token_account_idx,
4957            mint_account_idx,
4958            authority_account_idx,
4959        )?;
4960
4961        Ok(tx.with_instructions(instruction_data))
4962    }
4963
4964    /// Build token program CloseAccount transaction
4965    pub fn build_token_close_account(
4966        fee_payer: TnPubkey,
4967        token_program: TnPubkey,
4968        token_account: TnPubkey,
4969        destination: TnPubkey,
4970        authority: TnPubkey,
4971        fee: u64,
4972        nonce: u64,
4973        start_slot: u64,
4974    ) -> Result<Transaction> {
4975        let base_tx = Transaction::new(fee_payer, token_program, fee, nonce)
4976            .with_start_slot(start_slot)
4977            .with_expiry_after(100)
4978            .with_compute_units(300_000)
4979            .with_state_units(0)
4980            .with_memory_units(10_000);
4981
4982        let mut rw_accounts = vec![token_account];
4983        let destination_in_accounts = destination != fee_payer;
4984        if destination_in_accounts {
4985            rw_accounts.push(destination);
4986        }
4987
4988        let (tx_after_rw, rw_indices) = add_sorted_rw_accounts(base_tx, &rw_accounts);
4989        let token_account_idx = rw_indices[0];
4990        let destination_idx = if destination_in_accounts {
4991            rw_indices[1]
4992        } else {
4993            0u16
4994        };
4995
4996        let mut tx = tx_after_rw;
4997        let authority_account_idx = if authority == fee_payer {
4998            0u16
4999        } else {
5000            let base_ro_idx = 2 + rw_indices.len() as u16;
5001            let (tx_after_ro, ro_indices) = add_sorted_ro_accounts(tx, base_ro_idx, &[authority]);
5002            tx = tx_after_ro;
5003            ro_indices[0]
5004        };
5005
5006        let instruction_data = build_token_close_account_instruction(
5007            token_account_idx,
5008            destination_idx,
5009            authority_account_idx,
5010        )?;
5011
5012        Ok(tx.with_instructions(instruction_data))
5013    }
5014
5015    /// Build WTHRU initialize transaction
5016    pub fn build_wthru_initialize_mint(
5017        fee_payer: TnPubkey,
5018        wthru_program: TnPubkey,
5019        token_program: TnPubkey,
5020        mint_account: TnPubkey,
5021        vault_account: TnPubkey,
5022        decimals: u8,
5023        mint_seed: [u8; 32],
5024        mint_proof: Vec<u8>,
5025        vault_proof: Vec<u8>,
5026        fee: u64,
5027        nonce: u64,
5028        start_slot: u64,
5029    ) -> Result<Transaction> {
5030        let mut tx = Transaction::new(fee_payer, wthru_program, fee, nonce)
5031            .with_start_slot(start_slot)
5032            .with_expiry_after(100)
5033            .with_compute_units(500_000)
5034            .with_state_units(2) // New mint and vault.
5035            .with_memory_units(10_000);
5036
5037        let accounts = [
5038            (mint_account, true),
5039            (vault_account, true),
5040            (token_program, false),
5041        ];
5042
5043        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
5044        tx = tx_with_accounts;
5045
5046        let mint_account_idx = indices[0];
5047        let vault_account_idx = indices[1];
5048        let token_program_idx = indices[2];
5049
5050        let instruction_data = build_wthru_initialize_mint_instruction(
5051            token_program_idx,
5052            mint_account_idx,
5053            vault_account_idx,
5054            decimals,
5055            mint_seed,
5056            mint_proof,
5057            vault_proof,
5058        )?;
5059
5060        Ok(tx.with_instructions(instruction_data))
5061    }
5062
5063    /// Build WTHRU deposit transaction
5064    ///
5065    /// The deposit instruction mints the vault's unaccounted native balance
5066    /// delta to `dest_token_account` and does not transfer any native THRU
5067    /// itself. The transfer into the vault must therefore be in the same
5068    /// transaction as this instruction (e.g. batched via the multicall
5069    /// program); if the two are submitted separately, the delta sits
5070    /// unattributed on-chain and any caller can be credited it instead.
5071    pub fn build_wthru_deposit(
5072        fee_payer: TnPubkey,
5073        wthru_program: TnPubkey,
5074        token_program: TnPubkey,
5075        mint_account: TnPubkey,
5076        vault_account: TnPubkey,
5077        dest_token_account: TnPubkey,
5078        fee: u64,
5079        nonce: u64,
5080        start_slot: u64,
5081    ) -> Result<Transaction> {
5082        let mut tx = Transaction::new(fee_payer, wthru_program, fee, nonce)
5083            .with_start_slot(start_slot)
5084            .with_expiry_after(100)
5085            .with_compute_units(400_000)
5086            .with_state_units(0)
5087            .with_memory_units(10_000);
5088
5089        let accounts = [
5090            (mint_account, true),
5091            (vault_account, true),
5092            (dest_token_account, true),
5093            (token_program, false),
5094        ];
5095
5096        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
5097        tx = tx_with_accounts;
5098
5099        let mint_account_idx = indices[0];
5100        let vault_account_idx = indices[1];
5101        let dest_account_idx = indices[2];
5102        let token_program_idx = indices[3];
5103
5104        let instruction_data = build_wthru_deposit_instruction(
5105            token_program_idx,
5106            vault_account_idx,
5107            mint_account_idx,
5108            dest_account_idx,
5109        )?;
5110
5111        Ok(tx.with_instructions(instruction_data))
5112    }
5113
5114    /// Build WTHRU withdraw transaction
5115    pub fn build_wthru_withdraw(
5116        fee_payer: TnPubkey,
5117        wthru_program: TnPubkey,
5118        token_program: TnPubkey,
5119        mint_account: TnPubkey,
5120        vault_account: TnPubkey,
5121        wthru_token_account: TnPubkey,
5122        recipient_account: TnPubkey,
5123        amount: u64,
5124        fee: u64,
5125        nonce: u64,
5126        start_slot: u64,
5127    ) -> Result<Transaction> {
5128        let mut tx = Transaction::new(fee_payer, wthru_program, fee, nonce)
5129            .with_start_slot(start_slot)
5130            .with_expiry_after(100)
5131            .with_compute_units(400_000)
5132            .with_state_units(0)
5133            .with_memory_units(10_000);
5134
5135        let accounts = [
5136            (mint_account, true),
5137            (vault_account, true),
5138            (wthru_token_account, true),
5139            (recipient_account, true),
5140            (token_program, false),
5141        ];
5142
5143        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
5144        tx = tx_with_accounts;
5145
5146        let mint_account_idx = indices[0];
5147        let vault_account_idx = indices[1];
5148        let token_account_idx = indices[2];
5149        let recipient_account_idx = indices[3];
5150        let token_program_idx = indices[4];
5151
5152        let owner_account_idx = 0u16; // fee payer/owner
5153
5154        let instruction_data = build_wthru_withdraw_instruction(
5155            token_program_idx,
5156            vault_account_idx,
5157            mint_account_idx,
5158            token_account_idx,
5159            owner_account_idx,
5160            recipient_account_idx,
5161            amount,
5162        )?;
5163
5164        Ok(tx.with_instructions(instruction_data))
5165    }
5166
5167    /// Build a block-producer (BP) bond CreateAccount transaction (disc 0).
5168    ///
5169    /// Two modes (see tn_block_producer_program.h:124-145):
5170    /// * Mode 1 (`create_signer_eoa == false`): the signer IS the fee payer; the
5171    ///   runtime-verified txn signature proves control.  `eoa_proof` must be
5172    ///   empty and `signer_eoa_signature` is ignored (pass zeros).
5173    /// * Mode 2 (`create_signer_eoa == true`): a third party pays.  The program
5174    ///   creates the signer's EOA via `account_create_eoa`, which requires
5175    ///   `signer_eoa_signature` = Ed25519 by the signer's key over the canonical
5176    ///   EOA-create authorization (chain id, fee payer, signer; see
5177    ///   [`bp_sign_eoa_creation`]) and the signer-EOA CREATION `eoa_proof`.
5178    ///
5179    /// Account writability: bond=rw, bond_ta=rw, mint=ro, token_program=ro, and
5180    /// in Mode 2 the signer EOA (== signer_pubkey) = rw (it is created here).
5181    #[allow(clippy::too_many_arguments)]
5182    pub fn build_bp_create_account(
5183        fee_payer: TnPubkey,
5184        bp_program: TnPubkey,
5185        token_program: TnPubkey,
5186        bond_account: TnPubkey,
5187        bond_ta: TnPubkey,
5188        mint_account: TnPubkey,
5189        signer_pubkey: TnPubkey,
5190        bond_authority: TnPubkey,
5191        create_signer_eoa: bool,
5192        signer_eoa_signature: [u8; 64],
5193        bond_proof: Vec<u8>,
5194        ta_proof: Vec<u8>,
5195        eoa_proof: Vec<u8>,
5196        fee: u64,
5197        nonce: u64,
5198        start_slot: u64,
5199    ) -> Result<Transaction> {
5200        let tx = Transaction::new(fee_payer, bp_program, fee, nonce)
5201            .with_start_slot(start_slot)
5202            .with_expiry_after(100)
5203            .with_compute_units(50_000_000)
5204            .with_state_units(2 + u16::from(create_signer_eoa)) // Bond, token account, optional EOA.
5205            .with_memory_units(50_000);
5206
5207        let mut accounts: Vec<(TnPubkey, bool)> = vec![
5208            (bond_account, true),
5209            (bond_ta, true),
5210            (mint_account, false),
5211            (token_program, false),
5212        ];
5213        if create_signer_eoa {
5214            /* The signer EOA is created by account_create_eoa, so it must be a
5215            writable creating account (mirrors the C Mode 2 test). */
5216            accounts.push((signer_pubkey, true));
5217        }
5218
5219        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5220        let bond_account_idx = indices[0];
5221        let bond_ta_idx = indices[1];
5222        let mint_account_idx = indices[2];
5223        let token_program_idx = indices[3];
5224        let signer_eoa_idx = if create_signer_eoa { indices[4] } else { 0u16 };
5225
5226        let instruction_data = build_bp_create_account_instruction(
5227            token_program_idx,
5228            bond_account_idx,
5229            bond_ta_idx,
5230            mint_account_idx,
5231            signer_eoa_idx,
5232            create_signer_eoa,
5233            &signer_pubkey,
5234            &bond_authority,
5235            &signer_eoa_signature,
5236            &bond_proof,
5237            &ta_proof,
5238            &eoa_proof,
5239        )?;
5240
5241        Ok(tx.with_instructions(instruction_data))
5242    }
5243
5244    /// Build a BP SetBondAuthority transaction (disc 2).  The current bond
5245    /// authority signs by being the fee payer.
5246    pub fn build_bp_set_authority(
5247        fee_payer: TnPubkey,
5248        bp_program: TnPubkey,
5249        bond_account: TnPubkey,
5250        new_bond_authority: TnPubkey,
5251        fee: u64,
5252        nonce: u64,
5253        start_slot: u64,
5254    ) -> Result<Transaction> {
5255        let tx = bp_base_tx(fee_payer, bp_program, fee, nonce, start_slot);
5256        let (tx, indices) = add_sorted_accounts(tx, &[(bond_account, true)]);
5257        let bond_account_idx = indices[0];
5258
5259        let mut instruction_data = Vec::new();
5260        instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_SET_BOND_AUTHORITY.to_le_bytes());
5261        instruction_data.extend_from_slice(&bond_account_idx.to_le_bytes());
5262        instruction_data.extend_from_slice(&new_bond_authority);
5263
5264        Ok(tx.with_instructions(instruction_data))
5265    }
5266
5267    /// Build a BP Deposit transaction (disc 3).  Stages `amount` from the
5268    /// operator's `source_ta` into the bond TA.  The bond authority and the
5269    /// source-TA owner are both the fee payer.
5270    #[allow(clippy::too_many_arguments)]
5271    pub fn build_bp_deposit(
5272        fee_payer: TnPubkey,
5273        bp_program: TnPubkey,
5274        token_program: TnPubkey,
5275        bond_account: TnPubkey,
5276        bond_ta: TnPubkey,
5277        source_ta: TnPubkey,
5278        amount: u64,
5279        fee: u64,
5280        nonce: u64,
5281        start_slot: u64,
5282    ) -> Result<Transaction> {
5283        let tx = bp_base_tx(fee_payer, bp_program, fee, nonce, start_slot);
5284        let accounts = [
5285            (bond_account, true),
5286            (bond_ta, true),
5287            (source_ta, true),
5288            (token_program, false),
5289        ];
5290        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5291
5292        let mut instruction_data = Vec::new();
5293        instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_DEPOSIT.to_le_bytes());
5294        instruction_data.extend_from_slice(&indices[3].to_le_bytes()); // token_program_idx
5295        instruction_data.extend_from_slice(&indices[0].to_le_bytes()); // bond_account_idx
5296        instruction_data.extend_from_slice(&indices[1].to_le_bytes()); // bond_ta_idx
5297        instruction_data.extend_from_slice(&indices[2].to_le_bytes()); // source_ta_idx
5298        instruction_data.extend_from_slice(&amount.to_le_bytes());
5299
5300        Ok(tx.with_instructions(instruction_data))
5301    }
5302
5303    /// Build a BP Withdrawal transaction (disc 4).  `from_active` selects the
5304    /// staged (immediate) or active (lockout-gated) path.
5305    #[allow(clippy::too_many_arguments)]
5306    pub fn build_bp_withdrawal(
5307        fee_payer: TnPubkey,
5308        bp_program: TnPubkey,
5309        token_program: TnPubkey,
5310        bond_account: TnPubkey,
5311        bond_ta: TnPubkey,
5312        dest_ta: TnPubkey,
5313        attestor_table: TnPubkey,
5314        from_active: bool,
5315        amount: u64,
5316        fee: u64,
5317        nonce: u64,
5318        start_slot: u64,
5319    ) -> Result<Transaction> {
5320        let tx = bp_base_tx(fee_payer, bp_program, fee, nonce, start_slot);
5321        let accounts = [
5322            (bond_account, true),
5323            (bond_ta, true),
5324            (dest_ta, true),
5325            (attestor_table, false),
5326            (token_program, false),
5327        ];
5328        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5329
5330        let mut instruction_data = Vec::new();
5331        instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_WITHDRAWAL.to_le_bytes());
5332        instruction_data.extend_from_slice(&indices[4].to_le_bytes()); // token_program_idx
5333        instruction_data.extend_from_slice(&indices[0].to_le_bytes()); // bond_account_idx
5334        instruction_data.extend_from_slice(&indices[1].to_le_bytes()); // bond_ta_idx
5335        instruction_data.extend_from_slice(&indices[2].to_le_bytes()); // dest_ta_idx
5336        instruction_data.extend_from_slice(&indices[3].to_le_bytes()); // attestor_table_idx
5337        instruction_data.push(if from_active { 1u8 } else { 0u8 });
5338        instruction_data.extend_from_slice(&amount.to_le_bytes());
5339
5340        Ok(tx.with_instructions(instruction_data))
5341    }
5342
5343    /// Build a BP UpdateBond transaction (disc 5).  Moves funds between staged
5344    /// and active to reach `new_active`, raising `unlock_slot`.
5345    #[allow(clippy::too_many_arguments)]
5346    pub fn build_bp_update_bond(
5347        fee_payer: TnPubkey,
5348        bp_program: TnPubkey,
5349        bond_account: TnPubkey,
5350        attestor_table: TnPubkey,
5351        new_unlock_slot: u64,
5352        new_active: u64,
5353        fee: u64,
5354        nonce: u64,
5355        start_slot: u64,
5356    ) -> Result<Transaction> {
5357        let tx = bp_base_tx(fee_payer, bp_program, fee, nonce, start_slot);
5358        let accounts = [(bond_account, true), (attestor_table, false)];
5359        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5360
5361        let mut instruction_data = Vec::new();
5362        instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_UPDATE_BOND.to_le_bytes());
5363        instruction_data.extend_from_slice(&indices[0].to_le_bytes()); // bond_account_idx
5364        instruction_data.extend_from_slice(&indices[1].to_le_bytes()); // attestor_table_idx
5365        instruction_data.extend_from_slice(&new_unlock_slot.to_le_bytes());
5366        instruction_data.extend_from_slice(&new_active.to_le_bytes());
5367
5368        Ok(tx.with_instructions(instruction_data))
5369    }
5370
5371    /// Build a BP DeleteAccount transaction (disc 6).  Returns native lamports
5372    /// to `dest`; requires active==0 && staged==0 && slot>=unlock_slot.  `dest`
5373    /// may equal the fee payer (collapses to index 0 via add_sorted_accounts).
5374    pub fn build_bp_delete_account(
5375        fee_payer: TnPubkey,
5376        bp_program: TnPubkey,
5377        bond_account: TnPubkey,
5378        dest: TnPubkey,
5379        fee: u64,
5380        nonce: u64,
5381        start_slot: u64,
5382    ) -> Result<Transaction> {
5383        let tx = bp_base_tx(fee_payer, bp_program, fee, nonce, start_slot);
5384        let accounts = [(bond_account, true), (dest, true)];
5385        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5386
5387        let mut instruction_data = Vec::new();
5388        instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_DELETE_ACCOUNT.to_le_bytes());
5389        instruction_data.extend_from_slice(&indices[0].to_le_bytes()); // bond_account_idx
5390        instruction_data.extend_from_slice(&indices[1].to_le_bytes()); // dest_idx
5391
5392        Ok(tx.with_instructions(instruction_data))
5393    }
5394
5395    /// Build a BP Sweep transaction (disc 7).  Reclaims stray inbound transfers
5396    /// (bond_TA.balance - active - staged) to `dest_ta`.
5397    #[allow(clippy::too_many_arguments)]
5398    pub fn build_bp_sweep(
5399        fee_payer: TnPubkey,
5400        bp_program: TnPubkey,
5401        token_program: TnPubkey,
5402        bond_account: TnPubkey,
5403        bond_ta: TnPubkey,
5404        dest_ta: TnPubkey,
5405        fee: u64,
5406        nonce: u64,
5407        start_slot: u64,
5408    ) -> Result<Transaction> {
5409        let tx = bp_base_tx(fee_payer, bp_program, fee, nonce, start_slot);
5410        let accounts = [
5411            (bond_account, true),
5412            (bond_ta, true),
5413            (dest_ta, true),
5414            (token_program, false),
5415        ];
5416        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5417
5418        let mut instruction_data = Vec::new();
5419        instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_SWEEP.to_le_bytes());
5420        instruction_data.extend_from_slice(&indices[3].to_le_bytes()); // token_program_idx
5421        instruction_data.extend_from_slice(&indices[0].to_le_bytes()); // bond_account_idx
5422        instruction_data.extend_from_slice(&indices[1].to_le_bytes()); // bond_ta_idx
5423        instruction_data.extend_from_slice(&indices[2].to_le_bytes()); // dest_ta_idx
5424
5425        Ok(tx.with_instructions(instruction_data))
5426    }
5427
5428    /// Build faucet program Deposit transaction
5429    /// The faucet program will invoke the EOA program to transfer from depositor to faucet account
5430    pub fn build_faucet_deposit(
5431        fee_payer: TnPubkey,
5432        faucet_program: TnPubkey,
5433        faucet_account: TnPubkey,
5434        depositor_account: TnPubkey,
5435        eoa_program: TnPubkey,
5436        amount: u64,
5437        fee: u64,
5438        nonce: u64,
5439        start_slot: u64,
5440    ) -> Result<Transaction> {
5441        let tx = Transaction::new(fee_payer, faucet_program, fee, nonce)
5442            .with_start_slot(start_slot)
5443            .with_expiry_after(100)
5444            .with_compute_units(300_000)
5445            .with_state_units(0)
5446            .with_memory_units(10_000);
5447
5448        let (tx, depositor_account_idx) = Self::ensure_rw_account(tx, depositor_account);
5449        let (tx, faucet_account_idx) = Self::ensure_rw_account(tx, faucet_account);
5450        let (tx, eoa_program_idx) = Self::ensure_ro_account(tx, eoa_program);
5451
5452        let instruction_data = build_faucet_deposit_instruction(
5453            faucet_account_idx,
5454            depositor_account_idx,
5455            eoa_program_idx,
5456            amount,
5457        )?;
5458
5459        Ok(tx.with_instructions(instruction_data))
5460    }
5461
5462    fn resolve_account_index(tx: &Transaction, target: &TnPubkey) -> Option<u16> {
5463        if *target == tx.fee_payer {
5464            return Some(0u16);
5465        }
5466
5467        if *target == tx.program {
5468            return Some(1u16);
5469        }
5470
5471        if let Some(ref rw) = tx.rw_accs {
5472            if let Some(pos) = rw.iter().position(|acc| acc == target) {
5473                return Some(2u16 + pos as u16);
5474            }
5475        }
5476
5477        if let Some(ref ro) = tx.r_accs {
5478            let base = 2u16 + tx.rw_accs.as_ref().map_or(0u16, |v| v.len() as u16);
5479            if let Some(pos) = ro.iter().position(|acc| acc == target) {
5480                return Some(base + pos as u16);
5481            }
5482        }
5483
5484        None
5485    }
5486
5487    fn ensure_rw_account(mut tx: Transaction, account: TnPubkey) -> (Transaction, u16) {
5488        if let Some(idx) = Self::resolve_account_index(&tx, &account) {
5489            return (tx, idx);
5490        }
5491
5492        tx = tx.add_rw_account(account);
5493        let idx = Self::resolve_account_index(&tx, &account)
5494            .expect("read-write account index should exist after insertion");
5495
5496        (tx, idx)
5497    }
5498
5499    fn ensure_ro_account(mut tx: Transaction, account: TnPubkey) -> (Transaction, u16) {
5500        if let Some(idx) = Self::resolve_account_index(&tx, &account) {
5501            return (tx, idx);
5502        }
5503
5504        tx = tx.add_r_account(account);
5505        let idx = Self::resolve_account_index(&tx, &account)
5506            .expect("read-only account index should exist after insertion");
5507
5508        (tx, idx)
5509    }
5510
5511    /// Build faucet program Withdraw transaction
5512    pub fn build_faucet_withdraw(
5513        fee_payer: TnPubkey,
5514        faucet_program: TnPubkey,
5515        faucet_account: TnPubkey,
5516        recipient_account: TnPubkey,
5517        amount: u64,
5518        fee: u64,
5519        nonce: u64,
5520        start_slot: u64,
5521    ) -> Result<Transaction> {
5522        let mut tx = Transaction::new(fee_payer, faucet_program, fee, nonce)
5523            .with_start_slot(start_slot)
5524            .with_expiry_after(100)
5525            .with_compute_units(300_000)
5526            .with_state_units(0)
5527            .with_memory_units(10_000);
5528
5529        // Determine account indices, handling duplicates with fee_payer and between accounts
5530        // Check for duplicates first
5531        let faucet_is_fee_payer = faucet_account == fee_payer;
5532        let recipient_is_fee_payer = recipient_account == fee_payer;
5533        let recipient_is_faucet = recipient_account == faucet_account;
5534
5535        let (faucet_account_idx, recipient_account_idx) =
5536            if faucet_is_fee_payer && recipient_is_fee_payer {
5537                // Both are fee_payer (same account)
5538                (0u16, 0u16)
5539            } else if faucet_is_fee_payer {
5540                // Faucet is fee_payer, recipient is different
5541                tx = tx.add_rw_account(recipient_account);
5542                (0u16, 2u16)
5543            } else if recipient_is_fee_payer {
5544                // Recipient is fee_payer, faucet is different
5545                tx = tx.add_rw_account(faucet_account);
5546                (2u16, 0u16)
5547            } else if recipient_is_faucet {
5548                // Both are same account (but not fee_payer)
5549                tx = tx.add_rw_account(faucet_account);
5550                (2u16, 2u16)
5551            } else {
5552                // Both are different accounts, add in sorted order
5553                if faucet_account < recipient_account {
5554                    tx = tx.add_rw_account(faucet_account);
5555                    tx = tx.add_rw_account(recipient_account);
5556                    (2u16, 3u16)
5557                } else {
5558                    tx = tx.add_rw_account(recipient_account);
5559                    tx = tx.add_rw_account(faucet_account);
5560                    (3u16, 2u16)
5561                }
5562            };
5563
5564        let instruction_data =
5565            build_faucet_withdraw_instruction(faucet_account_idx, recipient_account_idx, amount)?;
5566
5567        Ok(tx.with_instructions(instruction_data))
5568    }
5569
5570    /// Build consensus validator program ACTIVATE transaction.
5571    ///
5572    /// This creates a transaction that activates a validator in the consensus system.
5573    /// The validator must have tokens in their source_token_account which will be
5574    /// transferred to the converted_vault.
5575    ///
5576    /// # Arguments
5577    /// * `fee_payer` - The validator identity (also the signer)
5578    /// * `source_token_account` - The validator's token account with staking tokens
5579    /// * `bls_pk` - BLS public key for the validator as tn_bls_pubkey_t bytes
5580    /// * `claim_authority` - Pubkey that can claim rewards for this validator
5581    /// * `token_amount` - Amount of tokens to stake
5582    /// * `fee` - Transaction fee
5583    /// * `nonce` - Account nonce
5584    /// * `start_slot` - Starting slot for transaction validity
5585    pub fn build_activate(
5586        fee_payer: TnPubkey,
5587        source_token_account: TnPubkey,
5588        bls_pk: [u8; 96],
5589        claim_authority: TnPubkey,
5590        token_amount: u64,
5591        fee: u64,
5592        nonce: u64,
5593        start_slot: u64,
5594    ) -> Result<Transaction> {
5595        Self::build_activate_with_accounts(
5596            fee_payer,
5597            ConsensusValidatorAccounts::default(),
5598            source_token_account,
5599            bls_pk,
5600            claim_authority,
5601            token_amount,
5602            fee,
5603            nonce,
5604            start_slot,
5605        )
5606    }
5607
5608    /// Build consensus validator program ACTIVATE transaction using custom fixed
5609    /// account addresses.
5610    pub fn build_activate_with_accounts(
5611        fee_payer: TnPubkey,
5612        accounts: ConsensusValidatorAccounts,
5613        source_token_account: TnPubkey,
5614        bls_pk: [u8; 96],
5615        claim_authority: TnPubkey,
5616        token_amount: u64,
5617        fee: u64,
5618        nonce: u64,
5619        start_slot: u64,
5620    ) -> Result<Transaction> {
5621        let tx = build_consensus_validator_tx(fee_payer, accounts.program, fee, nonce, start_slot);
5622
5623        /* Add accounts - must be sorted by pubkey within RW and RO groups:
5624        RW: attestor_table, source_token_account, converted_vault
5625        RO: token_program
5626        identity/fee_payer is already index 0 */
5627        let accounts = [
5628            (accounts.attestor_table, true),  /* RW */
5629            (source_token_account, true),     /* RW */
5630            (accounts.converted_vault, true), /* RW */
5631            (accounts.token_program, false),  /* RO */
5632        ];
5633        let (tx, indices) = add_sorted_accounts(tx, &accounts);
5634        let attestor_table_idx = indices[0];
5635        let source_token_account_idx = indices[1];
5636        let converted_vault_idx = indices[2];
5637        let token_program_idx = indices[3];
5638
5639        /* fee_payer is always index 0 */
5640        let identity_idx = 0u16;
5641
5642        let instruction_data = build_activate_instruction(
5643            attestor_table_idx as u64,
5644            token_program_idx,
5645            source_token_account_idx,
5646            converted_vault_idx,
5647            identity_idx,
5648            bls_pk,
5649            claim_authority,
5650            token_amount,
5651        )?;
5652
5653        Ok(tx.with_instructions(instruction_data))
5654    }
5655
5656    /// Build consensus validator program DEACTIVATE transaction.
5657    pub fn build_deactivate(
5658        fee_payer: TnPubkey,
5659        dest_token_account: TnPubkey,
5660        fee: u64,
5661        nonce: u64,
5662        start_slot: u64,
5663    ) -> Result<Transaction> {
5664        Self::build_deactivate_with_accounts(
5665            fee_payer,
5666            ConsensusValidatorAccounts::default(),
5667            dest_token_account,
5668            fee,
5669            nonce,
5670            start_slot,
5671        )
5672    }
5673
5674    /// Build consensus validator program DEACTIVATE transaction using custom
5675    /// fixed account addresses.
5676    pub fn build_deactivate_with_accounts(
5677        fee_payer: TnPubkey,
5678        accounts: ConsensusValidatorAccounts,
5679        dest_token_account: TnPubkey,
5680        fee: u64,
5681        nonce: u64,
5682        start_slot: u64,
5683    ) -> Result<Transaction> {
5684        let tx = build_consensus_validator_tx(fee_payer, accounts.program, fee, nonce, start_slot);
5685
5686        let tx_accounts = [
5687            (accounts.attestor_table, true),
5688            (accounts.unclaimed_vault, true),
5689            (dest_token_account, true),
5690            (accounts.token_program, false),
5691        ];
5692        let (tx, indices) = add_sorted_accounts(tx, &tx_accounts);
5693        let attestor_table_idx = indices[0];
5694        let unclaimed_vault_idx = indices[1];
5695        let dest_token_account_idx = indices[2];
5696        let token_program_idx = indices[3];
5697
5698        let instruction_data = build_deactivate_instruction(
5699            attestor_table_idx as u64,
5700            token_program_idx,
5701            unclaimed_vault_idx,
5702            dest_token_account_idx,
5703            0u16,
5704        )?;
5705
5706        Ok(tx.with_instructions(instruction_data))
5707    }
5708
5709    /// Build consensus validator program CONVERT_TOKENS transaction.
5710    pub fn build_convert_tokens(
5711        fee_payer: TnPubkey,
5712        source_token_account: TnPubkey,
5713        token_amount: u64,
5714        fee: u64,
5715        nonce: u64,
5716        start_slot: u64,
5717    ) -> Result<Transaction> {
5718        Self::build_convert_tokens_with_accounts(
5719            fee_payer,
5720            ConsensusValidatorAccounts::default(),
5721            source_token_account,
5722            token_amount,
5723            fee,
5724            nonce,
5725            start_slot,
5726        )
5727    }
5728
5729    /// Build consensus validator program CONVERT_TOKENS transaction using
5730    /// custom fixed account addresses.
5731    pub fn build_convert_tokens_with_accounts(
5732        fee_payer: TnPubkey,
5733        accounts: ConsensusValidatorAccounts,
5734        source_token_account: TnPubkey,
5735        token_amount: u64,
5736        fee: u64,
5737        nonce: u64,
5738        start_slot: u64,
5739    ) -> Result<Transaction> {
5740        let tx = build_consensus_validator_tx(fee_payer, accounts.program, fee, nonce, start_slot);
5741
5742        let tx_accounts = [
5743            (accounts.attestor_table, true),
5744            (source_token_account, true),
5745            (accounts.converted_vault, true),
5746            (accounts.token_program, false),
5747        ];
5748        let (tx, indices) = add_sorted_accounts(tx, &tx_accounts);
5749        let attestor_table_idx = indices[0];
5750        let source_token_account_idx = indices[1];
5751        let converted_vault_idx = indices[2];
5752        let token_program_idx = indices[3];
5753
5754        let instruction_data = build_convert_tokens_instruction(
5755            attestor_table_idx as u64,
5756            token_program_idx,
5757            source_token_account_idx,
5758            converted_vault_idx,
5759            0u16,
5760            token_amount,
5761        )?;
5762
5763        Ok(tx.with_instructions(instruction_data))
5764    }
5765
5766    /// Build consensus validator program CLAIM transaction.
5767    pub fn build_claim(
5768        fee_payer: TnPubkey,
5769        subject_attestor: TnPubkey,
5770        dest_token_account: TnPubkey,
5771        fee: u64,
5772        nonce: u64,
5773        start_slot: u64,
5774    ) -> Result<Transaction> {
5775        Self::build_claim_with_accounts(
5776            fee_payer,
5777            ConsensusValidatorAccounts::default(),
5778            subject_attestor,
5779            dest_token_account,
5780            fee,
5781            nonce,
5782            start_slot,
5783        )
5784    }
5785
5786    /// Build consensus validator program CLAIM transaction using custom fixed
5787    /// account addresses.
5788    pub fn build_claim_with_accounts(
5789        fee_payer: TnPubkey,
5790        accounts: ConsensusValidatorAccounts,
5791        subject_attestor: TnPubkey,
5792        dest_token_account: TnPubkey,
5793        fee: u64,
5794        nonce: u64,
5795        start_slot: u64,
5796    ) -> Result<Transaction> {
5797        let tx = build_consensus_validator_tx(fee_payer, accounts.program, fee, nonce, start_slot);
5798
5799        let tx_accounts = [
5800            (accounts.attestor_table, true),
5801            (accounts.unclaimed_vault, true),
5802            (dest_token_account, true),
5803            (accounts.token_program, false),
5804        ];
5805        let (tx, indices) = add_sorted_accounts(tx, &tx_accounts);
5806        let attestor_table_idx = indices[0];
5807        let unclaimed_vault_idx = indices[1];
5808        let dest_token_account_idx = indices[2];
5809        let token_program_idx = indices[3];
5810
5811        let instruction_data = build_claim_instruction(
5812            attestor_table_idx as u64,
5813            token_program_idx,
5814            unclaimed_vault_idx,
5815            dest_token_account_idx,
5816            0u16,
5817            subject_attestor,
5818        )?;
5819
5820        Ok(tx.with_instructions(instruction_data))
5821    }
5822
5823    /// Build consensus validator program SET_CLAIM_AUTH transaction.
5824    pub fn build_set_claim_authority(
5825        fee_payer: TnPubkey,
5826        subject_attestor: TnPubkey,
5827        new_claim_authority: TnPubkey,
5828        fee: u64,
5829        nonce: u64,
5830        start_slot: u64,
5831    ) -> Result<Transaction> {
5832        Self::build_set_claim_authority_with_accounts(
5833            fee_payer,
5834            ConsensusValidatorAccounts::default(),
5835            subject_attestor,
5836            new_claim_authority,
5837            fee,
5838            nonce,
5839            start_slot,
5840        )
5841    }
5842
5843    /// Build consensus validator program SET_CLAIM_AUTH transaction using
5844    /// custom fixed account addresses.
5845    pub fn build_set_claim_authority_with_accounts(
5846        fee_payer: TnPubkey,
5847        accounts: ConsensusValidatorAccounts,
5848        subject_attestor: TnPubkey,
5849        new_claim_authority: TnPubkey,
5850        fee: u64,
5851        nonce: u64,
5852        start_slot: u64,
5853    ) -> Result<Transaction> {
5854        let tx = build_consensus_validator_tx(fee_payer, accounts.program, fee, nonce, start_slot);
5855
5856        let tx_accounts = [(accounts.attestor_table, true)];
5857        let (tx, indices) = add_sorted_accounts(tx, &tx_accounts);
5858        let attestor_table_idx = indices[0];
5859
5860        let instruction_data = build_set_claim_authority_instruction(
5861            attestor_table_idx as u64,
5862            0u16,
5863            subject_attestor,
5864            new_claim_authority,
5865        )?;
5866
5867        Ok(tx.with_instructions(instruction_data))
5868    }
5869
5870    /// Build name service InitializeRoot transaction
5871    pub fn build_name_service_initialize_root(
5872        fee_payer: TnPubkey,
5873        name_service_program: TnPubkey,
5874        registrar_account: TnPubkey,
5875        authority_account: TnPubkey,
5876        root_name: &str,
5877        state_proof: Vec<u8>,
5878        fee: u64,
5879        nonce: u64,
5880        start_slot: u64,
5881    ) -> Result<Transaction> {
5882        let mut tx = Transaction::new(fee_payer, name_service_program, fee, nonce)
5883            .with_start_slot(start_slot)
5884            .with_expiry_after(100)
5885            .with_compute_units(500_000)
5886            .with_state_units(1)
5887            .with_memory_units(10_000);
5888
5889        let accounts = [(registrar_account, true), (authority_account, false)];
5890        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
5891        tx = tx_with_accounts;
5892
5893        let registrar_account_idx = indices[0];
5894        let authority_account_idx = indices[1];
5895
5896        let instruction_data = build_name_service_initialize_root_instruction(
5897            registrar_account_idx,
5898            authority_account_idx,
5899            root_name,
5900            state_proof,
5901        )?;
5902
5903        Ok(tx.with_instructions(instruction_data))
5904    }
5905
5906    /// Build name service RegisterSubdomain transaction
5907    pub fn build_name_service_register_subdomain(
5908        fee_payer: TnPubkey,
5909        name_service_program: TnPubkey,
5910        domain_account: TnPubkey,
5911        parent_account: TnPubkey,
5912        owner_account: TnPubkey,
5913        authority_account: TnPubkey,
5914        domain_name: &str,
5915        state_proof: Vec<u8>,
5916        fee: u64,
5917        nonce: u64,
5918        start_slot: u64,
5919    ) -> Result<Transaction> {
5920        let mut tx = Transaction::new(fee_payer, name_service_program, fee, nonce)
5921            .with_start_slot(start_slot)
5922            .with_expiry_after(100)
5923            .with_compute_units(500_000)
5924            .with_state_units(1)
5925            .with_memory_units(10_000);
5926
5927        let accounts = [
5928            (domain_account, true),
5929            (parent_account, true),
5930            (owner_account, false),
5931            (authority_account, false),
5932        ];
5933        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
5934        tx = tx_with_accounts;
5935
5936        let domain_account_idx = indices[0];
5937        let parent_account_idx = indices[1];
5938        let owner_account_idx = indices[2];
5939        let authority_account_idx = indices[3];
5940
5941        let instruction_data = build_name_service_register_subdomain_instruction(
5942            domain_account_idx,
5943            parent_account_idx,
5944            owner_account_idx,
5945            authority_account_idx,
5946            domain_name,
5947            state_proof,
5948        )?;
5949
5950        Ok(tx.with_instructions(instruction_data))
5951    }
5952
5953    /// Build name service AppendRecord transaction
5954    pub fn build_name_service_append_record(
5955        fee_payer: TnPubkey,
5956        name_service_program: TnPubkey,
5957        domain_account: TnPubkey,
5958        owner_account: TnPubkey,
5959        key: &[u8],
5960        value: &[u8],
5961        fee: u64,
5962        nonce: u64,
5963        start_slot: u64,
5964    ) -> Result<Transaction> {
5965        let mut tx = Transaction::new(fee_payer, name_service_program, fee, nonce)
5966            .with_start_slot(start_slot)
5967            .with_expiry_after(100)
5968            .with_compute_units(250_000)
5969            .with_state_units(1)
5970            .with_memory_units(10_000);
5971
5972        let accounts = [(domain_account, true), (owner_account, false)];
5973        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
5974        tx = tx_with_accounts;
5975
5976        let domain_account_idx = indices[0];
5977        let owner_account_idx = indices[1];
5978
5979        let instruction_data = build_name_service_append_record_instruction(
5980            domain_account_idx,
5981            owner_account_idx,
5982            key,
5983            value,
5984        )?;
5985
5986        Ok(tx.with_instructions(instruction_data))
5987    }
5988
5989    /// Build name service DeleteRecord transaction
5990    pub fn build_name_service_delete_record(
5991        fee_payer: TnPubkey,
5992        name_service_program: TnPubkey,
5993        domain_account: TnPubkey,
5994        owner_account: TnPubkey,
5995        key: &[u8],
5996        fee: u64,
5997        nonce: u64,
5998        start_slot: u64,
5999    ) -> Result<Transaction> {
6000        let mut tx = Transaction::new(fee_payer, name_service_program, fee, nonce)
6001            .with_start_slot(start_slot)
6002            .with_expiry_after(100)
6003            .with_compute_units(200_000)
6004            .with_state_units(0)
6005            .with_memory_units(10_000);
6006
6007        let accounts = [(domain_account, true), (owner_account, false)];
6008        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
6009        tx = tx_with_accounts;
6010
6011        let domain_account_idx = indices[0];
6012        let owner_account_idx = indices[1];
6013
6014        let instruction_data = build_name_service_delete_record_instruction(
6015            domain_account_idx,
6016            owner_account_idx,
6017            key,
6018        )?;
6019
6020        Ok(tx.with_instructions(instruction_data))
6021    }
6022
6023    /// Build name service UnregisterSubdomain transaction
6024    pub fn build_name_service_unregister_subdomain(
6025        fee_payer: TnPubkey,
6026        name_service_program: TnPubkey,
6027        domain_account: TnPubkey,
6028        owner_account: TnPubkey,
6029        fee: u64,
6030        nonce: u64,
6031        start_slot: u64,
6032    ) -> Result<Transaction> {
6033        let mut tx = Transaction::new(fee_payer, name_service_program, fee, nonce)
6034            .with_start_slot(start_slot)
6035            .with_expiry_after(100)
6036            .with_compute_units(200_000)
6037            .with_state_units(0)
6038            .with_memory_units(10_000);
6039
6040        let accounts = [(domain_account, true), (owner_account, false)];
6041        let (tx_with_accounts, indices) = add_sorted_accounts(tx, &accounts);
6042        tx = tx_with_accounts;
6043
6044        let domain_account_idx = indices[0];
6045        let owner_account_idx = indices[1];
6046
6047        let instruction_data = build_name_service_unregister_subdomain_instruction(
6048            domain_account_idx,
6049            owner_account_idx,
6050        )?;
6051
6052        Ok(tx.with_instructions(instruction_data))
6053    }
6054
6055    /// Build thru registrar InitializeRegistry transaction
6056    pub fn build_thru_registrar_initialize_registry(
6057        fee_payer: TnPubkey,
6058        thru_registrar_program: TnPubkey,
6059        config_account: TnPubkey,
6060        name_service_program: TnPubkey,
6061        root_registrar_account: TnPubkey,
6062        treasurer_account: TnPubkey,
6063        token_mint_account: TnPubkey,
6064        token_program: TnPubkey,
6065        root_domain_name: &str,
6066        price_per_year: u64,
6067        config_proof: Vec<u8>,
6068        registrar_proof: Vec<u8>,
6069        fee: u64,
6070        nonce: u64,
6071        start_slot: u64,
6072    ) -> Result<Transaction> {
6073        let mut tx = Transaction::new(fee_payer, thru_registrar_program, fee, nonce)
6074            .with_start_slot(start_slot)
6075            .with_expiry_after(100)
6076            .with_compute_units(500_000)
6077            .with_state_units(2) // New configuration and root.
6078            .with_memory_units(10_000);
6079
6080        // Add accounts in sorted order (read-write first, then read-only)
6081        // Registrar must be writable because the base name service CPI creates/resizes it.
6082        let mut rw_accounts = vec![config_account, root_registrar_account];
6083        rw_accounts.sort();
6084
6085        let mut ro_accounts = vec![
6086            name_service_program,
6087            treasurer_account,
6088            token_mint_account,
6089            token_program,
6090        ];
6091        ro_accounts.sort();
6092
6093        // Add RW accounts
6094        let mut config_account_idx = 0u16;
6095        let mut root_registrar_account_idx = 0u16;
6096        for (i, account) in rw_accounts.iter().enumerate() {
6097            let idx = (2 + i) as u16;
6098            if *account == config_account {
6099                config_account_idx = idx;
6100            } else if *account == root_registrar_account {
6101                root_registrar_account_idx = idx;
6102            }
6103            tx = tx.add_rw_account(*account);
6104        }
6105
6106        // Add RO accounts
6107        let base_ro_idx = 2 + rw_accounts.len() as u16;
6108        let mut name_service_program_idx = 0u16;
6109        let mut treasurer_account_idx = 0u16;
6110        let mut token_mint_account_idx = 0u16;
6111        let mut token_program_idx = 0u16;
6112
6113        for (i, account) in ro_accounts.iter().enumerate() {
6114            let idx = base_ro_idx + i as u16;
6115            if *account == name_service_program {
6116                name_service_program_idx = idx;
6117            } else if *account == root_registrar_account {
6118                root_registrar_account_idx = idx;
6119            } else if *account == treasurer_account {
6120                treasurer_account_idx = idx;
6121            } else if *account == token_mint_account {
6122                token_mint_account_idx = idx;
6123            } else if *account == token_program {
6124                token_program_idx = idx;
6125            }
6126            tx = tx.add_r_account(*account);
6127        }
6128
6129        let instruction_data = build_thru_registrar_initialize_registry_instruction(
6130            config_account_idx,
6131            name_service_program_idx,
6132            root_registrar_account_idx,
6133            treasurer_account_idx,
6134            token_mint_account_idx,
6135            token_program_idx,
6136            root_domain_name,
6137            price_per_year,
6138            config_proof,
6139            registrar_proof,
6140        )?;
6141
6142        Ok(tx.with_instructions(instruction_data))
6143    }
6144
6145    /// Build thru registrar PurchaseDomain transaction
6146    pub fn build_thru_registrar_purchase_domain(
6147        fee_payer: TnPubkey,
6148        thru_registrar_program: TnPubkey,
6149        config_account: TnPubkey,
6150        lease_account: TnPubkey,
6151        domain_account: TnPubkey,
6152        name_service_program: TnPubkey,
6153        root_registrar_account: TnPubkey,
6154        treasurer_account: TnPubkey,
6155        payer_token_account: TnPubkey,
6156        token_mint_account: TnPubkey,
6157        token_program: TnPubkey,
6158        domain_name: &str,
6159        years: u8,
6160        lease_proof: Vec<u8>,
6161        domain_proof: Vec<u8>,
6162        fee: u64,
6163        nonce: u64,
6164        start_slot: u64,
6165    ) -> Result<Transaction> {
6166        let mut tx = Transaction::new(fee_payer, thru_registrar_program, fee, nonce)
6167            .with_start_slot(start_slot)
6168            .with_expiry_after(100)
6169            .with_compute_units(500_000)
6170            .with_state_units(2) // New lease and domain.
6171            .with_memory_units(10_000);
6172
6173        // Add accounts in sorted order
6174        // Token accounts must be writable for transfer; lease/domain are created; root registrar and config are updated via CPI.
6175        let mut rw_accounts = vec![
6176            config_account,
6177            lease_account,
6178            domain_account,
6179            treasurer_account,
6180            payer_token_account,
6181            root_registrar_account,
6182        ];
6183        rw_accounts.sort();
6184
6185        let mut ro_accounts = vec![name_service_program, token_mint_account, token_program];
6186        ro_accounts.sort();
6187
6188        // Add RW accounts
6189        let mut config_account_idx = 0u16;
6190        let mut lease_account_idx = 0u16;
6191        let mut domain_account_idx = 0u16;
6192        let mut treasurer_account_idx = 0u16;
6193        let mut payer_token_account_idx = 0u16;
6194        let mut root_registrar_account_idx = 0u16;
6195        for (i, account) in rw_accounts.iter().enumerate() {
6196            let idx = (2 + i) as u16;
6197            if *account == config_account {
6198                config_account_idx = idx;
6199            } else if *account == lease_account {
6200                lease_account_idx = idx;
6201            } else if *account == domain_account {
6202                domain_account_idx = idx;
6203            } else if *account == treasurer_account {
6204                treasurer_account_idx = idx;
6205            } else if *account == payer_token_account {
6206                payer_token_account_idx = idx;
6207            } else if *account == root_registrar_account {
6208                root_registrar_account_idx = idx;
6209            }
6210            tx = tx.add_rw_account(*account);
6211        }
6212
6213        // Add RO accounts
6214        let base_ro_idx = 2 + rw_accounts.len() as u16;
6215        let mut name_service_program_idx = 0u16;
6216        let mut token_mint_account_idx = 0u16;
6217        let mut token_program_idx = 0u16;
6218
6219        for (i, account) in ro_accounts.iter().enumerate() {
6220            let idx = base_ro_idx + i as u16;
6221            if *account == config_account {
6222                config_account_idx = idx; // Should remain zero; config moved to RW set
6223            } else if *account == name_service_program {
6224                name_service_program_idx = idx;
6225            } else if *account == root_registrar_account {
6226                root_registrar_account_idx = idx;
6227            } else if *account == treasurer_account {
6228                treasurer_account_idx = idx;
6229            } else if *account == payer_token_account {
6230                payer_token_account_idx = idx;
6231            } else if *account == token_mint_account {
6232                token_mint_account_idx = idx;
6233            } else if *account == token_program {
6234                token_program_idx = idx;
6235            }
6236            tx = tx.add_r_account(*account);
6237        }
6238
6239        let instruction_data = build_thru_registrar_purchase_domain_instruction(
6240            config_account_idx,
6241            lease_account_idx,
6242            domain_account_idx,
6243            name_service_program_idx,
6244            root_registrar_account_idx,
6245            treasurer_account_idx,
6246            payer_token_account_idx,
6247            token_mint_account_idx,
6248            token_program_idx,
6249            domain_name,
6250            years,
6251            lease_proof,
6252            domain_proof,
6253        )?;
6254
6255        Ok(tx.with_instructions(instruction_data))
6256    }
6257
6258    /// Build thru registrar RenewLease transaction
6259    pub fn build_thru_registrar_renew_lease(
6260        fee_payer: TnPubkey,
6261        thru_registrar_program: TnPubkey,
6262        config_account: TnPubkey,
6263        lease_account: TnPubkey,
6264        treasurer_account: TnPubkey,
6265        payer_token_account: TnPubkey,
6266        token_mint_account: TnPubkey,
6267        token_program: TnPubkey,
6268        years: u8,
6269        fee: u64,
6270        nonce: u64,
6271        start_slot: u64,
6272    ) -> Result<Transaction> {
6273        let mut tx = Transaction::new(fee_payer, thru_registrar_program, fee, nonce)
6274            .with_start_slot(start_slot)
6275            .with_expiry_after(100)
6276            .with_compute_units(300_000)
6277            .with_state_units(0)
6278            .with_memory_units(10_000);
6279
6280        // Add accounts in sorted order
6281        // Token accounts must be writable for transfer.
6282        let mut rw_accounts = vec![lease_account, treasurer_account, payer_token_account];
6283        rw_accounts.sort();
6284
6285        let mut ro_accounts = vec![config_account, token_mint_account, token_program];
6286        ro_accounts.sort();
6287
6288        // Add RW accounts
6289        let mut lease_account_idx = 0u16;
6290        let mut treasurer_account_idx = 0u16;
6291        let mut payer_token_account_idx = 0u16;
6292        for (i, account) in rw_accounts.iter().enumerate() {
6293            let idx = (2 + i) as u16;
6294            if *account == lease_account {
6295                lease_account_idx = idx;
6296            } else if *account == treasurer_account {
6297                treasurer_account_idx = idx;
6298            } else if *account == payer_token_account {
6299                payer_token_account_idx = idx;
6300            }
6301            tx = tx.add_rw_account(*account);
6302        }
6303
6304        // Add RO accounts
6305        let base_ro_idx = 2 + rw_accounts.len() as u16;
6306        let mut config_account_idx = 0u16;
6307        let mut token_mint_account_idx = 0u16;
6308        let mut token_program_idx = 0u16;
6309
6310        for (i, account) in ro_accounts.iter().enumerate() {
6311            let idx = base_ro_idx + i as u16;
6312            if *account == config_account {
6313                config_account_idx = idx;
6314            } else if *account == token_mint_account {
6315                token_mint_account_idx = idx;
6316            } else if *account == token_program {
6317                token_program_idx = idx;
6318            }
6319            tx = tx.add_r_account(*account);
6320        }
6321
6322        let instruction_data = build_thru_registrar_renew_lease_instruction(
6323            config_account_idx,
6324            lease_account_idx,
6325            treasurer_account_idx,
6326            payer_token_account_idx,
6327            token_mint_account_idx,
6328            token_program_idx,
6329            years,
6330        )?;
6331
6332        Ok(tx.with_instructions(instruction_data))
6333    }
6334
6335    /// Build thru registrar ClaimExpiredDomain transaction
6336    pub fn build_thru_registrar_claim_expired_domain(
6337        fee_payer: TnPubkey,
6338        thru_registrar_program: TnPubkey,
6339        config_account: TnPubkey,
6340        lease_account: TnPubkey,
6341        treasurer_account: TnPubkey,
6342        payer_token_account: TnPubkey,
6343        token_mint_account: TnPubkey,
6344        token_program: TnPubkey,
6345        years: u8,
6346        fee: u64,
6347        nonce: u64,
6348        start_slot: u64,
6349    ) -> Result<Transaction> {
6350        let mut tx = Transaction::new(fee_payer, thru_registrar_program, fee, nonce)
6351            .with_start_slot(start_slot)
6352            .with_expiry_after(100)
6353            .with_compute_units(300_000)
6354            .with_state_units(0)
6355            .with_memory_units(10_000);
6356
6357        // Add accounts in sorted order
6358        // Token accounts must be writable for transfer.
6359        let mut rw_accounts = vec![lease_account, treasurer_account, payer_token_account];
6360        rw_accounts.sort();
6361
6362        let mut ro_accounts = vec![config_account, token_mint_account, token_program];
6363        ro_accounts.sort();
6364
6365        // Add RW accounts
6366        let mut lease_account_idx = 0u16;
6367        let mut treasurer_account_idx = 0u16;
6368        let mut payer_token_account_idx = 0u16;
6369        for (i, account) in rw_accounts.iter().enumerate() {
6370            let idx = (2 + i) as u16;
6371            if *account == lease_account {
6372                lease_account_idx = idx;
6373            } else if *account == treasurer_account {
6374                treasurer_account_idx = idx;
6375            } else if *account == payer_token_account {
6376                payer_token_account_idx = idx;
6377            }
6378            tx = tx.add_rw_account(*account);
6379        }
6380
6381        // Add RO accounts
6382        let base_ro_idx = 2 + rw_accounts.len() as u16;
6383        let mut config_account_idx = 0u16;
6384        let mut token_mint_account_idx = 0u16;
6385        let mut token_program_idx = 0u16;
6386
6387        for (i, account) in ro_accounts.iter().enumerate() {
6388            let idx = base_ro_idx + i as u16;
6389            if *account == config_account {
6390                config_account_idx = idx;
6391            } else if *account == token_mint_account {
6392                token_mint_account_idx = idx;
6393            } else if *account == token_program {
6394                token_program_idx = idx;
6395            }
6396            tx = tx.add_r_account(*account);
6397        }
6398
6399        let instruction_data = build_thru_registrar_claim_expired_domain_instruction(
6400            config_account_idx,
6401            lease_account_idx,
6402            treasurer_account_idx,
6403            payer_token_account_idx,
6404            token_mint_account_idx,
6405            token_program_idx,
6406            years,
6407        )?;
6408
6409        Ok(tx.with_instructions(instruction_data))
6410    }
6411}
6412
6413/// Build token InitializeMint instruction data
6414fn build_token_initialize_mint_instruction(
6415    mint_account_idx: u16,
6416    decimals: u8,
6417    creator: TnPubkey,
6418    mint_authority: TnPubkey,
6419    freeze_authority: Option<TnPubkey>,
6420    ticker: &str,
6421    seed: [u8; 32],
6422    state_proof: Vec<u8>,
6423) -> Result<Vec<u8>> {
6424    let mut instruction_data = Vec::new();
6425
6426    // Instruction tag
6427    instruction_data.push(TOKEN_INSTRUCTION_INITIALIZE_MINT);
6428
6429    // mint_account_index (u16)
6430    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
6431
6432    // decimals (u8)
6433    instruction_data.push(decimals);
6434
6435    // creator (32 bytes)
6436    instruction_data.extend_from_slice(&creator);
6437
6438    // mint_authority (32 bytes)
6439    instruction_data.extend_from_slice(&mint_authority);
6440
6441    // freeze_authority (32 bytes) and has_freeze_authority flag
6442    let (freeze_auth, has_freeze_auth) = match freeze_authority {
6443        Some(auth) => (auth, 1u8),
6444        None => ([0u8; 32], 0u8),
6445    };
6446    instruction_data.extend_from_slice(&freeze_auth);
6447    instruction_data.push(has_freeze_auth);
6448
6449    // ticker_len and ticker_bytes (max 8 bytes)
6450    let ticker_bytes = ticker.as_bytes();
6451    if ticker_bytes.len() > 8 {
6452        return Err(anyhow::anyhow!("Ticker must be 8 characters or less"));
6453    }
6454
6455    instruction_data.push(ticker_bytes.len() as u8);
6456    let mut ticker_padded = [0u8; 8];
6457    ticker_padded[..ticker_bytes.len()].copy_from_slice(ticker_bytes);
6458    instruction_data.extend_from_slice(&ticker_padded);
6459
6460    // seed (32 bytes)
6461    instruction_data.extend_from_slice(&seed);
6462
6463    // state proof (variable length)
6464    instruction_data.extend_from_slice(&state_proof);
6465
6466    Ok(instruction_data)
6467}
6468
6469/// Build token InitializeAccount instruction data
6470fn build_token_initialize_account_instruction(
6471    token_account_idx: u16,
6472    mint_account_idx: u16,
6473    owner_account_idx: u16,
6474    seed: [u8; 32],
6475    state_proof: Vec<u8>,
6476) -> Result<Vec<u8>> {
6477    let mut instruction_data = Vec::new();
6478
6479    // Instruction tag
6480    instruction_data.push(TOKEN_INSTRUCTION_INITIALIZE_ACCOUNT);
6481
6482    // token_account_index (u16)
6483    instruction_data.extend_from_slice(&token_account_idx.to_le_bytes());
6484
6485    // mint_account_index (u16)
6486    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
6487
6488    // owner_account_index (u16)
6489    instruction_data.extend_from_slice(&owner_account_idx.to_le_bytes());
6490
6491    // seed (32 bytes)
6492    instruction_data.extend_from_slice(&seed);
6493
6494    // state proof (variable length)
6495    instruction_data.extend_from_slice(&state_proof);
6496
6497    Ok(instruction_data)
6498}
6499
6500/// Build token Transfer instruction data
6501fn build_token_transfer_instruction(
6502    source_account_idx: u16,
6503    dest_account_idx: u16,
6504    amount: u64,
6505) -> Result<Vec<u8>> {
6506    let mut instruction_data = Vec::new();
6507
6508    // Instruction tag
6509    instruction_data.push(TOKEN_INSTRUCTION_TRANSFER);
6510
6511    // source_account_index (u16)
6512    instruction_data.extend_from_slice(&source_account_idx.to_le_bytes());
6513
6514    // dest_account_index (u16)
6515    instruction_data.extend_from_slice(&dest_account_idx.to_le_bytes());
6516
6517    // amount (u64)
6518    instruction_data.extend_from_slice(&amount.to_le_bytes());
6519
6520    Ok(instruction_data)
6521}
6522
6523/// Build token MintTo instruction data
6524fn build_token_mint_to_instruction(
6525    mint_account_idx: u16,
6526    dest_account_idx: u16,
6527    authority_idx: u16,
6528    amount: u64,
6529) -> Result<Vec<u8>> {
6530    let mut instruction_data = Vec::new();
6531
6532    // Instruction tag
6533    instruction_data.push(TOKEN_INSTRUCTION_MINT_TO);
6534
6535    // mint_account_index (u16)
6536    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
6537
6538    // dest_account_index (u16)
6539    instruction_data.extend_from_slice(&dest_account_idx.to_le_bytes());
6540
6541    // authority_index (u16)
6542    instruction_data.extend_from_slice(&authority_idx.to_le_bytes());
6543
6544    // amount (u64)
6545    instruction_data.extend_from_slice(&amount.to_le_bytes());
6546
6547    Ok(instruction_data)
6548}
6549
6550/// Build token Burn instruction data
6551fn build_token_burn_instruction(
6552    token_account_idx: u16,
6553    mint_account_idx: u16,
6554    authority_idx: u16,
6555    amount: u64,
6556) -> Result<Vec<u8>> {
6557    let mut instruction_data = Vec::new();
6558
6559    // Instruction tag
6560    instruction_data.push(TOKEN_INSTRUCTION_BURN);
6561
6562    // token_account_index (u16)
6563    instruction_data.extend_from_slice(&token_account_idx.to_le_bytes());
6564
6565    // mint_account_index (u16)
6566    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
6567
6568    // authority_index (u16)
6569    instruction_data.extend_from_slice(&authority_idx.to_le_bytes());
6570
6571    // amount (u64)
6572    instruction_data.extend_from_slice(&amount.to_le_bytes());
6573
6574    Ok(instruction_data)
6575}
6576
6577/// Build token FreezeAccount instruction data
6578fn build_token_freeze_account_instruction(
6579    token_account_idx: u16,
6580    mint_account_idx: u16,
6581    authority_idx: u16,
6582) -> Result<Vec<u8>> {
6583    let mut instruction_data = Vec::new();
6584
6585    // Instruction tag
6586    instruction_data.push(TOKEN_INSTRUCTION_FREEZE_ACCOUNT);
6587
6588    // token_account_index (u16)
6589    instruction_data.extend_from_slice(&token_account_idx.to_le_bytes());
6590
6591    // mint_account_index (u16)
6592    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
6593
6594    // authority_index (u16)
6595    instruction_data.extend_from_slice(&authority_idx.to_le_bytes());
6596
6597    Ok(instruction_data)
6598}
6599
6600/// Build token ThawAccount instruction data
6601fn build_token_thaw_account_instruction(
6602    token_account_idx: u16,
6603    mint_account_idx: u16,
6604    authority_idx: u16,
6605) -> Result<Vec<u8>> {
6606    let mut instruction_data = Vec::new();
6607
6608    // Instruction tag
6609    instruction_data.push(TOKEN_INSTRUCTION_THAW_ACCOUNT);
6610
6611    // token_account_index (u16)
6612    instruction_data.extend_from_slice(&token_account_idx.to_le_bytes());
6613
6614    // mint_account_index (u16)
6615    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
6616
6617    // authority_index (u16)
6618    instruction_data.extend_from_slice(&authority_idx.to_le_bytes());
6619
6620    Ok(instruction_data)
6621}
6622
6623/// Build token CloseAccount instruction data
6624fn build_token_close_account_instruction(
6625    token_account_idx: u16,
6626    destination_idx: u16,
6627    authority_idx: u16,
6628) -> Result<Vec<u8>> {
6629    let mut instruction_data = Vec::new();
6630
6631    // Instruction tag
6632    instruction_data.push(TOKEN_INSTRUCTION_CLOSE_ACCOUNT);
6633
6634    // token_account_index (u16)
6635    instruction_data.extend_from_slice(&token_account_idx.to_le_bytes());
6636
6637    // destination_index (u16)
6638    instruction_data.extend_from_slice(&destination_idx.to_le_bytes());
6639
6640    // authority_index (u16)
6641    instruction_data.extend_from_slice(&authority_idx.to_le_bytes());
6642
6643    Ok(instruction_data)
6644}
6645
6646fn build_wthru_initialize_mint_instruction(
6647    token_program_idx: u16,
6648    mint_account_idx: u16,
6649    vault_account_idx: u16,
6650    decimals: u8,
6651    mint_seed: [u8; 32],
6652    mint_proof: Vec<u8>,
6653    vault_proof: Vec<u8>,
6654) -> Result<Vec<u8>> {
6655    let mint_proof_len =
6656        u64::try_from(mint_proof.len()).map_err(|_| anyhow::anyhow!("mint proof too large"))?;
6657    let vault_proof_len =
6658        u64::try_from(vault_proof.len()).map_err(|_| anyhow::anyhow!("vault proof too large"))?;
6659
6660    let mut instruction_data = Vec::new();
6661    instruction_data.extend_from_slice(&TN_WTHRU_INSTRUCTION_INITIALIZE_MINT.to_le_bytes());
6662    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
6663    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
6664    instruction_data.extend_from_slice(&vault_account_idx.to_le_bytes());
6665    instruction_data.push(decimals);
6666    instruction_data.extend_from_slice(&mint_seed);
6667    instruction_data.extend_from_slice(&mint_proof_len.to_le_bytes());
6668    instruction_data.extend_from_slice(&vault_proof_len.to_le_bytes());
6669    instruction_data.extend_from_slice(&mint_proof);
6670    instruction_data.extend_from_slice(&vault_proof);
6671
6672    Ok(instruction_data)
6673}
6674
6675fn build_wthru_deposit_instruction(
6676    token_program_idx: u16,
6677    vault_account_idx: u16,
6678    mint_account_idx: u16,
6679    dest_account_idx: u16,
6680) -> Result<Vec<u8>> {
6681    let mut instruction_data = Vec::new();
6682    instruction_data.extend_from_slice(&TN_WTHRU_INSTRUCTION_DEPOSIT.to_le_bytes());
6683    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
6684    instruction_data.extend_from_slice(&vault_account_idx.to_le_bytes());
6685    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
6686    instruction_data.extend_from_slice(&dest_account_idx.to_le_bytes());
6687
6688    Ok(instruction_data)
6689}
6690
6691fn build_wthru_withdraw_instruction(
6692    token_program_idx: u16,
6693    vault_account_idx: u16,
6694    mint_account_idx: u16,
6695    wthru_token_account_idx: u16,
6696    owner_account_idx: u16,
6697    recipient_account_idx: u16,
6698    amount: u64,
6699) -> Result<Vec<u8>> {
6700    let mut instruction_data = Vec::new();
6701    instruction_data.extend_from_slice(&TN_WTHRU_INSTRUCTION_WITHDRAW.to_le_bytes());
6702    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
6703    instruction_data.extend_from_slice(&vault_account_idx.to_le_bytes());
6704    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
6705    instruction_data.extend_from_slice(&wthru_token_account_idx.to_le_bytes());
6706    instruction_data.extend_from_slice(&owner_account_idx.to_le_bytes());
6707    instruction_data.extend_from_slice(&recipient_account_idx.to_le_bytes());
6708    instruction_data.extend_from_slice(&amount.to_le_bytes());
6709
6710    Ok(instruction_data)
6711}
6712
6713/// Build BP CreateAccount (disc 0) instruction data.
6714///
6715/// Wire layout = u32 discriminant || tn_bp_create_account_args (packed, 164 B)
6716/// || bond_proof || ta_proof || eoa_proof.  The args struct field order mirrors
6717/// tn_block_producer_program.h:146-161 exactly.
6718#[allow(clippy::too_many_arguments)]
6719fn build_bp_create_account_instruction(
6720    token_program_idx: u16,
6721    bond_account_idx: u16,
6722    bond_ta_idx: u16,
6723    mint_account_idx: u16,
6724    signer_eoa_idx: u16,
6725    create_signer_eoa: bool,
6726    signer_pubkey: &[u8; 32],
6727    bond_authority: &[u8; 32],
6728    signer_eoa_signature: &[u8; 64],
6729    bond_proof: &[u8],
6730    ta_proof: &[u8],
6731    eoa_proof: &[u8],
6732) -> Result<Vec<u8>> {
6733    let bond_proof_size =
6734        u64::try_from(bond_proof.len()).map_err(|_| anyhow::anyhow!("bond proof too large"))?;
6735    let ta_proof_size =
6736        u64::try_from(ta_proof.len()).map_err(|_| anyhow::anyhow!("ta proof too large"))?;
6737    let eoa_proof_size =
6738        u64::try_from(eoa_proof.len()).map_err(|_| anyhow::anyhow!("eoa proof too large"))?;
6739
6740    let mut instruction_data = Vec::new();
6741    instruction_data.extend_from_slice(&TN_BP_INSTRUCTION_CREATE_ACCOUNT.to_le_bytes());
6742    /* tn_bp_create_account_args (packed) */
6743    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
6744    instruction_data.extend_from_slice(&bond_account_idx.to_le_bytes());
6745    instruction_data.extend_from_slice(&bond_ta_idx.to_le_bytes());
6746    instruction_data.extend_from_slice(&mint_account_idx.to_le_bytes());
6747    instruction_data.extend_from_slice(&signer_eoa_idx.to_le_bytes());
6748    instruction_data.push(if create_signer_eoa { 1u8 } else { 0u8 }); // create_signer_eoa
6749    instruction_data.push(0u8); // reserved (must be 0)
6750    instruction_data.extend_from_slice(signer_pubkey);
6751    instruction_data.extend_from_slice(bond_authority);
6752    instruction_data.extend_from_slice(signer_eoa_signature);
6753    instruction_data.extend_from_slice(&bond_proof_size.to_le_bytes());
6754    instruction_data.extend_from_slice(&ta_proof_size.to_le_bytes());
6755    instruction_data.extend_from_slice(&eoa_proof_size.to_le_bytes());
6756    /* trailing proofs */
6757    instruction_data.extend_from_slice(bond_proof);
6758    instruction_data.extend_from_slice(ta_proof);
6759    instruction_data.extend_from_slice(eoa_proof);
6760
6761    Ok(instruction_data)
6762}
6763
6764/// Build faucet Deposit instruction data
6765fn build_faucet_deposit_instruction(
6766    faucet_account_idx: u16,
6767    depositor_account_idx: u16,
6768    eoa_program_idx: u16,
6769    amount: u64,
6770) -> Result<Vec<u8>> {
6771    let mut instruction_data = Vec::new();
6772
6773    // Discriminant: TN_FAUCET_INSTRUCTION_DEPOSIT = 0 (u32, 4 bytes little-endian)
6774    instruction_data.extend_from_slice(&0u32.to_le_bytes());
6775
6776    // tn_faucet_deposit_args_t structure:
6777    // - faucet_account_idx (u16, 2 bytes little-endian)
6778    instruction_data.extend_from_slice(&faucet_account_idx.to_le_bytes());
6779
6780    // - depositor_account_idx (u16, 2 bytes little-endian)
6781    instruction_data.extend_from_slice(&depositor_account_idx.to_le_bytes());
6782
6783    // - eoa_program_idx (u16, 2 bytes little-endian)
6784    instruction_data.extend_from_slice(&eoa_program_idx.to_le_bytes());
6785
6786    // - amount (u64, 8 bytes little-endian)
6787    instruction_data.extend_from_slice(&amount.to_le_bytes());
6788
6789    Ok(instruction_data)
6790}
6791
6792/// Build faucet Withdraw instruction data
6793fn build_faucet_withdraw_instruction(
6794    faucet_account_idx: u16,
6795    recipient_account_idx: u16,
6796    amount: u64,
6797) -> Result<Vec<u8>> {
6798    let mut instruction_data = Vec::new();
6799
6800    // Discriminant: TN_FAUCET_INSTRUCTION_WITHDRAW = 1 (u32, 4 bytes little-endian)
6801    instruction_data.extend_from_slice(&1u32.to_le_bytes());
6802
6803    // tn_faucet_withdraw_args_t structure:
6804    // - faucet_account_idx (u16, 2 bytes little-endian)
6805    instruction_data.extend_from_slice(&faucet_account_idx.to_le_bytes());
6806
6807    // - recipient_account_idx (u16, 2 bytes little-endian)
6808    instruction_data.extend_from_slice(&recipient_account_idx.to_le_bytes());
6809
6810    // - amount (u64, 8 bytes little-endian)
6811    instruction_data.extend_from_slice(&amount.to_le_bytes());
6812
6813    Ok(instruction_data)
6814}
6815
6816/// Build consensus validator ACTIVATE instruction data.
6817/// Matches tn_consensus_validator_activate_args_t structure.
6818fn build_activate_instruction(
6819    attestor_table_idx: u64,
6820    token_program_idx: u16,
6821    source_token_account_idx: u16,
6822    converted_vault_idx: u16,
6823    identity_idx: u16,
6824    bls_pk: [u8; 96],
6825    claim_authority: [u8; 32],
6826    token_amount: u64,
6827) -> Result<Vec<u8>> {
6828    let mut instruction_data = Vec::new();
6829
6830    /* Discriminant: TN_CONSENSUS_VALIDATOR_INSTRUCTION_ACTIVATE = 1 (u32, 4 bytes LE) */
6831    instruction_data.extend_from_slice(&1u32.to_le_bytes());
6832
6833    /* tn_consensus_validator_activate_args_t structure (packed): */
6834    /* - attestor_table_idx (u64, 8 bytes LE) */
6835    instruction_data.extend_from_slice(&attestor_table_idx.to_le_bytes());
6836
6837    /* - token_program_idx (u16, 2 bytes LE) */
6838    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
6839
6840    /* - source_token_account_idx (u16, 2 bytes LE) */
6841    instruction_data.extend_from_slice(&source_token_account_idx.to_le_bytes());
6842
6843    /* - converted_vault_idx (u16, 2 bytes LE) */
6844    instruction_data.extend_from_slice(&converted_vault_idx.to_le_bytes());
6845
6846    /* - identity_idx (u16, 2 bytes LE) */
6847    instruction_data.extend_from_slice(&identity_idx.to_le_bytes());
6848
6849    /* - bls_pk (96 bytes, tn_bls_pubkey_t / blst_p1_affine) */
6850    instruction_data.extend_from_slice(&bls_pk);
6851
6852    /* - claim_authority (32 bytes, pubkey) */
6853    instruction_data.extend_from_slice(&claim_authority);
6854
6855    /* - token_amount (u64, 8 bytes LE) */
6856    instruction_data.extend_from_slice(&token_amount.to_le_bytes());
6857
6858    Ok(instruction_data)
6859}
6860
6861/// Build consensus validator DEACTIVATE instruction data.
6862/// Matches tn_consensus_validator_deactivate_args_t structure.
6863fn build_deactivate_instruction(
6864    attestor_table_idx: u64,
6865    token_program_idx: u16,
6866    unclaimed_vault_idx: u16,
6867    dest_token_account_idx: u16,
6868    identity_idx: u16,
6869) -> Result<Vec<u8>> {
6870    let mut instruction_data = Vec::new();
6871
6872    instruction_data.extend_from_slice(&2u32.to_le_bytes());
6873    instruction_data.extend_from_slice(&attestor_table_idx.to_le_bytes());
6874    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
6875    instruction_data.extend_from_slice(&unclaimed_vault_idx.to_le_bytes());
6876    instruction_data.extend_from_slice(&dest_token_account_idx.to_le_bytes());
6877    instruction_data.extend_from_slice(&identity_idx.to_le_bytes());
6878
6879    Ok(instruction_data)
6880}
6881
6882/// Build consensus validator CONVERT_TOKENS instruction data.
6883/// Matches tn_consensus_validator_convert_args_t structure.
6884fn build_convert_tokens_instruction(
6885    attestor_table_idx: u64,
6886    token_program_idx: u16,
6887    source_token_account_idx: u16,
6888    converted_vault_idx: u16,
6889    identity_idx: u16,
6890    token_amount: u64,
6891) -> Result<Vec<u8>> {
6892    let mut instruction_data = Vec::new();
6893
6894    instruction_data.extend_from_slice(&3u32.to_le_bytes());
6895    instruction_data.extend_from_slice(&attestor_table_idx.to_le_bytes());
6896    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
6897    instruction_data.extend_from_slice(&source_token_account_idx.to_le_bytes());
6898    instruction_data.extend_from_slice(&converted_vault_idx.to_le_bytes());
6899    instruction_data.extend_from_slice(&identity_idx.to_le_bytes());
6900    instruction_data.extend_from_slice(&token_amount.to_le_bytes());
6901
6902    Ok(instruction_data)
6903}
6904
6905/// Build consensus validator CLAIM instruction data.
6906/// Matches tn_consensus_validator_claim_args_t structure.
6907fn build_claim_instruction(
6908    attestor_table_idx: u64,
6909    token_program_idx: u16,
6910    unclaimed_vault_idx: u16,
6911    dest_token_account_idx: u16,
6912    claim_authority_idx: u16,
6913    subject_attestor: TnPubkey,
6914) -> Result<Vec<u8>> {
6915    let mut instruction_data = Vec::new();
6916
6917    instruction_data.extend_from_slice(&4u32.to_le_bytes());
6918    instruction_data.extend_from_slice(&attestor_table_idx.to_le_bytes());
6919    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
6920    instruction_data.extend_from_slice(&unclaimed_vault_idx.to_le_bytes());
6921    instruction_data.extend_from_slice(&dest_token_account_idx.to_le_bytes());
6922    instruction_data.extend_from_slice(&claim_authority_idx.to_le_bytes());
6923    instruction_data.extend_from_slice(&subject_attestor);
6924
6925    Ok(instruction_data)
6926}
6927
6928/// Build consensus validator SET_CLAIM_AUTH instruction data.
6929/// Matches tn_consensus_validator_set_claim_auth_args_t structure.
6930fn build_set_claim_authority_instruction(
6931    attestor_table_idx: u64,
6932    current_claim_auth_idx: u16,
6933    subject_attestor: TnPubkey,
6934    new_claim_authority: TnPubkey,
6935) -> Result<Vec<u8>> {
6936    let mut instruction_data = Vec::new();
6937
6938    instruction_data.extend_from_slice(&5u32.to_le_bytes());
6939    instruction_data.extend_from_slice(&attestor_table_idx.to_le_bytes());
6940    instruction_data.extend_from_slice(&current_claim_auth_idx.to_le_bytes());
6941    instruction_data.extend_from_slice(&subject_attestor);
6942    instruction_data.extend_from_slice(&new_claim_authority);
6943
6944    Ok(instruction_data)
6945}
6946
6947#[repr(C, packed)]
6948struct NameServiceInitializeRootArgs {
6949    registrar_account_idx: u16,
6950    authority_account_idx: u16,
6951    root_name: [u8; TN_NAME_SERVICE_MAX_DOMAIN_LENGTH],
6952    root_name_length: u32,
6953}
6954
6955#[repr(C, packed)]
6956struct NameServiceRegisterSubdomainArgs {
6957    domain_account_idx: u16,
6958    parent_account_idx: u16,
6959    owner_account_idx: u16,
6960    authority_account_idx: u16,
6961    name: [u8; TN_NAME_SERVICE_MAX_DOMAIN_LENGTH],
6962    name_length: u32,
6963}
6964
6965#[repr(C, packed)]
6966struct NameServiceAppendRecordArgs {
6967    domain_account_idx: u16,
6968    owner_account_idx: u16,
6969    key_length: u32,
6970    key: [u8; TN_NAME_SERVICE_MAX_KEY_LENGTH],
6971    value_length: u32,
6972    value: [u8; TN_NAME_SERVICE_MAX_VALUE_LENGTH],
6973}
6974
6975#[repr(C, packed)]
6976struct NameServiceDeleteRecordArgs {
6977    domain_account_idx: u16,
6978    owner_account_idx: u16,
6979    key_length: u32,
6980    key: [u8; TN_NAME_SERVICE_MAX_KEY_LENGTH],
6981}
6982
6983#[repr(C, packed)]
6984struct NameServiceUnregisterSubdomainArgs {
6985    domain_account_idx: u16,
6986    owner_account_idx: u16,
6987}
6988
6989/// Build name service InitializeRoot instruction data
6990fn build_name_service_initialize_root_instruction(
6991    registrar_account_idx: u16,
6992    authority_account_idx: u16,
6993    root_name: &str,
6994    state_proof: Vec<u8>,
6995) -> Result<Vec<u8>> {
6996    let root_name_bytes = root_name.as_bytes();
6997    if root_name_bytes.is_empty() || root_name_bytes.len() > TN_NAME_SERVICE_MAX_DOMAIN_LENGTH {
6998        return Err(anyhow::anyhow!(
6999            "Root name length must be between 1 and {}",
7000            TN_NAME_SERVICE_MAX_DOMAIN_LENGTH
7001        ));
7002    }
7003
7004    let mut args = NameServiceInitializeRootArgs {
7005        registrar_account_idx,
7006        authority_account_idx,
7007        root_name: [0u8; TN_NAME_SERVICE_MAX_DOMAIN_LENGTH],
7008        root_name_length: root_name_bytes.len() as u32,
7009    };
7010    args.root_name[..root_name_bytes.len()].copy_from_slice(root_name_bytes);
7011
7012    let mut instruction_data = Vec::new();
7013    instruction_data.extend_from_slice(&TN_NAME_SERVICE_INSTRUCTION_INITIALIZE_ROOT.to_le_bytes());
7014
7015    let args_bytes = unsafe {
7016        std::slice::from_raw_parts(
7017            &args as *const _ as *const u8,
7018            std::mem::size_of::<NameServiceInitializeRootArgs>(),
7019        )
7020    };
7021    instruction_data.extend_from_slice(args_bytes);
7022
7023    instruction_data.extend_from_slice(&TN_NAME_SERVICE_PROOF_INLINE.to_le_bytes());
7024    instruction_data.extend_from_slice(&state_proof);
7025
7026    Ok(instruction_data)
7027}
7028
7029/// Build name service RegisterSubdomain instruction data
7030fn build_name_service_register_subdomain_instruction(
7031    domain_account_idx: u16,
7032    parent_account_idx: u16,
7033    owner_account_idx: u16,
7034    authority_account_idx: u16,
7035    domain_name: &str,
7036    state_proof: Vec<u8>,
7037) -> Result<Vec<u8>> {
7038    let domain_bytes = domain_name.as_bytes();
7039    if domain_bytes.is_empty() || domain_bytes.len() > TN_NAME_SERVICE_MAX_DOMAIN_LENGTH {
7040        return Err(anyhow::anyhow!(
7041            "Domain name length must be between 1 and {}",
7042            TN_NAME_SERVICE_MAX_DOMAIN_LENGTH
7043        ));
7044    }
7045
7046    let mut args = NameServiceRegisterSubdomainArgs {
7047        domain_account_idx,
7048        parent_account_idx,
7049        owner_account_idx,
7050        authority_account_idx,
7051        name: [0u8; TN_NAME_SERVICE_MAX_DOMAIN_LENGTH],
7052        name_length: domain_bytes.len() as u32,
7053    };
7054    args.name[..domain_bytes.len()].copy_from_slice(domain_bytes);
7055
7056    let mut instruction_data = Vec::new();
7057    instruction_data
7058        .extend_from_slice(&TN_NAME_SERVICE_INSTRUCTION_REGISTER_SUBDOMAIN.to_le_bytes());
7059
7060    let args_bytes = unsafe {
7061        std::slice::from_raw_parts(
7062            &args as *const _ as *const u8,
7063            std::mem::size_of::<NameServiceRegisterSubdomainArgs>(),
7064        )
7065    };
7066    instruction_data.extend_from_slice(args_bytes);
7067
7068    instruction_data.extend_from_slice(&TN_NAME_SERVICE_PROOF_INLINE.to_le_bytes());
7069    instruction_data.extend_from_slice(&state_proof);
7070
7071    Ok(instruction_data)
7072}
7073
7074/// Build name service AppendRecord instruction data
7075fn build_name_service_append_record_instruction(
7076    domain_account_idx: u16,
7077    owner_account_idx: u16,
7078    key: &[u8],
7079    value: &[u8],
7080) -> Result<Vec<u8>> {
7081    if key.is_empty() || key.len() > TN_NAME_SERVICE_MAX_KEY_LENGTH {
7082        return Err(anyhow::anyhow!(
7083            "Key length must be between 1 and {} bytes",
7084            TN_NAME_SERVICE_MAX_KEY_LENGTH
7085        ));
7086    }
7087    if value.len() > TN_NAME_SERVICE_MAX_VALUE_LENGTH {
7088        return Err(anyhow::anyhow!(
7089            "Value length must be <= {} bytes",
7090            TN_NAME_SERVICE_MAX_VALUE_LENGTH
7091        ));
7092    }
7093
7094    let mut args = NameServiceAppendRecordArgs {
7095        domain_account_idx,
7096        owner_account_idx,
7097        key_length: key.len() as u32,
7098        key: [0u8; TN_NAME_SERVICE_MAX_KEY_LENGTH],
7099        value_length: value.len() as u32,
7100        value: [0u8; TN_NAME_SERVICE_MAX_VALUE_LENGTH],
7101    };
7102    args.key[..key.len()].copy_from_slice(key);
7103    args.value[..value.len()].copy_from_slice(value);
7104
7105    let mut instruction_data = Vec::new();
7106    instruction_data.extend_from_slice(&TN_NAME_SERVICE_INSTRUCTION_APPEND_RECORD.to_le_bytes());
7107
7108    let args_bytes = unsafe {
7109        std::slice::from_raw_parts(
7110            &args as *const _ as *const u8,
7111            std::mem::size_of::<NameServiceAppendRecordArgs>(),
7112        )
7113    };
7114    instruction_data.extend_from_slice(args_bytes);
7115
7116    Ok(instruction_data)
7117}
7118
7119/// Build name service DeleteRecord instruction data
7120fn build_name_service_delete_record_instruction(
7121    domain_account_idx: u16,
7122    owner_account_idx: u16,
7123    key: &[u8],
7124) -> Result<Vec<u8>> {
7125    if key.is_empty() || key.len() > TN_NAME_SERVICE_MAX_KEY_LENGTH {
7126        return Err(anyhow::anyhow!(
7127            "Key length must be between 1 and {} bytes",
7128            TN_NAME_SERVICE_MAX_KEY_LENGTH
7129        ));
7130    }
7131
7132    let mut args = NameServiceDeleteRecordArgs {
7133        domain_account_idx,
7134        owner_account_idx,
7135        key_length: key.len() as u32,
7136        key: [0u8; TN_NAME_SERVICE_MAX_KEY_LENGTH],
7137    };
7138    args.key[..key.len()].copy_from_slice(key);
7139
7140    let mut instruction_data = Vec::new();
7141    instruction_data.extend_from_slice(&TN_NAME_SERVICE_INSTRUCTION_DELETE_RECORD.to_le_bytes());
7142
7143    let args_bytes = unsafe {
7144        std::slice::from_raw_parts(
7145            &args as *const _ as *const u8,
7146            std::mem::size_of::<NameServiceDeleteRecordArgs>(),
7147        )
7148    };
7149    instruction_data.extend_from_slice(args_bytes);
7150
7151    Ok(instruction_data)
7152}
7153
7154/// Build name service UnregisterSubdomain instruction data
7155fn build_name_service_unregister_subdomain_instruction(
7156    domain_account_idx: u16,
7157    owner_account_idx: u16,
7158) -> Result<Vec<u8>> {
7159    let args = NameServiceUnregisterSubdomainArgs {
7160        domain_account_idx,
7161        owner_account_idx,
7162    };
7163
7164    let mut instruction_data = Vec::new();
7165    instruction_data.extend_from_slice(&TN_NAME_SERVICE_INSTRUCTION_UNREGISTER.to_le_bytes());
7166
7167    let args_bytes = unsafe {
7168        std::slice::from_raw_parts(
7169            &args as *const _ as *const u8,
7170            std::mem::size_of::<NameServiceUnregisterSubdomainArgs>(),
7171        )
7172    };
7173    instruction_data.extend_from_slice(args_bytes);
7174
7175    Ok(instruction_data)
7176}
7177
7178/// Build thru registrar InitializeRegistry instruction data
7179fn build_thru_registrar_initialize_registry_instruction(
7180    config_account_idx: u16,
7181    name_service_program_idx: u16,
7182    root_registrar_account_idx: u16,
7183    treasurer_account_idx: u16,
7184    token_mint_account_idx: u16,
7185    token_program_idx: u16,
7186    root_domain_name: &str,
7187    price_per_year: u64,
7188    config_proof: Vec<u8>,
7189    registrar_proof: Vec<u8>,
7190) -> Result<Vec<u8>> {
7191    let mut instruction_data = Vec::new();
7192
7193    // Discriminant: TN_THRU_REGISTRAR_INSTRUCTION_INITIALIZE_REGISTRY = 0 (u32, 4 bytes little-endian)
7194    instruction_data
7195        .extend_from_slice(&TN_THRU_REGISTRAR_INSTRUCTION_INITIALIZE_REGISTRY.to_le_bytes());
7196
7197    // tn_thru_registrar_initialize_registry_args_t structure:
7198    // - config_account_idx (u16, 2 bytes little-endian)
7199    instruction_data.extend_from_slice(&config_account_idx.to_le_bytes());
7200    // - name_service_program_account_idx (u16, 2 bytes little-endian)
7201    instruction_data.extend_from_slice(&name_service_program_idx.to_le_bytes());
7202    // - root_registrar_account_idx (u16, 2 bytes little-endian)
7203    instruction_data.extend_from_slice(&root_registrar_account_idx.to_le_bytes());
7204    // - treasurer_account_idx (u16, 2 bytes little-endian)
7205    instruction_data.extend_from_slice(&treasurer_account_idx.to_le_bytes());
7206    // - token_mint_account_idx (u16, 2 bytes little-endian)
7207    instruction_data.extend_from_slice(&token_mint_account_idx.to_le_bytes());
7208    // - token_program_account_idx (u16, 2 bytes little-endian)
7209    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
7210    // - root_domain_name (64 bytes, padded with zeros)
7211    let domain_bytes = root_domain_name.as_bytes();
7212    if domain_bytes.len() > 64 {
7213        return Err(anyhow::anyhow!(
7214            "Root domain name must be 64 characters or less"
7215        ));
7216    }
7217    let mut domain_padded = [0u8; 64];
7218    domain_padded[..domain_bytes.len()].copy_from_slice(domain_bytes);
7219    instruction_data.extend_from_slice(&domain_padded);
7220    // - root_domain_name_length (u32, 4 bytes little-endian)
7221    instruction_data.extend_from_slice(&(domain_bytes.len() as u32).to_le_bytes());
7222    // - price_per_year (u64, 8 bytes little-endian)
7223    instruction_data.extend_from_slice(&price_per_year.to_le_bytes());
7224
7225    // Variable-length proofs follow:
7226    // - config_proof (variable length)
7227    instruction_data.extend_from_slice(&config_proof);
7228    // - registrar_proof (variable length)
7229    instruction_data.extend_from_slice(&registrar_proof);
7230
7231    Ok(instruction_data)
7232}
7233
7234/// Build thru registrar PurchaseDomain instruction data
7235fn build_thru_registrar_purchase_domain_instruction(
7236    config_account_idx: u16,
7237    lease_account_idx: u16,
7238    domain_account_idx: u16,
7239    name_service_program_idx: u16,
7240    root_registrar_account_idx: u16,
7241    treasurer_account_idx: u16,
7242    payer_token_account_idx: u16,
7243    token_mint_account_idx: u16,
7244    token_program_idx: u16,
7245    domain_name: &str,
7246    years: u8,
7247    lease_proof: Vec<u8>,
7248    domain_proof: Vec<u8>,
7249) -> Result<Vec<u8>> {
7250    let mut instruction_data = Vec::new();
7251
7252    // Discriminant: TN_THRU_REGISTRAR_INSTRUCTION_PURCHASE_DOMAIN = 1 (u32, 4 bytes little-endian)
7253    instruction_data
7254        .extend_from_slice(&TN_THRU_REGISTRAR_INSTRUCTION_PURCHASE_DOMAIN.to_le_bytes());
7255
7256    // tn_thru_registrar_purchase_domain_args_t structure:
7257    // - config_account_idx (u16, 2 bytes little-endian)
7258    instruction_data.extend_from_slice(&config_account_idx.to_le_bytes());
7259    // - lease_account_idx (u16, 2 bytes little-endian)
7260    instruction_data.extend_from_slice(&lease_account_idx.to_le_bytes());
7261    // - domain_account_idx (u16, 2 bytes little-endian)
7262    instruction_data.extend_from_slice(&domain_account_idx.to_le_bytes());
7263    // - name_service_program_account_idx (u16, 2 bytes little-endian)
7264    instruction_data.extend_from_slice(&name_service_program_idx.to_le_bytes());
7265    // - root_registrar_account_idx (u16, 2 bytes little-endian)
7266    instruction_data.extend_from_slice(&root_registrar_account_idx.to_le_bytes());
7267    // - treasurer_account_idx (u16, 2 bytes little-endian)
7268    instruction_data.extend_from_slice(&treasurer_account_idx.to_le_bytes());
7269    // - payer_token_account_idx (u16, 2 bytes little-endian)
7270    instruction_data.extend_from_slice(&payer_token_account_idx.to_le_bytes());
7271    // - token_mint_account_idx (u16, 2 bytes little-endian)
7272    instruction_data.extend_from_slice(&token_mint_account_idx.to_le_bytes());
7273    // - token_program_account_idx (u16, 2 bytes little-endian)
7274    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
7275    // - domain_name (64 bytes, padded with zeros)
7276    let domain_bytes = domain_name.as_bytes();
7277    if domain_bytes.len() > 64 {
7278        return Err(anyhow::anyhow!("Domain name must be 64 characters or less"));
7279    }
7280    let mut domain_padded = [0u8; 64];
7281    domain_padded[..domain_bytes.len()].copy_from_slice(domain_bytes);
7282    instruction_data.extend_from_slice(&domain_padded);
7283    // - domain_name_length (u32, 4 bytes little-endian)
7284    instruction_data.extend_from_slice(&(domain_bytes.len() as u32).to_le_bytes());
7285    // - years (u8, 1 byte)
7286    instruction_data.push(years);
7287
7288    // Variable-length proofs follow:
7289    // - lease_proof (variable length)
7290    instruction_data.extend_from_slice(&lease_proof);
7291    // - domain_proof (variable length)
7292    instruction_data.extend_from_slice(&domain_proof);
7293
7294    Ok(instruction_data)
7295}
7296
7297/// Build thru registrar RenewLease instruction data
7298fn build_thru_registrar_renew_lease_instruction(
7299    config_account_idx: u16,
7300    lease_account_idx: u16,
7301    treasurer_account_idx: u16,
7302    payer_token_account_idx: u16,
7303    token_mint_account_idx: u16,
7304    token_program_idx: u16,
7305    years: u8,
7306) -> Result<Vec<u8>> {
7307    let mut instruction_data = Vec::new();
7308
7309    // Discriminant: TN_THRU_REGISTRAR_INSTRUCTION_RENEW_LEASE = 2 (u32, 4 bytes little-endian)
7310    instruction_data.extend_from_slice(&TN_THRU_REGISTRAR_INSTRUCTION_RENEW_LEASE.to_le_bytes());
7311
7312    // tn_thru_registrar_renew_lease_args_t structure:
7313    // - config_account_idx (u16, 2 bytes little-endian)
7314    instruction_data.extend_from_slice(&config_account_idx.to_le_bytes());
7315    // - lease_account_idx (u16, 2 bytes little-endian)
7316    instruction_data.extend_from_slice(&lease_account_idx.to_le_bytes());
7317    // - treasurer_account_idx (u16, 2 bytes little-endian)
7318    instruction_data.extend_from_slice(&treasurer_account_idx.to_le_bytes());
7319    // - payer_token_account_idx (u16, 2 bytes little-endian)
7320    instruction_data.extend_from_slice(&payer_token_account_idx.to_le_bytes());
7321    // - token_mint_account_idx (u16, 2 bytes little-endian)
7322    instruction_data.extend_from_slice(&token_mint_account_idx.to_le_bytes());
7323    // - token_program_account_idx (u16, 2 bytes little-endian)
7324    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
7325    // - years (u8, 1 byte)
7326    instruction_data.push(years);
7327
7328    Ok(instruction_data)
7329}
7330
7331/// Build thru registrar ClaimExpiredDomain instruction data
7332fn build_thru_registrar_claim_expired_domain_instruction(
7333    config_account_idx: u16,
7334    lease_account_idx: u16,
7335    treasurer_account_idx: u16,
7336    payer_token_account_idx: u16,
7337    token_mint_account_idx: u16,
7338    token_program_idx: u16,
7339    years: u8,
7340) -> Result<Vec<u8>> {
7341    let mut instruction_data = Vec::new();
7342
7343    // Discriminant: TN_THRU_REGISTRAR_INSTRUCTION_CLAIM_EXPIRED_DOMAIN = 3 (u32, 4 bytes little-endian)
7344    instruction_data
7345        .extend_from_slice(&TN_THRU_REGISTRAR_INSTRUCTION_CLAIM_EXPIRED_DOMAIN.to_le_bytes());
7346
7347    // tn_thru_registrar_claim_expired_domain_args_t structure:
7348    // - config_account_idx (u16, 2 bytes little-endian)
7349    instruction_data.extend_from_slice(&config_account_idx.to_le_bytes());
7350    // - lease_account_idx (u16, 2 bytes little-endian)
7351    instruction_data.extend_from_slice(&lease_account_idx.to_le_bytes());
7352    // - treasurer_account_idx (u16, 2 bytes little-endian)
7353    instruction_data.extend_from_slice(&treasurer_account_idx.to_le_bytes());
7354    // - payer_token_account_idx (u16, 2 bytes little-endian)
7355    instruction_data.extend_from_slice(&payer_token_account_idx.to_le_bytes());
7356    // - token_mint_account_idx (u16, 2 bytes little-endian)
7357    instruction_data.extend_from_slice(&token_mint_account_idx.to_le_bytes());
7358    // - token_program_account_idx (u16, 2 bytes little-endian)
7359    instruction_data.extend_from_slice(&token_program_idx.to_le_bytes());
7360    // - years (u8, 1 byte)
7361    instruction_data.push(years);
7362
7363    Ok(instruction_data)
7364}