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
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
use core::convert::Infallible;

#[cfg(target_family = "wasm")]
pub mod internal {
    use core::convert::Infallible;

    pub use soroban_env_guest::*;
    pub type EnvImpl = Guest;
    pub type MaybeEnvImpl = Guest;

    // In the Guest case, Env::Error is already Infallible so there is no work
    // to do to "reject an error": if an error occurs in the environment, the
    // host will trap our VM and we'll never get here at all.
    pub(crate) fn reject_err<T>(_env: &Guest, r: Result<T, Infallible>) -> Result<T, Infallible> {
        r
    }
}

#[cfg(not(target_family = "wasm"))]
pub mod internal {
    use core::convert::Infallible;

    pub use soroban_env_host::*;
    pub type EnvImpl = Host;
    pub type MaybeEnvImpl = Option<Host>;

    // When we have `feature="testutils"` (or are in cfg(test)) we enable feature
    // `soroban-env-{common,host}/testutils` which in turn adds the helper method
    // `Env::escalate_error_to_panic` to the Env trait.
    //
    // When this is available we want to use it, because it works in concert
    // with a _different_ part of the host that's also `testutils`-gated: the
    // mechanism for emulating the WASM VM error-handling semantics with native
    // contracts. In particular when a WASM contract calls a host function that
    // fails with some error E, the host traps the VM (not returning to it at
    // all) and propagates E to the caller of the contract. This is simulated in
    // the native case by returning a (nontrivial) error E to us here, which we
    // then "reject" back to the host, which stores E in a temporary cell inside
    // any `TestContract` frame in progress and then _panics_, unwinding back to
    // a panic-catcher it installed when invoking the `TestContract` frame, and
    // then extracting E from the frame and returning it to its caller. This
    // simulates the "crash, but catching the error" behaviour of the WASM case.
    // This only works if we panic via `escalate_error_to_panic`.
    //
    // (The reason we don't just panic_any() here and let the panic-catcher do a
    // type-based catch is that there might _be_ no panic-catcher around us, and
    // we want to print out a nice error message in that case too, which
    // panic_any() does not do us the favor of producing. This is all very
    // subtle. See also soroban_env_host::Host::escalate_error_to_panic.)
    #[cfg(any(test, feature = "testutils"))]
    pub(crate) fn reject_err<T>(env: &Host, r: Result<T, HostError>) -> Result<T, Infallible> {
        r.map_err(|e| env.escalate_error_to_panic(e))
    }

    // When we're _not_ in a cfg enabling `soroban-env-{common,host}/testutils`,
    // there is no `Env::escalate_error_to_panic` to call, so we just panic
    // here. But this is ok because in that case there is also no multi-contract
    // calling machinery set up, nor probably any panic-catcher installed that
    // we need to hide error values for the benefit of. Any panic in this case
    // is probably going to unwind completely anyways. No special case needed.
    #[cfg(not(any(test, feature = "testutils")))]
    pub(crate) fn reject_err<T>(_env: &Host, r: Result<T, HostError>) -> Result<T, Infallible> {
        r.map_err(|e| panic!("{:?}", e))
    }

    #[doc(hidden)]
    impl<F, T> Convert<F, T> for super::Env
    where
        EnvImpl: Convert<F, T>,
    {
        type Error = <EnvImpl as Convert<F, T>>::Error;
        fn convert(&self, f: F) -> Result<T, Self::Error> {
            self.env_impl.convert(f)
        }
    }
}

pub use internal::xdr;
pub use internal::ConversionError;
pub use internal::EnvBase;
pub use internal::Error;
pub use internal::MapObject;
pub use internal::SymbolStr;
pub use internal::TryFromVal;
pub use internal::TryIntoVal;
pub use internal::Val;
pub use internal::VecObject;

pub trait IntoVal<E: internal::Env, T> {
    fn into_val(&self, e: &E) -> T;
}

pub trait FromVal<E: internal::Env, T> {
    fn from_val(e: &E, v: &T) -> Self;
}

impl<E: internal::Env, T, U> FromVal<E, T> for U
where
    U: TryFromVal<E, T>,
{
    fn from_val(e: &E, v: &T) -> Self {
        U::try_from_val(e, v).unwrap_optimized()
    }
}

impl<E: internal::Env, T, U> IntoVal<E, T> for U
where
    T: FromVal<E, Self>,
{
    fn into_val(&self, e: &E) -> T {
        T::from_val(e, self)
    }
}

use crate::auth::InvokerContractAuthEntry;
use crate::unwrap::UnwrapInfallible;
use crate::unwrap::UnwrapOptimized;
use crate::InvokeError;
use crate::{
    crypto::Crypto, deploy::Deployer, events::Events, ledger::Ledger, logs::Logs, prng::Prng,
    storage::Storage, Address, Vec,
};
use internal::{
    AddressObject, Bool, BytesObject, DurationObject, I128Object, I256Object, I256Val, I64Object,
    StorageType, StringObject, Symbol, SymbolObject, TimepointObject, U128Object, U256Object,
    U256Val, U32Val, U64Object, U64Val, Void,
};

#[doc(hidden)]
#[derive(Clone)]
pub struct MaybeEnv {
    maybe_env_impl: internal::MaybeEnvImpl,
    #[cfg(any(test, feature = "testutils"))]
    test_state: Option<EnvTestState>,
}

#[cfg(target_family = "wasm")]
impl TryFrom<MaybeEnv> for Env {
    type Error = Infallible;

    fn try_from(_value: MaybeEnv) -> Result<Self, Self::Error> {
        Ok(Env {
            env_impl: internal::EnvImpl {},
        })
    }
}

impl Default for MaybeEnv {
    fn default() -> Self {
        Self::none()
    }
}

#[cfg(target_family = "wasm")]
impl MaybeEnv {
    // separate function to be const
    pub const fn none() -> Self {
        Self {
            maybe_env_impl: internal::EnvImpl {},
        }
    }
}

#[cfg(not(target_family = "wasm"))]
impl MaybeEnv {
    // separate function to be const
    pub const fn none() -> Self {
        Self {
            maybe_env_impl: None,
            #[cfg(any(test, feature = "testutils"))]
            test_state: None,
        }
    }
}

#[cfg(target_family = "wasm")]
impl From<Env> for MaybeEnv {
    fn from(value: Env) -> Self {
        MaybeEnv {
            maybe_env_impl: value.env_impl,
        }
    }
}

#[cfg(not(target_family = "wasm"))]
impl TryFrom<MaybeEnv> for Env {
    type Error = ConversionError;

    fn try_from(value: MaybeEnv) -> Result<Self, Self::Error> {
        if let Some(env_impl) = value.maybe_env_impl {
            Ok(Env {
                env_impl,
                #[cfg(any(test, feature = "testutils"))]
                test_state: value.test_state.unwrap_or_default(),
            })
        } else {
            Err(ConversionError)
        }
    }
}

#[cfg(not(target_family = "wasm"))]
impl From<Env> for MaybeEnv {
    fn from(value: Env) -> Self {
        MaybeEnv {
            maybe_env_impl: Some(value.env_impl.clone()),
            #[cfg(any(test, feature = "testutils"))]
            test_state: Some(value.test_state.clone()),
        }
    }
}

/// The [Env] type provides access to the environment the contract is executing
/// within.
///
/// The [Env] provides access to information about the currently executing
/// contract, who invoked it, contract data, functions for signing, hashing,
/// etc.
///
/// Most types require access to an [Env] to be constructed or converted.
#[derive(Clone)]
pub struct Env {
    env_impl: internal::EnvImpl,
    #[cfg(any(test, feature = "testutils"))]
    test_state: EnvTestState,
}

impl Default for Env {
    #[cfg(not(any(test, feature = "testutils")))]
    fn default() -> Self {
        Self {
            env_impl: Default::default(),
        }
    }

    #[cfg(any(test, feature = "testutils"))]
    fn default() -> Self {
        Self::new_with_config(EnvTestConfig::default())
    }
}

#[cfg(any(test, feature = "testutils"))]
#[derive(Clone, Default)]
struct EnvTestState {
    config: EnvTestConfig,
    generators: Rc<RefCell<Generators>>,
    auth_snapshot: Rc<RefCell<AuthSnapshot>>,
    snapshot: Option<Rc<LedgerSnapshot>>,
}

/// Config for changing the default behavior of the Env when used in tests.
#[cfg(any(test, feature = "testutils"))]
#[derive(Clone)]
pub struct EnvTestConfig {
    /// Capture a test snapshot when the Env is dropped, causing a test snapshot
    /// JSON file to be written to disk when the Env is no longer referenced.
    /// Defaults to true.
    pub capture_snapshot_at_drop: bool,
}

#[cfg(any(test, feature = "testutils"))]
impl Default for EnvTestConfig {
    fn default() -> Self {
        Self {
            capture_snapshot_at_drop: true,
        }
    }
}

impl Env {
    /// Panic with the given error.
    ///
    /// Equivalent to `panic!`, but with an error value instead of a string.
    #[doc(hidden)]
    #[inline(always)]
    pub fn panic_with_error(&self, error: impl Into<internal::Error>) -> ! {
        _ = internal::Env::fail_with_error(self, error.into());
        #[cfg(target_family = "wasm")]
        core::arch::wasm32::unreachable();
        #[cfg(not(target_family = "wasm"))]
        unreachable!();
    }

    /// Get a [Storage] for accessing and updating persistent data owned by the
    /// currently executing contract.
    #[inline(always)]
    pub fn storage(&self) -> Storage {
        Storage::new(self)
    }

    /// Get [Events] for publishing events associated with the
    /// currently executing contract.
    #[inline(always)]
    pub fn events(&self) -> Events {
        Events::new(self)
    }

    /// Get a [Ledger] for accessing the current ledger.
    #[inline(always)]
    pub fn ledger(&self) -> Ledger {
        Ledger::new(self)
    }

    /// Get a deployer for deploying contracts.
    #[inline(always)]
    pub fn deployer(&self) -> Deployer {
        Deployer::new(self)
    }

    /// Get a [Crypto] for accessing the current cryptographic functions.
    #[inline(always)]
    pub fn crypto(&self) -> Crypto {
        Crypto::new(self)
    }

    /// Get a [Prng] for accessing the current functions which provide pseudo-randomness.
    ///
    /// # Warning
    ///
    /// **The pseudo-random generator returned is not suitable for
    /// security-sensitive work.**
    #[inline(always)]
    pub fn prng(&self) -> Prng {
        Prng::new(self)
    }

    /// Get the Address object corresponding to the current executing contract.
    pub fn current_contract_address(&self) -> Address {
        let address = internal::Env::get_current_contract_address(self).unwrap_infallible();
        unsafe { Address::unchecked_new(self.clone(), address) }
    }

    #[doc(hidden)]
    pub(crate) fn require_auth_for_args(&self, address: &Address, args: Vec<Val>) {
        internal::Env::require_auth_for_args(self, address.to_object(), args.to_object())
            .unwrap_infallible();
    }

    #[doc(hidden)]
    pub(crate) fn require_auth(&self, address: &Address) {
        internal::Env::require_auth(self, address.to_object()).unwrap_infallible();
    }

    /// Invokes a function of a contract that is registered in the [Env].
    ///
    /// # Panics
    ///
    /// Will panic if the `contract_id` does not match a registered contract,
    /// `func` does not match a function of the referenced contract, or the
    /// number of `args` do not match the argument count of the referenced
    /// contract function.
    ///
    /// Will panic if the contract that is invoked fails or aborts in anyway.
    ///
    /// Will panic if the value returned from the contract cannot be converted
    /// into the type `T`.
    pub fn invoke_contract<T>(
        &self,
        contract_address: &Address,
        func: &crate::Symbol,
        args: Vec<Val>,
    ) -> T
    where
        T: TryFromVal<Env, Val>,
    {
        let rv = internal::Env::call(
            self,
            contract_address.to_object(),
            func.to_symbol_val(),
            args.to_object(),
        )
        .unwrap_infallible();
        T::try_from_val(self, &rv)
            .map_err(|_| ConversionError)
            .unwrap()
    }

    /// Invokes a function of a contract that is registered in the [Env],
    /// returns an error if the invocation fails for any reason.
    pub fn try_invoke_contract<T, E>(
        &self,
        contract_address: &Address,
        func: &crate::Symbol,
        args: Vec<Val>,
    ) -> Result<Result<T, T::Error>, Result<E, InvokeError>>
    where
        T: TryFromVal<Env, Val>,
        E: TryFrom<Error>,
        E::Error: Into<InvokeError>,
    {
        let rv = internal::Env::try_call(
            self,
            contract_address.to_object(),
            func.to_symbol_val(),
            args.to_object(),
        )
        .unwrap_infallible();
        match internal::Error::try_from_val(self, &rv) {
            Ok(err) => Err(E::try_from(err).map_err(Into::into)),
            Err(ConversionError) => Ok(T::try_from_val(self, &rv)),
        }
    }

    /// Authorizes sub-contract calls on behalf of the current contract.
    ///
    /// All the direct calls that the current contract performs are always
    /// considered to have been authorized. This is only needed to authorize
    /// deeper calls that originate from the next contract call from the current
    /// contract.
    ///
    /// For example, if the contract A calls contract B, contract
    /// B calls contract C and contract C calls `A.require_auth()`, then an
    /// entry corresponding to C call has to be passed in `auth_entries`. It
    /// doesn't matter if contract B called `require_auth` or not. If contract A
    /// calls contract B again, then `authorize_as_current_contract` has to be
    /// called again with the respective entries.
    ///
    ///
    pub fn authorize_as_current_contract(&self, auth_entries: Vec<InvokerContractAuthEntry>) {
        internal::Env::authorize_as_curr_contract(self, auth_entries.to_object())
            .unwrap_infallible();
    }

    /// Get the [Logs] for logging debug events.
    #[inline(always)]
    #[deprecated(note = "use [Env::logs]")]
    #[doc(hidden)]
    pub fn logger(&self) -> Logs {
        self.logs()
    }

    /// Get the [Logs] for logging debug events.
    #[inline(always)]
    pub fn logs(&self) -> Logs {
        Logs::new(self)
    }
}

#[cfg(any(test, feature = "testutils"))]
use crate::{
    auth,
    testutils::{
        budget::Budget, Address as _, AuthSnapshot, AuthorizedInvocation, ContractFunctionSet,
        EventsSnapshot, Generators, Ledger as _, MockAuth, MockAuthContract, Snapshot,
    },
    Bytes, BytesN,
};
#[cfg(any(test, feature = "testutils"))]
use core::{cell::RefCell, cell::RefMut};
#[cfg(any(test, feature = "testutils"))]
use internal::ContractInvocationEvent;
#[cfg(any(test, feature = "testutils"))]
use soroban_ledger_snapshot::LedgerSnapshot;
#[cfg(any(test, feature = "testutils"))]
use std::{path::Path, rc::Rc};
#[cfg(any(test, feature = "testutils"))]
use xdr::{
    LedgerEntry, LedgerKey, LedgerKeyContractData, ScErrorCode, ScErrorType,
    SorobanAuthorizationEntry,
};

#[cfg(any(test, feature = "testutils"))]
#[cfg_attr(feature = "docs", doc(cfg(feature = "testutils")))]
impl Env {
    #[doc(hidden)]
    pub fn in_contract(&self) -> bool {
        self.env_impl.has_frame().unwrap()
    }

    #[doc(hidden)]
    pub fn host(&self) -> &internal::Host {
        &self.env_impl
    }

    #[doc(hidden)]
    pub(crate) fn with_generator<T>(&self, f: impl FnOnce(RefMut<'_, Generators>) -> T) -> T {
        f((*self.test_state.generators).borrow_mut())
    }

    pub fn new_with_config(config: EnvTestConfig) -> Env {
        struct EmptySnapshotSource();

        impl internal::storage::SnapshotSource for EmptySnapshotSource {
            fn get(
                &self,
                _key: &Rc<xdr::LedgerKey>,
            ) -> Result<(Rc<xdr::LedgerEntry>, Option<u32>), soroban_env_host::HostError>
            {
                let err: internal::Error = (ScErrorType::Storage, ScErrorCode::MissingValue).into();
                Err(err.into())
            }

            fn has(&self, _key: &Rc<xdr::LedgerKey>) -> Result<bool, soroban_env_host::HostError> {
                Ok(false)
            }
        }

        let rf = Rc::new(EmptySnapshotSource());
        let info = internal::LedgerInfo {
            protocol_version: 20,
            sequence_number: 0,
            timestamp: 0,
            network_id: [0; 32],
            base_reserve: 0,
            min_persistent_entry_ttl: 4096,
            min_temp_entry_ttl: 16,
            max_entry_ttl: 6_312_000,
        };

        Env::new_for_testutils(config, rf, None, info, None)
    }

    /// Used by multiple constructors to configure test environments consistently.
    fn new_for_testutils(
        config: EnvTestConfig,
        recording_footprint: Rc<dyn internal::storage::SnapshotSource>,
        generators: Option<Rc<RefCell<Generators>>>,
        ledger_info: internal::LedgerInfo,
        snapshot: Option<Rc<LedgerSnapshot>>,
    ) -> Env {
        let storage = internal::storage::Storage::with_recording_footprint(recording_footprint);
        let budget = internal::budget::Budget::default();
        let env_impl = internal::EnvImpl::with_storage_and_budget(storage, budget.clone());
        env_impl
            .set_source_account(xdr::AccountId(xdr::PublicKey::PublicKeyTypeEd25519(
                xdr::Uint256([0; 32]),
            )))
            .unwrap();
        env_impl
            .set_diagnostic_level(internal::DiagnosticLevel::Debug)
            .unwrap();
        env_impl.set_base_prng_seed([0; 32]).unwrap();

        let auth_snapshot = Rc::new(RefCell::new(AuthSnapshot::default()));
        let auth_snapshot_in_hook = auth_snapshot.clone();
        env_impl
            .set_top_contract_invocation_hook(Some(Rc::new(move |host, event| {
                match event {
                    ContractInvocationEvent::Start => {}
                    ContractInvocationEvent::Finish => {
                        let new_auths = host
                            .get_authenticated_authorizations()
                            // If an error occurs getting the authenticated authorizations
                            // it means that no auth has occurred.
                            .unwrap();
                        (*auth_snapshot_in_hook).borrow_mut().0.push(new_auths);
                    }
                }
            })))
            .unwrap();

        let env = Env {
            env_impl,
            test_state: EnvTestState {
                config,
                generators: generators.unwrap_or_default(),
                snapshot,
                auth_snapshot,
            },
        };

        env.ledger().set(ledger_info);

        env
    }

    /// Register a contract with the [Env] for testing.
    ///
    /// Passing a contract ID for the first arguments registers the contract
    /// with that contract ID. Providing `None` causes the Env to generate a new
    /// contract ID that is assigned to the contract.
    ///
    /// Registering a contract that is already registered replaces it.
    ///
    /// Returns the contract ID of the registered contract.
    ///
    /// ### Examples
    /// ```
    /// use soroban_sdk::{contract, contractimpl, BytesN, Env, Symbol};
    ///
    /// #[contract]
    /// pub struct HelloContract;
    ///
    /// #[contractimpl]
    /// impl HelloContract {
    ///     pub fn hello(env: Env, recipient: Symbol) -> Symbol {
    ///         todo!()
    ///     }
    /// }
    ///
    /// #[test]
    /// fn test() {
    /// # }
    /// # fn main() {
    ///     let env = Env::default();
    ///     let contract_id = env.register_contract(None, HelloContract);
    /// }
    /// ```
    pub fn register_contract<'a, T: ContractFunctionSet + 'static>(
        &self,
        contract_id: impl Into<Option<&'a Address>>,
        contract: T,
    ) -> Address {
        struct InternalContractFunctionSet<T: ContractFunctionSet>(pub(crate) T);
        impl<T: ContractFunctionSet> internal::ContractFunctionSet for InternalContractFunctionSet<T> {
            fn call(
                &self,
                func: &Symbol,
                env_impl: &internal::EnvImpl,
                args: &[Val],
            ) -> Option<Val> {
                let env = Env {
                    env_impl: env_impl.clone(),
                    test_state: Default::default(),
                };
                self.0.call(
                    crate::Symbol::try_from_val(&env, func)
                        .unwrap_infallible()
                        .to_string()
                        .as_str(),
                    env,
                    args,
                )
            }
        }

        let contract_id = if let Some(contract_id) = contract_id.into() {
            contract_id.clone()
        } else {
            Address::generate(self)
        };
        self.env_impl
            .register_test_contract(
                contract_id.to_object(),
                Rc::new(InternalContractFunctionSet(contract)),
            )
            .unwrap();
        contract_id
    }

    /// Register a contract in a WASM file with the [Env] for testing.
    ///
    /// Passing a contract ID for the first arguments registers the contract
    /// with that contract ID. Providing `None` causes the Env to generate a new
    /// contract ID that is assigned to the contract.
    ///
    /// Registering a contract that is already registered replaces it.
    ///
    /// Returns the contract ID of the registered contract.
    ///
    /// ### Examples
    /// ```
    /// use soroban_sdk::{BytesN, Env};
    ///
    /// const WASM: &[u8] = include_bytes!("../doctest_fixtures/contract.wasm");
    ///
    /// #[test]
    /// fn test() {
    /// # }
    /// # fn main() {
    ///     let env = Env::default();
    ///     env.register_contract_wasm(None, WASM);
    /// }
    /// ```
    pub fn register_contract_wasm<'a>(
        &self,
        contract_id: impl Into<Option<&'a Address>>,
        contract_wasm: impl IntoVal<Env, Bytes>,
    ) -> Address {
        let wasm_hash: BytesN<32> = self.deployer().upload_contract_wasm(contract_wasm);
        self.register_contract_with_optional_contract_id_and_executable(
            contract_id,
            xdr::ContractExecutable::Wasm(xdr::Hash(wasm_hash.into())),
        )
    }

    /// Register the built-in Stellar Asset Contract with provided admin address.
    ///
    /// Returns the contract ID of the registered token contract.
    ///
    /// The contract will wrap a randomly-generated Stellar asset. This function
    /// is useful for using in the tests when an arbitrary token contract
    /// instance is needed.
    pub fn register_stellar_asset_contract(&self, admin: Address) -> Address {
        let issuer_pk = self.with_generator(|mut g| g.address());
        let issuer_id = xdr::AccountId(xdr::PublicKey::PublicKeyTypeEd25519(xdr::Uint256(
            issuer_pk.clone(),
        )));

        self.host()
            .with_mut_storage(|storage| {
                let k = Rc::new(xdr::LedgerKey::Account(xdr::LedgerKeyAccount {
                    account_id: issuer_id.clone(),
                }));

                if !storage.has(
                    &k,
                    soroban_env_host::budget::AsBudget::as_budget(self.host()),
                )? {
                    let v = Rc::new(xdr::LedgerEntry {
                        data: xdr::LedgerEntryData::Account(xdr::AccountEntry {
                            account_id: issuer_id.clone(),
                            balance: 0,
                            flags: 0,
                            home_domain: Default::default(),
                            inflation_dest: None,
                            num_sub_entries: 0,
                            seq_num: xdr::SequenceNumber(0),
                            thresholds: xdr::Thresholds([1; 4]),
                            signers: xdr::VecM::default(),
                            ext: xdr::AccountEntryExt::V0,
                        }),
                        last_modified_ledger_seq: 0,
                        ext: xdr::LedgerEntryExt::V0,
                    });
                    storage.put(
                        &k,
                        &v,
                        None,
                        soroban_env_host::budget::AsBudget::as_budget(self.host()),
                    )?
                }
                Ok(())
            })
            .unwrap();

        let asset = xdr::Asset::CreditAlphanum4(xdr::AlphaNum4 {
            asset_code: xdr::AssetCode4([b'a', b'a', b'a', 0]),
            issuer: issuer_id.clone(),
        });
        let create = xdr::HostFunction::CreateContract(xdr::CreateContractArgs {
            contract_id_preimage: xdr::ContractIdPreimage::Asset(asset),
            executable: xdr::ContractExecutable::StellarAsset,
        });

        let token_id: Address = self
            .env_impl
            .invoke_function(create)
            .unwrap()
            .try_into_val(self)
            .unwrap();

        let prev_auth_manager = self.env_impl.snapshot_auth_manager().unwrap();
        self.env_impl.switch_to_recording_auth(true).unwrap();
        self.invoke_contract::<()>(
            &token_id,
            &soroban_sdk_macros::internal_symbol_short!("set_admin"),
            (admin,).try_into_val(self).unwrap(),
        );
        self.env_impl.set_auth_manager(prev_auth_manager).unwrap();
        token_id
    }

    fn register_contract_with_optional_contract_id_and_executable<'a>(
        &self,
        contract_id: impl Into<Option<&'a Address>>,
        executable: xdr::ContractExecutable,
    ) -> Address {
        if let Some(contract_id) = contract_id.into() {
            self.register_contract_with_contract_id_and_executable(contract_id, executable);
            contract_id.clone()
        } else {
            self.register_contract_with_source(executable)
        }
    }

    fn register_contract_with_source(&self, executable: xdr::ContractExecutable) -> Address {
        let prev_auth_manager = self.env_impl.snapshot_auth_manager().unwrap();
        self.env_impl.switch_to_recording_auth(true).unwrap();

        let contract_id: Address = self
            .env_impl
            .invoke_function(xdr::HostFunction::CreateContract(xdr::CreateContractArgs {
                contract_id_preimage: xdr::ContractIdPreimage::Address(
                    xdr::ContractIdPreimageFromAddress {
                        address: xdr::ScAddress::Contract(xdr::Hash(
                            self.with_generator(|mut g| g.address()),
                        )),
                        salt: xdr::Uint256([0; 32]),
                    },
                ),
                executable,
            }))
            .unwrap()
            .try_into_val(self)
            .unwrap();

        self.env_impl.set_auth_manager(prev_auth_manager).unwrap();

        contract_id
    }

    /// Set authorizations and signatures in the environment which will be
    /// consumed by contracts when they invoke [`Address::require_auth`] or
    /// [`Address::require_auth_for_args`] functions.
    ///
    /// Requires valid signatures for the authorization to be successful.
    ///
    /// This function can also be called on contract clients.
    ///
    /// To mock auth for testing, without requiring valid signatures, use
    /// [`mock_all_auths`][Self::mock_all_auths] or
    /// [`mock_auths`][Self::mock_auths]. If mocking of auths is enabled,
    /// calling [`set_auths`][Self::set_auths] disables any mocking.
    pub fn set_auths(&self, auths: &[SorobanAuthorizationEntry]) {
        self.env_impl
            .set_authorization_entries(auths.to_vec())
            .unwrap();
    }

    /// Mock authorizations in the environment which will cause matching invokes
    /// of [`Address::require_auth`] and [`Address::require_auth_for_args`] to
    /// pass.
    ///
    /// This function can also be called on contract clients.
    ///
    /// Authorizations not matching a mocked auth will fail.
    ///
    /// To mock all auths, use [`mock_all_auths`][Self::mock_all_auths].
    ///
    /// ### Examples
    /// ```
    /// use soroban_sdk::{contract, contractimpl, Env, Address, testutils::{Address as _, MockAuth, MockAuthInvoke}, IntoVal};
    ///
    /// #[contract]
    /// pub struct HelloContract;
    ///
    /// #[contractimpl]
    /// impl HelloContract {
    ///     pub fn hello(env: Env, from: Address) {
    ///         from.require_auth();
    ///         // TODO
    ///     }
    /// }
    ///
    /// #[test]
    /// fn test() {
    /// # }
    /// # fn main() {
    ///     let env = Env::default();
    ///     let contract_id = env.register_contract(None, HelloContract);
    ///
    ///     let client = HelloContractClient::new(&env, &contract_id);
    ///     let addr = Address::generate(&env);
    ///     client.mock_auths(&[
    ///         MockAuth {
    ///             address: &addr,
    ///             invoke: &MockAuthInvoke {
    ///                 contract: &contract_id,
    ///                 fn_name: "hello",
    ///                 args: (&addr,).into_val(&env),
    ///                 sub_invokes: &[],
    ///             },
    ///         },
    ///     ]).hello(&addr);
    /// }
    /// ```
    pub fn mock_auths(&self, auths: &[MockAuth]) {
        for a in auths {
            self.register_contract(a.address, MockAuthContract);
        }
        let auths = auths
            .iter()
            .cloned()
            .map(Into::into)
            .collect::<std::vec::Vec<_>>();
        self.env_impl.set_authorization_entries(auths).unwrap();
    }

    /// Mock all calls to the [`Address::require_auth`] and
    /// [`Address::require_auth_for_args`] functions in invoked contracts,
    /// having them succeed as if authorization was provided.
    ///
    /// When mocking is enabled, if the [`Address`] being authorized is the
    /// address of a contract, that contract's `__check_auth` function will not
    /// be called, and the contract does not need to exist or be registered in
    /// the test.
    ///
    /// When mocking is enabled, if the [`Address`] being authorized is the
    /// address of an account, the account does not need to exist.
    ///
    /// This function can also be called on contract clients.
    ///
    /// To disable mocking, see [`set_auths`][Self::set_auths].
    ///
    /// To access a list of auths that have occurred, see [`auths`][Self::auths].
    ///
    /// It is not currently possible to mock a subset of auths.
    ///
    /// ### Examples
    /// ```
    /// use soroban_sdk::{contract, contractimpl, Env, Address, testutils::Address as _};
    ///
    /// #[contract]
    /// pub struct HelloContract;
    ///
    /// #[contractimpl]
    /// impl HelloContract {
    ///     pub fn hello(env: Env, from: Address) {
    ///         from.require_auth();
    ///         // TODO
    ///     }
    /// }
    ///
    /// #[test]
    /// fn test() {
    /// # }
    /// # fn main() {
    ///     let env = Env::default();
    ///     let contract_id = env.register_contract(None, HelloContract);
    ///
    ///     env.mock_all_auths();
    ///
    ///     let client = HelloContractClient::new(&env, &contract_id);
    ///     let addr = Address::generate(&env);
    ///     client.hello(&addr);
    /// }
    /// ```
    pub fn mock_all_auths(&self) {
        self.env_impl.switch_to_recording_auth(true).unwrap();
    }

    /// A version of `mock_all_auths` that allows authorizations that are not
    /// present in the root invocation.
    ///
    /// Refer to `mock_all_auths` documentation for general information and
    /// prefer using `mock_all_auths` unless non-root authorization is required.
    ///
    /// The only difference from `mock_all_auths` is that this won't return an
    /// error when `require_auth` hasn't been called in the root invocation for
    /// any given address. This is useful to test contracts that bundle calls to
    /// another contract without atomicity requirements (i.e. any contract call
    /// can be frontrun).
    ///
    /// ### Examples
    /// ```
    /// use soroban_sdk::{contract, contractimpl, Env, Address, testutils::Address as _};
    ///
    /// #[contract]
    /// pub struct ContractA;
    ///
    /// #[contractimpl]
    /// impl ContractA {
    ///     pub fn do_auth(env: Env, addr: Address) {
    ///         addr.require_auth();
    ///     }
    /// }
    /// #[contract]
    /// pub struct ContractB;
    ///
    /// #[contractimpl]
    /// impl ContractB {
    ///     pub fn call_a(env: Env, contract_a: Address, addr: Address) {
    ///         // Notice there is no `require_auth` call here.
    ///         ContractAClient::new(&env, &contract_a).do_auth(&addr);
    ///     }
    /// }
    /// #[test]
    /// fn test() {
    /// # }
    /// # fn main() {
    ///     let env = Env::default();
    ///     let contract_a = env.register_contract(None, ContractA);
    ///     let contract_b = env.register_contract(None, ContractB);
    ///     // The regular `env.mock_all_auths()` would result in the call
    ///     // failure.
    ///     env.mock_all_auths_allowing_non_root_auth();
    ///
    ///     let client = ContractBClient::new(&env, &contract_b);
    ///     let addr = Address::generate(&env);
    ///     client.call_a(&contract_a, &addr);
    /// }
    /// ```
    pub fn mock_all_auths_allowing_non_root_auth(&self) {
        self.env_impl.switch_to_recording_auth(false).unwrap();
    }

    /// Returns a list of authorization trees that were seen during the last
    /// contract or authorized host function invocation.
    ///
    /// Use this in tests to verify that the expected authorizations with the
    /// expected arguments are required.
    ///
    /// The return value is a vector of authorizations represented by tuples of
    /// `(address, AuthorizedInvocation)`. `AuthorizedInvocation` describes the
    /// tree of `require_auth_for_args(address, args)` from the contract
    /// functions (or `require_auth` with all the arguments of the function
    /// invocation). It also might contain the authorized host functions (
    /// currently CreateContract is the only such function) in case if
    /// corresponding host functions have been called.
    ///
    /// Refer to documentation for `AuthorizedInvocation` for detailed
    /// information on its contents.
    ///
    /// The order of the returned vector is defined by the order of
    /// [`Address::require_auth`] calls. Repeated calls to
    /// [`Address::require_auth`] with the same address and args in the same
    /// tree of contract invocations will appear only once in the vector.
    ///
    /// ### Examples
    /// ```
    /// use soroban_sdk::{contract, contractimpl, testutils::{Address as _, AuthorizedFunction, AuthorizedInvocation}, symbol_short, Address, Symbol, Env, IntoVal};
    ///
    /// #[contract]
    /// pub struct Contract;
    ///
    /// #[contractimpl]
    /// impl Contract {
    ///     pub fn transfer(env: Env, address: Address, amount: i128) {
    ///         address.require_auth();
    ///     }
    ///     pub fn transfer2(env: Env, address: Address, amount: i128) {
    ///         address.require_auth_for_args((amount / 2,).into_val(&env));
    ///     }
    /// }
    ///
    /// #[test]
    /// fn test() {
    /// # }
    /// # #[cfg(feature = "testutils")]
    /// # fn main() {
    ///     extern crate std;
    ///     let env = Env::default();
    ///     let contract_id = env.register_contract(None, Contract);
    ///     let client = ContractClient::new(&env, &contract_id);
    ///     env.mock_all_auths();
    ///     let address = Address::generate(&env);
    ///     client.transfer(&address, &1000_i128);
    ///     assert_eq!(
    ///         env.auths(),
    ///         std::vec![(
    ///             address.clone(),
    ///             AuthorizedInvocation {
    ///                 function: AuthorizedFunction::Contract((
    ///                     client.address.clone(),
    ///                     symbol_short!("transfer"),
    ///                     (&address, 1000_i128,).into_val(&env)
    ///                 )),
    ///                 sub_invocations: std::vec![]
    ///             }
    ///         )]
    ///     );
    ///
    ///     client.transfer2(&address, &1000_i128);
    ///     assert_eq!(
    ///         env.auths(),
    ///        std::vec![(
    ///             address.clone(),
    ///             AuthorizedInvocation {
    ///                 function: AuthorizedFunction::Contract((
    ///                     client.address.clone(),
    ///                     symbol_short!("transfer2"),
    ///                     // `transfer2` requires auth for (amount / 2) == (1000 / 2) == 500.
    ///                     (500_i128,).into_val(&env)
    ///                 )),
    ///                 sub_invocations: std::vec![]
    ///             }
    ///         )]
    ///     );
    /// }
    /// # #[cfg(not(feature = "testutils"))]
    /// # fn main() { }
    /// ```
    pub fn auths(&self) -> std::vec::Vec<(Address, AuthorizedInvocation)> {
        (*self.test_state.auth_snapshot)
            .borrow()
            .0
            .last()
            .cloned()
            .unwrap_or_default()
            .into_iter()
            .map(|(sc_addr, invocation)| {
                (
                    xdr::ScVal::Address(sc_addr).try_into_val(self).unwrap(),
                    AuthorizedInvocation::from_xdr(self, &invocation),
                )
            })
            .collect()
    }

    /// Invokes the special `__check_auth` function of contracts that implement
    /// the custom account interface.
    ///
    /// `__check_auth` can't be called outside of the host-managed `require_auth`
    /// calls. This test utility allows testing custom account contracts without
    /// the need to setup complex contract call trees and enabling the enforcing
    /// auth on the host side.
    ///
    /// This function requires to provide the template argument for error. Use
    /// `soroban_sdk::Error` if `__check_auth` doesn't return a special
    /// contract error and use the error with `contracterror` attribute
    /// otherwise.
    ///
    /// ### Examples
    /// ```
    /// use soroban_sdk::{contract, contracterror, contractimpl, testutils::{Address as _, BytesN as _}, vec, auth::Context, BytesN, Env, Vec, Val};
    ///
    /// #[contracterror]
    /// #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
    /// #[repr(u32)]
    /// pub enum NoopAccountError {
    ///     SomeError = 1,
    /// }
    /// #[contract]
    /// struct NoopAccountContract;
    /// #[contractimpl]
    /// impl NoopAccountContract {
    ///
    ///     #[allow(non_snake_case)]
    ///     pub fn __check_auth(
    ///         _env: Env,
    ///         _signature_payload: BytesN<32>,
    ///         signature: Val,
    ///         _auth_context: Vec<Context>,
    ///     ) -> Result<(), NoopAccountError> {
    ///         if signature.is_void() {
    ///             Err(NoopAccountError::SomeError)
    ///         } else {
    ///             Ok(())
    ///         }
    ///     }
    /// }
    /// #[test]
    /// fn test() {
    /// # }
    /// # fn main() {
    ///     let e: Env = Default::default();
    ///     let account_contract = NoopAccountContractClient::new(&e, &e.register_contract(None, NoopAccountContract));
    ///     // Non-succesful call of `__check_auth` with a `contracterror` error.
    ///     assert_eq!(
    ///         e.try_invoke_contract_check_auth::<NoopAccountError>(
    ///             &account_contract.address,
    ///             &BytesN::from_array(&e, &[0; 32]),
    ///             ().into(),
    ///             &vec![&e],
    ///         ),
    ///         // The inner `Result` is for conversion error and will be Ok
    ///         // as long as a valid error type used.
    ///         Err(Ok(NoopAccountError::SomeError))
    ///     );
    ///     // Successful call of `__check_auth` with a `soroban_sdk::InvokeError`
    ///     // error - this should be compatible with any error type.
    ///     assert_eq!(
    ///         e.try_invoke_contract_check_auth::<soroban_sdk::InvokeError>(
    ///             &account_contract.address,
    ///             &BytesN::from_array(&e, &[0; 32]),
    ///             0_i32.into(),
    ///             &vec![&e],
    ///         ),
    ///         Ok(())
    ///     );
    /// }
    /// ```
    pub fn try_invoke_contract_check_auth<E>(
        &self,
        contract: &Address,
        signature_payload: &BytesN<32>,
        signature: Val,
        auth_context: &Vec<auth::Context>,
    ) -> Result<(), Result<E, InvokeError>>
    where
        E: TryFrom<Error>,
        E::Error: Into<InvokeError>,
    {
        let args = Vec::from_array(
            self,
            [signature_payload.to_val(), signature, auth_context.to_val()],
        );
        let res = self
            .host()
            .call_account_contract_check_auth(contract.to_object(), args.to_object());
        match res {
            Ok(rv) => Ok(rv.into_val(self)),
            Err(e) => Err(e.error.try_into().map_err(Into::into)),
        }
    }

    fn register_contract_with_contract_id_and_executable(
        &self,
        contract_address: &Address,
        executable: xdr::ContractExecutable,
    ) {
        let contract_id = contract_address.contract_id();
        let data_key = xdr::ScVal::LedgerKeyContractInstance;
        let key = Rc::new(LedgerKey::ContractData(LedgerKeyContractData {
            contract: xdr::ScAddress::Contract(contract_id.clone()),
            key: data_key.clone(),
            durability: xdr::ContractDataDurability::Persistent,
        }));

        let instance = xdr::ScContractInstance {
            executable,
            storage: Default::default(),
        };

        let entry = Rc::new(LedgerEntry {
            ext: xdr::LedgerEntryExt::V0,
            last_modified_ledger_seq: 0,
            data: xdr::LedgerEntryData::ContractData(xdr::ContractDataEntry {
                contract: xdr::ScAddress::Contract(contract_id.clone()),
                key: data_key,
                val: xdr::ScVal::ContractInstance(instance),
                durability: xdr::ContractDataDurability::Persistent,
                ext: xdr::ExtensionPoint::V0,
            }),
        });
        let live_until_ledger = self.ledger().sequence() + 1;
        self.env_impl
            .with_mut_storage(|storage| {
                storage.put(
                    &key,
                    &entry,
                    Some(live_until_ledger),
                    soroban_env_host::budget::AsBudget::as_budget(self.host()),
                )
            })
            .unwrap();
    }

    /// Run the function as if executed by the given contract ID.
    ///
    /// Used to write or read contract data, or take other actions in tests for
    /// setting up tests or asserting on internal state.
    pub fn as_contract<T>(&self, id: &Address, f: impl FnOnce() -> T) -> T {
        let id: [u8; 32] = id.contract_id().into();
        let func = Symbol::from_small_str("");
        let mut t: Option<T> = None;
        self.env_impl
            .with_test_contract_frame(id.into(), func, || {
                t = Some(f());
                Ok(().into())
            })
            .unwrap();
        t.unwrap()
    }

    /// Creates a new Env loaded with the [`Snapshot`].
    ///
    /// The ledger info and state in the snapshot are loaded into the Env.
    ///
    /// Events, as an output source only, are not loaded into the Env.
    pub fn from_snapshot(s: Snapshot) -> Env {
        Env::new_for_testutils(
            EnvTestConfig::default(), // TODO: Allow setting the config.
            Rc::new(s.ledger.clone()),
            Some(Rc::new(RefCell::new(s.generators))),
            s.ledger.ledger_info(),
            Some(Rc::new(s.ledger.clone())),
        )
    }

    /// Creates a new Env loaded with the ledger snapshot loaded from the file.
    ///
    /// The ledger info and state in the snapshot are loaded into the Env.
    ///
    /// Events, as an output source only, are not loaded into the Env.
    ///
    /// ### Panics
    ///
    /// If there is any error reading the file.
    pub fn from_snapshot_file(p: impl AsRef<Path>) -> Env {
        Self::from_snapshot(Snapshot::read_file(p).unwrap())
    }

    /// Create a snapshot from the Env's current state.
    pub fn to_snapshot(&self) -> Snapshot {
        Snapshot {
            generators: (*self.test_state.generators).borrow().clone(),
            auth: (*self.test_state.auth_snapshot).borrow().clone(),
            ledger: self.to_ledger_snapshot(),
            events: self.to_events_snapshot(),
        }
    }

    /// Create a snapshot file from the Env's current state.
    ///
    /// ### Panics
    ///
    /// If there is any error writing the file.
    pub fn to_snapshot_file(&self, p: impl AsRef<Path>) {
        self.to_snapshot().write_file(p).unwrap();
    }

    /// Creates a new Env loaded with the [`LedgerSnapshot`].
    ///
    /// The ledger info and state in the snapshot are loaded into the Env.
    pub fn from_ledger_snapshot(s: LedgerSnapshot) -> Env {
        Env::new_for_testutils(
            EnvTestConfig::default(), // TODO: Allow setting the config.
            Rc::new(s.clone()),
            None,
            s.ledger_info(),
            Some(Rc::new(s.clone())),
        )
    }

    /// Creates a new Env loaded with the ledger snapshot loaded from the file.
    ///
    /// ### Panics
    ///
    /// If there is any error reading the file.
    pub fn from_ledger_snapshot_file(p: impl AsRef<Path>) -> Env {
        Self::from_ledger_snapshot(LedgerSnapshot::read_file(p).unwrap())
    }

    /// Create a snapshot from the Env's current state.
    pub fn to_ledger_snapshot(&self) -> LedgerSnapshot {
        let snapshot = self.test_state.snapshot.clone().unwrap_or_default();
        let mut snapshot = (*snapshot).clone();
        snapshot.set_ledger_info(self.ledger().get());
        let budget = soroban_env_host::budget::AsBudget::as_budget(&self.env_impl);
        let storage = self
            .env_impl
            .with_mut_storage(|s| Ok(s.map.clone()))
            .unwrap();
        snapshot.update_entries(storage.iter(budget).unwrap());
        snapshot
    }

    /// Create a snapshot file from the Env's current state.
    ///
    /// ### Panics
    ///
    /// If there is any error writing the file.
    pub fn to_ledger_snapshot_file(&self, p: impl AsRef<Path>) {
        self.to_ledger_snapshot().write_file(p).unwrap();
    }

    /// Create an events snapshot from the Env's current state.
    pub(crate) fn to_events_snapshot(&self) -> EventsSnapshot {
        EventsSnapshot(
            self.host()
                .get_events()
                .unwrap()
                .0
                .into_iter()
                .map(Into::into)
                .collect(),
        )
    }

    /// Get the budget that tracks the resources consumed for the environment.
    pub fn budget(&self) -> Budget {
        Budget::new(self.env_impl.budget_cloned())
    }
}

#[cfg(any(test, feature = "testutils"))]
impl Drop for Env {
    fn drop(&mut self) {
        // If the env impl (Host) is finishable, that means this Env is the last
        // Env to hold a reference to the Host. The Env should only write a test
        // snapshot at that point when no other references to the host exist,
        // because it is only when there are no other references that the host
        // is being dropped.
        if self.env_impl.can_finish() && self.test_state.config.capture_snapshot_at_drop {
            self.to_test_snapshot_file();
        }
    }
}

#[cfg(any(test, feature = "testutils"))]
#[derive(Default, Clone)]
struct LastTestSnapshot {
    name: String,
    number: usize,
}

#[cfg(any(test, feature = "testutils"))]
thread_local! {
    static LAST_TEST_SNAPSHOT: RefCell<LastTestSnapshot> = RefCell::new(LastTestSnapshot::default());
}

#[doc(hidden)]
#[cfg(any(test, feature = "testutils"))]
impl Env {
    /// Create a snapshot file for the currently executing test.
    ///
    /// Writes the file to the `test_snapshots/{test-name}.N.json` path where
    /// `N` is incremented for each unique `Env` in the test.
    ///
    /// Use to record the observable behavior of a test, and changes to that
    /// behavior over time. Commit the test snapshot file to version control and
    /// watch for changes in it on contract change, SDK upgrade, protocol
    /// upgrade, and other important events.
    ///
    /// No file will be created if the environment has no meaningful data such
    /// as stored entries or events.
    ///
    /// ### Panics
    ///
    /// If there is any error writing the file.
    pub(crate) fn to_test_snapshot_file(&self) {
        let snapshot = self.to_snapshot();

        // Don't write a snapshot that has no data in it.
        if snapshot.ledger.entries().into_iter().count() == 0
            && snapshot.events.0.is_empty()
            && snapshot.auth.0.is_empty()
        {
            return;
        }

        // Determine path to write test snapshots to.
        let thread = std::thread::current();
        let Some(test_name) = thread.name() else {
            // The stock unit test runner sets a thread name.
            // If there is no thread name, assume this is not running as
            // part of a unit test, and do nothing.
            return;
        };
        if test_name == "main" {
            // When doc tests are running they're all run with the thread name
            // main. There's no way to detect which doc test is being run and
            // there's little value in writing and overwriting a single file for
            // all doc tests.
            return;
        }
        let file_number = LAST_TEST_SNAPSHOT.with_borrow_mut(|l| {
            if test_name == l.name {
                *l = LastTestSnapshot::default();
                l.name = test_name.to_owned();
            }
            l.number += 1;
            l.number
        });
        // Break up the test name into directories, using :: as the separator.
        // The :: module separator cannot be written into the filename because
        // some operating systems (e.g. Windows) do not allow the : character in
        // filenames.
        let test_name_path = test_name
            .split("::")
            .map(|p| std::path::Path::new(p).to_path_buf())
            .reduce(|p0, p1| p0.join(p1))
            .expect("test name to not be empty");
        let dir = std::path::Path::new("test_snapshots");
        let p = dir
            .join(&test_name_path)
            .with_extension(format!("{file_number}.json"));

        // Write test snapshots to file.
        eprintln!("Writing test snapshot file for test {test_name:?} to {p:?}.");
        snapshot.write_file(p).unwrap();
    }
}

#[doc(hidden)]
impl internal::EnvBase for Env {
    type Error = Infallible;

    // This exists to allow code in conversion paths to upgrade an Error to an
    // Env::Error with some control granted to the underlying Env (and panic
    // paths kept out of the host). We delegate this to our env_impl and then,
    // since our own Error type is Infallible, immediately throw it into either
    // the env_impl's Error escalation path (if testing), or just plain panic.
    #[cfg(not(target_family = "wasm"))]
    fn error_from_error_val(&self, e: crate::Error) -> Self::Error {
        let host_err = self.env_impl.error_from_error_val(e);
        #[cfg(any(test, feature = "testutils"))]
        self.env_impl.escalate_error_to_panic(host_err);
        #[cfg(not(any(test, feature = "testutils")))]
        panic!("{:?}", host_err);
    }

    // When targeting wasm we don't even need to do that, just delegate to
    // the Guest's impl, which calls core::arch::wasm32::unreachable.
    #[cfg(target_family = "wasm")]
    fn error_from_error_val(&self, e: crate::Error) -> Self::Error {
        self.env_impl.error_from_error_val(e)
    }

    fn check_protocol_version_lower_bound(&self, v: u32) -> Result<(), Self::Error> {
        Ok(self
            .env_impl
            .check_protocol_version_lower_bound(v)
            .unwrap_optimized())
    }

    fn check_protocol_version_upper_bound(&self, v: u32) -> Result<(), Self::Error> {
        Ok(self
            .env_impl
            .check_protocol_version_upper_bound(v)
            .unwrap_optimized())
    }

    // Note: the function `escalate_error_to_panic` only exists _on the `Env`
    // trait_ when the feature `soroban-env-common/testutils` is enabled. This
    // is because the host wants to never have this function even _compiled in_
    // when building for production, as it might be accidentally called (we have
    // mistakenly done so with conversion and comparison traits in the past).
    //
    // As a result, we only implement it here (fairly meaninglessly) when we're
    // in `cfg(test)` (which enables `soroban-env-host/testutils` thus
    // `soroban-env-common/testutils`) or when we've had our own `testutils`
    // feature enabled (which does the same).
    //
    // See the `internal::reject_err` functions above for more detail about what
    // it actually does (when implemented for real, on the host). In this
    // not-very-serious impl, since `Self::Error` is `Infallible`, this instance
    // can never actually be called and so its body is just a trivial
    // transformation from one empty type to another, for Type System Reasons.
    #[cfg(any(test, feature = "testutils"))]
    fn escalate_error_to_panic(&self, e: Self::Error) -> ! {
        match e {}
    }

    fn check_same_env(&self, other: &Self) -> Result<(), Self::Error> {
        Ok(self
            .env_impl
            .check_same_env(&other.env_impl)
            .unwrap_optimized())
    }

    fn bytes_copy_from_slice(
        &self,
        b: BytesObject,
        b_pos: U32Val,
        slice: &[u8],
    ) -> Result<BytesObject, Self::Error> {
        Ok(self
            .env_impl
            .bytes_copy_from_slice(b, b_pos, slice)
            .unwrap_optimized())
    }

    fn bytes_copy_to_slice(
        &self,
        b: BytesObject,
        b_pos: U32Val,
        slice: &mut [u8],
    ) -> Result<(), Self::Error> {
        Ok(self
            .env_impl
            .bytes_copy_to_slice(b, b_pos, slice)
            .unwrap_optimized())
    }

    fn bytes_new_from_slice(&self, slice: &[u8]) -> Result<BytesObject, Self::Error> {
        Ok(self.env_impl.bytes_new_from_slice(slice).unwrap_optimized())
    }

    fn log_from_slice(&self, msg: &str, args: &[Val]) -> Result<Void, Self::Error> {
        Ok(self.env_impl.log_from_slice(msg, args).unwrap_optimized())
    }

    fn string_copy_to_slice(
        &self,
        b: StringObject,
        b_pos: U32Val,
        slice: &mut [u8],
    ) -> Result<(), Self::Error> {
        Ok(self
            .env_impl
            .string_copy_to_slice(b, b_pos, slice)
            .unwrap_optimized())
    }

    fn symbol_copy_to_slice(
        &self,
        b: SymbolObject,
        b_pos: U32Val,
        mem: &mut [u8],
    ) -> Result<(), Self::Error> {
        Ok(self
            .env_impl
            .symbol_copy_to_slice(b, b_pos, mem)
            .unwrap_optimized())
    }

    fn string_new_from_slice(&self, slice: &[u8]) -> Result<StringObject, Self::Error> {
        Ok(self
            .env_impl
            .string_new_from_slice(slice)
            .unwrap_optimized())
    }

    fn symbol_new_from_slice(&self, slice: &[u8]) -> Result<SymbolObject, Self::Error> {
        Ok(self
            .env_impl
            .symbol_new_from_slice(slice)
            .unwrap_optimized())
    }

    fn map_new_from_slices(&self, keys: &[&str], vals: &[Val]) -> Result<MapObject, Self::Error> {
        Ok(self
            .env_impl
            .map_new_from_slices(keys, vals)
            .unwrap_optimized())
    }

    fn map_unpack_to_slice(
        &self,
        map: MapObject,
        keys: &[&str],
        vals: &mut [Val],
    ) -> Result<Void, Self::Error> {
        Ok(self
            .env_impl
            .map_unpack_to_slice(map, keys, vals)
            .unwrap_optimized())
    }

    fn vec_new_from_slice(&self, vals: &[Val]) -> Result<VecObject, Self::Error> {
        Ok(self.env_impl.vec_new_from_slice(vals).unwrap_optimized())
    }

    fn vec_unpack_to_slice(&self, vec: VecObject, vals: &mut [Val]) -> Result<Void, Self::Error> {
        Ok(self
            .env_impl
            .vec_unpack_to_slice(vec, vals)
            .unwrap_optimized())
    }

    fn symbol_index_in_strs(&self, key: Symbol, strs: &[&str]) -> Result<U32Val, Self::Error> {
        Ok(self
            .env_impl
            .symbol_index_in_strs(key, strs)
            .unwrap_optimized())
    }
}

///////////////////////////////////////////////////////////////////////////////
/// X-macro use: impl Env for SDK's Env
///////////////////////////////////////////////////////////////////////////////

// This is a helper macro used only by impl_env_for_sdk below. It consumes a
// token-tree of the form:
//
//  {fn $fn_id:ident $args:tt -> $ret:ty}
//
// and produces the the corresponding method definition to be used in the
// SDK's Env implementation of the Env (calling through to the corresponding
// guest or host implementation).
macro_rules! sdk_function_helper {
    {$mod_id:ident, fn $fn_id:ident($($arg:ident:$type:ty),*) -> $ret:ty}
    =>
    {
        fn $fn_id(&self, $($arg:$type),*) -> Result<$ret, Self::Error> {
            internal::reject_err(&self.env_impl, self.env_impl.$fn_id($($arg),*))
        }
    };
}

// This is a callback macro that pattern-matches the token-tree passed by the
// x-macro (call_macro_with_all_host_functions) and produces a suite of
// forwarding-method definitions, which it places in the body of the declaration
// of the implementation of Env for the SDK's Env.
macro_rules! impl_env_for_sdk {
    {
        $(
            // This outer pattern matches a single 'mod' block of the token-tree
            // passed from the x-macro to this macro. It is embedded in a `$()*`
            // pattern-repetition matcher so that it will match all provided
            // 'mod' blocks provided.
            $(#[$mod_attr:meta])*
            mod $mod_id:ident $mod_str:literal
            {
                $(
                    // This inner pattern matches a single function description
                    // inside a 'mod' block in the token-tree passed from the
                    // x-macro to this macro. It is embedded in a `$()*`
                    // pattern-repetition matcher so that it will match all such
                    // descriptions.
                    $(#[$fn_attr:meta])*
                    { $fn_str:literal, $($min_proto:literal)?, $($max_proto:literal)?, fn $fn_id:ident $args:tt -> $ret:ty }
                )*
            }
        )*
    }

    =>  // The part of the macro above this line is a matcher; below is its expansion.

    {
        // This macro expands to a single item: the implementation of Env for
        // the SDK's Env struct used by client contract code running in a WASM VM.
        #[doc(hidden)]
        impl internal::Env for Env
        {
            $(
                $(
                    // This invokes the guest_function_helper! macro above
                    // passing only the relevant parts of the declaration
                    // matched by the inner pattern above. It is embedded in two
                    // nested `$()*` pattern-repetition expanders that
                    // correspond to the pattern-repetition matchers in the
                    // match section, but we ignore the structure of the 'mod'
                    // block repetition-level from the outer pattern in the
                    // expansion, flattening all functions from all 'mod' blocks
                    // into the implementation of Env for Guest.
                    sdk_function_helper!{$mod_id, fn $fn_id $args -> $ret}
                )*
            )*
        }
    };
}

// Here we invoke the x-macro passing generate_env_trait as its callback macro.
internal::call_macro_with_all_host_functions! { impl_env_for_sdk }