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
//! Transaction builder utilities for Solana
use anyhow::Result;
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_sdk::{
account::Account,
hash::Hash,
instruction::Instruction,
message::{v0, AddressLookupTableAccount, Message, VersionedMessage},
pubkey::Pubkey,
signature::{Keypair, Signature, Signer},
transaction::{Transaction, VersionedTransaction},
};
/// Builder for constructing Solana transactions from instructions and signers
///
/// This struct is similar to transaction result types from various Solana
/// program SDKs, containing the instructions and additional signers needed to
/// build and execute a transaction.
#[derive(Debug)]
pub struct TransactionBuilder {
/// A vector of `Instruction` objects required to execute the transaction.
pub instructions: Vec<Instruction>,
/// A vector of `Keypair` objects representing additional signers required
/// for the instructions.
pub additional_signers: Vec<Keypair>,
/// A vector of `AddressLookupTableAccount` objects for V0 transactions.
/// Address lookup tables allow transactions to reference more accounts than
/// the legacy format.
pub address_lookup_tables: Vec<AddressLookupTableAccount>,
}
impl TransactionBuilder {
/// Create a new empty `TransactionBuilder`
pub fn new() -> Self {
Self {
instructions: Vec::new(),
additional_signers: Vec::new(),
address_lookup_tables: Vec::new(),
}
}
/// Create a new `TransactionBuilder` with the given instructions and
/// signers
pub fn with_components(
instructions: Vec<Instruction>,
additional_signers: Vec<Keypair>,
) -> Self {
Self { instructions, additional_signers, address_lookup_tables: Vec::new() }
}
/// Add an instruction to the builder
pub fn add_instruction(&mut self, instruction: Instruction) -> &mut Self {
self.instructions.push(instruction);
self
}
/// Add multiple instructions to the builder
pub fn add_instructions(&mut self, instructions: Vec<Instruction>) -> &mut Self {
self.instructions.extend(instructions);
self
}
/// Add an additional signer to the builder
pub fn add_signer(&mut self, signer: Keypair) -> &mut Self {
self.additional_signers.push(signer);
self
}
/// Add multiple additional signers to the builder
pub fn add_signers(&mut self, signers: Vec<Keypair>) -> &mut Self {
self.additional_signers.extend(signers);
self
}
/// Add an address lookup table to the builder
///
/// Address lookup tables allow V0 transactions to reference more accounts
/// than the legacy format by storing account addresses in on-chain lookup
/// tables.
///
/// # Arguments
/// * `lookup_table` - The address lookup table account to add
///
/// # Returns
/// `&mut Self` for method chaining
pub fn add_lookup_table(&mut self, lookup_table: AddressLookupTableAccount) -> &mut Self {
self.address_lookup_tables.push(lookup_table);
self
}
/// Add multiple address lookup tables to the builder
///
/// # Arguments
/// * `lookup_tables` - A vector of address lookup table accounts to add
///
/// # Returns
/// `&mut Self` for method chaining
pub fn add_lookup_tables(
&mut self,
lookup_tables: Vec<AddressLookupTableAccount>,
) -> &mut Self {
self.address_lookup_tables.extend(lookup_tables);
self
}
/// Add an address lookup table by fetching it from RPC using its address
///
/// This method fetches the lookup table from the RPC and adds it to the
/// builder.
///
/// # Arguments
/// * `rpc_client` - The RPC client to fetch the lookup table from
/// * `lookup_table_pubkey` - The public key of the lookup table to fetch
/// and add
///
/// # Returns
/// `&mut Self` for method chaining
///
/// # Example
/// ```ignore
/// use waterpump_solana_core::transaction_builder::TransactionBuilder;
/// use solana_client::nonblocking::rpc_client::RpcClient;
/// use solana_sdk::pubkey::Pubkey;
///
/// # async fn example() -> anyhow::Result<()> {
/// let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com".to_string());
/// let lookup_table_pubkey = Pubkey::from_str("...")?;
///
/// let mut builder = TransactionBuilder::new();
/// builder.add_lookup_table_by_address(&rpc_client, &lookup_table_pubkey).await?;
/// # Ok(())
/// # }
/// ```
pub async fn add_lookup_table_by_address(
&mut self,
rpc_client: &RpcClient,
lookup_table_pubkey: &Pubkey,
) -> Result<&mut Self> {
let lookup_table = Self::fetch_lookup_table(rpc_client, lookup_table_pubkey).await?;
self.address_lookup_tables.push(lookup_table);
Ok(self)
}
/// Add multiple address lookup tables by fetching them from RPC using their
/// addresses
///
/// This method fetches multiple lookup tables from the RPC in a single
/// batch call and adds them to the builder.
///
/// # Arguments
/// * `rpc_client` - The RPC client to fetch the lookup tables from
/// * `lookup_table_pubkeys` - A slice of public keys of the lookup tables
/// to fetch and add
///
/// # Returns
/// `&mut Self` for method chaining
///
/// # Example
/// ```ignore
/// use waterpump_solana_core::transaction_builder::TransactionBuilder;
/// use solana_client::nonblocking::rpc_client::RpcClient;
/// use solana_sdk::pubkey::Pubkey;
///
/// # async fn example() -> anyhow::Result<()> {
/// let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com".to_string());
/// let lookup_table_pubkeys = vec![/* lookup table pubkeys */];
///
/// let mut builder = TransactionBuilder::new();
/// builder.add_lookup_tables_by_addresses(&rpc_client, &lookup_table_pubkeys).await?;
/// # Ok(())
/// # }
/// ```
pub async fn add_lookup_tables_by_addresses(
&mut self,
rpc_client: &RpcClient,
lookup_table_pubkeys: &[Pubkey],
) -> Result<&mut Self> {
let lookup_tables = Self::fetch_lookup_tables(rpc_client, lookup_table_pubkeys).await?;
self.address_lookup_tables.extend(lookup_tables);
Ok(self)
}
/// Build a versioned transaction with the given fee payer
///
/// # Arguments
/// * `fee_payer` - The keypair that will pay for the transaction fees
///
/// # Returns
/// A signed `VersionedTransaction` ready to be sent
///
/// # Note
/// This method uses a default blockhash. For production use, prefer
/// `build_transaction_with_blockhash` with a recent blockhash from RPC,
/// or use `send`/`send_and_confirm` which fetch the latest blockhash
/// automatically.
pub fn build_transaction(&self, fee_payer: &Keypair) -> Result<VersionedTransaction> {
self.build_transaction_with_blockhash(fee_payer, &Hash::default())
}
/// Build a versioned transaction with the given fee payer and blockhash
///
/// # Arguments
/// * `fee_payer` - The keypair that will pay for the transaction fees
/// * `recent_blockhash` - The recent blockhash to use for the transaction
///
/// # Returns
/// A signed `VersionedTransaction` ready to be sent
///
/// # Errors
/// Returns an error if:
/// - The V0 message fails to compile
/// - The versioned transaction fails to create or sign
pub fn build_transaction_with_blockhash(
&self,
fee_payer: &Keypair,
recent_blockhash: &Hash,
) -> Result<VersionedTransaction> {
// Collect all signers (fee payer + additional signers)
let mut signers: Vec<&Keypair> = vec![fee_payer];
signers.extend(self.additional_signers.iter());
// Build a V0 message (supports address lookup tables)
let message = v0::Message::try_compile(
&fee_payer.pubkey(),
&self.instructions,
&self.address_lookup_tables,
*recent_blockhash,
)
.map_err(|e| anyhow::anyhow!("Failed to compile V0 message: {}", e))?;
// Create and sign the versioned transaction
VersionedTransaction::try_new(VersionedMessage::V0(message), &signers)
.map_err(|e| anyhow::anyhow!("Failed to create VersionedTransaction: {}", e))
}
/// Build a legacy transaction with the given fee payer
///
/// Legacy transactions don't support address lookup tables and are limited
/// to 64 accounts. Use versioned transactions if you need more accounts
/// or address lookup tables.
///
/// # Arguments
/// * `fee_payer` - The keypair that will pay for the transaction fees
///
/// # Returns
/// A signed `Transaction` ready to be sent
///
/// # Note
/// This method uses a default blockhash. For production use, prefer
/// `build_legacy_transaction_with_blockhash` with a recent blockhash from
/// RPC, or use `send`/`send_and_confirm` which fetch the latest
/// blockhash automatically.
pub fn build_legacy_transaction(&self, fee_payer: &Keypair) -> Transaction {
self.build_legacy_transaction_with_blockhash(fee_payer, &Hash::default())
}
/// Build a legacy transaction with the given fee payer and blockhash
///
/// Legacy transactions don't support address lookup tables and are limited
/// to 64 accounts. Use versioned transactions if you need more accounts
/// or address lookup tables.
///
/// # Arguments
/// * `fee_payer` - The keypair that will pay for the transaction fees
/// * `recent_blockhash` - The recent blockhash to use for the transaction
///
/// # Returns
/// A signed `Transaction` ready to be sent
///
/// # Panics
/// Panics if the transaction requires more than 64 accounts (legacy limit)
pub fn build_legacy_transaction_with_blockhash(
&self,
fee_payer: &Keypair,
recent_blockhash: &Hash,
) -> Transaction {
// Collect all signers (fee payer + additional signers)
let mut signers: Vec<&Keypair> = vec![fee_payer];
signers.extend(self.additional_signers.iter());
// Build a legacy message (no address lookup tables)
let message = Message::new(&self.instructions, Some(&fee_payer.pubkey()));
// Create and sign the legacy transaction
let mut transaction = Transaction::new_unsigned(message);
transaction.sign(&signers, *recent_blockhash);
transaction
}
/// Build a versioned transaction with the given fee payer pubkey
///
/// This method is useful when the fee payer keypair is not available,
/// but you still want to construct the transaction structure.
/// Additional signers will be used to sign the transaction, but the fee
/// payer must sign it separately.
///
/// # Arguments
/// * `fee_payer_pubkey` - The public key of the fee payer
///
/// # Returns
/// A `VersionedTransaction` signed by additional signers (if any), but
/// still needs to be signed by the fee payer
///
/// # Errors
/// Returns an error if:
/// - The V0 message fails to compile
/// - The versioned transaction fails to create
/// - There are no additional signers (fee payer keypair is not available)
pub fn build_partially_signed_transaction(
&self,
fee_payer_pubkey: &Pubkey,
) -> Result<VersionedTransaction> {
// Build a V0 message (supports address lookup tables)
// Note: Using default blockhash for partially signed transactions
let message = v0::Message::try_compile(
fee_payer_pubkey,
&self.instructions,
&self.address_lookup_tables,
Hash::default(),
)
.map_err(|e| anyhow::anyhow!("Failed to compile V0 message: {}", e))?;
let versioned_message = VersionedMessage::V0(message);
// Sign with additional signers if any
if !self.additional_signers.is_empty() {
let signers: Vec<&Keypair> = self.additional_signers.iter().collect();
let tx = VersionedTransaction::try_new(versioned_message, &signers)
.map_err(|e| anyhow::anyhow!("Failed to create VersionedTransaction: {}", e))?;
Ok(tx)
} else {
Err(anyhow::anyhow!(
"build_partially_signed_transaction requires at least one additional signer when \
fee payer keypair is not available. Use build_transaction() if you have the fee \
payer keypair."
))
}
}
/// Get the number of instructions
pub fn instruction_count(&self) -> usize { self.instructions.len() }
/// Get the number of additional signers
pub fn signer_count(&self) -> usize { self.additional_signers.len() }
/// Check if the builder is empty (no instructions)
pub fn is_empty(&self) -> bool { self.instructions.is_empty() }
/// Consume the builder and return its components
pub fn into_components(
self,
) -> (Vec<Instruction>, Vec<Keypair>, Vec<AddressLookupTableAccount>) {
(self.instructions, self.additional_signers, self.address_lookup_tables)
}
/// Merge another `TransactionBuilder` into this one
///
/// This method takes all instructions, signers, and lookup tables from the
/// other builder and adds them to this builder. The other builder is
/// consumed in the process.
///
/// # Arguments
/// * `other` - The `TransactionBuilder` to merge into this one
///
/// # Returns
/// `&mut Self` for method chaining
///
/// # Example
/// ```ignore
/// use waterpump_solana_core::transaction_builder::TransactionBuilder;
///
/// let mut builder1 = TransactionBuilder::new();
/// builder1.add_instruction(instruction1);
///
/// let mut builder2 = TransactionBuilder::new();
/// builder2.add_instruction(instruction2);
///
/// builder1.merge(builder2); // builder1 now contains both instructions
/// ```
pub fn merge(&mut self, other: TransactionBuilder) -> &mut Self {
self.instructions.extend(other.instructions);
self.additional_signers.extend(other.additional_signers);
self.address_lookup_tables.extend(other.address_lookup_tables);
self
}
/// Create a new `TransactionBuilder` by merging two builders
///
/// This is a static method that takes two builders and creates a new one
/// containing all instructions and signers from both. Both input builders
/// are consumed.
///
/// # Arguments
/// * `first` - The first `TransactionBuilder` to merge
/// * `second` - The second `TransactionBuilder` to merge
///
/// # Returns
/// A new `TransactionBuilder` containing all instructions and signers from
/// both builders
///
/// # Example
/// ```ignore
/// use waterpump_solana_core::transaction_builder::TransactionBuilder;
///
/// let builder1 = TransactionBuilder::new();
/// let builder2 = TransactionBuilder::new();
///
/// let merged = TransactionBuilder::merge_builders(builder1, builder2);
/// ```
pub fn merge_builders(
mut first: TransactionBuilder,
second: TransactionBuilder,
) -> TransactionBuilder {
first.merge(second);
first
}
/// Build and send a transaction, then wait for confirmation
///
/// This method:
/// 1. Gets the latest blockhash from the RPC client
/// 2. Builds a versioned transaction with the fee payer and recent
/// blockhash
/// 3. Sends it to the network via the RPC client
/// 4. Waits for confirmation
/// 5. Returns the transaction signature
///
/// # Arguments
/// * `rpc_client` - The RPC client to use for sending the transaction
/// * `fee_payer` - The keypair that will pay for the transaction fees
///
/// # Returns
/// The transaction signature if successful
pub async fn send_and_confirm(
&self,
rpc_client: &RpcClient,
fee_payer: &Keypair,
) -> Result<Signature> {
// Get the latest blockhash
let recent_blockhash = rpc_client
.get_latest_blockhash()
.await
.map_err(|e| anyhow::anyhow!("Failed to get latest blockhash: {}", e))?;
// Build transaction with the recent blockhash
let transaction = self.build_transaction_with_blockhash(fee_payer, &recent_blockhash)?;
let signature = rpc_client
.send_and_confirm_transaction(&transaction)
.await
.map_err(|e| anyhow::anyhow!("Failed to send and confirm transaction: {}", e))?;
Ok(signature)
}
/// Build and send a transaction
///
/// This method:
/// 1. Gets the latest blockhash from the RPC client
/// 2. Builds a versioned transaction with the fee payer and recent
/// blockhash
/// 3. Sends it to the network via the RPC client
/// 4. Returns the transaction signature
///
/// # Arguments
/// * `rpc_client` - The RPC client to use for sending the transaction
/// * `fee_payer` - The keypair that will pay for the transaction fees
///
/// # Returns
/// The transaction signature if successful
pub async fn send(&self, rpc_client: &RpcClient, fee_payer: &Keypair) -> Result<Signature> {
// Get the latest blockhash
let recent_blockhash = rpc_client
.get_latest_blockhash()
.await
.map_err(|e| anyhow::anyhow!("Failed to get latest blockhash: {}", e))?;
// Build transaction with the recent blockhash
let transaction = self.build_transaction_with_blockhash(fee_payer, &recent_blockhash)?;
let signature = rpc_client
.send_transaction(&transaction)
.await
.map_err(|e| anyhow::anyhow!("Failed to send transaction: {}", e))?;
Ok(signature)
}
/// Simulate a transaction without sending it to the network
///
/// This method:
/// 1. Gets the latest blockhash from the RPC client
/// 2. Builds a versioned transaction with the fee payer and recent
/// blockhash
/// 3. Simulates the transaction execution via the RPC client
/// 4. Returns the simulation result
///
/// # Arguments
/// * `rpc_client` - The RPC client to use for simulating the transaction
/// * `fee_payer` - The keypair that will pay for the transaction fees
///
/// # Returns
/// The simulation result containing execution status, logs, and compute
/// units used
pub async fn simulate(
&self,
rpc_client: &RpcClient,
fee_payer: &Keypair,
) -> Result<solana_client::rpc_response::RpcSimulateTransactionResult> {
use solana_client::rpc_config::RpcSimulateTransactionConfig;
// Get the latest blockhash
let recent_blockhash = rpc_client
.get_latest_blockhash()
.await
.map_err(|e| anyhow::anyhow!("Failed to get latest blockhash: {}", e))?;
// Build transaction with the recent blockhash
let transaction = self.build_transaction_with_blockhash(fee_payer, &recent_blockhash)?;
// Simulate the transaction with default config
let config = RpcSimulateTransactionConfig::default();
let response = rpc_client
.simulate_transaction_with_config(&transaction, config)
.await
.map_err(|e| anyhow::anyhow!("Failed to simulate transaction: {}", e))?;
if let Some(err) = response.value.err {
return Err(anyhow::anyhow!("Failed to simulate transaction: {}", err));
}
Ok(response.value)
}
}
impl Default for TransactionBuilder {
fn default() -> Self { Self::new() }
}
impl From<(Vec<Instruction>, Vec<Keypair>)> for TransactionBuilder {
fn from((instructions, additional_signers): (Vec<Instruction>, Vec<Keypair>)) -> Self {
Self::with_components(instructions, additional_signers)
}
}
/// Helper functions for working with address lookup tables
impl TransactionBuilder {
/// Fetch an address lookup table from RPC and create an
/// AddressLookupTableAccount
///
/// This function fetches the lookup table account data from the Solana
/// network, deserializes it, and creates an `AddressLookupTableAccount`
/// that can be used in V0 transactions.
///
/// # Arguments
/// * `rpc_client` - The RPC client to fetch the lookup table from
/// * `lookup_table_pubkey` - The public key of the address lookup table
///
/// # Returns
/// An `AddressLookupTableAccount` containing the lookup table's key and
/// addresses
///
/// # Example
/// ```ignore
/// use waterpump_solana_core::transaction_builder::TransactionBuilder;
/// use solana_client::nonblocking::rpc_client::RpcClient;
/// use solana_sdk::pubkey::Pubkey;
///
/// # async fn example() -> anyhow::Result<()> {
/// let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com".to_string());
/// let lookup_table_pubkey = Pubkey::from_str("...")?;
///
/// let lookup_table_account = TransactionBuilder::fetch_lookup_table(
/// &rpc_client,
/// &lookup_table_pubkey,
/// ).await?;
///
/// let mut builder = TransactionBuilder::new();
/// builder.add_lookup_table(lookup_table_account);
/// # Ok(())
/// # }
/// ```
/// Parse AddressLookupTable account data
///
/// This is a helper function to parse raw account data into an
/// AddressLookupTableAccount. Structure (based on
/// solana-program/src/address_lookup_table/state.rs):
/// - Discriminator: 1 byte (0x01 for AddressLookupTable)
/// - Authority: 32 bytes (Pubkey)
/// - Deactivation slot: 8 bytes (u64, little-endian)
/// - Last extended slot: 8 bytes (u64, little-endian)
/// - Last extended slot start index: 4 bytes (u32, little-endian)
/// - Padding: 4 bytes
/// - Addresses: variable length, each Pubkey is 32 bytes
fn parse_lookup_table_account(
pubkey: &Pubkey,
account: &Account,
) -> Result<AddressLookupTableAccount> {
let data = &account.data;
if data.is_empty() {
return Err(anyhow::anyhow!("Lookup table account {} data is empty", pubkey));
}
// Check discriminator (should be 0x01)
if data[0] != 0x01 {
return Err(anyhow::anyhow!(
"Invalid lookup table discriminator for {}: expected 0x01, got 0x{:02x}",
pubkey,
data[0]
));
}
// Header size: 1 (discriminator) + 32 (authority) + 8 + 8 + 4 + 4 = 57 bytes
const HEADER_SIZE: usize = 1 + 32 + 8 + 8 + 4 + 4;
if data.len() < HEADER_SIZE {
return Err(anyhow::anyhow!(
"Lookup table account {} data too short: {} bytes, expected at least {}",
pubkey,
data.len(),
HEADER_SIZE
));
}
// Extract addresses (each Pubkey is 32 bytes)
// Account data may have padding at the end, so we parse only complete 32-byte
// chunks
let addresses_data = &data[HEADER_SIZE..];
let num_complete_addresses = addresses_data.len() / 32;
if num_complete_addresses == 0 {
return Err(anyhow::anyhow!(
"No complete addresses found in lookup table {}: {} bytes remaining after header",
pubkey,
addresses_data.len()
));
}
let mut addresses = Vec::with_capacity(num_complete_addresses);
for chunk in addresses_data.chunks_exact(32).take(num_complete_addresses) {
let address = Pubkey::try_from(chunk).map_err(|e| {
anyhow::anyhow!("Failed to parse pubkey from lookup table {}: {}", pubkey, e)
})?;
addresses.push(address);
}
Ok(AddressLookupTableAccount { key: *pubkey, addresses })
}
/// Fetch a single address lookup table from RPC
///
/// This is a convenience wrapper around `fetch_lookup_tables`.
///
/// # Arguments
/// * `rpc_client` - The RPC client to fetch the lookup table from
/// * `lookup_table_pubkey` - The public key of the lookup table to fetch
///
/// # Returns
/// An `AddressLookupTableAccount` object
///
/// # Example
/// ```ignore
/// use waterpump_solana_core::transaction_builder::TransactionBuilder;
/// use solana_client::nonblocking::rpc_client::RpcClient;
///
/// # async fn example() -> anyhow::Result<()> {
/// let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com".to_string());
/// let pubkey = /* lookup table pubkey */;
///
/// let lookup_table = TransactionBuilder::fetch_lookup_table(
/// &rpc_client,
/// &pubkey,
/// ).await?;
///
/// let mut builder = TransactionBuilder::new();
/// builder.add_lookup_table(lookup_table);
/// # Ok(())
/// # }
/// ```
pub async fn fetch_lookup_table(
rpc_client: &RpcClient,
lookup_table_pubkey: &Pubkey,
) -> Result<AddressLookupTableAccount> {
let mut tables = Self::fetch_lookup_tables(rpc_client, &[*lookup_table_pubkey]).await?;
tables
.pop()
.ok_or_else(|| anyhow::anyhow!("Failed to fetch lookup table {}", lookup_table_pubkey))
}
/// Fetch multiple address lookup tables from RPC
///
/// This function uses `get_multiple_accounts` for efficient batch fetching.
///
/// # Arguments
/// * `rpc_client` - The RPC client to fetch the lookup tables from
/// * `lookup_table_pubkeys` - A slice of public keys for the lookup tables
/// to fetch
///
/// # Returns
/// A vector of `AddressLookupTableAccount` objects
///
/// # Example
/// ```ignore
/// use waterpump_solana_core::transaction_builder::TransactionBuilder;
/// use solana_client::nonblocking::rpc_client::RpcClient;
///
/// # async fn example() -> anyhow::Result<()> {
/// let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com".to_string());
/// let pubkeys = vec![/* lookup table pubkeys */];
///
/// let lookup_tables = TransactionBuilder::fetch_lookup_tables(
/// &rpc_client,
/// &pubkeys,
/// ).await?;
///
/// let mut builder = TransactionBuilder::new();
/// builder.add_lookup_tables(lookup_tables);
/// # Ok(())
/// # }
/// ```
pub async fn fetch_lookup_tables(
rpc_client: &RpcClient,
lookup_table_pubkeys: &[Pubkey],
) -> Result<Vec<AddressLookupTableAccount>> {
if lookup_table_pubkeys.is_empty() {
return Ok(Vec::new());
}
// Fetch all accounts in a single RPC call
let accounts = rpc_client
.get_multiple_accounts(lookup_table_pubkeys)
.await
.map_err(|e| anyhow::anyhow!("Failed to fetch lookup table accounts: {}", e))?;
// Parse each account into AddressLookupTableAccount
let mut lookup_tables = Vec::new();
for (i, account_opt) in accounts.iter().enumerate() {
let pubkey = &lookup_table_pubkeys[i];
match account_opt {
Some(account) => {
let lookup_table = Self::parse_lookup_table_account(pubkey, account)?;
lookup_tables.push(lookup_table);
}
None => {
return Err(anyhow::anyhow!("Lookup table account {} not found", pubkey));
}
}
}
Ok(lookup_tables)
}
}