referrerpolicy=no-referrer-when-downgrade
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
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Benchmarks for the contracts pallet
#![cfg(feature = "runtime-benchmarks")]

mod call_builder;
mod code;
mod sandbox;
use self::{
	call_builder::CallSetup,
	code::{body, ImportedMemory, Location, ModuleDefinition, WasmModule},
	sandbox::Sandbox,
};
use crate::{
	exec::{Key, SeedOf},
	migration::{
		codegen::LATEST_MIGRATION_VERSION, v09, v10, v11, v12, v13, v14, v15, v16, MigrationStep,
	},
	storage::WriteOutcome,
	wasm::BenchEnv,
	Pallet as Contracts, *,
};
use alloc::{vec, vec::Vec};
use codec::{Encode, MaxEncodedLen};
use frame_benchmarking::v2::*;
use frame_support::{
	self, assert_ok,
	pallet_prelude::StorageVersion,
	storage::child,
	traits::{fungible::InspectHold, Currency},
	weights::{Weight, WeightMeter},
};
use frame_system::RawOrigin;
use pallet_balances;
use pallet_contracts_uapi::{CallFlags, ReturnErrorCode};
use sp_runtime::traits::{Bounded, Hash};
use wasm_instrument::parity_wasm::elements::{Instruction, Local, ValueType};

/// How many runs we do per API benchmark.
///
/// This is picked more or less arbitrary. We experimented with different numbers until
/// the results appeared to be stable. Reducing the number would speed up the benchmarks
/// but might make the results less precise.
const API_BENCHMARK_RUNS: u32 = 1600;

/// How many runs we do per instruction benchmark.
///
/// Same rationale as for [`API_BENCHMARK_RUNS`]. The number is bigger because instruction
/// benchmarks are faster.
const INSTR_BENCHMARK_RUNS: u32 = 5000;

/// Number of layers in a Radix16 unbalanced trie.
const UNBALANCED_TRIE_LAYERS: u32 = 20;

/// An instantiated and deployed contract.
#[derive(Clone)]
struct Contract<T: Config> {
	caller: T::AccountId,
	account_id: T::AccountId,
	addr: AccountIdLookupOf<T>,
	value: BalanceOf<T>,
}

impl<T> Contract<T>
where
	T: Config + pallet_balances::Config,
	<BalanceOf<T> as HasCompact>::Type: Clone + Eq + PartialEq + Debug + TypeInfo + Encode,
{
	/// Create new contract and use a default account id as instantiator.
	fn new(module: WasmModule<T>, data: Vec<u8>) -> Result<Contract<T>, &'static str> {
		Self::with_index(0, module, data)
	}

	/// Create new contract and use an account id derived from the supplied index as instantiator.
	fn with_index(
		index: u32,
		module: WasmModule<T>,
		data: Vec<u8>,
	) -> Result<Contract<T>, &'static str> {
		Self::with_caller(account("instantiator", index, 0), module, data)
	}

	/// Create new contract and use the supplied `caller` as instantiator.
	fn with_caller(
		caller: T::AccountId,
		module: WasmModule<T>,
		data: Vec<u8>,
	) -> Result<Contract<T>, &'static str> {
		let value = Pallet::<T>::min_balance();
		T::Currency::set_balance(&caller, caller_funding::<T>());
		let salt = vec![0xff];
		let addr = Contracts::<T>::contract_address(&caller, &module.hash, &data, &salt);

		Contracts::<T>::store_code_raw(module.code, caller.clone())?;
		Contracts::<T>::instantiate(
			RawOrigin::Signed(caller.clone()).into(),
			value,
			Weight::MAX,
			None,
			module.hash,
			data,
			salt,
		)?;

		let result =
			Contract { caller, account_id: addr.clone(), addr: T::Lookup::unlookup(addr), value };

		ContractInfoOf::<T>::insert(&result.account_id, result.info()?);

		Ok(result)
	}

	/// Create a new contract with the supplied storage item count and size each.
	fn with_storage(
		code: WasmModule<T>,
		stor_num: u32,
		stor_size: u32,
	) -> Result<Self, &'static str> {
		let contract = Contract::<T>::new(code, vec![])?;
		let storage_items = (0..stor_num)
			.map(|i| {
				let hash = T::Hashing::hash_of(&i)
					.as_ref()
					.try_into()
					.map_err(|_| "Hash too big for storage key")?;
				Ok((hash, vec![42u8; stor_size as usize]))
			})
			.collect::<Result<Vec<_>, &'static str>>()?;
		contract.store(&storage_items)?;
		Ok(contract)
	}

	/// Store the supplied storage items into this contracts storage.
	fn store(&self, items: &Vec<([u8; 32], Vec<u8>)>) -> Result<(), &'static str> {
		let info = self.info()?;
		for item in items {
			info.write(&Key::Fix(item.0), Some(item.1.clone()), None, false)
				.map_err(|_| "Failed to write storage to restoration dest")?;
		}
		<ContractInfoOf<T>>::insert(&self.account_id, info);
		Ok(())
	}

	/// Create a new contract with the specified unbalanced storage trie.
	fn with_unbalanced_storage_trie(code: WasmModule<T>, key: &[u8]) -> Result<Self, &'static str> {
		if (key.len() as u32) < (UNBALANCED_TRIE_LAYERS + 1) / 2 {
			return Err("Key size too small to create the specified trie");
		}

		let value = vec![16u8; T::Schedule::get().limits.payload_len as usize];
		let contract = Contract::<T>::new(code, vec![])?;
		let info = contract.info()?;
		let child_trie_info = info.child_trie_info();
		child::put_raw(&child_trie_info, &key, &value);
		for l in 0..UNBALANCED_TRIE_LAYERS {
			let pos = l as usize / 2;
			let mut key_new = key.to_vec();
			for i in 0u8..16 {
				key_new[pos] = if l % 2 == 0 {
					(key_new[pos] & 0xF0) | i
				} else {
					(key_new[pos] & 0x0F) | (i << 4)
				};

				if key == &key_new {
					continue
				}
				child::put_raw(&child_trie_info, &key_new, &value);
			}
		}
		Ok(contract)
	}

	/// Get the `ContractInfo` of the `addr` or an error if it no longer exists.
	fn address_info(addr: &T::AccountId) -> Result<ContractInfo<T>, &'static str> {
		ContractInfoOf::<T>::get(addr).ok_or("Expected contract to exist at this point.")
	}

	/// Get the `ContractInfo` of this contract or an error if it no longer exists.
	fn info(&self) -> Result<ContractInfo<T>, &'static str> {
		Self::address_info(&self.account_id)
	}

	/// Set the balance of the contract to the supplied amount.
	fn set_balance(&self, balance: BalanceOf<T>) {
		T::Currency::set_balance(&self.account_id, balance);
	}

	/// Returns `true` iff all storage entries related to code storage exist.
	fn code_exists(hash: &CodeHash<T>) -> bool {
		<PristineCode<T>>::contains_key(hash) && <CodeInfoOf<T>>::contains_key(&hash)
	}

	/// Returns `true` iff no storage entry related to code storage exist.
	fn code_removed(hash: &CodeHash<T>) -> bool {
		!<PristineCode<T>>::contains_key(hash) && !<CodeInfoOf<T>>::contains_key(&hash)
	}
}

/// The funding that each account that either calls or instantiates contracts is funded with.
fn caller_funding<T: Config>() -> BalanceOf<T> {
	// Minting can overflow, so we can't abuse of the funding. This value happens to be big enough,
	// but not too big to make the total supply overflow.
	BalanceOf::<T>::max_value() / 10_000u32.into()
}

#[benchmarks(
	where
		<BalanceOf<T> as codec::HasCompact>::Type: Clone + Eq + PartialEq + core::fmt::Debug + scale_info::TypeInfo + codec::Encode,
		T: Config + pallet_balances::Config,
		BalanceOf<T>: From<<pallet_balances::Pallet<T> as Currency<T::AccountId>>::Balance>,
		<pallet_balances::Pallet<T> as Currency<T::AccountId>>::Balance: From<BalanceOf<T>>,
)]
mod benchmarks {
	use super::*;

	// The base weight consumed on processing contracts deletion queue.
	#[benchmark(pov_mode = Measured)]
	fn on_process_deletion_queue_batch() {
		#[block]
		{
			ContractInfo::<T>::process_deletion_queue_batch(&mut WeightMeter::new())
		}
	}

	#[benchmark(skip_meta, pov_mode = Measured)]
	fn on_initialize_per_trie_key(k: Linear<0, 1024>) -> Result<(), BenchmarkError> {
		let instance = Contract::<T>::with_storage(
			WasmModule::dummy(),
			k,
			T::Schedule::get().limits.payload_len,
		)?;
		instance.info()?.queue_trie_for_deletion();

		#[block]
		{
			ContractInfo::<T>::process_deletion_queue_batch(&mut WeightMeter::new())
		}

		Ok(())
	}

	// This benchmarks the v9 migration step (update codeStorage).
	#[benchmark(pov_mode = Measured)]
	fn v9_migration_step(c: Linear<0, { T::MaxCodeLen::get() }>) {
		v09::store_old_dummy_code::<T>(c as usize);
		let mut m = v09::Migration::<T>::default();
		#[block]
		{
			m.step(&mut WeightMeter::new());
		}
	}

	// This benchmarks the v10 migration step (use dedicated deposit_account).
	#[benchmark(pov_mode = Measured)]
	fn v10_migration_step() -> Result<(), BenchmarkError> {
		let contract =
			<Contract<T>>::with_caller(whitelisted_caller(), WasmModule::dummy(), vec![])?;

		v10::store_old_contract_info::<T, pallet_balances::Pallet<T>>(
			contract.account_id.clone(),
			contract.info()?,
		);
		let mut m = v10::Migration::<T, pallet_balances::Pallet<T>>::default();

		#[block]
		{
			m.step(&mut WeightMeter::new());
		}

		Ok(())
	}

	// This benchmarks the v11 migration step (Don't rely on reserved balances keeping an account
	// alive).
	#[benchmark(pov_mode = Measured)]
	fn v11_migration_step(k: Linear<0, 1024>) {
		v11::fill_old_queue::<T>(k as usize);
		let mut m = v11::Migration::<T>::default();

		#[block]
		{
			m.step(&mut WeightMeter::new());
		}
	}

	// This benchmarks the v12 migration step (Move `OwnerInfo` to `CodeInfo`,
	// add `determinism` field to the latter, clear `CodeStorage`
	// and repay deposits).
	#[benchmark(pov_mode = Measured)]
	fn v12_migration_step(c: Linear<0, { T::MaxCodeLen::get() }>) {
		v12::store_old_dummy_code::<T, pallet_balances::Pallet<T>>(
			c as usize,
			account::<T::AccountId>("account", 0, 0),
		);
		let mut m = v12::Migration::<T, pallet_balances::Pallet<T>>::default();

		#[block]
		{
			m.step(&mut WeightMeter::new());
		}
	}

	// This benchmarks the v13 migration step (Add delegate_dependencies field).
	#[benchmark(pov_mode = Measured)]
	fn v13_migration_step() -> Result<(), BenchmarkError> {
		let contract =
			<Contract<T>>::with_caller(whitelisted_caller(), WasmModule::dummy(), vec![])?;

		v13::store_old_contract_info::<T>(contract.account_id.clone(), contract.info()?);
		let mut m = v13::Migration::<T>::default();

		#[block]
		{
			m.step(&mut WeightMeter::new());
		}
		Ok(())
	}

	// This benchmarks the v14 migration step (Move code owners' reserved balance to be held
	// instead).
	#[benchmark(pov_mode = Measured)]
	fn v14_migration_step() {
		let account = account::<T::AccountId>("account", 0, 0);
		T::Currency::set_balance(&account, caller_funding::<T>());
		v14::store_dummy_code::<T, pallet_balances::Pallet<T>>(account);
		let mut m = v14::Migration::<T, pallet_balances::Pallet<T>>::default();

		#[block]
		{
			m.step(&mut WeightMeter::new());
		}
	}

	// This benchmarks the v15 migration step (remove deposit account).
	#[benchmark(pov_mode = Measured)]
	fn v15_migration_step() -> Result<(), BenchmarkError> {
		let contract =
			<Contract<T>>::with_caller(whitelisted_caller(), WasmModule::dummy(), vec![])?;

		v15::store_old_contract_info::<T>(contract.account_id.clone(), contract.info()?);
		let mut m = v15::Migration::<T>::default();

		#[block]
		{
			m.step(&mut WeightMeter::new());
		}

		Ok(())
	}

	// This benchmarks the v16 migration step (Remove ED from base_deposit).
	#[benchmark(pov_mode = Measured)]
	fn v16_migration_step() -> Result<(), BenchmarkError> {
		let contract =
			<Contract<T>>::with_caller(whitelisted_caller(), WasmModule::dummy(), vec![])?;

		let info = contract.info()?;
		let base_deposit = v16::store_old_contract_info::<T>(contract.account_id.clone(), &info);
		let mut m = v16::Migration::<T>::default();

		#[block]
		{
			m.step(&mut WeightMeter::new());
		}
		let ed = Pallet::<T>::min_balance();
		let info = v16::ContractInfoOf::<T>::get(&contract.account_id).unwrap();
		assert_eq!(info.storage_base_deposit, base_deposit - ed);
		Ok(())
	}

	// This benchmarks the weight of executing Migration::migrate to execute a noop migration.
	#[benchmark(pov_mode = Measured)]
	fn migration_noop() {
		let version = LATEST_MIGRATION_VERSION;
		StorageVersion::new(version).put::<Pallet<T>>();
		#[block]
		{
			Migration::<T>::migrate(&mut WeightMeter::new());
		}
		assert_eq!(StorageVersion::get::<Pallet<T>>(), version);
	}

	// This benchmarks the weight of dispatching migrate to execute 1 `NoopMigration`
	#[benchmark(pov_mode = Measured)]
	fn migrate() {
		let latest_version = LATEST_MIGRATION_VERSION;
		StorageVersion::new(latest_version - 2).put::<Pallet<T>>();
		<Migration<T, false> as frame_support::traits::OnRuntimeUpgrade>::on_runtime_upgrade();

		#[extrinsic_call]
		_(RawOrigin::Signed(whitelisted_caller()), Weight::MAX);

		assert_eq!(StorageVersion::get::<Pallet<T>>(), latest_version - 1);
	}

	// This benchmarks the weight of running on_runtime_upgrade when there are no migration in
	// progress.
	#[benchmark(pov_mode = Measured)]
	fn on_runtime_upgrade_noop() {
		let latest_version = LATEST_MIGRATION_VERSION;
		StorageVersion::new(latest_version).put::<Pallet<T>>();
		#[block]
		{
			<Migration<T, false> as frame_support::traits::OnRuntimeUpgrade>::on_runtime_upgrade();
		}
		assert!(MigrationInProgress::<T>::get().is_none());
	}

	// This benchmarks the weight of running on_runtime_upgrade when there is a migration in
	// progress.
	#[benchmark(pov_mode = Measured)]
	fn on_runtime_upgrade_in_progress() {
		let latest_version = LATEST_MIGRATION_VERSION;
		StorageVersion::new(latest_version - 2).put::<Pallet<T>>();
		let v = vec![42u8].try_into().ok();
		MigrationInProgress::<T>::set(v.clone());
		#[block]
		{
			<Migration<T, false> as frame_support::traits::OnRuntimeUpgrade>::on_runtime_upgrade();
		}
		assert!(MigrationInProgress::<T>::get().is_some());
		assert_eq!(MigrationInProgress::<T>::get(), v);
	}

	// This benchmarks the weight of running on_runtime_upgrade when there is a migration to
	// process.
	#[benchmark(pov_mode = Measured)]
	fn on_runtime_upgrade() {
		let latest_version = LATEST_MIGRATION_VERSION;
		StorageVersion::new(latest_version - 2).put::<Pallet<T>>();
		#[block]
		{
			<Migration<T, false> as frame_support::traits::OnRuntimeUpgrade>::on_runtime_upgrade();
		}
		assert!(MigrationInProgress::<T>::get().is_some());
	}

	// This benchmarks the overhead of loading a code of size `c` byte from storage and into
	// the sandbox. This does **not** include the actual execution for which the gas meter
	// is responsible. This is achieved by generating all code to the `deploy` function
	// which is in the wasm module but not executed on `call`.
	// The results are supposed to be used as `call_with_code_per_byte(c) -
	// call_with_code_per_byte(0)`.
	#[benchmark(pov_mode = Measured)]
	fn call_with_code_per_byte(
		c: Linear<0, { T::MaxCodeLen::get() }>,
	) -> Result<(), BenchmarkError> {
		let instance = Contract::<T>::with_caller(
			whitelisted_caller(),
			WasmModule::sized(c, Location::Deploy, false),
			vec![],
		)?;
		let value = Pallet::<T>::min_balance();
		let callee = instance.addr;

		#[extrinsic_call]
		call(RawOrigin::Signed(instance.caller.clone()), callee, value, Weight::MAX, None, vec![]);

		Ok(())
	}

	// `c`: Size of the code in bytes.
	// `i`: Size of the input in bytes.
	// `s`: Size of the salt in bytes.
	#[benchmark(pov_mode = Measured)]
	fn instantiate_with_code(
		c: Linear<0, { T::MaxCodeLen::get() }>,
		i: Linear<0, { code::max_pages::<T>() * 64 * 1024 }>,
		s: Linear<0, { code::max_pages::<T>() * 64 * 1024 }>,
	) {
		let input = vec![42u8; i as usize];
		let salt = vec![42u8; s as usize];
		let value = Pallet::<T>::min_balance();
		let caller = whitelisted_caller();
		T::Currency::set_balance(&caller, caller_funding::<T>());
		let WasmModule { code, hash, .. } = WasmModule::<T>::sized(c, Location::Call, false);
		let origin = RawOrigin::Signed(caller.clone());
		let addr = Contracts::<T>::contract_address(&caller, &hash, &input, &salt);
		#[extrinsic_call]
		_(origin, value, Weight::MAX, None, code, input, salt);

		let deposit =
			T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr);
		// uploading the code reserves some balance in the callers account
		let code_deposit =
			T::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &caller);
		assert_eq!(
			T::Currency::balance(&caller),
			caller_funding::<T>() - value - deposit - code_deposit - Pallet::<T>::min_balance(),
		);
		// contract has the full value
		assert_eq!(T::Currency::balance(&addr), value + Pallet::<T>::min_balance());
	}

	// `i`: Size of the input in bytes.
	// `s`: Size of the salt in bytes.
	#[benchmark(pov_mode = Measured)]
	fn instantiate(
		i: Linear<0, { code::max_pages::<T>() * 64 * 1024 }>,
		s: Linear<0, { code::max_pages::<T>() * 64 * 1024 }>,
	) -> Result<(), BenchmarkError> {
		let input = vec![42u8; i as usize];
		let salt = vec![42u8; s as usize];
		let value = Pallet::<T>::min_balance();
		let caller = whitelisted_caller();
		T::Currency::set_balance(&caller, caller_funding::<T>());
		let WasmModule { code, hash, .. } = WasmModule::<T>::dummy();
		let addr = Contracts::<T>::contract_address(&caller, &hash, &input, &salt);
		Contracts::<T>::store_code_raw(code, caller.clone())?;

		#[extrinsic_call]
		_(RawOrigin::Signed(caller.clone()), value, Weight::MAX, None, hash, input, salt);

		let deposit =
			T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr);
		// value was removed from the caller
		assert_eq!(
			T::Currency::balance(&caller),
			caller_funding::<T>() - value - deposit - Pallet::<T>::min_balance(),
		);
		// contract has the full value
		assert_eq!(T::Currency::balance(&addr), value + Pallet::<T>::min_balance());

		Ok(())
	}

	// We just call a dummy contract to measure the overhead of the call extrinsic.
	// The size of the data has no influence on the costs of this extrinsic as long as the contract
	// won't call `seal_input` in its constructor to copy the data to contract memory.
	// The dummy contract used here does not do this. The costs for the data copy is billed as
	// part of `seal_input`. The costs for invoking a contract of a specific size are not part
	// of this benchmark because we cannot know the size of the contract when issuing a call
	// transaction. See `call_with_code_per_byte` for this.
	#[benchmark(pov_mode = Measured)]
	fn call() -> Result<(), BenchmarkError> {
		let data = vec![42u8; 1024];
		let instance =
			Contract::<T>::with_caller(whitelisted_caller(), WasmModule::dummy(), vec![])?;
		let value = Pallet::<T>::min_balance();
		let origin = RawOrigin::Signed(instance.caller.clone());
		let callee = instance.addr.clone();
		let before = T::Currency::balance(&instance.account_id);
		#[extrinsic_call]
		_(origin, callee, value, Weight::MAX, None, data);
		let deposit = T::Currency::balance_on_hold(
			&HoldReason::StorageDepositReserve.into(),
			&instance.account_id,
		);
		// value and value transferred via call should be removed from the caller
		assert_eq!(
			T::Currency::balance(&instance.caller),
			caller_funding::<T>() - instance.value - value - deposit - Pallet::<T>::min_balance(),
		);
		// contract should have received the value
		assert_eq!(T::Currency::balance(&instance.account_id), before + value);
		// contract should still exist
		instance.info()?;

		Ok(())
	}

	// This constructs a contract that is maximal expensive to instrument.
	// It creates a maximum number of metering blocks per byte.
	// `c`: Size of the code in bytes.
	#[benchmark(pov_mode = Measured)]
	fn upload_code_determinism_enforced(c: Linear<0, { T::MaxCodeLen::get() }>) {
		let caller = whitelisted_caller();
		T::Currency::set_balance(&caller, caller_funding::<T>());
		let WasmModule { code, hash, .. } = WasmModule::<T>::sized(c, Location::Call, false);
		let origin = RawOrigin::Signed(caller.clone());
		#[extrinsic_call]
		upload_code(origin, code, None, Determinism::Enforced);
		// uploading the code reserves some balance in the callers account
		assert!(T::Currency::total_balance_on_hold(&caller) > 0u32.into());
		assert!(<Contract<T>>::code_exists(&hash));
	}

	// Uploading code with [`Determinism::Relaxed`] should be more expensive than uploading code
	// with [`Determinism::Enforced`], as we always try to save the code with
	// [`Determinism::Enforced`] first.
	#[benchmark(pov_mode = Measured)]
	fn upload_code_determinism_relaxed(c: Linear<0, { T::MaxCodeLen::get() }>) {
		let caller = whitelisted_caller();
		T::Currency::set_balance(&caller, caller_funding::<T>());
		let WasmModule { code, hash, .. } = WasmModule::<T>::sized(c, Location::Call, true);
		let origin = RawOrigin::Signed(caller.clone());
		#[extrinsic_call]
		upload_code(origin, code, None, Determinism::Relaxed);
		assert!(T::Currency::total_balance_on_hold(&caller) > 0u32.into());
		assert!(<Contract<T>>::code_exists(&hash));
		// Ensure that the benchmark follows the most expensive path, i.e., the code is saved with
		assert_eq!(CodeInfoOf::<T>::get(&hash).unwrap().determinism(), Determinism::Relaxed);
	}

	// Removing code does not depend on the size of the contract because all the information
	// needed to verify the removal claim (refcount, owner) is stored in a separate storage
	// item (`CodeInfoOf`).
	#[benchmark(pov_mode = Measured)]
	fn remove_code() -> Result<(), BenchmarkError> {
		let caller = whitelisted_caller();
		T::Currency::set_balance(&caller, caller_funding::<T>());
		let WasmModule { code, hash, .. } = WasmModule::<T>::dummy();
		let origin = RawOrigin::Signed(caller.clone());
		let uploaded =
			<Contracts<T>>::bare_upload_code(caller.clone(), code, None, Determinism::Enforced)?;
		assert_eq!(uploaded.code_hash, hash);
		assert_eq!(uploaded.deposit, T::Currency::total_balance_on_hold(&caller));
		assert!(<Contract<T>>::code_exists(&hash));
		#[extrinsic_call]
		_(origin, hash);
		// removing the code should have unreserved the deposit
		assert_eq!(T::Currency::total_balance_on_hold(&caller), 0u32.into());
		assert!(<Contract<T>>::code_removed(&hash));
		Ok(())
	}

	#[benchmark(pov_mode = Measured)]
	fn set_code() -> Result<(), BenchmarkError> {
		let instance =
			<Contract<T>>::with_caller(whitelisted_caller(), WasmModule::dummy(), vec![])?;
		// we just add some bytes so that the code hash is different
		let WasmModule { code, hash, .. } = <WasmModule<T>>::dummy_with_bytes(128);
		<Contracts<T>>::store_code_raw(code, instance.caller.clone())?;
		let callee = instance.addr.clone();
		assert_ne!(instance.info()?.code_hash, hash);
		#[extrinsic_call]
		_(RawOrigin::Root, callee, hash);
		assert_eq!(instance.info()?.code_hash, hash);
		Ok(())
	}

	#[benchmark(pov_mode = Measured)]
	fn noop_host_fn(r: Linear<0, API_BENCHMARK_RUNS>) {
		let mut setup = CallSetup::<T>::new(WasmModule::noop(r));
		let (mut ext, module) = setup.ext();
		let func = CallSetup::<T>::prepare_call(&mut ext, module, vec![]);
		#[block]
		{
			func.call();
		}
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_caller() {
		let len = <T::AccountId as MaxEncodedLen>::max_encoded_len() as u32;
		build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_caller(&mut runtime, &mut memory, 4, 0);
		}

		assert_ok!(result);
		assert_eq!(
			&<T::AccountId as Decode>::decode(&mut &memory[4..]).unwrap(),
			runtime.ext().caller().account_id().unwrap()
		);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_is_contract() {
		let Contract { account_id, .. } =
			Contract::<T>::with_index(1, WasmModule::dummy(), vec![]).unwrap();

		build_runtime!(runtime, memory: [account_id.encode(), ]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_is_contract(&mut runtime, &mut memory, 0);
		}

		assert_eq!(result.unwrap(), 1);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_code_hash() {
		let contract = Contract::<T>::with_index(1, WasmModule::dummy(), vec![]).unwrap();
		let len = <CodeHash<T> as MaxEncodedLen>::max_encoded_len() as u32;
		build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], contract.account_id.encode(), ]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_code_hash(&mut runtime, &mut memory, 4 + len, 4, 0);
		}

		assert_ok!(result);
		assert_eq!(
			<CodeHash<T> as Decode>::decode(&mut &memory[4..]).unwrap(),
			contract.info().unwrap().code_hash
		);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_own_code_hash() {
		let len = <CodeHash<T> as MaxEncodedLen>::max_encoded_len() as u32;
		build_runtime!(runtime, contract, memory: [len.to_le_bytes(), vec![0u8; len as _], ]);
		let result;
		#[block]
		{
			result = BenchEnv::seal0_own_code_hash(&mut runtime, &mut memory, 4, 0);
		}

		assert_ok!(result);
		assert_eq!(
			<CodeHash<T> as Decode>::decode(&mut &memory[4..]).unwrap(),
			contract.info().unwrap().code_hash
		);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_caller_is_origin() {
		build_runtime!(runtime, memory: []);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_caller_is_origin(&mut runtime, &mut memory);
		}
		assert_eq!(result.unwrap(), 1u32);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_caller_is_root() {
		let mut setup = CallSetup::<T>::default();
		setup.set_origin(Origin::Root);
		let (mut ext, _) = setup.ext();
		let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_caller_is_root(&mut runtime, &mut [0u8; 0]);
		}
		assert_eq!(result.unwrap(), 1u32);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_address() {
		let len = <AccountIdOf<T> as MaxEncodedLen>::max_encoded_len() as u32;
		build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_address(&mut runtime, &mut memory, 4, 0);
		}
		assert_ok!(result);
		assert_eq!(
			&<T::AccountId as Decode>::decode(&mut &memory[4..]).unwrap(),
			runtime.ext().address()
		);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_gas_left() {
		// use correct max_encoded_len when new version of parity-scale-codec is released
		let len = 18u32;
		assert!(<Weight as MaxEncodedLen>::max_encoded_len() as u32 != len);
		build_runtime!(runtime, memory: [32u32.to_le_bytes(), vec![0u8; len as _], ]);

		let result;
		#[block]
		{
			result = BenchEnv::seal1_gas_left(&mut runtime, &mut memory, 4, 0);
		}
		assert_ok!(result);
		assert_eq!(
			<Weight as Decode>::decode(&mut &memory[4..]).unwrap(),
			runtime.ext().gas_meter().gas_left()
		);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_balance() {
		let len = <T::Balance as MaxEncodedLen>::max_encoded_len() as u32;
		build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]);
		let result;
		#[block]
		{
			result = BenchEnv::seal0_seal_balance(&mut runtime, &mut memory, 4, 0);
		}
		assert_ok!(result);
		assert_eq!(
			<T::Balance as Decode>::decode(&mut &memory[4..]).unwrap(),
			runtime.ext().balance().into()
		);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_value_transferred() {
		let len = <T::Balance as MaxEncodedLen>::max_encoded_len() as u32;
		build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]);
		let result;
		#[block]
		{
			result = BenchEnv::seal0_value_transferred(&mut runtime, &mut memory, 4, 0);
		}
		assert_ok!(result);
		assert_eq!(
			<T::Balance as Decode>::decode(&mut &memory[4..]).unwrap(),
			runtime.ext().value_transferred().into()
		);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_minimum_balance() {
		let len = <T::Balance as MaxEncodedLen>::max_encoded_len() as u32;
		build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]);
		let result;
		#[block]
		{
			result = BenchEnv::seal0_minimum_balance(&mut runtime, &mut memory, 4, 0);
		}
		assert_ok!(result);
		assert_eq!(
			<T::Balance as Decode>::decode(&mut &memory[4..]).unwrap(),
			runtime.ext().minimum_balance().into()
		);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_block_number() {
		let len = <BlockNumberFor<T> as MaxEncodedLen>::max_encoded_len() as u32;
		build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]);
		let result;
		#[block]
		{
			result = BenchEnv::seal0_seal_block_number(&mut runtime, &mut memory, 4, 0);
		}
		assert_ok!(result);
		assert_eq!(
			<BlockNumberFor<T>>::decode(&mut &memory[4..]).unwrap(),
			runtime.ext().block_number()
		);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_now() {
		let len = <MomentOf<T> as MaxEncodedLen>::max_encoded_len() as u32;
		build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]);
		let result;
		#[block]
		{
			result = BenchEnv::seal0_seal_now(&mut runtime, &mut memory, 4, 0);
		}
		assert_ok!(result);
		assert_eq!(<MomentOf<T>>::decode(&mut &memory[4..]).unwrap(), *runtime.ext().now());
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_weight_to_fee() {
		let len = <T::Balance as MaxEncodedLen>::max_encoded_len() as u32;
		build_runtime!(runtime, memory: [len.to_le_bytes(), vec![0u8; len as _], ]);
		let weight = Weight::from_parts(500_000, 300_000);
		let result;
		#[block]
		{
			result = BenchEnv::seal1_weight_to_fee(
				&mut runtime,
				&mut memory,
				weight.ref_time(),
				weight.proof_size(),
				4,
				0,
			);
		}
		assert_ok!(result);
		assert_eq!(
			<BalanceOf<T>>::decode(&mut &memory[4..]).unwrap(),
			runtime.ext().get_weight_price(weight)
		);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_input(n: Linear<0, { code::max_pages::<T>() * 64 * 1024 - 4 }>) {
		let mut setup = CallSetup::<T>::default();
		let (mut ext, _) = setup.ext();
		let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![42u8; n as usize]);
		let mut memory = memory!(n.to_le_bytes(), vec![0u8; n as usize],);
		let result;
		#[block]
		{
			result = BenchEnv::seal0_input(&mut runtime, &mut memory, 4, 0);
		}
		assert_ok!(result);
		assert_eq!(&memory[4..], &vec![42u8; n as usize]);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_return(n: Linear<0, { code::max_pages::<T>() * 64 * 1024 - 4 }>) {
		build_runtime!(runtime, memory: [n.to_le_bytes(), vec![42u8; n as usize], ]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_seal_return(&mut runtime, &mut memory, 0, 0, n);
		}

		assert!(matches!(
			result,
			Err(crate::wasm::TrapReason::Return(crate::wasm::ReturnData { .. }))
		));
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_terminate(
		n: Linear<0, { T::MaxDelegateDependencies::get() }>,
	) -> Result<(), BenchmarkError> {
		let beneficiary = account::<T::AccountId>("beneficiary", 0, 0);
		let caller = whitelisted_caller();

		build_runtime!(runtime, memory: [beneficiary.encode(),]);

		T::Currency::set_balance(&caller, caller_funding::<T>());

		(0..n).for_each(|i| {
			let new_code = WasmModule::<T>::dummy_with_bytes(65 + i);
			Contracts::<T>::store_code_raw(new_code.code, caller.clone()).unwrap();
			runtime.ext().lock_delegate_dependency(new_code.hash).unwrap();
		});

		let result;
		#[block]
		{
			result = BenchEnv::seal1_terminate(&mut runtime, &mut memory, 0);
		}

		assert!(matches!(result, Err(crate::wasm::TrapReason::Termination)));

		Ok(())
	}

	// We benchmark only for the maximum subject length. We assume that this is some lowish
	// number (< 1 KB). Therefore we are not overcharging too much in case a smaller subject is
	// used.
	#[benchmark(pov_mode = Measured)]
	fn seal_random() {
		let subject_len = T::Schedule::get().limits.subject_len;
		assert!(subject_len < 1024);

		let output_len =
			<(SeedOf<T>, BlockNumberFor<T>) as MaxEncodedLen>::max_encoded_len() as u32;

		build_runtime!(runtime, memory: [
			output_len.to_le_bytes(),
			vec![42u8; subject_len as _],
			vec![0u8; output_len as _],
		]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_random(
				&mut runtime,
				&mut memory,
				4,               // subject_ptr
				subject_len,     // subject_len
				subject_len + 4, // output_ptr
				0,               // output_len_ptr
			);
		}

		assert_ok!(result);
		assert_ok!(<(SeedOf<T>, BlockNumberFor<T>)>::decode(&mut &memory[subject_len as _..]));
	}

	// Benchmark the overhead that topics generate.
	// `t`: Number of topics
	// `n`: Size of event payload in bytes
	#[benchmark(pov_mode = Measured)]
	fn seal_deposit_event(
		t: Linear<0, { T::Schedule::get().limits.event_topics }>,
		n: Linear<0, { T::Schedule::get().limits.payload_len }>,
	) {
		let topics = (0..t).map(|i| T::Hashing::hash_of(&i)).collect::<Vec<_>>().encode();
		let topics_len = topics.len() as u32;

		build_runtime!(runtime, memory: [
			n.to_le_bytes(),
			topics,
			vec![0u8; n as _],
		]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_deposit_event(
				&mut runtime,
				&mut memory,
				4,              // topics_ptr
				topics_len,     // topics_len
				4 + topics_len, // data_ptr
				0,              // data_len
			);
		}

		assert_ok!(result);
	}

	// Benchmark debug_message call
	// Whereas this function is used in RPC mode only, it still should be secured
	// against an excessive use.
	//
	// i: size of input in bytes up to maximum allowed contract memory or maximum allowed debug
	// buffer size, whichever is less.
	#[benchmark]
	fn seal_debug_message(
		i: Linear<
			0,
			{
				(T::Schedule::get().limits.memory_pages * 64 * 1024)
					.min(T::MaxDebugBufferLen::get())
			},
		>,
	) {
		let mut setup = CallSetup::<T>::default();
		setup.enable_debug_message();
		let (mut ext, _) = setup.ext();
		let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]);
		// Fill memory with printable ASCII bytes.
		let mut memory = (0..i).zip((32..127).cycle()).map(|i| i.1).collect::<Vec<_>>();

		let result;
		#[block]
		{
			result = BenchEnv::seal0_debug_message(&mut runtime, &mut memory, 0, i);
		}
		assert_ok!(result);
		assert_eq!(setup.debug_message().unwrap().len() as u32, i);
	}

	#[benchmark(skip_meta, pov_mode = Measured)]
	fn get_storage_empty() -> Result<(), BenchmarkError> {
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = vec![0u8; max_key_len as usize];
		let max_value_len = T::Schedule::get().limits.payload_len as usize;
		let value = vec![1u8; max_value_len];

		let instance = Contract::<T>::new(WasmModule::dummy(), vec![])?;
		let info = instance.info()?;
		let child_trie_info = info.child_trie_info();
		info.bench_write_raw(&key, Some(value.clone()), false)
			.map_err(|_| "Failed to write to storage during setup.")?;

		let result;
		#[block]
		{
			result = child::get_raw(&child_trie_info, &key);
		}

		assert_eq!(result, Some(value));
		Ok(())
	}

	#[benchmark(skip_meta, pov_mode = Measured)]
	fn get_storage_full() -> Result<(), BenchmarkError> {
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = vec![0u8; max_key_len as usize];
		let max_value_len = T::Schedule::get().limits.payload_len;
		let value = vec![1u8; max_value_len as usize];

		let instance = Contract::<T>::with_unbalanced_storage_trie(WasmModule::dummy(), &key)?;
		let info = instance.info()?;
		let child_trie_info = info.child_trie_info();
		info.bench_write_raw(&key, Some(value.clone()), false)
			.map_err(|_| "Failed to write to storage during setup.")?;

		let result;
		#[block]
		{
			result = child::get_raw(&child_trie_info, &key);
		}

		assert_eq!(result, Some(value));
		Ok(())
	}

	#[benchmark(skip_meta, pov_mode = Measured)]
	fn set_storage_empty() -> Result<(), BenchmarkError> {
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = vec![0u8; max_key_len as usize];
		let max_value_len = T::Schedule::get().limits.payload_len as usize;
		let value = vec![1u8; max_value_len];

		let instance = Contract::<T>::new(WasmModule::dummy(), vec![])?;
		let info = instance.info()?;
		let child_trie_info = info.child_trie_info();
		info.bench_write_raw(&key, Some(vec![42u8; max_value_len]), false)
			.map_err(|_| "Failed to write to storage during setup.")?;

		let val = Some(value.clone());
		let result;
		#[block]
		{
			result = info.bench_write_raw(&key, val, true);
		}

		assert_ok!(result);
		assert_eq!(child::get_raw(&child_trie_info, &key).unwrap(), value);
		Ok(())
	}

	#[benchmark(skip_meta, pov_mode = Measured)]
	fn set_storage_full() -> Result<(), BenchmarkError> {
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = vec![0u8; max_key_len as usize];
		let max_value_len = T::Schedule::get().limits.payload_len;
		let value = vec![1u8; max_value_len as usize];

		let instance = Contract::<T>::with_unbalanced_storage_trie(WasmModule::dummy(), &key)?;
		let info = instance.info()?;
		let child_trie_info = info.child_trie_info();
		info.bench_write_raw(&key, Some(vec![42u8; max_value_len as usize]), false)
			.map_err(|_| "Failed to write to storage during setup.")?;

		let val = Some(value.clone());
		let result;
		#[block]
		{
			result = info.bench_write_raw(&key, val, true);
		}

		assert_ok!(result);
		assert_eq!(child::get_raw(&child_trie_info, &key).unwrap(), value);
		Ok(())
	}

	// n: new byte size
	// o: old byte size
	#[benchmark(skip_meta, pov_mode = Measured)]
	fn seal_set_storage(
		n: Linear<0, { T::Schedule::get().limits.payload_len }>,
		o: Linear<0, { T::Schedule::get().limits.payload_len }>,
	) -> Result<(), BenchmarkError> {
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;
		let value = vec![1u8; n as usize];

		build_runtime!(runtime, instance, memory: [ key.to_vec(), value.clone(), ]);
		let info = instance.info()?;

		info.write(&key, Some(vec![42u8; o as usize]), None, false)
			.map_err(|_| "Failed to write to storage during setup.")?;

		let result;
		#[block]
		{
			result = BenchEnv::seal2_set_storage(
				&mut runtime,
				&mut memory,
				0,           // key_ptr
				max_key_len, // key_len
				max_key_len, // value_ptr
				n,           // value_len
			);
		}

		assert_ok!(result);
		assert_eq!(info.read(&key).unwrap(), value);
		Ok(())
	}

	#[benchmark(skip_meta, pov_mode = Measured)]
	fn seal_clear_storage(
		n: Linear<0, { T::Schedule::get().limits.payload_len }>,
	) -> Result<(), BenchmarkError> {
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;
		build_runtime!(runtime, instance, memory: [ key.to_vec(), ]);
		let info = instance.info()?;

		info.write(&key, Some(vec![42u8; n as usize]), None, false)
			.map_err(|_| "Failed to write to storage during setup.")?;

		let result;
		#[block]
		{
			result = BenchEnv::seal1_clear_storage(&mut runtime, &mut memory, 0, max_key_len);
		}

		assert_ok!(result);
		assert!(info.read(&key).is_none());
		Ok(())
	}

	#[benchmark(skip_meta, pov_mode = Measured)]
	fn seal_get_storage(
		n: Linear<0, { T::Schedule::get().limits.payload_len }>,
	) -> Result<(), BenchmarkError> {
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;
		build_runtime!(runtime, instance, memory: [ key.to_vec(), n.to_le_bytes(), vec![0u8; n as _], ]);
		let info = instance.info()?;

		info.write(&key, Some(vec![42u8; n as usize]), None, false)
			.map_err(|_| "Failed to write to storage during setup.")?;

		let out_ptr = max_key_len + 4;
		let result;
		#[block]
		{
			result = BenchEnv::seal1_get_storage(
				&mut runtime,
				&mut memory,
				0,           // key_ptr
				max_key_len, // key_len
				out_ptr,     // out_ptr
				max_key_len, // out_len_ptr
			);
		}

		assert_ok!(result);
		assert_eq!(&info.read(&key).unwrap(), &memory[out_ptr as usize..]);
		Ok(())
	}

	#[benchmark(skip_meta, pov_mode = Measured)]
	fn seal_contains_storage(
		n: Linear<0, { T::Schedule::get().limits.payload_len }>,
	) -> Result<(), BenchmarkError> {
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;
		build_runtime!(runtime, instance, memory: [ key.to_vec(), ]);
		let info = instance.info()?;

		info.write(&key, Some(vec![42u8; n as usize]), None, false)
			.map_err(|_| "Failed to write to storage during setup.")?;

		let result;
		#[block]
		{
			result = BenchEnv::seal1_contains_storage(&mut runtime, &mut memory, 0, max_key_len);
		}

		assert_eq!(result.unwrap(), n);
		Ok(())
	}

	#[benchmark(skip_meta, pov_mode = Measured)]
	fn seal_take_storage(
		n: Linear<0, { T::Schedule::get().limits.payload_len }>,
	) -> Result<(), BenchmarkError> {
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;
		build_runtime!(runtime, instance, memory: [ key.to_vec(), n.to_le_bytes(), vec![0u8; n as _], ]);
		let info = instance.info()?;

		let value = vec![42u8; n as usize];
		info.write(&key, Some(value.clone()), None, false)
			.map_err(|_| "Failed to write to storage during setup.")?;

		let out_ptr = max_key_len + 4;
		let result;
		#[block]
		{
			result = BenchEnv::seal0_take_storage(
				&mut runtime,
				&mut memory,
				0,           // key_ptr
				max_key_len, // key_len
				out_ptr,     // out_ptr
				max_key_len, // out_len_ptr
			);
		}

		assert_ok!(result);
		assert!(&info.read(&key).is_none());
		assert_eq!(&value, &memory[out_ptr as usize..]);
		Ok(())
	}

	// We use both full and empty benchmarks here instead of benchmarking transient_storage
	// (BTreeMap) directly. This approach is necessary because benchmarking this BTreeMap is very
	// slow. Additionally, we use linear regression for our benchmarks, and the BTreeMap's log(n)
	// complexity can introduce approximation errors.
	#[benchmark(pov_mode = Ignored)]
	fn set_transient_storage_empty() -> Result<(), BenchmarkError> {
		let max_value_len = T::Schedule::get().limits.payload_len;
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;
		let value = Some(vec![42u8; max_value_len as _]);
		let mut setup = CallSetup::<T>::default();
		let (mut ext, _) = setup.ext();
		let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]);
		runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX;
		let result;
		#[block]
		{
			result = runtime.ext().set_transient_storage(&key, value, false);
		}

		assert_eq!(result, Ok(WriteOutcome::New));
		assert_eq!(runtime.ext().get_transient_storage(&key), Some(vec![42u8; max_value_len as _]));
		Ok(())
	}

	#[benchmark(pov_mode = Ignored)]
	fn set_transient_storage_full() -> Result<(), BenchmarkError> {
		let max_value_len = T::Schedule::get().limits.payload_len;
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;
		let value = Some(vec![42u8; max_value_len as _]);
		let mut setup = CallSetup::<T>::default();
		setup.set_transient_storage_size(T::MaxTransientStorageSize::get());
		let (mut ext, _) = setup.ext();
		let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]);
		runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX;
		let result;
		#[block]
		{
			result = runtime.ext().set_transient_storage(&key, value, false);
		}

		assert_eq!(result, Ok(WriteOutcome::New));
		assert_eq!(runtime.ext().get_transient_storage(&key), Some(vec![42u8; max_value_len as _]));
		Ok(())
	}

	#[benchmark(pov_mode = Ignored)]
	fn get_transient_storage_empty() -> Result<(), BenchmarkError> {
		let max_value_len = T::Schedule::get().limits.payload_len;
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;

		let mut setup = CallSetup::<T>::default();
		let (mut ext, _) = setup.ext();
		let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]);
		runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX;
		runtime
			.ext()
			.set_transient_storage(&key, Some(vec![42u8; max_value_len as _]), false)
			.map_err(|_| "Failed to write to transient storage during setup.")?;
		let result;
		#[block]
		{
			result = runtime.ext().get_transient_storage(&key);
		}

		assert_eq!(result, Some(vec![42u8; max_value_len as _]));
		Ok(())
	}

	#[benchmark(pov_mode = Ignored)]
	fn get_transient_storage_full() -> Result<(), BenchmarkError> {
		let max_value_len = T::Schedule::get().limits.payload_len;
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;

		let mut setup = CallSetup::<T>::default();
		setup.set_transient_storage_size(T::MaxTransientStorageSize::get());
		let (mut ext, _) = setup.ext();
		let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]);
		runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX;
		runtime
			.ext()
			.set_transient_storage(&key, Some(vec![42u8; max_value_len as _]), false)
			.map_err(|_| "Failed to write to transient storage during setup.")?;
		let result;
		#[block]
		{
			result = runtime.ext().get_transient_storage(&key);
		}

		assert_eq!(result, Some(vec![42u8; max_value_len as _]));
		Ok(())
	}

	// The weight of journal rollbacks should be taken into account when setting storage.
	#[benchmark(pov_mode = Ignored)]
	fn rollback_transient_storage() -> Result<(), BenchmarkError> {
		let max_value_len = T::Schedule::get().limits.payload_len;
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;

		let mut setup = CallSetup::<T>::default();
		setup.set_transient_storage_size(T::MaxTransientStorageSize::get());
		let (mut ext, _) = setup.ext();
		let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]);
		runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX;
		runtime.ext().transient_storage().start_transaction();
		runtime
			.ext()
			.set_transient_storage(&key, Some(vec![42u8; max_value_len as _]), false)
			.map_err(|_| "Failed to write to transient storage during setup.")?;
		#[block]
		{
			runtime.ext().transient_storage().rollback_transaction();
		}

		assert_eq!(runtime.ext().get_transient_storage(&key), None);
		Ok(())
	}

	// n: new byte size
	// o: old byte size
	#[benchmark(pov_mode = Measured)]
	fn seal_set_transient_storage(
		n: Linear<0, { T::Schedule::get().limits.payload_len }>,
		o: Linear<0, { T::Schedule::get().limits.payload_len }>,
	) -> Result<(), BenchmarkError> {
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;
		let value = vec![1u8; n as usize];
		build_runtime!(runtime, memory: [ key.to_vec(), value.clone(), ]);
		runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX;
		runtime
			.ext()
			.set_transient_storage(&key, Some(vec![42u8; o as usize]), false)
			.map_err(|_| "Failed to write to transient storage during setup.")?;

		let result;
		#[block]
		{
			result = BenchEnv::seal0_set_transient_storage(
				&mut runtime,
				&mut memory,
				0,           // key_ptr
				max_key_len, // key_len
				max_key_len, // value_ptr
				n,           // value_len
			);
		}

		assert_ok!(result);
		assert_eq!(runtime.ext().get_transient_storage(&key).unwrap(), value);
		Ok(())
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_clear_transient_storage(
		n: Linear<0, { T::Schedule::get().limits.payload_len }>,
	) -> Result<(), BenchmarkError> {
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;
		build_runtime!(runtime, memory: [ key.to_vec(), ]);
		runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX;
		runtime
			.ext()
			.set_transient_storage(&key, Some(vec![42u8; n as usize]), false)
			.map_err(|_| "Failed to write to transient storage during setup.")?;

		let result;
		#[block]
		{
			result =
				BenchEnv::seal0_clear_transient_storage(&mut runtime, &mut memory, 0, max_key_len);
		}

		assert_ok!(result);
		assert!(runtime.ext().get_transient_storage(&key).is_none());
		Ok(())
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_get_transient_storage(
		n: Linear<0, { T::Schedule::get().limits.payload_len }>,
	) -> Result<(), BenchmarkError> {
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;
		build_runtime!(runtime, memory: [ key.to_vec(), n.to_le_bytes(), vec![0u8; n as _], ]);
		runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX;
		runtime
			.ext()
			.set_transient_storage(&key, Some(vec![42u8; n as usize]), false)
			.map_err(|_| "Failed to write to transient storage during setup.")?;

		let out_ptr = max_key_len + 4;
		let result;
		#[block]
		{
			result = BenchEnv::seal0_get_transient_storage(
				&mut runtime,
				&mut memory,
				0,           // key_ptr
				max_key_len, // key_len
				out_ptr,     // out_ptr
				max_key_len, // out_len_ptr
			);
		}

		assert_ok!(result);
		assert_eq!(
			&runtime.ext().get_transient_storage(&key).unwrap(),
			&memory[out_ptr as usize..]
		);
		Ok(())
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_contains_transient_storage(
		n: Linear<0, { T::Schedule::get().limits.payload_len }>,
	) -> Result<(), BenchmarkError> {
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;
		build_runtime!(runtime, memory: [ key.to_vec(), ]);
		runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX;
		runtime
			.ext()
			.set_transient_storage(&key, Some(vec![42u8; n as usize]), false)
			.map_err(|_| "Failed to write to transient storage during setup.")?;

		let result;
		#[block]
		{
			result = BenchEnv::seal0_contains_transient_storage(
				&mut runtime,
				&mut memory,
				0,
				max_key_len,
			);
		}

		assert_eq!(result.unwrap(), n);
		Ok(())
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_take_transient_storage(
		n: Linear<0, { T::Schedule::get().limits.payload_len }>,
	) -> Result<(), BenchmarkError> {
		let n = T::Schedule::get().limits.payload_len;
		let max_key_len = T::MaxStorageKeyLen::get();
		let key = Key::<T>::try_from_var(vec![0u8; max_key_len as usize])
			.map_err(|_| "Key has wrong length")?;
		build_runtime!(runtime, memory: [ key.to_vec(), n.to_le_bytes(), vec![0u8; n as _], ]);
		runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX;
		let value = vec![42u8; n as usize];
		runtime
			.ext()
			.set_transient_storage(&key, Some(value.clone()), false)
			.map_err(|_| "Failed to write to transient storage during setup.")?;

		let out_ptr = max_key_len + 4;
		let result;
		#[block]
		{
			result = BenchEnv::seal0_take_transient_storage(
				&mut runtime,
				&mut memory,
				0,           // key_ptr
				max_key_len, // key_len
				out_ptr,     // out_ptr
				max_key_len, // out_len_ptr
			);
		}

		assert_ok!(result);
		assert!(&runtime.ext().get_transient_storage(&key).is_none());
		assert_eq!(&value, &memory[out_ptr as usize..]);
		Ok(())
	}

	// We transfer to unique accounts.
	#[benchmark(pov_mode = Measured)]
	fn seal_transfer() {
		let account = account::<T::AccountId>("receiver", 0, 0);
		let value = Pallet::<T>::min_balance();
		assert!(value > 0u32.into());

		let mut setup = CallSetup::<T>::default();
		setup.set_balance(value);
		let (mut ext, _) = setup.ext();
		let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]);

		let account_bytes = account.encode();
		let account_len = account_bytes.len() as u32;
		let value_bytes = value.encode();
		let value_len = value_bytes.len() as u32;
		let mut memory = memory!(account_bytes, value_bytes,);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_transfer(
				&mut runtime,
				&mut memory,
				0, // account_ptr
				account_len,
				account_len,
				value_len,
			);
		}

		assert_ok!(result);
	}

	// t: with or without some value to transfer
	// i: size of the input data
	#[benchmark(pov_mode = Measured)]
	fn seal_call(t: Linear<0, 1>, i: Linear<0, { code::max_pages::<T>() * 64 * 1024 }>) {
		let Contract { account_id: callee, .. } =
			Contract::<T>::with_index(1, WasmModule::dummy(), vec![]).unwrap();
		let callee_bytes = callee.encode();
		let callee_len = callee_bytes.len() as u32;

		let value: BalanceOf<T> = t.into();
		let value_bytes = value.encode();

		let deposit: BalanceOf<T> = (u32::MAX - 100).into();
		let deposit_bytes = deposit.encode();
		let deposit_len = deposit_bytes.len() as u32;

		let mut setup = CallSetup::<T>::default();
		setup.set_storage_deposit_limit(deposit);
		setup.set_data(vec![42; i as usize]);
		setup.set_origin(Origin::from_account_id(setup.contract().account_id.clone()));

		let (mut ext, _) = setup.ext();
		let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]);
		let mut memory = memory!(callee_bytes, deposit_bytes, value_bytes,);

		let result;
		#[block]
		{
			result = BenchEnv::seal2_call(
				&mut runtime,
				&mut memory,
				CallFlags::CLONE_INPUT.bits(), // flags
				0,                             // callee_ptr
				0,                             // ref_time_limit
				0,                             // proof_size_limit
				callee_len,                    // deposit_ptr
				callee_len + deposit_len,      // value_ptr
				0,                             // input_data_ptr
				0,                             // input_data_len
				SENTINEL,                      // output_ptr
				0,                             // output_len_ptr
			);
		}

		assert_ok!(result);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_delegate_call() -> Result<(), BenchmarkError> {
		let hash = Contract::<T>::with_index(1, WasmModule::dummy(), vec![])?.info()?.code_hash;

		let mut setup = CallSetup::<T>::default();
		setup.set_origin(Origin::from_account_id(setup.contract().account_id.clone()));

		let (mut ext, _) = setup.ext();
		let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]);
		let mut memory = memory!(hash.encode(),);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_delegate_call(
				&mut runtime,
				&mut memory,
				0,        // flags
				0,        // code_hash_ptr
				0,        // input_data_ptr
				0,        // input_data_len
				SENTINEL, // output_ptr
				0,
			);
		}

		assert_ok!(result);
		Ok(())
	}

	// t: value to transfer
	// i: size of input in bytes
	// s: size of salt in bytes
	#[benchmark(pov_mode = Measured)]
	fn seal_instantiate(
		i: Linear<0, { (code::max_pages::<T>() - 1) * 64 * 1024 }>,
		s: Linear<0, { (code::max_pages::<T>() - 1) * 64 * 1024 }>,
	) -> Result<(), BenchmarkError> {
		let hash = Contract::<T>::with_index(1, WasmModule::dummy(), vec![])?.info()?.code_hash;
		let hash_bytes = hash.encode();
		let hash_len = hash_bytes.len() as u32;

		let value: BalanceOf<T> = 1u32.into();
		let value_bytes = value.encode();
		let value_len = value_bytes.len() as u32;

		let deposit: BalanceOf<T> = 0u32.into();
		let deposit_bytes = deposit.encode();
		let deposit_len = deposit_bytes.len() as u32;

		let mut setup = CallSetup::<T>::default();
		setup.set_origin(Origin::from_account_id(setup.contract().account_id.clone()));
		setup.set_balance(value + (Pallet::<T>::min_balance() * 2u32.into()));

		let account_id = &setup.contract().account_id.clone();
		let (mut ext, _) = setup.ext();
		let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]);

		let input = vec![42u8; i as _];
		let salt = vec![42u8; s as _];
		let addr = Contracts::<T>::contract_address(&account_id, &hash, &input, &salt);
		let mut memory = memory!(hash_bytes, deposit_bytes, value_bytes, input, salt,);

		let mut offset = {
			let mut current = 0u32;
			move |after: u32| {
				current += after;
				current
			}
		};

		assert!(ContractInfoOf::<T>::get(&addr).is_none());

		let result;
		#[block]
		{
			result = BenchEnv::seal2_instantiate(
				&mut runtime,
				&mut memory,
				0,                   // code_hash_ptr
				0,                   // ref_time_limit
				0,                   // proof_size_limit
				offset(hash_len),    // deposit_ptr
				offset(deposit_len), // value_ptr
				offset(value_len),   // input_data_ptr
				i,                   // input_data_len
				SENTINEL,            // address_ptr
				0,                   // address_len_ptr
				SENTINEL,            // output_ptr
				0,                   // output_len_ptr
				offset(i),           // salt_ptr
				s,                   // salt_len
			);
		}

		assert_ok!(result);
		assert!(ContractInfoOf::<T>::get(&addr).is_some());
		assert_eq!(T::Currency::balance(&addr), Pallet::<T>::min_balance() + value);
		Ok(())
	}

	// `n`: Input to hash in bytes
	#[benchmark(pov_mode = Measured)]
	fn seal_hash_sha2_256(n: Linear<0, { code::max_pages::<T>() * 64 * 1024 }>) {
		build_runtime!(runtime, memory: [[0u8; 32], vec![0u8; n as usize], ]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_hash_sha2_256(&mut runtime, &mut memory, 32, n, 0);
		}
		assert_eq!(sp_io::hashing::sha2_256(&memory[32..]), &memory[0..32]);
		assert_ok!(result);
	}

	// `n`: Input to hash in bytes
	#[benchmark(pov_mode = Measured)]
	fn seal_hash_keccak_256(n: Linear<0, { code::max_pages::<T>() * 64 * 1024 }>) {
		build_runtime!(runtime, memory: [[0u8; 32], vec![0u8; n as usize], ]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_hash_keccak_256(&mut runtime, &mut memory, 32, n, 0);
		}
		assert_eq!(sp_io::hashing::keccak_256(&memory[32..]), &memory[0..32]);
		assert_ok!(result);
	}

	// `n`: Input to hash in bytes
	#[benchmark(pov_mode = Measured)]
	fn seal_hash_blake2_256(n: Linear<0, { code::max_pages::<T>() * 64 * 1024 }>) {
		build_runtime!(runtime, memory: [[0u8; 32], vec![0u8; n as usize], ]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_hash_blake2_256(&mut runtime, &mut memory, 32, n, 0);
		}
		assert_eq!(sp_io::hashing::blake2_256(&memory[32..]), &memory[0..32]);
		assert_ok!(result);
	}

	// `n`: Input to hash in bytes
	#[benchmark(pov_mode = Measured)]
	fn seal_hash_blake2_128(n: Linear<0, { code::max_pages::<T>() * 64 * 1024 }>) {
		build_runtime!(runtime, memory: [[0u8; 16], vec![0u8; n as usize], ]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_hash_blake2_128(&mut runtime, &mut memory, 16, n, 0);
		}
		assert_eq!(sp_io::hashing::blake2_128(&memory[16..]), &memory[0..16]);
		assert_ok!(result);
	}

	// `n`: Message input length to verify in bytes.
	// need some buffer so the code size does not exceed the max code size.
	#[benchmark(pov_mode = Measured)]
	fn seal_sr25519_verify(n: Linear<0, { T::MaxCodeLen::get() - 255 }>) {
		let message = (0..n).zip((32u8..127u8).cycle()).map(|(_, c)| c).collect::<Vec<_>>();
		let message_len = message.len() as u32;

		let key_type = sp_core::crypto::KeyTypeId(*b"code");
		let pub_key = sp_io::crypto::sr25519_generate(key_type, None);
		let sig =
			sp_io::crypto::sr25519_sign(key_type, &pub_key, &message).expect("Generates signature");
		let sig = AsRef::<[u8; 64]>::as_ref(&sig).to_vec();
		let sig_len = sig.len() as u32;

		build_runtime!(runtime, memory: [sig, pub_key.to_vec(), message, ]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_sr25519_verify(
				&mut runtime,
				&mut memory,
				0,                              // signature_ptr
				sig_len,                        // pub_key_ptr
				message_len,                    // message_len
				sig_len + pub_key.len() as u32, // message_ptr
			);
		}

		assert_eq!(result.unwrap(), ReturnErrorCode::Success);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_ecdsa_recover() {
		let message_hash = sp_io::hashing::blake2_256("Hello world".as_bytes());
		let key_type = sp_core::crypto::KeyTypeId(*b"code");
		let signature = {
			let pub_key = sp_io::crypto::ecdsa_generate(key_type, None);
			let sig = sp_io::crypto::ecdsa_sign_prehashed(key_type, &pub_key, &message_hash)
				.expect("Generates signature");
			AsRef::<[u8; 65]>::as_ref(&sig).to_vec()
		};

		build_runtime!(runtime, memory: [signature, message_hash, [0u8; 33], ]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_ecdsa_recover(
				&mut runtime,
				&mut memory,
				0,       // signature_ptr
				65,      // message_hash_ptr
				65 + 32, // output_ptr
			);
		}

		assert_eq!(result.unwrap(), ReturnErrorCode::Success);
	}

	// Only calling the function itself for the list of
	// generated different ECDSA keys.
	// This is a slow call: We reduce the number of runs.
	#[benchmark(pov_mode = Measured)]
	fn seal_ecdsa_to_eth_address() {
		let key_type = sp_core::crypto::KeyTypeId(*b"code");
		let pub_key_bytes = sp_io::crypto::ecdsa_generate(key_type, None).0;
		build_runtime!(runtime, memory: [[0u8; 20], pub_key_bytes,]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_ecdsa_to_eth_address(
				&mut runtime,
				&mut memory,
				20, // key_ptr
				0,  // output_ptr
			);
		}

		assert_ok!(result);
		assert_eq!(&memory[..20], runtime.ext().ecdsa_to_eth_address(&pub_key_bytes).unwrap());
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_set_code_hash() -> Result<(), BenchmarkError> {
		let code_hash =
			Contract::<T>::with_index(1, WasmModule::dummy(), vec![])?.info()?.code_hash;

		build_runtime!(runtime, memory: [ code_hash.encode(),]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_set_code_hash(&mut runtime, &mut memory, 0);
		}

		assert_ok!(result);
		Ok(())
	}

	#[benchmark(pov_mode = Measured)]
	fn lock_delegate_dependency() -> Result<(), BenchmarkError> {
		let code_hash = Contract::<T>::with_index(1, WasmModule::dummy_with_bytes(1), vec![])?
			.info()?
			.code_hash;

		build_runtime!(runtime, memory: [ code_hash.encode(),]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_lock_delegate_dependency(&mut runtime, &mut memory, 0);
		}

		assert_ok!(result);
		Ok(())
	}

	#[benchmark]
	fn unlock_delegate_dependency() -> Result<(), BenchmarkError> {
		let code_hash = Contract::<T>::with_index(1, WasmModule::dummy_with_bytes(1), vec![])?
			.info()?
			.code_hash;

		build_runtime!(runtime, memory: [ code_hash.encode(),]);
		BenchEnv::seal0_lock_delegate_dependency(&mut runtime, &mut memory, 0).unwrap();

		let result;
		#[block]
		{
			result = BenchEnv::seal0_unlock_delegate_dependency(&mut runtime, &mut memory, 0);
		}

		assert_ok!(result);
		Ok(())
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_reentrance_count() {
		build_runtime!(runtime, memory: []);
		let result;
		#[block]
		{
			result = BenchEnv::seal0_reentrance_count(&mut runtime, &mut memory)
		}

		assert_eq!(result.unwrap(), 0);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_account_reentrance_count() {
		let Contract { account_id, .. } =
			Contract::<T>::with_index(1, WasmModule::dummy(), vec![]).unwrap();
		build_runtime!(runtime, memory: [account_id.encode(),]);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_account_reentrance_count(&mut runtime, &mut memory, 0);
		}

		assert_eq!(result.unwrap(), 0);
	}

	#[benchmark(pov_mode = Measured)]
	fn seal_instantiation_nonce() {
		build_runtime!(runtime, memory: []);

		let result;
		#[block]
		{
			result = BenchEnv::seal0_instantiation_nonce(&mut runtime, &mut memory);
		}

		assert_eq!(result.unwrap(), 1);
	}

	// We load `i64` values from random linear memory locations and store the loaded
	// values back into yet another random linear memory location.
	// The random addresses are uniformly distributed across the entire span of the linear memory.
	// We do this to enforce random memory accesses which are particularly expensive.
	//
	// The combination of this computation is our weight base `w_base`.
	#[benchmark(pov_mode = Ignored)]
	fn instr_i64_load_store(r: Linear<0, INSTR_BENCHMARK_RUNS>) -> Result<(), BenchmarkError> {
		use rand::prelude::*;

		// We do not need to be secure here. Fixed seed allows for deterministic results.
		let mut rng = rand_pcg::Pcg32::seed_from_u64(8446744073709551615);

		let memory = ImportedMemory::max::<T>();
		let bytes_per_page = 65536;
		let bytes_per_memory = memory.max_pages * bytes_per_page;
		let mut sbox = Sandbox::from(&WasmModule::<T>::from(ModuleDefinition {
			memory: Some(memory),
			call_body: Some(body::repeated_with_locals_using(
				&[Local::new(1, ValueType::I64)],
				r,
				|| {
					// Instruction sequence to load a `i64` from linear memory
					// at a random memory location and store it back into another
					// location of the linear memory.
					let c0: i32 = rng.gen_range(0..bytes_per_memory as i32);
					let c1: i32 = rng.gen_range(0..bytes_per_memory as i32);
					[
						Instruction::I32Const(c0), // address for `i64.load_8s`
						Instruction::I64Load8S(0, 0),
						Instruction::SetLocal(0),  /* temporarily store value loaded in
						                            * `i64.load_8s` */
						Instruction::I32Const(c1), // address for `i64.store8`
						Instruction::GetLocal(0),  // value to be stores in `i64.store8`
						Instruction::I64Store8(0, 0),
					]
				},
			)),
			..Default::default()
		}));
		#[block]
		{
			sbox.invoke();
		}
		Ok(())
	}

	// This is no benchmark. It merely exist to have an easy way to pretty print the currently
	// configured `Schedule` during benchmark development. Check the README on how to print this.
	#[benchmark(extra, pov_mode = Ignored)]
	fn print_schedule() -> Result<(), BenchmarkError> {
		let max_weight = <T as frame_system::Config>::BlockWeights::get().max_block;
		let (weight_per_key, key_budget) =
			ContractInfo::<T>::deletion_budget(&mut WeightMeter::with_limit(max_weight));
		let schedule = T::Schedule::get();
		log::info!(target: LOG_TARGET, "
		{schedule:#?}
		###############################################
		Lazy deletion weight per key: {weight_per_key}
		Lazy deletion keys per block: {key_budget}
		");
		#[block]
		{}

		Err(BenchmarkError::Skip)
	}

	impl_benchmark_test_suite!(
		Contracts,
		crate::tests::ExtBuilder::default().build(),
		crate::tests::Test,
	);
}