-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathintegration.rs
More file actions
7883 lines (6876 loc) · 275 KB
/
integration.rs
File metadata and controls
7883 lines (6876 loc) · 275 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::{str::FromStr, sync::Arc, time::Duration};
use base64::Engine;
use crossbeam_channel::{unbounded, unbounded as crossbeam_unbounded};
use jsonrpc_core::{
Error, Result as JsonRpcResult,
futures::future::{self, join_all},
};
use jsonrpc_core_client::transports::http;
use solana_account::Account;
use solana_account_decoder::{UiAccountData, UiAccountEncoding, parse_account_data::ParsedAccount};
use solana_address_lookup_table_interface::state::{AddressLookupTable, LookupTableMeta};
use solana_client::{
nonblocking::rpc_client::RpcClient, rpc_config::RpcSimulateTransactionConfig,
rpc_response::RpcLogsResponse,
};
use solana_clock::{Clock, Slot};
use solana_commitment_config::{CommitmentConfig, CommitmentLevel};
use solana_compute_budget_interface::ComputeBudgetInstruction;
use solana_epoch_info::EpochInfo;
use solana_hash::Hash;
use solana_keypair::Keypair;
use solana_message::{
AddressLookupTableAccount, Message, VersionedMessage, legacy,
v0::{self},
};
use solana_pubkey::Pubkey;
use solana_rpc_client_api::response::Response as RpcResponse;
use solana_signer::Signer;
use solana_system_interface::{
instruction as system_instruction, instruction::transfer, program as system_program,
};
use solana_transaction::{Transaction, versioned::VersionedTransaction};
use surfpool_types::{
DEFAULT_SLOT_TIME_MS, Idl, RpcProfileDepth, RpcProfileResultConfig, SimnetCommand, SimnetEvent,
SurfpoolConfig, UiAccountChange, UiAccountProfileState, UiKeyedProfileResult,
types::{
BlockProductionMode, RpcConfig, SimnetConfig, SubgraphConfig, TransactionStatusEvent,
UuidOrSignature,
},
};
use test_case::test_case;
use tokio::{sync::RwLock, task};
use uuid::Uuid;
pub const LAMPORTS_PER_SOL: u64 = 1_000_000_000;
use crate::{
PluginManagerCommand,
error::SurfpoolError,
rpc::{
RunloopContext,
full::FullClient,
minimal::MinimalClient,
surfnet_cheatcodes::{SurfnetCheatcodes, SurfnetCheatcodesRpc},
},
runloops::start_local_surfnet_runloop,
storage::tests::TestType,
surfnet::{SignatureSubscriptionType, locker::SurfnetSvmLocker, svm::SurfnetSvm},
tests::helpers::get_free_port,
types::{TimeTravelConfig, TransactionLoadedAddresses},
};
fn wait_for_ready_and_connected(simnet_events_rx: &crossbeam_channel::Receiver<SimnetEvent>) {
let mut ready = false;
let mut connected = false;
loop {
match simnet_events_rx.recv() {
Ok(SimnetEvent::Ready(_)) => {
println!("Simnet is ready");
ready = true;
}
Ok(SimnetEvent::Connected(_)) => {
println!("Simnet is connected");
connected = true;
}
_ => (),
}
if ready && connected {
break;
}
}
}
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test]
async fn test_simnet_ready(test_type: TestType) {
let config = SurfpoolConfig {
simnets: vec![SimnetConfig {
block_production_mode: BlockProductionMode::Manual, // Prevent ticks
..SimnetConfig::default()
}],
..SurfpoolConfig::default()
};
let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
let (simnet_commands_tx, simnet_commands_rx) = unbounded();
let (subgraph_commands_tx, _subgraph_commands_rx) = unbounded();
let svm_locker = SurfnetSvmLocker::new(surfnet_svm);
let _handle = hiro_system_kit::thread_named("test").spawn(move || {
let future = start_local_surfnet_runloop(
svm_locker,
config,
subgraph_commands_tx,
simnet_commands_tx,
simnet_commands_rx,
geyser_events_rx,
);
if let Err(e) = hiro_system_kit::nestable_block_on(future) {
panic!("{e:?}");
}
});
match simnet_events_rx.recv() {
Ok(SimnetEvent::Ready(_)) | Ok(SimnetEvent::Connected(_)) => (),
e => panic!("Expected Ready event: {e:?}"),
}
}
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test]
async fn test_simnet_ticks(test_type: TestType) {
let bind_host = "127.0.0.1";
let bind_port = get_free_port().unwrap();
let ws_port = get_free_port().unwrap();
let config = SurfpoolConfig {
simnets: vec![SimnetConfig {
slot_time: 1,
..SimnetConfig::default()
}],
rpc: RpcConfig {
bind_host: bind_host.to_string(),
bind_port,
ws_port,
..Default::default()
},
..SurfpoolConfig::default()
};
let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
let (simnet_commands_tx, simnet_commands_rx) = unbounded();
let (subgraph_commands_tx, _subgraph_commands_rx) = unbounded();
let (test_tx, test_rx) = unbounded();
let svm_locker = SurfnetSvmLocker::new(surfnet_svm);
let _handle = hiro_system_kit::thread_named("test").spawn(move || {
let future = start_local_surfnet_runloop(
svm_locker,
config,
subgraph_commands_tx,
simnet_commands_tx,
simnet_commands_rx,
geyser_events_rx,
);
if let Err(e) = hiro_system_kit::nestable_block_on(future) {
panic!("{e:?}");
}
});
let _ = hiro_system_kit::thread_named("ticks").spawn(move || {
let mut ticks = 0;
loop {
match simnet_events_rx.recv() {
Ok(SimnetEvent::SystemClockUpdated(_)) => ticks += 1,
_ => (),
}
if ticks > 100 {
let _ = test_tx.send(true);
}
}
});
match test_rx.recv_timeout(Duration::from_secs(20)) {
Ok(_) => (),
Err(e) => panic!("not enough ticks: {e:?}"),
}
}
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test]
async fn test_simnet_some_sol_transfers(test_type: TestType) {
let n_addresses = 10;
let airdrop_keypairs = (0..n_addresses).map(|_| Keypair::new()).collect::<Vec<_>>();
let airdrop_addresses: Vec<Pubkey> = airdrop_keypairs.iter().map(|kp| kp.pubkey()).collect();
let airdrop_token_amount = LAMPORTS_PER_SOL;
let bind_host = "127.0.0.1";
let bind_port = get_free_port().unwrap();
let ws_port = get_free_port().unwrap();
let config = SurfpoolConfig {
simnets: vec![SimnetConfig {
slot_time: 1,
airdrop_addresses: airdrop_addresses.clone(),
airdrop_token_amount,
..SimnetConfig::default()
}],
rpc: RpcConfig {
bind_host: bind_host.to_string(),
bind_port,
ws_port,
..Default::default()
},
..SurfpoolConfig::default()
};
let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
let (simnet_commands_tx, simnet_commands_rx) = unbounded();
let (subgraph_commands_tx, _subgraph_commands_rx) = unbounded();
let svm_locker = SurfnetSvmLocker::new(surfnet_svm);
let _handle = hiro_system_kit::thread_named("test").spawn(move || {
let future = start_local_surfnet_runloop(
svm_locker,
config,
subgraph_commands_tx,
simnet_commands_tx,
simnet_commands_rx,
geyser_events_rx,
);
if let Err(e) = hiro_system_kit::nestable_block_on(future) {
panic!("{e:?}");
}
});
wait_for_ready_and_connected(&simnet_events_rx);
let minimal_client =
http::connect::<MinimalClient>(format!("http://{bind_host}:{bind_port}").as_str())
.await
.expect("Failed to connect to Surfpool");
let full_client =
http::connect::<FullClient>(format!("http://{bind_host}:{bind_port}").as_str())
.await
.expect("Failed to connect to Surfpool");
let recent_blockhash = full_client
.get_latest_blockhash(None)
.await
.map(|r| {
Hash::from_str(r.value.blockhash.as_str()).expect("Failed to deserialize blockhash")
})
.expect("Failed to get blockhash");
let balances = join_all(
airdrop_addresses
.iter()
.map(|pk| minimal_client.get_balance(pk.to_string(), None)),
)
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()
.expect("Failed to fetch balances");
assert!(
balances.iter().all(|b| b.value == airdrop_token_amount),
"All addresses did not receive the airdrop"
);
let _transfers = join_all(airdrop_keypairs.iter().map(|kp| {
let msg = Message::new_with_blockhash(
&[system_instruction::transfer(
&kp.pubkey(),
&airdrop_addresses[0],
airdrop_token_amount / 2,
)],
Some(&kp.pubkey()),
&recent_blockhash,
);
let Ok(tx) = VersionedTransaction::try_new(
VersionedMessage::Legacy(msg),
&vec![kp.insecure_clone()],
) else {
return Box::pin(future::err(Error::invalid_params("tx")));
};
let Ok(encoded) = bincode::serialize(&tx) else {
return Box::pin(future::err(Error::invalid_params("encoded")));
};
let data = bs58::encode(encoded).into_string();
Box::pin(future::ready(Ok(full_client.send_transaction(data, None))))
}))
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()
.expect("Transfers failed");
// Wait for all transactions to be received
let expected = airdrop_addresses.len();
let _ = task::spawn_blocking(move || {
let mut processed = 0;
loop {
match simnet_events_rx.recv() {
Ok(SimnetEvent::TransactionProcessed(..)) => processed += 1,
_ => (),
}
if processed == expected {
break;
}
}
})
.await;
let final_balances = join_all(
airdrop_addresses
.iter()
.map(|pk| minimal_client.get_balance(pk.to_string(), None)),
)
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()
.expect("Failed to fetch final balances");
assert!(
final_balances.iter().enumerate().all(|(i, b)| {
if i == 0 {
b.value > airdrop_token_amount
} else {
b.value < airdrop_token_amount / 2
}
}), // TODO: compute fee
"Some transfers failed"
);
}
// This test is pretty minimal for lookup tables at this point.
// We are creating a v0 transaction with a lookup table that does exist on mainnet,
// and sending that tx to surfpool. We are verifying that the transaction is processed
// and that the lookup table and its entries are fetched from mainnet and added to the accounts in the SVM.
// However, we are not actually setting up a tx that will use the lookup table internally,
// we are kind of just trusting that LiteSVM will do its job here.
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_add_alt_entries_fetching(test_type: TestType) {
let payer = Keypair::new();
let pk = payer.pubkey();
let bind_host = "127.0.0.1";
let bind_port = get_free_port().unwrap();
let ws_port = get_free_port().unwrap();
let airdrop_token_amount = LAMPORTS_PER_SOL;
let config = SurfpoolConfig {
simnets: vec![SimnetConfig {
slot_time: 1,
airdrop_addresses: vec![pk], // just one
airdrop_token_amount,
..SimnetConfig::default()
}],
rpc: RpcConfig {
bind_host: bind_host.to_string(),
bind_port,
ws_port,
..Default::default()
},
..SurfpoolConfig::default()
};
println!("Initializing SVM, binding to port {}", bind_port);
let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
let (simnet_commands_tx, simnet_commands_rx) = unbounded();
let (subgraph_commands_tx, _subgraph_commands_rx) = unbounded();
let svm_locker = Arc::new(RwLock::new(surfnet_svm));
let moved_svm_locker = svm_locker.clone();
let _handle = hiro_system_kit::thread_named("test").spawn(move || {
let future = start_local_surfnet_runloop(
SurfnetSvmLocker(moved_svm_locker),
config,
subgraph_commands_tx,
simnet_commands_tx,
simnet_commands_rx,
geyser_events_rx,
);
if let Err(e) = hiro_system_kit::nestable_block_on(future) {
panic!("{e:?}");
}
});
let svm_locker = SurfnetSvmLocker(svm_locker);
wait_for_ready_and_connected(&simnet_events_rx);
let full_client =
http::connect::<FullClient>(format!("http://{bind_host}:{bind_port}").as_str())
.await
.expect("Failed to connect to Surfpool");
let recent_blockhash = full_client
.get_latest_blockhash(None)
.await
.map(|r| {
Hash::from_str(r.value.blockhash.as_str()).expect("Failed to deserialize blockhash")
})
.expect("Failed to get blockhash");
let random_address = Pubkey::from_str_const("7zdYkYf7yD83j3TLXmkhxn6LjQP9y9bQ4pjfpquP8Hqw");
let instruction = transfer(&pk, &random_address, 100);
let alt_address = Pubkey::from_str_const("5KcPJehcpBLcPde2UhmY4dE9zCrv2r9AKFmW5CGtY1io"); // a mainnet lookup table
let address_lookup_table_account = AddressLookupTableAccount {
key: alt_address,
addresses: vec![random_address],
};
let tx = VersionedTransaction::try_new(
VersionedMessage::V0(
v0::Message::try_compile(
&payer.pubkey(),
&[instruction],
&[address_lookup_table_account],
recent_blockhash,
)
.expect("Failed to compile message"),
),
&[payer],
)
.expect("Failed to create transaction");
let Ok(encoded) = bincode::serialize(&tx) else {
panic!("Failed to serialize transaction");
};
let data = bs58::encode(encoded).into_string();
// Wait for all transactions to be received
let _ = match full_client.send_transaction(data, None).await {
Ok(res) => println!("Send transaction result: {}", res),
Err(err) => println!("Send transaction error result: {}", err),
};
let mut processed = 0;
let expected = 1;
let mut alt_updated = false;
loop {
match simnet_events_rx.recv() {
Ok(SimnetEvent::TransactionProcessed(..)) => processed += 1,
Ok(SimnetEvent::AccountUpdate(_, account)) => {
if account == alt_address {
alt_updated = true;
}
}
Ok(SimnetEvent::ClockUpdate(_)) => {
// do nothing
}
Ok(SimnetEvent::SystemClockUpdated(_)) => {
// do nothing - clock ticks from time travel or normal progression
}
other => println!("Unexpected event: {:?}", other),
}
if processed == expected && alt_updated {
break;
}
}
// get all the account keys + the address lookup tables + table_entries from the txn
let alts = tx.message.address_table_lookups().clone().unwrap();
let mut acc_keys = tx.message.static_account_keys().to_vec();
let mut alt_pubkeys = alts.iter().map(|msg| msg.account_key).collect::<Vec<_>>();
let mut table_entries = join_all(alts.iter().map(|msg| async {
let mut loaded_addresses = TransactionLoadedAddresses::new();
svm_locker
.get_lookup_table_addresses(&None, msg, &mut loaded_addresses)
.await?;
Ok::<_, SurfpoolError>(
loaded_addresses
.all_loaded_addresses()
.into_iter()
.map(|p| *p)
.collect::<Vec<Pubkey>>(),
)
}))
.await
.into_iter()
.collect::<Result<Vec<Vec<Pubkey>>, SurfpoolError>>()
.unwrap()
.into_iter()
.flatten()
.collect();
acc_keys.append(&mut alt_pubkeys);
acc_keys.append(&mut table_entries);
assert!(
acc_keys.iter().all(|key| {
svm_locker
.get_account_local(key)
.inner
.map_account()
.is_ok()
}),
"account not found"
);
}
// This test is pretty minimal for lookup tables at this point.
// We are creating a v0 transaction with a lookup table that does exist on mainnet,
// and sending that tx to surfpool. We are verifying that the transaction is processed
// and that the lookup table and its entries are fetched from mainnet and added to the accounts in the SVM.
// However, we are not actually setting up a tx that will use the lookup table internally,
// we are kind of just trusting that LiteSVM will do its job here.
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_simulate_add_alt_entries_fetching(test_type: TestType) {
let payer = Keypair::new();
let pk = payer.pubkey();
let bind_host = "127.0.0.1";
let bind_port = get_free_port().unwrap();
let ws_port = get_free_port().unwrap();
let airdrop_token_amount = LAMPORTS_PER_SOL;
let config = SurfpoolConfig {
simnets: vec![SimnetConfig {
slot_time: 1,
airdrop_addresses: vec![pk], // just one
airdrop_token_amount,
..SimnetConfig::default()
}],
rpc: RpcConfig {
bind_host: bind_host.to_string(),
bind_port,
ws_port,
..Default::default()
},
..SurfpoolConfig::default()
};
let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
let (simnet_commands_tx, simnet_commands_rx) = unbounded();
let (subgraph_commands_tx, _subgraph_commands_rx) = unbounded();
let svm_locker = Arc::new(RwLock::new(surfnet_svm));
let moved_svm_locker = svm_locker.clone();
let _handle = hiro_system_kit::thread_named("test").spawn(move || {
let future = start_local_surfnet_runloop(
SurfnetSvmLocker(moved_svm_locker),
config,
subgraph_commands_tx,
simnet_commands_tx,
simnet_commands_rx,
geyser_events_rx,
);
if let Err(e) = hiro_system_kit::nestable_block_on(future) {
panic!("{e:?}");
}
});
let svm_locker = SurfnetSvmLocker(svm_locker);
wait_for_ready_and_connected(&simnet_events_rx);
let full_client =
http::connect::<FullClient>(format!("http://{bind_host}:{bind_port}").as_str())
.await
.expect("Failed to connect to Surfpool");
let random_address = Pubkey::from_str_const("7zdYkYf7yD83j3TLXmkhxn6LjQP9y9bQ4pjfpquP8Hqw");
let instruction = transfer(&pk, &random_address, 100);
let recent_blockhash = svm_locker.with_svm_reader(|svm_reader| svm_reader.latest_blockhash());
let alt_address = Pubkey::from_str_const("5KcPJehcpBLcPde2UhmY4dE9zCrv2r9AKFmW5CGtY1io"); // a mainnet lookup table
let address_lookup_table_account = AddressLookupTableAccount {
key: alt_address,
addresses: vec![random_address],
};
let tx = VersionedTransaction::try_new(
VersionedMessage::V0(
v0::Message::try_compile(
&payer.pubkey(),
&[instruction],
&[address_lookup_table_account],
recent_blockhash,
)
.expect("Failed to compile message"),
),
&[payer],
)
.expect("Failed to create transaction");
let Ok(encoded) = bincode::serialize(&tx) else {
panic!("Failed to serialize transaction");
};
let data = bs58::encode(encoded).into_string();
let simulation_res = full_client
.simulate_transaction(data.clone(), None)
.await
.unwrap();
assert_eq!(
simulation_res.value.err, None,
"Unexpected simulation error"
);
assert!(
simulation_res.value.loaded_accounts_data_size.is_some(),
"Expected loaded_accounts_data_size to be present"
);
assert_eq!(
simulation_res.value.loaded_accounts_data_size.unwrap(),
140134,
"Incorrect loaded_accounts_data_size value"
);
let simulation_res2 = full_client
.simulate_transaction(
data,
Some(RpcSimulateTransactionConfig {
sig_verify: false,
replace_recent_blockhash: false,
commitment: Some(CommitmentConfig::confirmed()),
encoding: None,
accounts: None,
min_context_slot: None,
inner_instructions: false,
}),
)
.await
.unwrap();
assert_eq!(
simulation_res2.value.err, None,
"Unexpected simulation error"
);
assert!(
simulation_res2.value.loaded_accounts_data_size.is_some(),
"Expected loaded_accounts_data_size to be present"
);
assert!(
simulation_res2.value.loaded_accounts_data_size.unwrap() > 0,
"Expected loaded_accounts_data_size to be greater than 0"
);
}
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_simulate_transaction_no_signers(test_type: TestType) {
let payer = Keypair::new();
let pk = payer.pubkey();
let lamports = LAMPORTS_PER_SOL;
let bind_host = "127.0.0.1";
let bind_port = get_free_port().unwrap();
let ws_port = get_free_port().unwrap();
let airdrop_token_amount = LAMPORTS_PER_SOL;
let config = SurfpoolConfig {
simnets: vec![SimnetConfig {
slot_time: 1,
airdrop_addresses: vec![pk], // just one
airdrop_token_amount,
..SimnetConfig::default()
}],
rpc: RpcConfig {
bind_host: bind_host.to_string(),
bind_port,
ws_port,
..Default::default()
},
..SurfpoolConfig::default()
};
let (surfnet_svm, simnet_events_rx, geyser_events_rx) = test_type.initialize_svm();
let (simnet_commands_tx, simnet_commands_rx) = unbounded();
let (subgraph_commands_tx, _subgraph_commands_rx) = unbounded();
let svm_locker = Arc::new(RwLock::new(surfnet_svm));
let moved_svm_locker = svm_locker.clone();
let _handle = hiro_system_kit::thread_named("test").spawn(move || {
let future = start_local_surfnet_runloop(
SurfnetSvmLocker(moved_svm_locker),
config,
subgraph_commands_tx,
simnet_commands_tx,
simnet_commands_rx,
geyser_events_rx,
);
if let Err(e) = hiro_system_kit::nestable_block_on(future) {
panic!("{e:?}");
}
});
let svm_locker = SurfnetSvmLocker(svm_locker);
wait_for_ready_and_connected(&simnet_events_rx);
let full_client =
http::connect::<FullClient>(format!("http://{bind_host}:{bind_port}").as_str())
.await
.expect("Failed to connect to Surfpool");
let _ = full_client
.request_airdrop(payer.pubkey().to_string(), 2 * lamports, None)
.await;
let recent_blockhash = svm_locker
.get_latest_blockhash(&CommitmentConfig::confirmed())
.unwrap();
//build_legacy_transaction
let mut msg = legacy::Message::new(
&[system_instruction::transfer(&payer.pubkey(), &pk, lamports)],
Some(&payer.pubkey()),
);
msg.recent_blockhash = recent_blockhash;
let tx = Transaction::new_unsigned(msg);
let simulation_res = full_client
.simulate_transaction(
bs58::encode(bincode::serialize(&tx).unwrap()).into_string(),
Some(RpcSimulateTransactionConfig {
sig_verify: false,
replace_recent_blockhash: false,
commitment: Some(CommitmentConfig::finalized()),
encoding: None,
accounts: None,
min_context_slot: None,
inner_instructions: false,
}),
)
.await
.unwrap();
assert_eq!(
simulation_res.value.err, None,
"Unexpected simulation error"
);
assert!(
simulation_res.value.loaded_accounts_data_size.is_some(),
"Expected loaded_accounts_data_size to be present"
);
assert!(
simulation_res.value.loaded_accounts_data_size.unwrap() > 0,
"Expected loaded_accounts_data_size to be greater than 0"
);
}
#[cfg_attr(feature = "ignore_tests_ci", ignore = "flaky CI tests")]
#[test_case(TestType::sqlite(); "with on-disk sqlite db")]
#[test_case(TestType::in_memory(); "with in-memory sqlite db")]
#[test_case(TestType::no_db(); "with no db")]
#[cfg_attr(feature = "postgres", test_case(TestType::postgres(); "with postgres db"))]
#[tokio::test(flavor = "multi_thread")]
async fn test_surfnet_estimate_compute_units(test_type: TestType) {
let (mut svm_instance, _simnet_events_rx, _geyser_events_rx) = test_type.initialize_svm();
let rpc_server = crate::rpc::surfnet_cheatcodes::SurfnetCheatcodesRpc;
let payer = Keypair::new();
let recipient = Pubkey::new_unique();
let lamports_to_send = 1_000_000;
svm_instance
.airdrop(&payer.pubkey(), lamports_to_send * 2)
.unwrap()
.unwrap();
let instruction = transfer(&payer.pubkey(), &recipient, lamports_to_send);
let latest_blockhash = svm_instance.latest_blockhash();
let message =
Message::new_with_blockhash(&[instruction], Some(&payer.pubkey()), &latest_blockhash);
let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(message.clone()), &[&payer])
.unwrap();
let tx_bytes = bincode::serialize(&tx).unwrap();
let tx_b64 = base64::engine::general_purpose::STANDARD.encode(&tx_bytes);
// Manually construct RunloopContext
let svm_locker_for_context = SurfnetSvmLocker::new(svm_instance);
let (simnet_cmd_tx, _simnet_cmd_rx) = crossbeam_unbounded::<SimnetCommand>();
let (plugin_cmd_tx, _plugin_cmd_rx) = crossbeam_unbounded::<PluginManagerCommand>();
let runloop_context = RunloopContext {
id: None,
svm_locker: svm_locker_for_context.clone(),
simnet_commands_tx: simnet_cmd_tx,
plugin_manager_commands_tx: plugin_cmd_tx,
remote_rpc_client: None,
rpc_config: RpcConfig::default(),
};
// Test with None tag
let response_no_tag_initial: JsonRpcResult<RpcResponse<UiKeyedProfileResult>> = rpc_server
.profile_transaction(Some(runloop_context.clone()), tx_b64.clone(), None, None)
.await;
assert!(
response_no_tag_initial.is_ok(),
"RPC call with None tag failed: {:?}",
response_no_tag_initial.err()
);
let rpc_response_value_no_tag = response_no_tag_initial.unwrap().value;
assert!(
rpc_response_value_no_tag
.transaction_profile
.error_message
.is_none(),
"CU estimation with None tag failed"
);
assert!(
rpc_response_value_no_tag
.transaction_profile
.compute_units_consumed
> 0,
"Invalid compute units consumed for None tag"
);
assert!(
rpc_response_value_no_tag
.transaction_profile
.log_messages
.is_some(),
"Log messages should be present for None tag"
);
// Test 1: Estimate with a tag and retrieve
let tag1 = "test_tag_1".to_string();
println!("\nTesting with tag: {}", tag1);
let response_tagged_1: JsonRpcResult<RpcResponse<UiKeyedProfileResult>> = rpc_server
.profile_transaction(
Some(runloop_context.clone()),
tx_b64.clone(),
Some(tag1.clone()),
None,
)
.await;
assert!(
response_tagged_1.is_ok(),
"RPC call with tag1 failed: {:?}",
response_tagged_1.err()
);
let rpc_response_tagged_1_value = response_tagged_1.unwrap().value;
assert!(
rpc_response_tagged_1_value
.transaction_profile
.error_message
.is_none(),
"CU estimation with tag1 failed"
);
println!("Retrieving profile results for tag: {}", tag1);
let results_vec_tag1 = rpc_server
.get_profile_results_by_tag(Some(runloop_context.clone()), tag1.clone(), None)
.unwrap()
.value
.unwrap_or_default();
assert_eq!(results_vec_tag1.len(), 1, "Expected 1 result for tag1");
assert_eq!(
results_vec_tag1[0]
.transaction_profile
.compute_units_consumed,
rpc_response_tagged_1_value
.transaction_profile
.compute_units_consumed
);
assert_eq!(
results_vec_tag1[0]
.transaction_profile
.error_message
.is_none(),
rpc_response_tagged_1_value
.transaction_profile
.error_message
.is_none()
);
// Test 2: Retrieve with a non-existent tag
let tag_non_existent = "non_existent_tag".to_string();
println!(
"\nTesting retrieval with non-existent tag: {}",
tag_non_existent
);
let results_non_existent_vec = rpc_server
.get_profile_results_by_tag(
Some(runloop_context.clone()),
tag_non_existent.clone(),
None,
)
.unwrap()
.value
.unwrap_or_default();
assert!(
results_non_existent_vec.is_empty(),
"Expected empty vec for non-existent tag"
);
// Test 3: Estimate multiple times with the same tag
let tag2 = "test_tag_2".to_string();
println!("\nTesting multiple estimations with tag: {}", tag2);
let response_tagged_2a: JsonRpcResult<RpcResponse<UiKeyedProfileResult>> = rpc_server
.profile_transaction(
Some(runloop_context.clone()),
tx_b64.clone(),
Some(tag2.clone()),
None,
)
.await;
assert!(response_tagged_2a.is_ok(), "First call with tag2 failed");
let cu_2a_profile_result = response_tagged_2a.unwrap().value;
println!(
"CU estimation 1 (tag: {}): consumed = {}, success = {}",
tag2,
cu_2a_profile_result
.transaction_profile
.compute_units_consumed,
cu_2a_profile_result
.transaction_profile
.error_message
.is_none()
);
let response_tagged_2b: JsonRpcResult<RpcResponse<UiKeyedProfileResult>> = rpc_server
.profile_transaction(
Some(runloop_context.clone()),
tx_b64.clone(),
Some(tag2.clone()),
None,
)
.await;
assert!(response_tagged_2b.is_ok(), "Second call with tag2 failed");
let cu_2b_profile_result = response_tagged_2b.unwrap().value;
println!("Retrieving profile results for tag: {}", tag2);
let results_response_tag2 =
rpc_server.get_profile_results_by_tag(Some(runloop_context.clone()), tag2.clone(), None);
assert!(
results_response_tag2.is_ok(),
"get_profile_results for tag2 failed"
);
let results_vec_tag2 = results_response_tag2.unwrap().value.unwrap_or_default();
assert_eq!(results_vec_tag2.len(), 2, "Expected 2 results for tag2");
assert_eq!(
results_vec_tag2[0]
.transaction_profile
.compute_units_consumed,
cu_2a_profile_result
.transaction_profile
.compute_units_consumed
);
assert_eq!(
results_vec_tag2[1]
.transaction_profile
.compute_units_consumed,
cu_2b_profile_result
.transaction_profile
.compute_units_consumed
);
// Test 4: Estimate with another None tag, ensure it doesn't affect tagged results for tag1
println!(
"\nTesting None tag again to ensure no interference with tag: {}",
tag1
);
let response_no_tag_again: JsonRpcResult<RpcResponse<UiKeyedProfileResult>> = rpc_server
.profile_transaction(Some(runloop_context.clone()), tx_b64.clone(), None, None)
.await;
assert!(
response_no_tag_again.is_ok(),
"RPC call with None tag (again) failed"
);
let _rpc_response_no_tag_again_value = response_no_tag_again.unwrap().value;
println!("Retrieving profile results for tag: {} again", tag1);
let results_response_tag1_again =
rpc_server.get_profile_results_by_tag(Some(runloop_context), tag1.clone(), None);
assert!(
results_response_tag1_again.is_ok(),
"get_profile_results for tag1 (again) failed"
);
let results_vec_tag1_again = results_response_tag1_again
.unwrap()
.value
.unwrap_or_default();
assert_eq!(