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
#![allow(missing_docs)] // `construct_macro` doesn't allow doc comments for the runtime type.

/// Macro creating a minimal runtime with the given name. Optionally can take a chain extension
/// type as a second argument.
///
/// The new macro will automatically implement `drink::Runtime`.
#[macro_export]
macro_rules! create_minimal_runtime {
    ($name:ident) => {
        create_minimal_runtime!($name, ());
    };
    ($name:ident, $chain_extension: ty) => {
        // ------------ Put all the boilerplate into an auxiliary module -----------------------------------
        mod construct_runtime {

            // ------------ Bring some common types into the scope -----------------------------------------
            use $crate::frame_support::{
                construct_runtime,
                derive_impl,
                parameter_types,
                sp_runtime::{
                    testing::H256,
                    traits::Convert,
                    AccountId32, Perbill,
                },
                traits::{ConstBool, ConstU128, ConstU32, ConstU64, Currency, Randomness},
                weights::Weight,
            };
            use $crate::runtime::pallet_contracts_debugging::DrinkDebug;

            // ------------ Define the runtime type as a collection of pallets -----------------------------
            construct_runtime!(
                pub enum $name {
                    System: $crate::frame_system,
                    Balances: $crate::pallet_balances,
                    Timestamp: $crate::pallet_timestamp,
                    Contracts: $crate::pallet_contracts,
                }
            );

            // ------------ Configure pallet system --------------------------------------------------------
            #[derive_impl($crate::frame_system::config_preludes::SolochainDefaultConfig as $crate::frame_system::DefaultConfig)]
            impl $crate::frame_system::Config for $name {
                type Block = $crate::frame_system::mocking::MockBlockU32<$name>;
                type Version = ();
                type BlockHashCount = ConstU32<250>;
                type AccountData = $crate::pallet_balances::AccountData<<$name as $crate::pallet_balances::Config>::Balance>;
            }

            // ------------ Configure pallet balances ------------------------------------------------------
            impl $crate::pallet_balances::Config for $name {
                type RuntimeEvent = RuntimeEvent;
                type WeightInfo = ();
                type Balance = u128;
                type DustRemoval = ();
                type ExistentialDeposit = ConstU128<1>;
                type AccountStore = System;
                type ReserveIdentifier = [u8; 8];
                type FreezeIdentifier = ();
                type MaxLocks = ();
                type MaxReserves = ();
                type MaxHolds = ConstU32<1>;
                type MaxFreezes = ();
                type RuntimeHoldReason = RuntimeHoldReason;
                type RuntimeFreezeReason = RuntimeFreezeReason;
            }

            // ------------ Configure pallet timestamp -----------------------------------------------------
            impl $crate::pallet_timestamp::Config for $name {
                type Moment = u64;
                type OnTimestampSet = ();
                type MinimumPeriod = ConstU64<1>;
                type WeightInfo = ();
            }

            // ------------ Configure pallet contracts -----------------------------------------------------
            pub enum SandboxRandomness {}
            impl Randomness<H256, u32> for SandboxRandomness {
                fn random(_subject: &[u8]) -> (H256, u32) {
                    unreachable!("No randomness")
                }
            }

            type BalanceOf = <Balances as Currency<AccountId32>>::Balance;
            impl Convert<Weight, BalanceOf> for $name {
                fn convert(w: Weight) -> BalanceOf {
                    w.ref_time().into()
                }
            }

            parameter_types! {
                pub SandboxSchedule: $crate::pallet_contracts::Schedule<$name> = {
                    <$crate::pallet_contracts::Schedule<$name>>::default()
                };
                pub DeletionWeightLimit: Weight = Weight::zero();
                pub DefaultDepositLimit: BalanceOf = 10_000_000;
                pub CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0);
                pub MaxDelegateDependencies: u32 = 32;
            }

            impl $crate::pallet_contracts::Config for $name {
                type Time = Timestamp;
                type Randomness = SandboxRandomness;
                type Currency = Balances;
                type RuntimeEvent = RuntimeEvent;
                type RuntimeCall = RuntimeCall;
                type CallFilter = ();
                type WeightPrice = Self;
                type WeightInfo = ();
                type ChainExtension = $chain_extension;
                type Schedule = SandboxSchedule;
                type CallStack = [$crate::pallet_contracts::Frame<Self>; 5];
                type DepositPerByte = ConstU128<1>;
                type DepositPerItem = ConstU128<1>;
                type AddressGenerator = $crate::pallet_contracts::DefaultAddressGenerator;
                type MaxCodeLen = ConstU32<{ 123 * 1024 }>;
                type MaxStorageKeyLen = ConstU32<128>;
                type UnsafeUnstableInterface = ConstBool<false>;
                type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>;
                type Migrations = ();
                type DefaultDepositLimit = DefaultDepositLimit;
                type Debug = DrinkDebug;
                type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
                type MaxDelegateDependencies = MaxDelegateDependencies;
                type RuntimeHoldReason = RuntimeHoldReason;
                type Environment = ();
                type Xcm = ();
            }
        }

        // ------------ Export runtime type itself, pallets and useful types from the auxiliary module -----
        pub use construct_runtime::{
            $name, Balances, Contracts, PalletInfo, RuntimeCall, RuntimeEvent, RuntimeHoldReason,
            RuntimeOrigin, System, Timestamp,
        };

        impl_runtime!(super::$name, super::$name);
    };
}

#[macro_export]
macro_rules! impl_runtime {
    ($runtime:ty, $config:ty) => {
        mod runtime_runner {
            use std::time::SystemTime;
            use $crate::AccountId32;
            use $crate::runtime::{AccountIdFor, Runtime, RuntimeMetadataPrefixed};
            use $crate::frame_system::pallet_prelude::BlockNumberFor;
            use $crate::frame_support::{
                sp_runtime::{traits::Dispatchable, BuildStorage, Storage},
                traits::Hooks,
            };


            type System = $crate::frame_system::Pallet<$config>;
            type Contracts = $crate::pallet_contracts::Pallet<$config>;
            type Balances = $crate::pallet_balances::Pallet<$config>;
            type Timestamp = $crate::pallet_timestamp::Pallet<$config>;

            impl Runtime for $runtime {
                type Config = $config;
                fn initialize_storage(storage: &mut Storage) -> Result<(), String> {
                    const INITIAL_BALANCE: u128 = 1_000_000_000_000_000;
                    $crate::pallet_balances::GenesisConfig::<$config> {
                        balances: vec![(Self::default_actor(), INITIAL_BALANCE)],
                    }
                    .assimilate_storage(storage)
                }

                fn initialize_block(
                    height: $crate::frame_system::pallet_prelude::BlockNumberFor<Self::Config>,
                    parent_hash: <Self::Config as $crate::frame_system::Config>::Hash,
                ) -> Result<(), String> {
                    System::reset_events();
                    System::initialize(&height, &parent_hash, &Default::default());

                    Balances::on_initialize(height);
                    Timestamp::set_timestamp(
                        SystemTime::now()
                            .duration_since(SystemTime::UNIX_EPOCH)
                            .expect("Time went backwards")
                            .as_secs(),
                    );
                    Timestamp::on_initialize(height);
                    Contracts::on_initialize(height);

                    System::note_finished_initialize();

                    Ok(())
                }

                fn finalize_block(
                    height: BlockNumberFor<Self::Config>,
                ) -> Result<<Self::Config as $crate::frame_system::Config>::Hash, String> {
                    Contracts::on_finalize(height);
                    Timestamp::on_finalize(height);
                    Balances::on_finalize(height);

                    Ok(System::finalize().hash())
                }

                fn default_actor() -> AccountIdFor<Self::Config> {
                    AccountId32::new([1u8; 32])
                }

                fn get_metadata() -> RuntimeMetadataPrefixed {
                    <$config>::metadata()
                }

                fn convert_account_to_origin(
                    account: AccountIdFor<Self::Config>,
                ) -> <<$config as $crate::frame_system::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin {
                    Some(account).into()
                }
            }
        }
    };
}

create_minimal_runtime!(MinimalRuntime);