1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
use crate::*;

use solana_program::pubkey::Pubkey;
use solana_program::instruction::Instruction;
use solana_address_lookup_table_program::state::AddressLookupTable;
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_program::address_lookup_table_account::AddressLookupTableAccount;
use solana_program::hash::Hash;
use solana_sdk::compute_budget::ComputeBudgetInstruction;
use solana_program::message::v0;
use solana_program::message::VersionedMessage;
use solana_sdk::signer::Signer;
use solana_sdk::transaction::VersionedTransaction;
use tokio::sync::RwLockReadGuard;
use std::ops::Deref;
use std::sync::Arc;
use solana_sdk::transaction::Transaction;
pub use solana_sdk::signer::keypair::Keypair;

/// A trait for types that can act as signers for transactions.
pub trait AsSigner: Send + Sync {
    /// Returns a reference to the signer.
    fn as_signer(&self) -> &dyn Signer;

    fn signer_pubkey(&self) -> Pubkey {
        self.as_signer().pubkey()
    }
}

pub trait ToKeypair: Send + Sync {
    fn keypair(&self) -> &Keypair;
}

// Implement AsSigner for any type that implements ToKeypair
impl<T> AsSigner for T
where
    T: ToKeypair,
{
    fn as_signer(&self) -> &dyn Signer {
        // Use the keypair method from the ToKeypair trait to get the Keypair
        // and then return a reference to it as a &dyn Signer.
        // The Keypair struct already implements the Signer trait.
        self.keypair()
    }
}

// Implementations

impl ToKeypair for Keypair {
    fn keypair(&self) -> &Keypair {
        &self
    }
}
impl<'a> ToKeypair for &'a Keypair {
    fn keypair(&self) -> &'a Keypair {
        self
    }
}

// Arc

impl ToKeypair for Arc<Keypair> {
    fn keypair(&self) -> &Keypair {
        &self
    }
}
impl<'a> AsSigner for Arc<&'a Keypair> {
    fn as_signer(&self) -> &dyn Signer {
        *self.as_ref()
    }
}
impl<'a> ToKeypair for &'a Arc<Keypair> {
    fn keypair(&self) -> &Keypair {
        &self
    }
}
impl ToKeypair for Arc<Arc<Keypair>> {
    fn keypair(&self) -> &Keypair {
        &self.as_ref()
    }
}
impl ToKeypair for Arc<Arc<Arc<Keypair>>> {
    fn keypair(&self) -> &Keypair {
        &self.as_ref().as_ref()
    }
}

// Box

impl<T> ToKeypair for Box<T>
where
    T: ToKeypair + ?Sized,
{
    fn keypair(&self) -> &Keypair {
        self.as_ref().keypair()
    }
}

// ArcSwap

impl<T> ToKeypair for arc_swap::Guard<Arc<T>>
where
    T: ToKeypair,
{
    fn keypair(&self) -> &Keypair {
        self.deref().keypair()
    }
}

// Tokio RwLock

impl<'a, T> ToKeypair for RwLockReadGuard<'a, T>
where
    T: ToKeypair + ?Sized,
{
    fn keypair(&self) -> &Keypair {
        self.deref().keypair()
    }
}

impl<'a, T> ToKeypair for Arc<RwLockReadGuard<'a, T>>
where
    T: ToKeypair + ?Sized,
{
    fn keypair(&self) -> &Keypair {
        self.as_ref().keypair()
    }
}

impl<'a> AsSigner for &RwLockReadGuard<'a, Keypair> {
    fn as_signer(&self) -> &dyn Signer {
        (*self).deref()
    }
}
impl<'a> AsSigner for &Arc<RwLockReadGuard<'a, Keypair>> {
    fn as_signer(&self) -> &dyn Signer {
        self.as_ref().deref()
    }
}

/// Represents a transaction object used for building Solana transactions.
///
/// The `TransactionBuilder` struct provides methods for constructing and manipulating Solana transactions.
/// It allows setting the payer, adding instructions, signers, and other transaction parameters.
/// The transaction can be converted to a legacy transaction format or executed directly using the Solana RPC client.
///
/// # Examples
///
/// Creating a new transaction object with a payer:
///
/// ```rust
/// use solana_sdk::pubkey::Pubkey;
/// use solana_sdk::instruction::Instruction;
/// use std::sync::Arc;
///
/// let payer = Pubkey::new_unique();
/// let transaction = TransactionBuilder::new(payer);
/// ```
///
/// Adding an instruction to the transaction:
///
/// ```rust
/// use solana_sdk::pubkey::Pubkey;
/// use solana_sdk::instruction::Instruction;
/// use std::sync::Arc;
///
/// let payer = Pubkey::new_unique();
/// let instruction = Instruction::new_with_bincode(program_id, data);
/// let transaction = TransactionBuilder::new(payer)
///     .add_ix(instruction);
/// ```
///
/// Converting the transaction object to a legacy transaction:
///
/// ```rust
/// use solana_sdk::pubkey::Pubkey;
/// use solana_sdk::instruction::Instruction;
/// use std::sync::Arc;
///
/// let payer = Pubkey::new_unique();
/// let instruction = Instruction::new_with_bincode(program_id, data);
/// let transaction = TransactionBuilder::new(payer)
///     .add_ix(instruction)
///     .to_legacy_tx();
/// ```
#[derive(Default, Clone)]
pub struct TransactionBuilder {
    payer: Pubkey,
    ixs: Vec<Instruction>,
    compute_units: Option<u32>,
    priority_fees: Option<u64>,
    recent_blockhash: Option<Hash>,
    min_context_slot: Option<u64>,
    address_lookup_tables: Vec<AddressLookupTableAccount>,
    signers: Vec<Arc<dyn AsSigner>>,
}
impl TransactionBuilder {
    pub fn new(payer: Pubkey) -> Self {
        Self {
            payer,
            ..Default::default()
        }
    }
    pub fn new_with_payer(payer: Arc<dyn AsSigner>) -> Self {
        Self {
            payer: payer.as_signer().pubkey(),
            signers: vec![Arc::clone(&payer)],
            ..Default::default()
        }
    }

    pub fn new_with_ixs(payer: Pubkey, ixs: impl IntoIterator<Item = Instruction>) -> Self {
        Self {
            payer,
            ixs: ixs.into_iter().collect::<Vec<Instruction>>(),
            ..Default::default()
        }
    }
    pub fn new_with_payer_and_ixs(
        payer: Arc<dyn AsSigner>,
        ixs: impl IntoIterator<Item = Instruction>,
    ) -> Self {
        Self {
            payer: payer.as_signer().pubkey(),
            signers: vec![Arc::clone(&payer)],
            ixs: ixs.into_iter().collect::<Vec<Instruction>>(),
            ..Default::default()
        }
    }

    // Builder methods, consumes self and returns self
    pub fn set_compute_units(mut self, compute_units: u32) -> Self {
        self.compute_units = Some(compute_units);
        self
    }
    pub fn set_priority_fees(mut self, priority_fees: u64) -> Self {
        self.priority_fees = Some(priority_fees);
        self
    }
    pub fn add_ix(mut self, ix: Instruction) -> Self {
        self.ixs.push(ix);
        self
    }
    pub fn has_signer(&self, signer: Pubkey) -> bool {
        self.signers
            .iter()
            .find(|s| s.as_signer().pubkey() == signer)
            .is_some()
    }
    pub fn has_payer(&self) -> bool {
        self.has_signer(self.payer)
    }
    pub fn add_signer(mut self, signer: Arc<dyn AsSigner>) -> TransactionBuilder {
        let signer_key = signer.as_signer().pubkey();
        if let None = self
            .signers
            .iter()
            .find(|s| s.as_signer().pubkey() == signer_key)
        {
            self.signers.push(Arc::clone(&signer));
        }

        self
    }
    pub fn add_signers(mut self, signers: Vec<Arc<dyn AsSigner>>) -> TransactionBuilder {
        for signer in signers {
            let signer_key = signer.as_signer().pubkey();
            if let None = self
                .signers
                .iter()
                .find(|s| s.as_signer().pubkey() == signer_key)
            {
                self.signers.push(Arc::clone(&signer));
            }
        }

        self
    }
    pub fn set_recent_blockhash(mut self, blockhash: Hash) -> Self {
        self.recent_blockhash = Some(blockhash);
        self
    }
    pub fn set_min_context_slot(mut self, min_context_slot: u64) -> Self {
        self.min_context_slot = Some(min_context_slot);
        self
    }

    pub fn add_address_lookup_account(
        mut self,
        address_lookup_table: AddressLookupTableAccount,
    ) -> Self {
        self.address_lookup_tables.push(address_lookup_table);
        self
    }
    pub fn add_address_lookup_accounts(
        mut self,
        mut address_lookup_tables: &mut Vec<AddressLookupTableAccount>,
    ) -> Self {
        self.address_lookup_tables
            .append(&mut address_lookup_tables);
        self
    }
    pub async fn add_address_lookup_table(
        mut self,
        rpc: &RpcClient,
        address_lookup_table_pubkey: Pubkey,
    ) -> Self {
        if let Ok(address_lookup_table) =
            TransactionBuilder::fetch_address_lookup_account(rpc, address_lookup_table_pubkey).await
        {
            self = self.add_address_lookup_account(address_lookup_table);
        }

        self
    }
    pub async fn add_address_lookup_tables(
        mut self,
        rpc: &RpcClient,
        address_lookup_table_pubkeys: Vec<Pubkey>,
    ) -> Self {
        if let Ok(mut address_lookup_tables) =
            TransactionBuilder::fetch_multiple_address_lookup_accounts(
                rpc,
                address_lookup_table_pubkeys,
            )
            .await
        {
            self = self.add_address_lookup_accounts(&mut address_lookup_tables);
        }

        self
    }

    // Getters
    pub fn payer(&self) -> Pubkey {
        self.payer
    }

    /// Return a vec of all of the required signers for the transaction.
    pub fn required_signers(&self) -> Vec<Pubkey> {
        let mut signers_required: Vec<Pubkey> = vec![];
        for ixn in self.ixs.clone() {
            for account in ixn.accounts {
                if account.is_signer && !signers_required.contains(&account.pubkey) {
                    signers_required.push(account.pubkey);
                }
            }
        }
        signers_required
    }

    /// Returns the stored signers for the transaction, removing any un-needed signers using the provided ixn's AccountMeta's.
    pub fn signers(&self) -> Result<Vec<&dyn Signer>, OnDemandError> {
        let mut signers: Vec<&dyn Signer> = vec![];
        for required_signer in self.required_signers().iter() {
            let mut found = false;

            for signer in &self.signers {
                let signer_key = signer.as_signer().pubkey();
                if signer_key == *required_signer {
                    found = true;
                    signers.push(signer.as_signer());
                    break;
                }
            }
            if !found {
                return Err(OnDemandError::SolanaMissingSigner);
            }
        }

        Ok(signers)
    }
    fn signers_with_payer<'a, T: AsSigner>(
        &'a self,
        payer: &'a T,
    ) -> Result<Vec<&'a dyn Signer>, OnDemandError> {
        let payer_signer = payer.as_signer();

        if payer_signer.pubkey() != self.payer {
            return Err(OnDemandError::SolanaPayerMismatch);
        }

        let mut signers: Vec<&dyn Signer> = vec![];
        for required_signer in self.required_signers().iter() {
            if required_signer == &self.payer {
                signers.push(payer_signer);
                continue;
            }

            let mut found = false;

            for signer in self.signers.iter() {
                let signer_key = signer.as_signer().pubkey();
                if signer_key == *required_signer {
                    found = true;
                    signers.push(signer.as_signer());
                    break;
                }
            }
            if !found {
                return Err(OnDemandError::SolanaMissingSigner);
            }
        }

        Ok(signers)
    }
    pub fn ixs(&self) -> Result<Vec<Instruction>, OnDemandError> {
        if self.ixs.len() == 0 {
            return Err(OnDemandError::SolanaInstructionsEmpty);
        }

        let mut pre_ixs = vec![];

        if let Some(compute_units) = self.compute_units {
            pre_ixs.push(ComputeBudgetInstruction::set_compute_unit_limit(
                std::cmp::max(std::cmp::min(compute_units, 1_400_000), 200_000),
            ));
        }
        // want this first so we unshift last
        if let Some(priority_fees) = self.priority_fees {
            pre_ixs.push(ComputeBudgetInstruction::set_compute_unit_price(
                std::cmp::min(10_000, priority_fees),
            ));
        }

        let ixs = vec![pre_ixs, self.ixs.clone()].concat();

        if ixs.len() > 10 {
            return Err(OnDemandError::SolanaInstructionOverflow);
        }

        Ok(ixs)
    }
    pub fn build_legacy_tx(
        payer: Pubkey,
        ixs: Vec<Instruction>,
        signers: Vec<&dyn Signer>,
        recent_blockhash: Hash,
    ) -> Result<Transaction, OnDemandError> {
        let mut tx = Transaction::new_with_payer(&ixs, Some(&payer));
        tx.try_sign(&signers, recent_blockhash).map_err(|_| OnDemandError::SolanaSignError)?;
        Ok(tx)
    }
    pub fn to_legacy_tx(&self) -> Result<Transaction, OnDemandError> {
        if !self.has_payer() {
            return Err(OnDemandError::SolanaPayerSignerMissing);
        }

        TransactionBuilder::build_legacy_tx(
            self.payer,
            self.ixs()?,
            self.signers()?,
            self.recent_blockhash.unwrap_or_default(),
        )
    }
    pub fn to_legacy_tx_with_payer<T: AsSigner + Send + Sync>(
        &self,
        payer: T,
    ) -> Result<Transaction, OnDemandError> {
        if payer.as_signer().pubkey() != self.payer {
            return Err(OnDemandError::SolanaPayerMismatch);
        }

        TransactionBuilder::build_legacy_tx(
            self.payer,
            self.ixs()?,
            self.signers_with_payer(&payer)?,
            self.recent_blockhash.unwrap_or_default(),
        )
    }
    pub fn to_legacy_tx_with_payer_and_blockhash<T: AsSigner + Send + Sync>(
        &self,
        payer: T,
        recent_blockhash: Option<Hash>,
    ) -> Result<Transaction, OnDemandError> {
        if payer.as_signer().pubkey() != self.payer {
            return Err(OnDemandError::SolanaPayerMismatch);
        }

        TransactionBuilder::build_legacy_tx(
            self.payer,
            self.ixs()?,
            self.signers_with_payer(&payer)?,
            recent_blockhash.unwrap_or(self.recent_blockhash.unwrap_or_default()),
        )
    }
    pub fn to_legacy_tx_with_blockhash(
        &self,
        recent_blockhash: Option<Hash>,
    ) -> Result<Transaction, OnDemandError> {
        TransactionBuilder::build_legacy_tx(
            self.payer,
            self.ixs()?,
            self.signers()?,
            self.recent_blockhash
                .unwrap_or(recent_blockhash.unwrap_or_default()),
        )
    }

    pub async fn fetch_address_lookup_account(
        rpc: &RpcClient,
        address_lookup_table_pubkey: Pubkey,
    ) -> Result<AddressLookupTableAccount, OnDemandError> {
        let account = rpc
            .get_account(&address_lookup_table_pubkey)
            .await
            .map_err(|_e| OnDemandError::NetworkError)?;
        let address_lookup_table =
            AddressLookupTable::deserialize(&account.data).map_err(|_| OnDemandError::AccountDeserializeError)?;
        let address_lookup_table_account = AddressLookupTableAccount {
            key: address_lookup_table_pubkey,
            addresses: address_lookup_table.addresses.to_vec(),
        };
        Ok(address_lookup_table_account)
    }

    pub async fn fetch_multiple_address_lookup_accounts(
        rpc: &RpcClient,
        address_lookup_pubkeys: Vec<Pubkey>,
    ) -> Result<Vec<AddressLookupTableAccount>, OnDemandError> {
        let address_lookup_accounts: Vec<AddressLookupTableAccount> =
            if address_lookup_pubkeys.is_empty() {
                vec![]
            } else {
                let accounts = rpc
                    .get_multiple_accounts(&address_lookup_pubkeys)
                    .await
                    .map_err(|_| OnDemandError::NetworkError)?;

                let mut address_lookup_accounts: Vec<AddressLookupTableAccount> = vec![];
                for (i, account) in accounts.iter().enumerate() {
                    let account = account.as_ref().ok_or(OnDemandError::AccountNotFound)?;
                    let address_lookup_table = AddressLookupTable::deserialize(&account.data)
                        .map_err(|_| OnDemandError::AccountDeserializeError)?;
                    let address_lookup_table_account = AddressLookupTableAccount {
                        key: address_lookup_pubkeys[i],
                        addresses: address_lookup_table.addresses.to_vec(),
                    };
                    address_lookup_accounts.push(address_lookup_table_account);
                }

                address_lookup_accounts
            };

        Ok(address_lookup_accounts)
    }

    pub fn build_v0_tx(
        payer: Pubkey,
        ixs: Vec<Instruction>,
        signers: Vec<&dyn Signer>,
        address_lookup_accounts: Vec<AddressLookupTableAccount>,
        recent_blockhash: Hash,
    ) -> Result<VersionedTransaction, OnDemandError> {
        let v0_message =
            v0::Message::try_compile(&payer, &ixs, &address_lookup_accounts, recent_blockhash)
                .unwrap();

        let v0_tx = VersionedTransaction::try_new(VersionedMessage::V0(v0_message), &signers)
            .unwrap();

        Ok(v0_tx)
    }

    pub fn to_v0_tx(&self) -> Result<VersionedTransaction, OnDemandError> {
        TransactionBuilder::build_v0_tx(
            self.payer,
            self.ixs()?,
            self.signers()?,
            self.address_lookup_tables.clone(),
            self.recent_blockhash.unwrap_or_default(),
        )
    }

    pub fn to_v0_tx_with_payer<T: AsSigner + Send + Sync>(
        &self,
        payer: T,
    ) -> Result<VersionedTransaction, OnDemandError> {
        if payer.as_signer().pubkey() != self.payer {
            return Err(OnDemandError::SolanaPayerMismatch);
        }

        TransactionBuilder::build_v0_tx(
            self.payer,
            self.ixs()?,
            self.signers_with_payer(&payer)?,
            self.address_lookup_tables.clone(),
            self.recent_blockhash.unwrap_or_default(),
        )
        .into()
    }
}

impl TryFrom<TransactionBuilder> for Transaction {
    type Error = OnDemandError;

    fn try_from(builder: TransactionBuilder) -> Result<Self, Self::Error> {
        builder.to_legacy_tx()
    }
}

impl TryFrom<TransactionBuilder> for VersionedTransaction {
    type Error = OnDemandError;

    fn try_from(builder: TransactionBuilder) -> Result<Self, Self::Error> {
        builder.to_v0_tx()
    }
}
// Types for TypeState builder pattern

// #[derive(Default, Clone)]
// pub struct EmptyIxs;

// #[derive(Default, Clone)]
// pub struct TransactionIxs(Vec<Instruction>);

// #[derive(Default, Clone)]
// pub struct TransactionBuilderV0<U> {
//     payer: Pubkey,
//     ixs: U,
//     compute_units: Option<u32>,
//     priority_fees: Option<u64>,
//     recent_blockhash: Option<Hash>,
//     min_context_slot: Option<u64>,
//     address_lookup_tables: Vec<Pubkey>,
//     signers: Vec<Arc<dyn AsSigner + Send + Sync>>,
// }
// impl TransactionBuilderV0<EmptyIxs> {
//     pub fn new(payer: Pubkey) -> Self {
//         Self {
//             payer,
//             ..Default::default()
//         }
//     }

//     pub fn add_ix(&self, ix: Instruction) -> TransactionBuilderV0<TransactionIxs> {
//         TransactionBuilderV0 {
//             payer: self.payer,
//             ixs: TransactionIxs(vec![ix]),
//             compute_units: self.compute_units,
//             priority_fees: self.priority_fees,
//             recent_blockhash: self.recent_blockhash,
//             min_context_slot: self.min_context_slot,
//             address_lookup_tables: self.address_lookup_tables.clone(),
//             signers: self.signers.clone(),
//         }
//     }
// }

#[cfg(test)]
mod tests {
    use super::*;

    use solana_sdk::signer::keypair::Keypair;
    use tokio::sync::{OnceCell, RwLock};

    // #[test]
    // fn test_missing_signer() {
        // let program_id = Pubkey::new_unique();
        // let payer = Arc::new(Keypair::new());
        // let missing_signer = Arc::new(Keypair::new());
//
        // let ixn = Instruction::new_with_borsh(
            // program_id,
            // &vec![1u8, 2u8, 3u8, 4u8],
            // vec![
                // AccountMeta::new(payer.pubkey(), true),
                // AccountMeta::new_readonly(missing_signer.pubkey(), true), // missing signer here
                // AccountMeta::new_readonly(Pubkey::new_unique(), false),
            // ],
        // );
//
        // let mut tx = TransactionBuilder::new(payer.pubkey()).add_ix(ixn);
//
        // assert_eq!(tx.ixs().unwrap_or_default().len(), 1);
        // assert_eq!(tx.payer(), payer.pubkey());
        // assert!(!tx.has_payer());
//
        // // 1. Should fail with missing payer
        // let to_tx_result = tx.to_legacy_tx();
        // assert!(to_tx_result.is_err());
//
        // if let OnDemandError::SolanaPayerSignerMissing(expected_payer) =
            // to_tx_result.as_ref().unwrap_err()
        // {
            // if *expected_payer != payer.pubkey().to_string() {
                // panic!("Unexpected error message: {}", to_tx_result.unwrap_err())
            // }
        // } else {
            // panic!("Unexpected error: {:?}", to_tx_result.unwrap_err())
        // }
//
        // // 2. Should fail with missing signer
        // let to_tx_result = tx.to_legacy_tx_with_payer(payer.clone());
        // assert!(to_tx_result.is_err());
//
        // if let OnDemandError::SolanaMissingSigner(signer) = to_tx_result.as_ref().unwrap_err() {
            // if *signer != missing_signer.pubkey().to_string() {
                // panic!("Unexpected error message: {}", to_tx_result.unwrap_err())
            // }
        // } else {
            // panic!("Unexpected error: {:?}", to_tx_result.unwrap_err())
        // }
//
        // // 3. Should succeed with missing signer added
        // tx = tx.add_signer(missing_signer);
        // let to_tx_result = tx.to_legacy_tx_with_payer(payer.clone());
        // assert!(to_tx_result.is_ok());
    // }

    #[test]
    fn test_add_compute_budget_ixs() {
        let payer = Arc::new(Keypair::new());
        let payer_pubkey = payer.pubkey();

        let tx = TransactionBuilder::new_with_payer(payer.clone())
            .add_ix(Instruction::new_with_borsh(
                Pubkey::new_unique(),
                &vec![1u8, 2u8, 3u8, 4u8],
                vec![
                    AccountMeta::new(payer_pubkey, true),
                    AccountMeta::new_readonly(Pubkey::new_unique(), false),
                ],
            ))
            .set_compute_units(750_000);
        assert_eq!(tx.ixs().unwrap_or_default().len(), 2);

        let tx = TransactionBuilder::new_with_payer(payer.clone())
            .add_ix(Instruction::new_with_borsh(
                Pubkey::new_unique(),
                &vec![1u8, 2u8, 3u8, 4u8],
                vec![
                    AccountMeta::new(payer_pubkey, true),
                    AccountMeta::new_readonly(Pubkey::new_unique(), false),
                ],
            ))
            .set_priority_fees(500);
        assert_eq!(tx.ixs().unwrap_or_default().len(), 2);

        let tx = TransactionBuilder::new_with_payer(payer.clone())
            .add_ix(Instruction::new_with_borsh(
                Pubkey::new_unique(),
                &vec![1u8, 2u8, 3u8, 4u8],
                vec![
                    AccountMeta::new(payer_pubkey, true),
                    AccountMeta::new_readonly(Pubkey::new_unique(), false),
                ],
            ))
            .set_compute_units(750_000)
            .set_priority_fees(500);
        assert_eq!(tx.ixs().unwrap_or_default().len(), 3);
    }

    #[test]
    fn test_transaction_builder_with_arc_payer() {
        let payer = Arc::new(Keypair::new());

        let tx = TransactionBuilder::new_with_payer(payer.clone())
            .add_ix(Instruction::new_with_borsh(
                Pubkey::new_unique(),
                &vec![1u8, 2u8, 3u8, 4u8],
                vec![
                    AccountMeta::new(payer.signer_pubkey(), true),
                    AccountMeta::new_readonly(Pubkey::new_unique(), false),
                ],
            ))
            .set_compute_units(750_000);

        assert_eq!(tx.payer, payer.pubkey());
    }

    pub static PAYER_KEYPAIR: OnceCell<Arc<RwLock<Arc<Keypair>>>> = OnceCell::const_new();

    async fn get_payer_keypair() -> &'static Arc<RwLock<Arc<Keypair>>> {
        PAYER_KEYPAIR
            .get_or_init(|| async { Arc::new(RwLock::new(Arc::new(Keypair::new()))) })
            .await
    }

    #[tokio::test]
    async fn test_transaction_builder_with_rwlock_payer() {
        let payer = get_payer_keypair().await;
        let payer_arc = payer.read().await.clone();

        let tx = TransactionBuilder::new_with_payer(payer_arc.clone())
            .add_ix(Instruction::new_with_borsh(
                Pubkey::new_unique(),
                &vec![1u8, 2u8, 3u8, 4u8],
                vec![
                    AccountMeta::new(payer_arc.signer_pubkey(), true),
                    AccountMeta::new_readonly(Pubkey::new_unique(), false),
                ],
            ))
            .set_compute_units(750_000);

        assert_eq!(tx.payer, payer_arc.pubkey());
    }

    #[tokio::test]
    async fn test_transaction_builder_with_arcswap_payer() {
        let payer = arc_swap::ArcSwap::new(Arc::new(Keypair::new()));
        let payer_arc = payer.load();

        let tx = TransactionBuilder::new_with_payer(payer_arc.clone())
            .add_ix(Instruction::new_with_borsh(
                Pubkey::new_unique(),
                &vec![1u8, 2u8, 3u8, 4u8],
                vec![
                    AccountMeta::new(payer_arc.signer_pubkey(), true),
                    AccountMeta::new_readonly(Pubkey::new_unique(), false),
                ],
            ))
            .set_compute_units(750_000);

        assert_eq!(tx.payer, payer_arc.pubkey());
    }
}