forked from solana-foundation/surfpool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocker.rs
More file actions
4872 lines (4379 loc) · 184 KB
/
locker.rs
File metadata and controls
4872 lines (4379 loc) · 184 KB
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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
collections::{BTreeMap, HashMap, HashSet},
sync::Arc,
time::SystemTime,
};
use bincode::serialized_size;
use crossbeam_channel::{Receiver, Sender};
use itertools::Itertools;
use litesvm::types::{
FailedTransactionMetadata, SimulatedTransactionInfo, TransactionMetadata, TransactionResult,
};
use solana_account::{Account, ReadableAccount};
use solana_account_decoder::{
UiAccount, UiAccountEncoding, UiDataSliceConfig,
parse_account_data::AccountAdditionalDataV3,
parse_bpf_loader::{BpfUpgradeableLoaderAccountType, UiProgram, parse_bpf_upgradeable_loader},
parse_token::UiTokenAmount,
};
use solana_address_lookup_table_interface::state::AddressLookupTable;
use solana_client::{
rpc_client::SerializableTransaction,
rpc_config::{
RpcAccountInfoConfig, RpcBlockConfig, RpcLargestAccountsConfig, RpcLargestAccountsFilter,
RpcSignaturesForAddressConfig, RpcTransactionConfig, RpcTransactionLogsFilter,
},
rpc_filter::RpcFilterType,
rpc_request::TokenAccountsFilter,
rpc_response::{
RpcAccountBalance, RpcConfirmedTransactionStatusWithSignature, RpcKeyedAccount,
RpcLogsResponse, RpcTokenAccountBalance,
},
};
use solana_clock::{Clock, Slot, UnixTimestamp};
use solana_commitment_config::{CommitmentConfig, CommitmentLevel};
use solana_epoch_info::EpochInfo;
use solana_epoch_schedule::EpochSchedule;
use solana_hash::Hash;
use solana_loader_v3_interface::{get_program_data_address, state::UpgradeableLoaderState};
use solana_message::{
Message, SimpleAddressLoader, VersionedMessage,
compiled_instruction::CompiledInstruction,
v0::{LoadedAddresses, MessageAddressTableLookup},
};
use solana_pubkey::Pubkey;
use solana_rpc_client_api::response::SlotInfo;
use solana_signature::Signature;
use solana_transaction::{sanitized::SanitizedTransaction, versioned::VersionedTransaction};
use solana_transaction_error::TransactionError;
use solana_transaction_status::{
EncodedConfirmedTransactionWithStatusMeta,
TransactionConfirmationStatus as SolanaTransactionConfirmationStatus, UiConfirmedBlock,
UiTransactionEncoding,
};
use surfpool_types::{
AccountSnapshot, ComputeUnitsEstimationResult, ExecutionCapture, ExportSnapshotConfig, Idl,
KeyedProfileResult, ProfileResult, RpcProfileResultConfig, RunbookExecutionStatusReport,
SimnetCommand, SimnetEvent, TransactionConfirmationStatus, TransactionStatusEvent,
UiKeyedProfileResult, UuidOrSignature, VersionedIdl,
};
use tokio::sync::RwLock;
use txtx_addon_kit::indexmap::IndexSet;
use uuid::Uuid;
use super::{
AccountFactory, GetAccountResult, GetTransactionResult, GeyserEvent, SignatureSubscriptionType,
SurfnetSvm, remote::SurfnetRemoteClient,
};
use crate::{
error::{SurfpoolError, SurfpoolResult},
helpers::time_travel::calculate_time_travel_clock,
rpc::utils::{convert_transaction_metadata_from_canonical, verify_pubkey},
surfnet::{FINALIZATION_SLOT_THRESHOLD, SLOTS_PER_EPOCH},
types::{
GeyserAccountUpdate, RemoteRpcResult, SurfnetTransactionStatus, TimeTravelConfig,
TokenAccount, TransactionLoadedAddresses, TransactionWithStatusMeta,
},
};
enum ProcessTransactionResult {
Success(TransactionMetadata),
SimulationFailure(FailedTransactionMetadata),
ExecutionFailure(FailedTransactionMetadata),
}
pub struct SvmAccessContext<T> {
pub slot: Slot,
pub latest_epoch_info: EpochInfo,
pub latest_blockhash: Hash,
pub inner: T,
}
impl<T> SvmAccessContext<T> {
pub fn new(slot: Slot, latest_epoch_info: EpochInfo, latest_blockhash: Hash, inner: T) -> Self {
Self {
slot,
latest_blockhash,
latest_epoch_info,
inner,
}
}
pub fn inner(&self) -> &T {
&self.inner
}
pub fn with_new_value<N>(&self, inner: N) -> SvmAccessContext<N> {
SvmAccessContext {
slot: self.slot,
latest_blockhash: self.latest_blockhash,
latest_epoch_info: self.latest_epoch_info.clone(),
inner,
}
}
}
pub type SurfpoolContextualizedResult<T> = SurfpoolResult<SvmAccessContext<T>>;
/// Helper function to apply an override to a JSON value using dot notation path
///
/// # Arguments
/// * `json` - The JSON value to modify
/// * `path` - Dot-separated path to the field (e.g., "price_message.price")
/// * `value` - The new value to set
///
/// # Returns
/// Result indicating success or error
pub struct SurfnetSvmLocker(pub Arc<RwLock<SurfnetSvm>>);
impl Clone for SurfnetSvmLocker {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
/// Functions for reading and writing to the underlying SurfnetSvm instance
impl SurfnetSvmLocker {
/// Explicitly shutdown the SVM, performing cleanup like WAL checkpoint for SQLite.
/// This should be called before the application exits to ensure data is persisted.
pub fn shutdown(&self) {
let read_lock = self.0.clone();
tokio::task::block_in_place(move || {
let read_guard = read_lock.blocking_read();
read_guard.shutdown();
});
}
/// Executes a read-only operation on the underlying `SurfnetSvm` by acquiring a blocking read lock.
/// Accepts a closure that receives a shared reference to `SurfnetSvm` and returns a value.
///
/// # Returns
/// The result produced by the closure.
pub fn with_svm_reader<T, F>(&self, reader: F) -> T
where
F: FnOnce(&SurfnetSvm) -> T + Send + Sync,
{
let read_lock = self.0.clone();
tokio::task::block_in_place(move || {
let read_guard = read_lock.blocking_read();
reader(&read_guard)
})
}
/// Executes a read-only operation and wraps the result in `SvmAccessContext`, capturing
/// slot, epoch info, and blockhash along with the closure's result.
fn with_contextualized_svm_reader<T, F>(&self, reader: F) -> SvmAccessContext<T>
where
F: Fn(&SurfnetSvm) -> T + Send + Sync,
T: Send + 'static,
{
let read_lock = self.0.clone();
tokio::task::block_in_place(move || {
let read_guard = read_lock.blocking_read();
let res = reader(&read_guard);
SvmAccessContext::new(
read_guard.get_latest_absolute_slot(),
read_guard.latest_epoch_info(),
read_guard.latest_blockhash(),
res,
)
})
}
/// Executes a write operation on the underlying `SurfnetSvm` by acquiring a blocking write lock.
/// Accepts a closure that receives a mutable reference to `SurfnetSvm` and returns a value.
///
/// # Returns
/// The result produced by the closure.
pub fn with_svm_writer<T, F>(&self, writer: F) -> T
where
F: FnOnce(&mut SurfnetSvm) -> T + Send + Sync,
T: Send + 'static,
{
let write_lock = self.0.clone();
tokio::task::block_in_place(move || {
let mut write_guard = write_lock.blocking_write();
writer(&mut write_guard)
})
}
}
/// Functions for creating and initializing the underlying SurfnetSvm instance
impl SurfnetSvmLocker {
/// Constructs a new `SurfnetSvmLocker` wrapping the given `SurfnetSvm` instance.
pub fn new(svm: SurfnetSvm) -> Self {
Self(Arc::new(RwLock::new(svm)))
}
/// Initializes the locked `SurfnetSvm` by fetching or defaulting epoch info,
/// then calling its `initialize` method. Returns the epoch info on success.
pub async fn initialize(
&self,
slot_time: u64,
remote_ctx: &Option<SurfnetRemoteClient>,
do_profile_instructions: bool,
log_bytes_limit: Option<usize>,
) -> SurfpoolResult<EpochInfo> {
let (mut epoch_info, epoch_schedule) = if let Some(remote_client) = remote_ctx {
let epoch_info = remote_client.get_epoch_info().await?;
let epoch_schedule = remote_client.get_epoch_schedule().await?;
(epoch_info, epoch_schedule)
} else {
let epoch_schedule = EpochSchedule::without_warmup();
(
EpochInfo {
epoch: 0,
slot_index: 0,
slots_in_epoch: epoch_schedule.slots_per_epoch,
absolute_slot: FINALIZATION_SLOT_THRESHOLD,
block_height: FINALIZATION_SLOT_THRESHOLD,
transaction_count: None,
},
epoch_schedule,
)
};
epoch_info.transaction_count = None;
self.with_svm_writer(|svm_writer| {
svm_writer.initialize(
epoch_info.clone(),
epoch_schedule.clone(),
slot_time,
remote_ctx,
do_profile_instructions,
log_bytes_limit,
);
});
Ok(epoch_info)
}
}
/// Functions for getting accounts from the underlying SurfnetSvm instance or remote client
impl SurfnetSvmLocker {
/// Retrieves a local account from the SVM cache, returning a contextualized result.
pub fn get_account_local(&self, pubkey: &Pubkey) -> SvmAccessContext<GetAccountResult> {
self.with_contextualized_svm_reader(|svm_reader| {
let result = svm_reader.inner.get_account_result(pubkey).unwrap();
if result.is_none() {
return match svm_reader.get_account_from_feature_set(pubkey) {
Some(account) => {
GetAccountResult::FoundAccount(
*pubkey, account,
// mark this as an account to insert into the SVM, since the feature is activated and LiteSVM doesn't
// automatically insert activated feature accounts
// TODO: mark as false once https://github.com/LiteSVM/litesvm/pull/308 is released
true,
)
}
None => GetAccountResult::None(*pubkey),
};
} else {
return result;
}
})
}
/// Attempts local retrieval, then fetches from remote if missing, returning a contextualized result.
///
/// Does not fetch from remote if the account has been explicitly closed by the user.
pub async fn get_account_local_then_remote(
&self,
client: &SurfnetRemoteClient,
pubkey: &Pubkey,
commitment_config: CommitmentConfig,
) -> SurfpoolContextualizedResult<GetAccountResult> {
let result = self.get_account_local(pubkey);
if result.inner.is_none() {
// Check if the account has been explicitly closed - if so, don't fetch from remote
let is_closed = self.get_closed_accounts().contains(pubkey);
if !is_closed {
let remote_account = client.get_account(pubkey, commitment_config).await?;
Ok(result.with_new_value(remote_account))
} else {
Ok(result)
}
} else {
Ok(result)
}
}
/// Retrieves an account, using local or remote based on context, applying a default factory if provided.
pub async fn get_account(
&self,
remote_ctx: &Option<(SurfnetRemoteClient, CommitmentConfig)>,
pubkey: &Pubkey,
factory: Option<AccountFactory>,
) -> SurfpoolContextualizedResult<GetAccountResult> {
let result = if let Some((remote_client, commitment_config)) = remote_ctx {
self.get_account_local_then_remote(remote_client, pubkey, *commitment_config)
.await?
} else {
self.get_account_local(pubkey)
};
match (&result.inner, factory) {
(&GetAccountResult::None(_), Some(factory)) => {
let default = factory(self.clone());
Ok(result.with_new_value(default))
}
_ => Ok(result),
}
}
/// Retrieves multiple accounts from local cache, returning a contextualized result.
pub fn get_multiple_accounts_local(
&self,
pubkeys: &[Pubkey],
) -> SvmAccessContext<Vec<GetAccountResult>> {
self.with_contextualized_svm_reader(|svm_reader| {
let mut accounts = vec![];
for pubkey in pubkeys {
let mut result = svm_reader.inner.get_account_result(pubkey).unwrap();
if result.is_none() {
result = match svm_reader.get_account_from_feature_set(pubkey) {
Some(account) => GetAccountResult::FoundAccount(
*pubkey, account,
// mark this as an account to insert into the SVM, since the feature is activated and LiteSVM doesn't
// automatically insert activated feature accounts
// TODO: mark as false once https://github.com/LiteSVM/litesvm/pull/308 is released
true,
),
None => GetAccountResult::None(*pubkey),
}
};
accounts.push(result);
}
accounts
})
}
/// Retrieves multiple accounts from local storage, with remote fallback for missing accounts.
///
/// Returns accounts in the same order as the input `pubkeys` array. Accounts found locally
/// are returned as-is; accounts not found locally are fetched from the remote RPC client.
/// Accounts that have been explicitly closed are not fetched from remote.
pub async fn get_multiple_accounts_with_remote_fallback(
&self,
client: &SurfnetRemoteClient,
pubkeys: &[Pubkey],
commitment_config: CommitmentConfig,
) -> SurfpoolContextualizedResult<Vec<GetAccountResult>> {
let SvmAccessContext {
slot,
latest_epoch_info,
latest_blockhash,
inner: local_results,
} = self.get_multiple_accounts_local(pubkeys);
// Get the closed accounts set
let closed_accounts = self.get_closed_accounts();
// Collect missing pubkeys that are NOT closed (local_results is already in correct order from pubkeys)
let missing_accounts: Vec<Pubkey> = local_results
.iter()
.filter_map(|result| match result {
GetAccountResult::None(pubkey) => {
if !closed_accounts.contains(pubkey) {
Some(*pubkey)
} else {
None
}
}
_ => None,
})
.collect();
if missing_accounts.is_empty() {
// All accounts found locally, already in correct order
return Ok(SvmAccessContext::new(
slot,
latest_epoch_info,
latest_blockhash,
local_results,
));
}
debug!(
"Missing accounts will be fetched: {}",
missing_accounts.iter().join(", ")
);
// Fetch missing accounts from remote
let remote_results = client
.get_multiple_accounts(&missing_accounts, commitment_config)
.await?;
// Build map of pubkey -> remote result for O(1) lookup
let remote_map: HashMap<Pubkey, GetAccountResult> = missing_accounts
.into_iter()
.zip(remote_results.into_iter())
.collect();
// Replace None entries with remote results while preserving order
// We iterate through original pubkeys array to ensure order is explicit
let combined_results: Vec<GetAccountResult> = pubkeys
.iter()
.zip(local_results.into_iter())
.map(|(pubkey, local_result)| {
match local_result {
GetAccountResult::None(_) => {
// Replace with remote result if available and not closed
if closed_accounts.contains(pubkey) {
GetAccountResult::None(*pubkey)
} else {
remote_map
.get(pubkey)
.cloned()
.unwrap_or(GetAccountResult::None(*pubkey))
}
}
found => {
debug!("Keeping local account: {}", pubkey);
found
} // Keep found accounts (no clone, just move)
}
})
.collect();
Ok(SvmAccessContext::new(
slot,
latest_epoch_info,
latest_blockhash,
combined_results,
))
}
/// Retrieves multiple accounts, using local or remote context and applying factory defaults if provided.
pub async fn get_multiple_accounts(
&self,
remote_ctx: &Option<(SurfnetRemoteClient, CommitmentConfig)>,
pubkeys: &[Pubkey],
factory: Option<AccountFactory>,
) -> SurfpoolContextualizedResult<Vec<GetAccountResult>> {
let results = if let Some((remote_client, commitment_config)) = remote_ctx {
self.get_multiple_accounts_with_remote_fallback(
remote_client,
pubkeys,
*commitment_config,
)
.await?
} else {
self.get_multiple_accounts_local(pubkeys)
};
let mut combined = Vec::with_capacity(results.inner.len());
for result in results.inner.clone() {
match (&result, &factory) {
(&GetAccountResult::None(_), Some(factory)) => {
let default = factory(self.clone());
combined.push(default);
}
_ => combined.push(result),
}
}
Ok(results.with_new_value(combined))
}
/// Loads accounts from a snapshot into the SVM.
///
/// This method should be called before geyser plugins start to ensure they receive
/// the account updates with `is_startup=true`.
///
/// # Arguments
/// * `snapshot` - A map of pubkey strings to optional account snapshots.
/// - If the value is Some(AccountSnapshot), the account is loaded directly.
/// - If the value is None, the account is fetched from the remote RPC (if available).
/// * `remote_client` - Optional remote RPC client to fetch None accounts.
/// * `commitment_config` - Commitment level for remote RPC calls.
///
/// # Returns
/// The number of accounts successfully loaded.
pub async fn load_snapshot(
&self,
snapshot: &BTreeMap<String, Option<AccountSnapshot>>,
remote_client: Option<&SurfnetRemoteClient>,
commitment_config: CommitmentConfig,
) -> SurfpoolResult<usize> {
use std::str::FromStr;
use base64::{Engine, prelude::BASE64_STANDARD};
let mut loaded_count = 0;
// Separate accounts into those with data and those needing remote fetch
let mut accounts_to_load: Vec<(Pubkey, Account)> = Vec::new();
let mut pubkeys_to_fetch: Vec<Pubkey> = Vec::new();
for (pubkey_str, account_snapshot_opt) in snapshot.iter() {
let pubkey = match Pubkey::from_str(pubkey_str) {
Ok(pk) => pk,
Err(e) => {
self.with_svm_reader(|svm| {
let _ = svm.simnet_events_tx.send(SimnetEvent::warn(format!(
"Skipping invalid pubkey '{}' in snapshot: {}",
pubkey_str, e
)));
});
continue;
}
};
match account_snapshot_opt {
Some(account_snapshot) => {
// Decode base64 data
let data = match BASE64_STANDARD.decode(&account_snapshot.data) {
Ok(d) => d,
Err(e) => {
self.with_svm_reader(|svm| {
let _ = svm.simnet_events_tx.send(SimnetEvent::warn(format!(
"Skipping account '{}': failed to decode base64 data: {}",
pubkey_str, e
)));
});
continue;
}
};
// Parse owner pubkey
let owner = match Pubkey::from_str(&account_snapshot.owner) {
Ok(pk) => pk,
Err(e) => {
self.with_svm_reader(|svm| {
let _ = svm.simnet_events_tx.send(SimnetEvent::warn(format!(
"Skipping account '{}': invalid owner pubkey: {}",
pubkey_str, e
)));
});
continue;
}
};
// Create the account
let account = Account {
lamports: account_snapshot.lamports,
data,
owner,
executable: account_snapshot.executable,
rent_epoch: account_snapshot.rent_epoch,
};
accounts_to_load.push((pubkey, account));
}
None => {
// Queue for remote fetch if client is available
if remote_client.is_some() {
pubkeys_to_fetch.push(pubkey);
}
}
}
}
// Fetch None accounts from remote RPC if client is available
if let Some(client) = remote_client {
if !pubkeys_to_fetch.is_empty() {
self.with_svm_reader(|svm| {
let _ = svm.simnet_events_tx.send(SimnetEvent::info(format!(
"Fetching {} accounts from remote RPC for snapshot",
pubkeys_to_fetch.len()
)));
});
match client
.get_multiple_accounts(&pubkeys_to_fetch, commitment_config)
.await
{
Ok(remote_results) => {
for (pubkey, result) in pubkeys_to_fetch.iter().zip(remote_results) {
match result {
GetAccountResult::FoundAccount(_, account, _) => {
accounts_to_load.push((*pubkey, account));
}
GetAccountResult::FoundProgramAccount(
(program_pubkey, program_account),
(data_pubkey, data_account_opt),
) => {
accounts_to_load.push((program_pubkey, program_account));
if let Some(data_account) = data_account_opt {
accounts_to_load.push((data_pubkey, data_account));
}
}
GetAccountResult::FoundTokenAccount(
(token_pubkey, token_account),
(mint_pubkey, mint_account_opt),
) => {
accounts_to_load.push((token_pubkey, token_account));
if let Some(mint_account) = mint_account_opt {
accounts_to_load.push((mint_pubkey, mint_account));
}
}
GetAccountResult::None(_) => {
// Account not found on remote, skip
}
}
}
}
Err(e) => {
self.with_svm_reader(|svm| {
let _ = svm.simnet_events_tx.send(SimnetEvent::warn(format!(
"Failed to fetch some accounts from remote: {}",
e
)));
});
}
}
}
}
// Load all accounts into the SVM
self.with_svm_writer(|svm| {
let slot = svm.get_latest_absolute_slot();
for (pubkey, account) in accounts_to_load {
if let Err(e) = svm.set_account(&pubkey, account.clone()) {
let _ = svm.simnet_events_tx.send(SimnetEvent::warn(format!(
"Failed to set account '{}': {}",
pubkey, e
)));
continue;
}
// Send startup account update to geyser
let write_version = svm.increment_write_version();
let _ = svm.geyser_events_tx.send(GeyserEvent::StartupAccountUpdate(
GeyserAccountUpdate::startup_update(pubkey, account, slot, write_version),
));
loaded_count += 1;
}
});
Ok(loaded_count)
}
/// Retrieves largest accounts from local cache, returning a contextualized result.
pub fn get_largest_accounts_local(
&self,
config: RpcLargestAccountsConfig,
) -> SurfpoolContextualizedResult<Vec<RpcAccountBalance>> {
let res: Vec<RpcAccountBalance> = self.with_svm_reader(|svm_reader| {
let non_circulating_accounts: Vec<_> = svm_reader
.non_circulating_accounts
.iter()
.flat_map(|acct| verify_pubkey(acct))
.collect();
let ordered_accounts = svm_reader
.get_all_accounts()?
.into_iter()
.sorted_by(|a, b| b.1.lamports().cmp(&a.1.lamports()))
.collect::<Vec<_>>();
let ordered_filtered_accounts = match config.filter {
Some(RpcLargestAccountsFilter::NonCirculating) => ordered_accounts
.into_iter()
.filter(|(pubkey, _)| non_circulating_accounts.contains(pubkey))
.collect::<Vec<_>>(),
Some(RpcLargestAccountsFilter::Circulating) => ordered_accounts
.into_iter()
.filter(|(pubkey, _)| !non_circulating_accounts.contains(pubkey))
.collect::<Vec<_>>(),
None => ordered_accounts,
};
Ok::<Vec<RpcAccountBalance>, SurfpoolError>(
ordered_filtered_accounts
.iter()
.take(20)
.map(|(pubkey, account)| RpcAccountBalance {
address: pubkey.to_string(),
lamports: account.lamports(),
})
.collect(),
)
})?;
Ok(self.with_contextualized_svm_reader(|_| res.to_owned()))
}
pub async fn get_largest_accounts_local_then_remote(
&self,
client: &SurfnetRemoteClient,
config: RpcLargestAccountsConfig,
commitment_config: CommitmentConfig,
) -> SurfpoolContextualizedResult<Vec<RpcAccountBalance>> {
// get all non-circulating and circulating pubkeys from the remote client first,
// and insert them locally
{
let remote_non_circulating_pubkeys_result = client
.get_largest_accounts(Some(RpcLargestAccountsConfig {
filter: Some(RpcLargestAccountsFilter::NonCirculating),
..config.clone()
}))
.await?;
let (mut remote_non_circulating_pubkeys, mut remote_circulating_pubkeys) =
match remote_non_circulating_pubkeys_result {
RemoteRpcResult::Ok(non_circulating_accounts) => {
let remote_circulating_pubkeys_result = client
.get_largest_accounts(Some(RpcLargestAccountsConfig {
filter: Some(RpcLargestAccountsFilter::Circulating),
..config.clone()
}))
.await?;
let remote_circulating_pubkeys = match remote_circulating_pubkeys_result {
RemoteRpcResult::Ok(circulating_accounts) => circulating_accounts,
RemoteRpcResult::MethodNotSupported => {
unreachable!()
}
};
(
non_circulating_accounts
.iter()
.map(|account_balance| verify_pubkey(&account_balance.address))
.collect::<SurfpoolResult<Vec<_>>>()?,
remote_circulating_pubkeys
.iter()
.map(|account_balance| verify_pubkey(&account_balance.address))
.collect::<SurfpoolResult<Vec<_>>>()?,
)
}
RemoteRpcResult::MethodNotSupported => {
let tx = self.simnet_events_tx();
let _ = tx.send(SimnetEvent::warn("The `getLargestAccounts` method was sent to the remote RPC, but this method isn't supported by your RPC provider. Only local accounts will be returned."));
(vec![], vec![])
}
};
let mut combined = Vec::with_capacity(
remote_non_circulating_pubkeys.len() + remote_circulating_pubkeys.len(),
);
combined.append(&mut remote_non_circulating_pubkeys);
combined.append(&mut remote_circulating_pubkeys);
let get_account_results = self
.get_multiple_accounts_with_remote_fallback(client, &combined, commitment_config)
.await?
.inner;
self.write_multiple_account_updates(&get_account_results);
}
// now that our local cache is aware of all large remote accounts, we can get the largest accounts locally
// and filter according to the config
self.get_largest_accounts_local(config)
}
pub async fn get_largest_accounts(
&self,
remote_ctx: &Option<(SurfnetRemoteClient, CommitmentConfig)>,
config: RpcLargestAccountsConfig,
) -> SurfpoolContextualizedResult<Vec<RpcAccountBalance>> {
if let Some((remote_client, commitment_config)) = remote_ctx {
self.get_largest_accounts_local_then_remote(remote_client, config, *commitment_config)
.await
} else {
self.get_largest_accounts_local(config)
}
}
pub fn account_to_rpc_keyed_account<T: ReadableAccount + Send + Sync>(
&self,
pubkey: &Pubkey,
account: &T,
config: &RpcAccountInfoConfig,
token_mint: Option<Pubkey>,
) -> RpcKeyedAccount {
self.with_svm_reader(|svm_reader| {
svm_reader.account_to_rpc_keyed_account(pubkey, account, config, token_mint)
})
}
}
/// Get signatures for Addresses
impl SurfnetSvmLocker {
pub fn get_signatures_for_address_local(
&self,
pubkey: &Pubkey,
config: Option<RpcSignaturesForAddressConfig>,
) -> SvmAccessContext<Vec<RpcConfirmedTransactionStatusWithSignature>> {
let RpcSignaturesForAddressConfig {
before,
until,
limit,
min_context_slot,
..
} = config.unwrap_or_default();
self.with_contextualized_svm_reader(move |svm_reader| {
let current_slot = svm_reader.get_latest_absolute_slot();
let limit = limit.unwrap_or(1000);
let config_before = &before;
let config_until = &until;
let mut before_slot = None;
let mut until_slot = None;
let sigs: Vec<_> = svm_reader
.transactions
.into_iter()
.map(|iter| {
iter.filter_map(|(sig, status)| {
let (
TransactionWithStatusMeta {
slot,
transaction,
meta,
},
_,
) = status
.as_processed()
.expect("expected processed transaction");
if slot < min_context_slot.unwrap_or_default() {
return None;
}
if Some(sig.clone()) == *config_before {
before_slot = Some(slot);
}
if Some(sig.clone()) == *config_until {
until_slot = Some(slot);
}
// Check if the pubkey is a signer
if !transaction.message.static_account_keys().contains(pubkey) {
return None;
}
// Determine confirmation status
let confirmation_status = match current_slot {
cs if cs == slot => SolanaTransactionConfirmationStatus::Processed,
cs if cs < slot + FINALIZATION_SLOT_THRESHOLD => {
SolanaTransactionConfirmationStatus::Confirmed
}
_ => SolanaTransactionConfirmationStatus::Finalized,
};
Some(RpcConfirmedTransactionStatusWithSignature {
err: match meta.status {
Ok(_) => None,
Err(e) => Some(e.into()),
},
slot,
memo: None,
block_time: None,
confirmation_status: Some(confirmation_status),
signature: sig,
})
})
.collect()
})
.unwrap_or_default();
let unique_slots: HashSet<u64> = sigs.iter().map(|s| s.slot).collect();
let mut sig_position: HashMap<String, usize> = HashMap::new();
for slot in unique_slots {
if let Ok(Some(block_header)) = svm_reader.blocks.get(&slot) {
for (idx, block_sig) in block_header.signatures.iter().enumerate() {
sig_position.insert(block_sig.to_string(), idx);
}
}
}
sigs.into_iter()
.filter(|sig| {
if before.is_none() && until.is_none() {
return true;
}
if before.is_some() && before_slot > Some(sig.slot) {
return true;
}
if until.is_some() && until_slot < Some(sig.slot) {
return true;
}
false
})
// order from most recent to least recent
.sorted_by(|a, b| {
b.slot.cmp(&a.slot).then_with(|| {
let a_pos = sig_position.get(&a.signature).unwrap_or(&usize::MAX);
let b_pos = sig_position.get(&b.signature).unwrap_or(&usize::MAX);
b_pos.cmp(&a_pos)
})
})
.take(limit)
.collect()
})
}
pub async fn get_signatures_for_address_local_then_remote(
&self,
client: &SurfnetRemoteClient,
pubkey: &Pubkey,
config: Option<RpcSignaturesForAddressConfig>,
) -> SurfpoolContextualizedResult<Vec<RpcConfirmedTransactionStatusWithSignature>> {
let results = self.get_signatures_for_address_local(pubkey, config.clone());
let limit = config.clone().and_then(|c| c.limit).unwrap_or(1000);
let mut combined_results = results.inner.clone();
if combined_results.len() < limit {
let mut remote_results = client.get_signatures_for_address(pubkey, config).await?;
combined_results.append(&mut remote_results);
}
Ok(results.with_new_value(combined_results))
}
pub async fn get_signatures_for_address(
&self,
remote_ctx: &Option<(SurfnetRemoteClient, ())>,
pubkey: &Pubkey,
config: Option<RpcSignaturesForAddressConfig>,
) -> SurfpoolContextualizedResult<Vec<RpcConfirmedTransactionStatusWithSignature>> {
let results = if let Some((remote_client, _)) = remote_ctx {
self.get_signatures_for_address_local_then_remote(remote_client, pubkey, config.clone())
.await?
} else {
self.get_signatures_for_address_local(pubkey, config)
};
Ok(results)
}
}
/// Functions for getting transactions from the underlying SurfnetSvm instance or remote client
impl SurfnetSvmLocker {
/// Retrieves a transaction by signature, using local or remote based on context.
pub async fn get_transaction(
&self,
remote_ctx: &Option<SurfnetRemoteClient>,
signature: &Signature,
config: RpcTransactionConfig,
) -> SurfpoolResult<GetTransactionResult> {
if let Some(remote_client) = remote_ctx {
self.get_transaction_local_then_remote(remote_client, signature, config)
.await
} else {
self.get_transaction_local(signature, &config)
}
}
/// Retrieves a transaction from local cache, returning a contextualized result.
pub fn get_transaction_local(
&self,
signature: &Signature,
config: &RpcTransactionConfig,
) -> SurfpoolResult<GetTransactionResult> {
self.with_svm_reader(|svm_reader| {
let latest_absolute_slot = svm_reader.get_latest_absolute_slot();
let Some(entry) = svm_reader.transactions.get(&signature.to_string())? else {
return Ok(GetTransactionResult::None(*signature));
};
let (transaction_with_status_meta, _) = entry.expect_processed();
let slot = transaction_with_status_meta.slot;
let block_time = svm_reader
.blocks
.get(&slot)?
.map(|b| (b.block_time / 1_000) as UnixTimestamp)
.unwrap_or(0);
let encoded = transaction_with_status_meta.encode(
config.encoding.unwrap_or(UiTransactionEncoding::JsonParsed),
config.max_supported_transaction_version,
true,
)?;
Ok(GetTransactionResult::found_transaction(
*signature,
EncodedConfirmedTransactionWithStatusMeta {
slot,
transaction: encoded,