magicsvm 0.2.0

A fast and lightweight Solana + MagicBlock VM simulator for testing solana programs
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
use {
    crate::magic::{
        base_action::{base_action_instruction, validator_fees_vault_pda},
        delegation_action::decrypt_post_delegation_instructions,
        effects::{EphemeralAccountEffect, MagicTransactionEffects, ScheduledBaseAction},
        magic_program::MagicProgramEntrypoint,
    },
    dlp_api::{
        args::PostDelegationActions, consts::DELEGATION_PROGRAM_ID, state::DelegationRecord,
    },
    ephemeral_rollups_sdk::{
        access_control::structs::EphemeralPermission,
        consts::{
            ASSOCIATED_TOKEN_PROGRAM_ID, EPHEMERAL_VAULT_ID, ESPL_TOKEN_PROGRAM_ID,
            MAGIC_CONTEXT_ID, MAGIC_PROGRAM_ID, PERMISSION_PROGRAM_ID, TOKEN_PROGRAM_ID,
        },
        ephemeral_accounts,
    },
    litesvm::{
        error::LiteSVMError,
        types::{FailedTransactionMetadata, SimulatedTransactionInfo, TransactionResult},
        LiteSVM,
    },
    magicblock_account::{
        Account as ForkAccount, AccountBuilder, AccountMode, AccountSharedData, ReadableAccount,
        WritableAccount,
    },
    solana_account::Account as StockAccount,
    solana_address::Address,
    solana_clock::Epoch,
    solana_fee_structure::FeeStructure,
    solana_hash::Hash,
    solana_keypair::Keypair,
    solana_message::{Message, VersionedMessage},
    solana_program_runtime::solana_sbpf::program::BuiltinFunctionDefinition,
    solana_rent::Rent,
    solana_sdk_ids::{bpf_loader_upgradeable, system_program},
    solana_signature::Signature,
    solana_signer::Signer,
    solana_sysvar::Sysvar,
    solana_sysvar_id::SysvarId,
    solana_transaction::{versioned::VersionedTransaction, InstructionError, Transaction},
    solana_transaction_error::TransactionError,
    std::{
        collections::{HashMap, HashSet},
        ops::{Deref, DerefMut},
        path::Path,
    },
    wincode::Serialize,
};

mod base_action;
mod delegation_action;
mod effects;
mod magic_program;

const SPL_TOKEN_ACCOUNT_LEN: usize = 165;
const SPL_TOKEN_ACCOUNT_STATE_INITIALIZED: u8 = 1;

/// Default lamports charged per signature by the underlying SVM, used to
/// pre-fund the fee payer so ephemeral transactions stay fee-free by default.
const DEFAULT_LAMPORTS_PER_SIGNATURE: u64 = 5_000;

/// Base58-encoded keypair used as the validator identity when a [`MagicSVM`] is
/// created without an explicit one (see [`MagicSVM::new`]).
pub const DEFAULT_VALIDATOR_IDENTITY: &str =
    "9Vo7TbA5YfC5a33JhAi9Fb41usA6JwecHNRw3f9MzzHAM8hFnXTzL5DcEHwsAFjuUZ8vNQcJ4XziRFpMc3gTgBQ";

/// Selects which of the two ledgers managed by a [`MagicSVM`] a transaction or
/// query is applied to.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TransactionTarget {
    /// The base layer (Solana L1) ledger.
    Base,
    /// The ephemeral rollup ledger, where delegated accounts live.
    Ephemeral,
}

/// A LiteSVM-based simulator that models both the Solana base layer and a
/// MagicBlock ephemeral rollup, keeping the two ledgers in sync as accounts are
/// delegated, committed and undelegated.
///
/// `MagicSVM` derefs to the base [`LiteSVM`], so the standard LiteSVM API is
/// available directly; the methods on this type add the MagicBlock-specific
/// behaviour and the [`TransactionTarget`]-aware variants.
pub struct MagicSVM {
    base: LiteSVM,
    ephemeral: LiteSVM,
    validator_keypair: Keypair,
    delegated_accounts: HashSet<Address>,
    authorized_user: Option<Address>,
}

impl Default for MagicSVM {
    fn default() -> Self {
        Self::new()
    }
}

impl Deref for MagicSVM {
    type Target = LiteSVM;

    fn deref(&self) -> &Self::Target {
        &self.base
    }
}

impl DerefMut for MagicSVM {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.base
    }
}

impl MagicSVM {
    /// Creates a new `MagicSVM` using the [`DEFAULT_VALIDATOR_IDENTITY`] as the
    /// validator keypair.
    pub fn new() -> Self {
        Self::new_with_validator_identity(Keypair::from_base58_string(DEFAULT_VALIDATOR_IDENTITY))
    }

    /// Creates a new `MagicSVM` with the given validator identity.
    ///
    /// This sets up both ledgers: the base layer is loaded with the delegation
    /// program, and the ephemeral layer is loaded with the Magic program along
    /// with its magic-context and shared-vault accounts. Both ledgers also load
    /// ESPL and the permission program.
    pub fn new_with_validator_identity(validator_keypair: Keypair) -> Self {
        let mut base = LiteSVM::new();
        base.add_program_with_loader(
            DELEGATION_PROGRAM_ID,
            include_bytes!("../../elfs/dlp.so"),
            bpf_loader_upgradeable::id(),
        )
        .unwrap();
        base.add_program_with_loader(
            ESPL_TOKEN_PROGRAM_ID,
            include_bytes!("../../elfs/espl.so"),
            bpf_loader_upgradeable::id(),
        )
        .unwrap();
        base.add_program_with_loader(
            PERMISSION_PROGRAM_ID,
            include_bytes!("../../elfs/permission.so"),
            bpf_loader_upgradeable::id(),
        )
        .unwrap();
        let validator_identity = validator_keypair.pubkey();
        let validator_fees_vault = validator_fees_vault_pda(validator_identity);
        let vault = AccountBuilder::from(ForkAccount {
            lamports: Rent::default().minimum_balance(8),
            data: vec![0; 8],
            owner: DELEGATION_PROGRAM_ID,
            executable: false,
            rent_epoch: Epoch::default(),
        })
        .build();
        base.accounts
            .add_account(validator_fees_vault, vault)
            .unwrap();
        base.airdrop(&validator_identity, 1_000_000_000).unwrap();
        let mut ephemeral =
            LiteSVM::new()
                .with_default_programs()
                .with_fee_structure(FeeStructure {
                    lamports_per_signature: 0,
                    lamports_per_write_lock: 0,
                    compute_fee_bins: vec![],
                });
        ephemeral.add_builtin(MAGIC_PROGRAM_ID, MagicProgramEntrypoint::register);
        ephemeral
            .add_program_with_loader(
                ESPL_TOKEN_PROGRAM_ID,
                include_bytes!("../../elfs/espl.so"),
                bpf_loader_upgradeable::id(),
            )
            .unwrap();
        ephemeral
            .add_program_with_loader(
                PERMISSION_PROGRAM_ID,
                include_bytes!("../../elfs/permission.so"),
                bpf_loader_upgradeable::id(),
            )
            .unwrap();
        let magic_context = AccountBuilder::from(ForkAccount {
            lamports: u64::MAX / 2,
            owner: MAGIC_PROGRAM_ID,
            ..Default::default()
        })
        .mode(AccountMode::Delegated)
        .build();
        ephemeral
            .accounts
            .add_account(MAGIC_CONTEXT_ID, magic_context)
            .unwrap();
        let shared_vault = AccountBuilder::from(ForkAccount {
            lamports: Rent::default().minimum_balance(0),
            data: vec![],
            owner: MAGIC_PROGRAM_ID,
            executable: false,
            rent_epoch: Epoch::default(),
        })
        .mode(AccountMode::Delegated)
        .build();
        ephemeral
            .accounts
            .add_account(EPHEMERAL_VAULT_ID, shared_vault)
            .unwrap();

        Self {
            base,
            ephemeral,
            validator_keypair,
            delegated_accounts: HashSet::new(),
            authorized_user: None,
        }
    }

    /// Returns the validator identity keypair.
    pub fn validator_keypair(&self) -> &Keypair {
        &self.validator_keypair
    }

    /// Returns the validator identity public key.
    pub fn validator_identity(&self) -> Address {
        self.validator_keypair.pubkey()
    }

    /// Returns a reference to the base layer [`LiteSVM`].
    pub fn base(&self) -> &LiteSVM {
        &self.base
    }

    /// Returns a mutable reference to the base layer [`LiteSVM`].
    pub fn base_mut(&mut self) -> &mut LiteSVM {
        &mut self.base
    }

    /// Returns a reference to the ephemeral rollup [`LiteSVM`].
    pub fn ephemeral(&self) -> &LiteSVM {
        &self.ephemeral
    }

    /// Returns a mutable reference to the ephemeral rollup [`LiteSVM`].
    pub fn ephemeral_mut(&mut self) -> &mut LiteSVM {
        &mut self.ephemeral
    }

    /// Sets the viewer identity used to filter private ephemeral accounts.
    ///
    /// `None` is an unauthorized viewer: private accounts are hidden from
    /// [`get_account_for`] when `target` is [`TransactionTarget::Ephemeral`].
    pub fn set_authorized_user(&mut self, user: Option<Address>) {
        self.authorized_user = user;
    }

    /// Returns the current viewer identity, if any.
    pub fn authorized_user(&self) -> Option<Address> {
        self.authorized_user
    }

    /// Sets a sysvar on both the base and ephemeral ledgers.
    pub fn set_sysvar<T>(&mut self, sysvar: &T)
    where
        T: Sysvar + SysvarId + Serialize<Src = T>,
    {
        self.base.set_sysvar(sysvar);
        self.ephemeral.set_sysvar(sysvar);
    }

    /// Warps the clock to `slot` on both the base and ephemeral ledgers.
    pub fn warp_to_slot(&mut self, slot: u64) {
        self.base.warp_to_slot(slot);
        self.ephemeral.warp_to_slot(slot);
    }

    /// Returns the account at `pubkey` from the base layer, or `None` if it does
    /// not exist.
    ///
    /// This shadows [`LiteSVM::get_account`] (reachable through `Deref`) so the
    /// PUBLIC return type is the STOCK [`solana_account::Account`] rather than
    /// the internal fork account type. Inherent methods take precedence over
    /// `Deref`, so callers always get the stock type.
    pub fn get_account(&self, pubkey: &Address) -> Option<StockAccount> {
        self.get_account_for(TransactionTarget::Base, pubkey)
    }

    /// Returns the account at `pubkey` from the given `target` ledger as a STOCK
    /// [`solana_account::Account`].
    ///
    /// For [`TransactionTarget::Ephemeral`], the ephemeral ledger is consulted
    /// first and the base ledger is used as a fallback. Private ephemeral
    /// accounts are hidden unless [`authorized_user`](Self::authorized_user) is
    /// a member of the account's permission.
    pub fn get_account_for(
        &self,
        target: TransactionTarget,
        pubkey: &Address,
    ) -> Option<StockAccount> {
        let fork = match target {
            TransactionTarget::Base => self.base.get_account(pubkey),
            TransactionTarget::Ephemeral => {
                if !self.viewer_can_read_ephemeral(pubkey) {
                    return None;
                }
                self.ephemeral
                    .get_account(pubkey)
                    .or_else(|| self.base.get_account(pubkey))
            }
        };
        fork.map(fork_account_to_stock)
    }

    fn viewer_can_read_ephemeral(&self, pubkey: &Address) -> bool {
        let (permission_pda, _) = EphemeralPermission::find_pda(pubkey);
        let Some(permission_account) = self
            .ephemeral
            .get_account(&permission_pda)
            .or_else(|| self.base.get_account(&permission_pda))
        else {
            return true;
        };
        if permission_account.owner != PERMISSION_PROGRAM_ID {
            return true;
        }
        let Ok(permission) = EphemeralPermission::from_bytes(&permission_account.data) else {
            return true;
        };
        if !permission.private {
            return true;
        }
        self.authorized_user.is_some_and(|user| {
            permission
                .members
                .iter()
                .any(|member| member.pubkey.as_ref() == user.as_ref())
        })
    }

    /// **⚠️ ADVANCED ACCESSOR ⚠️**
    ///
    /// Returns the account at `pubkey` as the internal fork
    /// [`magicblock_account::AccountSharedData`] from the given `target` ledger.
    ///
    /// Unlike the stock [`get_account_for`](MagicSVM::get_account_for), the
    /// returned value carries the MagicBlock lifecycle mode (delegated, ephemeral, ...).
    /// This intentionally exposes the fork type; for flag inspection prefer the
    /// stable, stock-friendly [`account_flags`](MagicSVM::account_flags).
    ///
    /// For [`TransactionTarget::Ephemeral`], the ephemeral ledger is consulted
    /// first and the base ledger is used as a fallback.
    pub fn get_shared_account_for(
        &self,
        target: TransactionTarget,
        pubkey: &Address,
    ) -> Option<AccountSharedData> {
        match target {
            TransactionTarget::Base => self.base.accounts.get_account(pubkey),
            TransactionTarget::Ephemeral => self
                .ephemeral
                .accounts
                .get_account(pubkey)
                .or_else(|| self.base.accounts.get_account(pubkey)),
        }
    }

    /// Sets the account at `pubkey` on the base layer from a STOCK
    /// [`solana_account::Account`].
    ///
    /// This shadows [`LiteSVM::set_account`] (reachable through `Deref`) so the
    /// PUBLIC parameter type is the STOCK account type; it is converted to the
    /// internal fork representation before being stored.
    pub fn set_account(
        &mut self,
        pubkey: Address,
        account: StockAccount,
    ) -> Result<(), LiteSVMError> {
        self.base
            .set_account(pubkey, stock_account_to_fork(account))
    }

    /// Returns the lamport balance of `pubkey` on the base layer.
    pub fn get_balance(&self, pubkey: &Address) -> Option<u64> {
        self.base.get_balance(pubkey)
    }

    /// Returns the latest blockhash of the base layer.
    pub fn latest_blockhash(&self) -> Hash {
        self.base.latest_blockhash()
    }

    /// Returns the latest blockhash of the given `target` ledger.
    pub fn latest_blockhash_for(&self, target: TransactionTarget) -> Hash {
        match target {
            TransactionTarget::Base => self.base.latest_blockhash(),
            TransactionTarget::Ephemeral => self.ephemeral.latest_blockhash(),
        }
    }

    /// Returns the result of a previously executed transaction identified by
    /// `signature` on the given `target` ledger.
    pub fn get_transaction_for(
        &self,
        target: TransactionTarget,
        signature: &Signature,
    ) -> Option<&TransactionResult> {
        match target {
            TransactionTarget::Base => self.base.get_transaction(signature),
            TransactionTarget::Ephemeral => self.ephemeral.get_transaction(signature),
        }
    }

    /// Expires the current blockhash of the given `target` ledger, forcing the
    /// next one to differ.
    pub fn expire_blockhash_for(&mut self, target: TransactionTarget) {
        match target {
            TransactionTarget::Base => self.base.expire_blockhash(),
            TransactionTarget::Ephemeral => self.ephemeral.expire_blockhash(),
        }
    }

    /// Airdrops `lamports` to `pubkey` on the base layer.
    pub fn airdrop(&mut self, pubkey: &Address, lamports: u64) -> TransactionResult {
        self.base.airdrop(pubkey, lamports)
    }

    /// Adds a program to both the base and ephemeral ledgers.
    pub fn add_program(
        &mut self,
        program_id: Address,
        program_bytes: &[u8],
    ) -> Result<(), LiteSVMError> {
        self.base.add_program(program_id, program_bytes)?;
        self.ephemeral.add_program(program_id, program_bytes)
    }

    /// Reads a program from `path` and adds it to both the base and ephemeral
    /// ledgers.
    pub fn add_program_from_file(
        &mut self,
        program_id: Address,
        path: impl AsRef<Path>,
    ) -> Result<(), LiteSVMError> {
        let program_bytes = std::fs::read(path).map_err(LiteSVMError::InvalidPath)?;
        self.add_program(program_id, &program_bytes)
    }

    /// Adds a program owned by `loader_id` to both the base and ephemeral
    /// ledgers.
    pub fn add_program_with_loader(
        &mut self,
        program_id: Address,
        program_bytes: &[u8],
        loader_id: Address,
    ) -> Result<(), LiteSVMError> {
        self.base
            .add_program_with_loader(program_id, program_bytes, loader_id)?;
        self.ephemeral
            .add_program_with_loader(program_id, program_bytes, loader_id)
    }

    /// Sends a transaction to the base layer, applying any MagicBlock effects
    /// (delegation, commit, undelegation) it triggers.
    pub fn send_transaction(&mut self, tx: impl Into<VersionedTransaction>) -> TransactionResult {
        self.send_transaction_to(TransactionTarget::Base, tx)
    }

    /// Sends a transaction to the given `target` ledger.
    ///
    /// For [`TransactionTarget::Base`], the resulting delegation/commit/
    /// undelegation effects are applied to keep both ledgers in sync. For
    /// [`TransactionTarget::Ephemeral`], writable accounts are first checked to
    /// be delegated, the fee payer and other undeleted readonly accounts are
    /// synced from the base layer, the transaction fee is refunded to the fee
    /// payer (ephemeral transactions are fee-free by default), and any magic
    /// program effects are applied afterwards; if applying the effects fails
    /// the transaction is rolled back on both ledgers.
    pub fn send_transaction_to(
        &mut self,
        target: TransactionTarget,
        tx: impl Into<VersionedTransaction>,
    ) -> TransactionResult {
        let vtx = tx.into();
        match target {
            TransactionTarget::Base => {
                let message = vtx.message.clone();
                let fee_payer = message
                    .static_account_keys()
                    .first()
                    .copied()
                    .unwrap_or_default();
                let writable_accounts = message
                    .static_account_keys()
                    .iter()
                    .enumerate()
                    .filter_map(|(index, key)| {
                        (index != 0
                            && message.is_maybe_writable_with_reserved_addresses(
                                index,
                                None::<&HashSet<Address>>,
                            ))
                        .then_some(*key)
                    })
                    .collect::<Vec<_>>();
                let result = self.base.send_transaction(vtx);
                if let Ok(meta) = result {
                    let effects =
                        MagicTransactionEffects::from_message_and_metadata(&message, &meta);
                    if let Err(err) = effects.apply_base(self, fee_payer) {
                        return Err(FailedTransactionMetadata { err, meta });
                    }
                    self.apply_base_account_state(&writable_accounts);
                    Ok(meta)
                } else {
                    result
                }
            }
            TransactionTarget::Ephemeral => {
                if let Err(err) = self.check_ephemeral_writable_accounts(&vtx.message) {
                    return Err(FailedTransactionMetadata {
                        err,
                        meta: Default::default(),
                    });
                }
                self.sync_ephemeral_fee_payer(&vtx.message);
                self.sync_ephemeral_readonly_accounts_from_base(&vtx.message);
                let message = vtx.message.clone();
                let fee_payer = message
                    .static_account_keys()
                    .first()
                    .copied()
                    .unwrap_or_default();
                let pre_accounts = self.ephemeral_accounts_snapshot(&message);
                let pre_base = self.base.clone();
                let pre_ephemeral = self.ephemeral.clone();
                let seeded_creates = self.seed_ephemeral_create_placeholders(&message);
                let prefund = self.prefund_ephemeral_fee(&message);
                let result = self.ephemeral.send_transaction(vtx);
                let fee = match &result {
                    Ok(meta) => meta.fee,
                    Err(failed) => failed.meta.fee,
                };
                self.settle_ephemeral_fee(&message, prefund, fee);
                if let Ok(meta) = &result {
                    let effects = MagicTransactionEffects::from_ephemeral_message_and_metadata(
                        &message, meta,
                    );
                    if let Err(err) =
                        self.reject_seeded_non_magic_creates(&seeded_creates, &effects)
                    {
                        self.base = pre_base;
                        self.ephemeral = pre_ephemeral;
                        return Err(FailedTransactionMetadata {
                            err,
                            meta: meta.clone(),
                        });
                    }
                    if let Err(err) = effects.apply_ephemeral_account(self, &pre_accounts) {
                        self.base = pre_base;
                        self.ephemeral = pre_ephemeral;
                        return Err(FailedTransactionMetadata {
                            err,
                            meta: meta.clone(),
                        });
                    }
                    if let Err(err) = effects.apply_base(self, fee_payer) {
                        self.base = pre_base;
                        self.ephemeral = pre_ephemeral;
                        return Err(FailedTransactionMetadata {
                            err,
                            meta: meta.clone(),
                        });
                    }
                    if let Err(err) = self.sync_projected_atas_to_eatas(&message) {
                        self.base = pre_base;
                        self.ephemeral = pre_ephemeral;
                        return Err(FailedTransactionMetadata {
                            err,
                            meta: meta.clone(),
                        });
                    }
                    self.unseed_ephemeral_create_placeholders(&seeded_creates);
                } else {
                    self.unseed_ephemeral_create_placeholders(&seeded_creates);
                }
                result
            }
        }
    }

    /// Simulates a transaction against the given `target` ledger without
    /// committing its effects.
    ///
    /// For [`TransactionTarget::Ephemeral`], writable accounts are still checked
    /// to be delegated before simulation.
    pub fn simulate_transaction_to(
        &mut self,
        target: TransactionTarget,
        tx: impl Into<VersionedTransaction>,
    ) -> std::result::Result<SimulatedTransactionInfo, FailedTransactionMetadata> {
        let vtx = tx.into();
        match target {
            TransactionTarget::Base => self.base.simulate_transaction(vtx),
            TransactionTarget::Ephemeral => {
                if let Err(err) = self.check_ephemeral_writable_accounts(&vtx.message) {
                    return Err(FailedTransactionMetadata {
                        err,
                        meta: Default::default(),
                    });
                }
                self.sync_ephemeral_fee_payer(&vtx.message);
                self.sync_ephemeral_readonly_accounts_from_base(&vtx.message);
                self.ephemeral.simulate_transaction(vtx)
            }
        }
    }

    /// Delegates an account to the ephemeral rollup.
    ///
    /// On the base layer the account's owner is set to the delegation program,
    /// while on the ephemeral layer a delegated copy retaining the original
    /// owner is installed. The account is recorded as delegated so that it
    /// becomes writable in ephemeral transactions.
    ///
    /// Returns [`TransactionError::AccountNotFound`] if the account does not
    /// exist on the base layer.
    pub fn delegate_account(&mut self, delegated_account: Address) -> Result<(), TransactionError> {
        let Some(mut base_account) = self.base.accounts.get_account(&delegated_account) else {
            return Err(TransactionError::AccountNotFound);
        };
        let original_owner = {
            let record_address = dlp_api::pda::delegation_record_pda_from_delegated_account(
                &delegated_account.to_bytes().into(),
            );
            if let Some(account) = self.base.get_account(&record_address.to_bytes().into()) {
                DelegationRecord::try_from_bytes_with_discriminator(&account.data)
                    .map(|rec| rec.owner.to_bytes().into())
                    .ok()
            } else {
                None
            }
            .unwrap_or(*base_account.owner())
        };
        base_account.set_owner(DELEGATION_PROGRAM_ID);
        self.base
            .accounts
            .add_account(delegated_account, base_account.clone())
            .map_err(|_| TransactionError::InvalidAccountIndex)?;

        base_account = with_mode(base_account, AccountMode::Delegated);
        base_account.set_owner(original_owner);
        self.ephemeral
            .accounts
            .add_account(delegated_account, base_account.clone())
            .map_err(|_| TransactionError::InvalidAccountIndex)?;
        self.delegated_accounts.insert(delegated_account);
        self.project_eata_to_ata(delegated_account, &base_account, original_owner)?;
        Ok(())
    }

    fn project_eata_to_ata(
        &mut self,
        delegated_account: Address,
        eata_account: &AccountSharedData,
        original_owner: Address,
    ) -> Result<(), TransactionError> {
        let Some((owner, mint, amount)) = parse_eata_data(eata_account.data()) else {
            return Ok(());
        };
        let expected_eata =
            Address::find_program_address(&[owner.as_ref(), mint.as_ref()], &ESPL_TOKEN_PROGRAM_ID)
                .0;
        if delegated_account != expected_eata || original_owner != ESPL_TOKEN_PROGRAM_ID {
            return Ok(());
        }

        let ata = Address::find_program_address(
            &[owner.as_ref(), TOKEN_PROGRAM_ID.as_ref(), mint.as_ref()],
            &ASSOCIATED_TOKEN_PROGRAM_ID,
        )
        .0;

        let mut ata_data = vec![0; SPL_TOKEN_ACCOUNT_LEN];
        ata_data[0..32].copy_from_slice(mint.as_ref());
        ata_data[32..64].copy_from_slice(owner.as_ref());
        ata_data[64..72].copy_from_slice(&amount.to_le_bytes());
        ata_data[108] = SPL_TOKEN_ACCOUNT_STATE_INITIALIZED;

        let ata_account = AccountBuilder::from(ForkAccount {
            lamports: Rent::default().minimum_balance(SPL_TOKEN_ACCOUNT_LEN),
            data: ata_data,
            owner: TOKEN_PROGRAM_ID,
            executable: false,
            rent_epoch: Epoch::default(),
        })
        .mode(AccountMode::Delegated)
        .build();
        self.ephemeral
            .accounts
            .add_account(ata, ata_account)
            .map_err(|_| TransactionError::InvalidAccountIndex)?;
        self.delegated_accounts.insert(ata);
        Ok(())
    }

    fn sync_projected_atas_to_eatas(
        &mut self,
        message: &VersionedMessage,
    ) -> Result<(), TransactionError> {
        for (index, ata) in message.static_account_keys().iter().enumerate() {
            if !message.is_maybe_writable_with_reserved_addresses(index, None::<&HashSet<Address>>)
            {
                continue;
            }
            let Some(ata_account) = self.ephemeral.accounts.get_account(ata) else {
                continue;
            };
            if *ata_account.owner() != TOKEN_PROGRAM_ID {
                continue;
            }
            let Some((owner, mint, amount)) = parse_token_account_data(ata_account.data()) else {
                continue;
            };
            let expected_ata = Address::find_program_address(
                &[owner.as_ref(), TOKEN_PROGRAM_ID.as_ref(), mint.as_ref()],
                &ASSOCIATED_TOKEN_PROGRAM_ID,
            )
            .0;
            if *ata != expected_ata {
                continue;
            }

            let eata = Address::find_program_address(
                &[owner.as_ref(), mint.as_ref()],
                &ESPL_TOKEN_PROGRAM_ID,
            )
            .0;
            if !self.delegated_accounts.contains(&eata) {
                continue;
            }
            let Some(mut eata_account) = self.ephemeral.accounts.get_account(&eata) else {
                continue;
            };
            if parse_eata_data(eata_account.data()).is_none() {
                continue;
            }
            eata_account.data_as_mut_slice()[64..72].copy_from_slice(&amount.to_le_bytes());
            self.ephemeral
                .accounts
                .add_account(eata, eata_account)
                .map_err(|_| TransactionError::InvalidAccountIndex)?;
        }
        Ok(())
    }

    /// Commits a delegated account's ephemeral state back to the base layer.
    ///
    /// Data and lamports are copied from the ephemeral copy. The base owner
    /// stays the delegation program until undelegate. Does nothing if the
    /// account is missing on either ledger.
    ///
    /// A projected SPL ATA is not written back onto the leftover base ATA;
    /// its backing EATA is committed instead.
    pub fn commit_account(&mut self, delegated_account: Address) {
        if let Some(eata) = self.eata_for_projected_ata(&delegated_account) {
            self.commit_account(eata);
            return;
        }
        let Some(ephemeral_account) = self.ephemeral.accounts.get_account(&delegated_account)
        else {
            return;
        };
        let Some(mut base_account) = self.base.accounts.get_account(&delegated_account) else {
            return;
        };
        base_account.set_lamports(ephemeral_account.lamports());
        base_account.set_data_from_slice(ephemeral_account.data());
        let _ = self
            .base
            .accounts
            .add_account(delegated_account, base_account);
    }

    /// Undelegates an account, returning ownership to the base layer.
    ///
    /// Latest ephemeral data and the original program owner are written to
    /// base, the account is removed from the delegated set, and the ephemeral
    /// copy is cleared.
    ///
    /// Undelegating a projected SPL ATA undelegates the backing EATA and clears
    /// the ephemeral projection without overwriting the leftover base ATA.
    pub fn undelegate_account(&mut self, delegated_account: Address) {
        if let Some(eata) = self.eata_for_projected_ata(&delegated_account) {
            self.undelegate_delegated_account(eata);
            self.clear_projected_ata(delegated_account);
            return;
        }
        let projected_ata = self.projected_ata_for_eata(&delegated_account);
        self.undelegate_delegated_account(delegated_account);
        if let Some(ata) = projected_ata {
            self.clear_projected_ata(ata);
        }
    }

    fn undelegate_delegated_account(&mut self, delegated_account: Address) {
        self.delegated_accounts.remove(&delegated_account);
        if let Some(ephemeral_account) = self.ephemeral.accounts.get_account(&delegated_account) {
            let base_account = with_mode(ephemeral_account, AccountMode::ReadOnly);
            let _ = self
                .base
                .accounts
                .add_account(delegated_account, base_account);
        } else if let Some(base_account) = self.base.accounts.get_account(&delegated_account) {
            let base_account = with_mode(base_account, AccountMode::ReadOnly);
            let _ = self
                .base
                .accounts
                .add_account(delegated_account, base_account);
        }
        let _ = self
            .ephemeral
            .set_account(delegated_account, ForkAccount::default());
    }

    fn clear_projected_ata(&mut self, ata: Address) {
        self.delegated_accounts.remove(&ata);
        let _ = self.ephemeral.set_account(ata, ForkAccount::default());
    }

    fn eata_for_projected_ata(&self, ata: &Address) -> Option<Address> {
        let ata_account = self.ephemeral.accounts.get_account(ata)?;
        if *ata_account.owner() != TOKEN_PROGRAM_ID {
            return None;
        }
        let (owner, mint, _) = parse_token_account_data(ata_account.data())?;
        let expected_ata = Address::find_program_address(
            &[owner.as_ref(), TOKEN_PROGRAM_ID.as_ref(), mint.as_ref()],
            &ASSOCIATED_TOKEN_PROGRAM_ID,
        )
        .0;
        if *ata != expected_ata {
            return None;
        }
        let eata =
            Address::find_program_address(&[owner.as_ref(), mint.as_ref()], &ESPL_TOKEN_PROGRAM_ID)
                .0;
        self.delegated_accounts.contains(&eata).then_some(eata)
    }

    fn projected_ata_for_eata(&self, eata: &Address) -> Option<Address> {
        let eata_account = self
            .ephemeral
            .accounts
            .get_account(eata)
            .or_else(|| self.base.accounts.get_account(eata))?;
        let (owner, mint, _) = parse_eata_data(eata_account.data())?;
        let expected_eata =
            Address::find_program_address(&[owner.as_ref(), mint.as_ref()], &ESPL_TOKEN_PROGRAM_ID)
                .0;
        if *eata != expected_eata {
            return None;
        }
        Some(
            Address::find_program_address(
                &[owner.as_ref(), TOKEN_PROGRAM_ID.as_ref(), mint.as_ref()],
                &ASSOCIATED_TOKEN_PROGRAM_ID,
            )
            .0,
        )
    }

    fn check_ephemeral_writable_accounts(
        &self,
        message: &VersionedMessage,
    ) -> Result<(), TransactionError> {
        for (index, key) in message.static_account_keys().iter().enumerate() {
            if message.is_maybe_writable_with_reserved_addresses(index, None::<&HashSet<Address>>)
                && !self.is_ephemeral_writable_exception(message, index, key)
                && !self.delegated_accounts.contains(key)
            {
                return Err(TransactionError::InvalidWritableAccount);
            }
        }
        Ok(())
    }

    /// Pre-inserts 0-lamport ephemeral placeholders for new writable accounts
    /// that a Magic create may populate. LiteSVM drops 0-lamport accounts on
    /// commit unless they are already tagged ephemeral, so MagicsVM must seed
    /// that flag before `send_transaction` or same-tx program writes are lost.
    fn seed_ephemeral_create_placeholders(&mut self, message: &VersionedMessage) -> Vec<Address> {
        if !message.static_account_keys().contains(&MAGIC_PROGRAM_ID)
            || !message.static_account_keys().contains(&EPHEMERAL_VAULT_ID)
        {
            return Vec::new();
        }
        let mut seeded = Vec::new();
        for (index, key) in message.static_account_keys().iter().enumerate() {
            if index == 0 || *key == MAGIC_CONTEXT_ID || *key == EPHEMERAL_VAULT_ID {
                continue;
            }
            if !message.is_maybe_writable_with_reserved_addresses(index, None::<&HashSet<Address>>)
            {
                continue;
            }
            if self.ephemeral.accounts.get_account(key).is_some() {
                continue;
            }
            let placeholder = with_mode(
                AccountSharedData::new(0, 0, &system_program::id()),
                AccountMode::Ephemeral,
            );
            self.ephemeral
                .accounts
                .add_account_no_checks(*key, placeholder);
            seeded.push(*key);
        }
        seeded
    }

    fn unseed_ephemeral_create_placeholders(&mut self, seeded: &[Address]) {
        for key in seeded {
            if self.is_ephemeral_create_placeholder(key) {
                let _ = self
                    .ephemeral
                    .accounts
                    .add_account(*key, AccountSharedData::new(0, 0, &system_program::id()));
            }
        }
    }

    /// Seeds exist so LiteSVM will keep 0-lamport Magic creates. If a seeded
    /// account was mutated without a corresponding Magic create effect, this
    /// was a regular account create and must be rejected.
    fn reject_seeded_non_magic_creates(
        &self,
        seeded: &[Address],
        effects: &MagicTransactionEffects,
    ) -> Result<(), TransactionError> {
        let magic_creates: HashSet<Address> = effects
            .ephemeral_accounts
            .iter()
            .filter_map(|effect| match effect {
                EphemeralAccountEffect::Create { account, .. } => Some(*account),
                _ => None,
            })
            .collect();
        for key in seeded {
            if magic_creates.contains(key) || self.is_ephemeral_create_placeholder(key) {
                continue;
            }
            return Err(TransactionError::InvalidWritableAccount);
        }
        Ok(())
    }

    fn is_ephemeral_create_placeholder(&self, key: &Address) -> bool {
        self.ephemeral
            .accounts
            .get_account(key)
            .is_some_and(|account| {
                account.lamports() == 0
                    && account.owner() == &system_program::id()
                    && account.data().is_empty()
            })
    }

    fn is_ephemeral_writable_exception(
        &self,
        message: &VersionedMessage,
        account_index: usize,
        key: &Address,
    ) -> bool {
        account_index == 0
            || *key == MAGIC_CONTEXT_ID
            || *key == EPHEMERAL_VAULT_ID
            || match self.ephemeral.accounts.get_account(key) {
                Some(account) => {
                    account.is(AccountMode::Ephemeral)
                        || (account.lamports() == 0
                            && account.owner() == &solana_sdk_ids::system_program::ID)
                }
                None => {
                    message.static_account_keys().contains(&MAGIC_PROGRAM_ID)
                        && message.static_account_keys().contains(&EPHEMERAL_VAULT_ID)
                }
            }
    }

    /// Pre-funds the fee payer on the ephemeral ledger so the SVM's fee
    /// validation succeeds even for payers that do not hold enough lamports to
    /// cover the fee. Transactions on the ephemeral rollup are fee-free by
    /// default, so no payer should be required to fund the fee.
    ///
    /// The pre-funded amount is removed again — and the fee the SVM charged is
    /// credited back — by [`Self::settle_ephemeral_fee`] once the transaction
    /// has run, leaving the fee payer at its real balance.
    fn prefund_ephemeral_fee(&mut self, message: &VersionedMessage) -> u64 {
        let prefund = u64::from(message.header().num_required_signatures)
            .saturating_mul(DEFAULT_LAMPORTS_PER_SIGNATURE);
        if prefund == 0 {
            return 0;
        }
        let Some(fee_payer) = message.static_account_keys().first().copied() else {
            return 0;
        };
        let mut account = self
            .ephemeral
            .accounts
            .get_account(&fee_payer)
            .unwrap_or_else(|| {
                let mut account = AccountSharedData::default();
                account.set_owner(system_program::id());
                account
            });
        if account.checked_add_lamports(prefund).is_err() {
            return 0;
        }
        if self
            .ephemeral
            .accounts
            .add_account(fee_payer, account)
            .is_err()
        {
            return 0;
        }
        prefund
    }

    /// Restores the fee payer to its real balance after an ephemeral
    /// transaction: the amount pre-funded by [`Self::prefund_ephemeral_fee`] is
    /// removed and the `fee` the SVM charged is credited back, so the net
    /// transaction fee on the ephemeral rollup is zero. The base layer keeps its
    /// normal fees.
    fn settle_ephemeral_fee(&mut self, message: &VersionedMessage, prefund: u64, fee: u64) {
        if prefund == 0 && fee == 0 {
            return;
        }
        let Some(fee_payer) = message.static_account_keys().first().copied() else {
            return;
        };
        let Some(mut account) = self.ephemeral.accounts.get_account(&fee_payer) else {
            return;
        };
        let adjusted = account
            .lamports()
            .saturating_add(fee)
            .saturating_sub(prefund);
        account.set_lamports(adjusted);
        let _ = self.ephemeral.accounts.add_account(fee_payer, account);
    }

    fn sync_ephemeral_fee_payer(&mut self, message: &VersionedMessage) {
        let Some(fee_payer) = message.static_account_keys().first() else {
            return;
        };
        if self.ephemeral.accounts.get_account(fee_payer).is_some() {
            return;
        }
        if let Some(account) = self.base.accounts.get_account(fee_payer) {
            let _ = self.ephemeral.accounts.add_account(*fee_payer, account);
        }
    }

    /// Copies undeleted, non-delegated readonly accounts from the base ledger
    /// onto the ephemeral SVM so execution can read them the way a real ER
    /// does. Delegated and writable accounts are left alone.
    fn sync_ephemeral_readonly_accounts_from_base(&mut self, message: &VersionedMessage) {
        for (index, key) in message.static_account_keys().iter().enumerate() {
            if index == 0
                || message
                    .is_maybe_writable_with_reserved_addresses(index, None::<&HashSet<Address>>)
                || self.delegated_accounts.contains(key)
            {
                continue;
            }
            let Some(account) = self.base.accounts.get_account(key) else {
                continue;
            };
            let _ = self.ephemeral.accounts.add_account(*key, account);
        }
    }

    fn ephemeral_accounts_snapshot(
        &self,
        message: &VersionedMessage,
    ) -> HashMap<Address, AccountSharedData> {
        message
            .static_account_keys()
            .iter()
            .filter_map(|key| {
                self.ephemeral
                    .accounts
                    .get_account(key)
                    .map(|account| (*key, account))
            })
            .collect()
    }

    fn create_ephemeral_account(
        &mut self,
        sponsor: Address,
        account: Address,
        owner: Address,
        data_len: u32,
    ) -> Result<(), TransactionError> {
        let rent = ephemeral_accounts::rent(data_len);
        self.transfer_ephemeral_rent(sponsor, EPHEMERAL_VAULT_ID, rent)?;
        let ephemeral_account = with_mode(
            self.ephemeral
                .accounts
                .get_account(&account)
                .unwrap_or_else(|| AccountSharedData::new(0, data_len as usize, &owner)),
            AccountMode::Ephemeral,
        );
        self.ephemeral
            .accounts
            .add_account_no_checks(account, ephemeral_account);
        Ok(())
    }

    fn resize_ephemeral_account(
        &mut self,
        sponsor: Address,
        account: Address,
        new_data_len: u32,
        pre_accounts: &HashMap<Address, AccountSharedData>,
    ) -> Result<(), TransactionError> {
        let mut ephemeral_account = self
            .ephemeral
            .accounts
            .get_account(&account)
            .or_else(|| pre_accounts.get(&account).cloned())
            .ok_or(TransactionError::AccountNotFound)?;
        if !ephemeral_account.is(AccountMode::Ephemeral) {
            return Err(TransactionError::InstructionError(
                0,
                InstructionError::InvalidAccountData,
            ));
        }

        let old_data_len = pre_accounts
            .get(&account)
            .map(|account| account.data().len())
            .unwrap_or_else(|| ephemeral_account.data().len())
            .try_into()
            .map_err(|_| {
                TransactionError::InstructionError(0, InstructionError::ArithmeticOverflow)
            })?;
        let old_rent = ephemeral_accounts::rent(old_data_len);
        let new_rent = ephemeral_accounts::rent(new_data_len);
        if new_rent >= old_rent {
            self.transfer_ephemeral_rent(sponsor, EPHEMERAL_VAULT_ID, new_rent - old_rent)?;
        } else {
            self.transfer_ephemeral_rent(EPHEMERAL_VAULT_ID, sponsor, old_rent - new_rent)?;
        }

        ephemeral_account.resize(new_data_len as usize, 0);
        self.ephemeral
            .accounts
            .add_account_no_checks(account, ephemeral_account);
        Ok(())
    }

    fn close_ephemeral_account(
        &mut self,
        sponsor: Address,
        account: Address,
        pre_accounts: &HashMap<Address, AccountSharedData>,
    ) -> Result<(), TransactionError> {
        let ephemeral_account = self
            .ephemeral
            .accounts
            .get_account(&account)
            .or_else(|| pre_accounts.get(&account).cloned())
            .ok_or(TransactionError::AccountNotFound)?;
        if !ephemeral_account.is(AccountMode::Ephemeral) {
            return Err(TransactionError::InstructionError(
                0,
                InstructionError::InvalidAccountData,
            ));
        }

        let data_len = ephemeral_account.data().len().try_into().map_err(|_| {
            TransactionError::InstructionError(0, InstructionError::ArithmeticOverflow)
        })?;
        self.transfer_ephemeral_rent(
            EPHEMERAL_VAULT_ID,
            sponsor,
            ephemeral_accounts::rent(data_len),
        )?;

        let mut closed = AccountSharedData::default();
        closed.set_owner(system_program::id());
        self.ephemeral
            .accounts
            .add_account(account, closed)
            .map_err(|_| TransactionError::InvalidAccountIndex)
    }

    fn transfer_ephemeral_rent(
        &mut self,
        from: Address,
        to: Address,
        amount: u64,
    ) -> Result<(), TransactionError> {
        let mut from_account = self
            .ephemeral
            .accounts
            .get_account(&from)
            .ok_or(TransactionError::AccountNotFound)?;
        let mut to_account = self
            .ephemeral
            .accounts
            .get_account(&to)
            .ok_or(TransactionError::AccountNotFound)?;
        from_account.checked_sub_lamports(amount).map_err(|_| {
            TransactionError::InstructionError(0, InstructionError::InsufficientFunds)
        })?;
        to_account.checked_add_lamports(amount).map_err(|_| {
            TransactionError::InstructionError(0, InstructionError::ArithmeticOverflow)
        })?;
        self.ephemeral
            .accounts
            .add_account(from, from_account)
            .map_err(|_| TransactionError::InvalidAccountIndex)?;
        self.ephemeral
            .accounts
            .add_account(to, to_account)
            .map_err(|_| TransactionError::InvalidAccountIndex)
    }

    fn run_post_delegation_actions(
        &mut self,
        actions: Option<PostDelegationActions>,
        fee_payer: Address,
    ) -> Result<(), TransactionError> {
        let Some(actions) = actions else {
            return Ok(());
        };

        let instructions = decrypt_post_delegation_instructions(
            actions,
            &self.validator_identity().to_bytes(),
            &self.validator_keypair.to_bytes(),
        )?;
        let payer = instructions
            .iter()
            .flat_map(|instruction| instruction.accounts.iter())
            .find(|account| account.is_signer)
            .map(|account| account.pubkey)
            .unwrap_or(fee_payer);
        let message = Message::new_with_blockhash(
            &instructions,
            Some(&payer),
            &self.ephemeral.latest_blockhash(),
        );
        let tx = Transaction::new_unsigned(message);
        let sigverify = self.ephemeral.get_sigverify();
        self.ephemeral.set_sigverify(false);
        let result = self.send_transaction_to(TransactionTarget::Ephemeral, tx);
        self.ephemeral.set_sigverify(sigverify);
        result.map(|_| ()).map_err(|err| err.err)
    }

    fn run_post_commit_actions(
        &mut self,
        actions: &[ScheduledBaseAction],
    ) -> Result<(), TransactionError> {
        if actions.is_empty() {
            return Ok(());
        }

        for scheduled in actions {
            let instruction = base_action_instruction(
                &scheduled.action,
                scheduled.escrow_authority,
                self.validator_identity(),
            );
            self.send_transaction_to(
                TransactionTarget::Base,
                Transaction::new_signed_with_payer(
                    &[instruction],
                    Some(&self.validator_identity()),
                    &[&self.validator_keypair],
                    self.base.latest_blockhash(),
                ),
            )
            .map_err(|err| err.err)?;
        }
        Ok(())
    }

    fn apply_base_account_state(&mut self, writable_accounts: &[Address]) {
        for account in writable_accounts {
            if self.has_delegation_metadata_for(account) {
                if !self.delegated_accounts.contains(account) {
                    let _ = self.delegate_account(*account);
                }
            } else if self.delegated_accounts.contains(account)
                && self
                    .base
                    .accounts
                    .get_account(account)
                    .is_some_and(|account| *account.owner() != DELEGATION_PROGRAM_ID)
                && !self.is_projected_ata_for_delegated_eata(account)
            {
                self.undelegate_account(*account);
            }
        }
    }

    fn is_projected_ata_for_delegated_eata(&self, ata: &Address) -> bool {
        self.eata_for_projected_ata(ata).is_some()
    }

    fn has_delegation_metadata_for(&self, delegated_account: &Address) -> bool {
        let metadata = Address::find_program_address(
            &[b"delegation-metadata", delegated_account.as_ref()],
            &DELEGATION_PROGRAM_ID,
        )
        .0;
        self.base
            .accounts
            .get_account(&metadata)
            .is_some_and(|account| *account.owner() == DELEGATION_PROGRAM_ID)
    }
}

fn with_mode(account: AccountSharedData, mode: AccountMode) -> AccountSharedData {
    AccountBuilder::from(account).mode(mode).build()
}

/// Converts an internal fork [`ForkAccount`] into a STOCK
/// [`solana_account::Account`] by copying its fields (the stock type carries no
/// MagicBlock flags).
fn fork_account_to_stock(account: ForkAccount) -> StockAccount {
    StockAccount {
        lamports: account.lamports,
        data: account.data,
        owner: account.owner,
        executable: account.executable,
        rent_epoch: account.rent_epoch,
    }
}

/// Converts a STOCK [`solana_account::Account`] into an internal fork
/// [`ForkAccount`] by copying its fields (flags default to unset).
fn stock_account_to_fork(account: StockAccount) -> ForkAccount {
    ForkAccount {
        lamports: account.lamports,
        data: account.data,
        owner: account.owner,
        executable: account.executable,
        rent_epoch: account.rent_epoch,
    }
}

fn parse_eata_data(data: &[u8]) -> Option<(Address, Address, u64)> {
    let owner = Address::new_from_array(data.get(0..32)?.try_into().ok()?);
    let mint = Address::new_from_array(data.get(32..64)?.try_into().ok()?);
    let amount = u64::from_le_bytes(data.get(64..72)?.try_into().ok()?);
    Some((owner, mint, amount))
}

fn parse_token_account_data(data: &[u8]) -> Option<(Address, Address, u64)> {
    let mint = Address::new_from_array(data.get(0..32)?.try_into().ok()?);
    let owner = Address::new_from_array(data.get(32..64)?.try_into().ok()?);
    let amount = u64::from_le_bytes(data.get(64..72)?.try_into().ok()?);
    Some((owner, mint, amount))
}