forked from open-web3-stack/open-runtime-module-library
-
Notifications
You must be signed in to change notification settings - Fork 4
/
mod.rs
398 lines (360 loc) · 10.6 KB
/
mod.rs
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
#![cfg(test)]
use super::*;
use crate as orml_xtokens;
use scale_info::TypeInfo;
use serde::{Deserialize, Serialize};
use sp_io::TestExternalities;
use sp_runtime::{AccountId32, BoundedVec, BuildStorage};
use xcm_builder::{CreateMatcher, MatchXcm};
use xcm_executor::traits::{ShouldExecute, WeightTrader};
use xcm_executor::Assets;
use xcm_simulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain, ProcessMessageError, TestExt};
pub mod para;
pub mod para_relative_view;
pub mod para_teleport;
pub mod relay;
pub mod teleport_currency_adapter;
pub const ALICE: AccountId32 = AccountId32::new([0u8; 32]);
pub const BOB: AccountId32 = AccountId32::new([1u8; 32]);
#[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, PartialOrd, Ord, codec::MaxEncodedLen, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum CurrencyId {
/// Relay chain token.
R,
/// Parachain A token.
A,
/// Parachain A A1 token.
A1,
/// Parachain B token.
B,
/// Parachain B B1 token
B1,
/// Parachain B B2 token
B2,
/// Parachain C token
C,
/// Parachain D token
D,
}
pub struct CurrencyIdConvert;
impl Convert<CurrencyId, Option<MultiLocation>> for CurrencyIdConvert {
fn convert(id: CurrencyId) -> Option<MultiLocation> {
match id {
CurrencyId::R => Some(Parent.into()),
CurrencyId::A => Some(
(
Parent,
Parachain(1),
Junction::from(BoundedVec::try_from(b"A".to_vec()).unwrap()),
)
.into(),
),
CurrencyId::A1 => Some(
(
Parent,
Parachain(1),
Junction::from(BoundedVec::try_from(b"A1".to_vec()).unwrap()),
)
.into(),
),
CurrencyId::B => Some(
(
Parent,
Parachain(2),
Junction::from(BoundedVec::try_from(b"B".to_vec()).unwrap()),
)
.into(),
),
CurrencyId::B1 => Some(
(
Parent,
Parachain(2),
Junction::from(BoundedVec::try_from(b"B1".to_vec()).unwrap()),
)
.into(),
),
CurrencyId::B2 => Some(
(
Parent,
Parachain(2),
Junction::from(BoundedVec::try_from(b"B2".to_vec()).unwrap()),
)
.into(),
),
CurrencyId::C => Some(
(
Parent,
Parachain(3),
Junction::from(BoundedVec::try_from(b"C".to_vec()).unwrap()),
)
.into(),
),
CurrencyId::D => Some(
(
Parent,
Parachain(4),
Junction::from(BoundedVec::try_from(b"D".to_vec()).unwrap()),
)
.into(),
),
}
}
}
impl Convert<MultiLocation, Option<CurrencyId>> for CurrencyIdConvert {
fn convert(l: MultiLocation) -> Option<CurrencyId> {
let mut a: Vec<u8> = "A".into();
a.resize(32, 0);
let mut a1: Vec<u8> = "A1".into();
a1.resize(32, 0);
let mut b: Vec<u8> = "B".into();
b.resize(32, 0);
let mut b1: Vec<u8> = "B1".into();
b1.resize(32, 0);
let mut b2: Vec<u8> = "B2".into();
b2.resize(32, 0);
let mut c: Vec<u8> = "C".into();
c.resize(32, 0);
let mut d: Vec<u8> = "D".into();
d.resize(32, 0);
if l == MultiLocation::parent() {
return Some(CurrencyId::R);
}
match l {
MultiLocation { parents, interior } if parents == 1 => match interior {
X2(Parachain(1), GeneralKey { data, .. }) if data.to_vec() == a => Some(CurrencyId::A),
X2(Parachain(1), GeneralKey { data, .. }) if data.to_vec() == a1 => Some(CurrencyId::A1),
X2(Parachain(2), GeneralKey { data, .. }) if data.to_vec() == b => Some(CurrencyId::B),
X2(Parachain(2), GeneralKey { data, .. }) if data.to_vec() == b1 => Some(CurrencyId::B1),
X2(Parachain(2), GeneralKey { data, .. }) if data.to_vec() == b2 => Some(CurrencyId::B2),
X2(Parachain(3), GeneralKey { data, .. }) if data.to_vec() == c => Some(CurrencyId::C),
X2(Parachain(4), GeneralKey { data, .. }) if data.to_vec() == d => Some(CurrencyId::D),
_ => None,
},
MultiLocation { parents, interior } if parents == 0 => match interior {
X1(GeneralKey { data, .. }) if data.to_vec() == a => Some(CurrencyId::A),
X1(GeneralKey { data, .. }) if data.to_vec() == b => Some(CurrencyId::B),
X1(GeneralKey { data, .. }) if data.to_vec() == a1 => Some(CurrencyId::A1),
X1(GeneralKey { data, .. }) if data.to_vec() == b1 => Some(CurrencyId::B1),
X1(GeneralKey { data, .. }) if data.to_vec() == b2 => Some(CurrencyId::B2),
X1(GeneralKey { data, .. }) if data.to_vec() == c => Some(CurrencyId::C),
X1(GeneralKey { data, .. }) if data.to_vec() == d => Some(CurrencyId::D),
_ => None,
},
_ => None,
}
}
}
impl Convert<MultiAsset, Option<CurrencyId>> for CurrencyIdConvert {
fn convert(a: MultiAsset) -> Option<CurrencyId> {
if let MultiAsset {
fun: Fungible(_),
id: Concrete(id),
} = a
{
Self::convert(id)
} else {
Option::None
}
}
}
pub type Balance = u128;
pub type Amount = i128;
decl_test_parachain! {
pub struct ParaA {
Runtime = para::Runtime,
XcmpMessageHandler = para::XcmpQueue,
DmpMessageHandler = para::DmpQueue,
new_ext = para_ext(1),
}
}
decl_test_parachain! {
pub struct ParaB {
Runtime = para::Runtime,
XcmpMessageHandler = para::XcmpQueue,
DmpMessageHandler = para::DmpQueue,
new_ext = para_ext(2),
}
}
decl_test_parachain! {
pub struct ParaC {
Runtime = para_teleport::Runtime,
XcmpMessageHandler = para_teleport::XcmpQueue,
DmpMessageHandler = para_teleport::DmpQueue,
new_ext = para_teleport_ext(3),
}
}
// This parachain is identical to the others but using relative view for self
// tokens
decl_test_parachain! {
pub struct ParaD {
Runtime = para_relative_view::Runtime,
XcmpMessageHandler = para::XcmpQueue,
DmpMessageHandler = para::DmpQueue,
new_ext = para_ext(4),
}
}
decl_test_relay_chain! {
pub struct Relay {
Runtime = relay::Runtime,
RuntimeCall = relay::RuntimeCall,
RuntimeEvent = relay::RuntimeEvent,
XcmConfig = relay::XcmConfig,
MessageQueue = relay::MessageQueue,
System = relay::System,
new_ext = relay_ext(),
}
}
decl_test_network! {
pub struct TestNet {
relay_chain = Relay,
parachains = vec![
(1, ParaA),
(2, ParaB),
(3, ParaC),
(4, ParaD),
],
}
}
pub type RelayBalances = pallet_balances::Pallet<relay::Runtime>;
pub type ParaTokens = orml_tokens::Pallet<para::Runtime>;
pub type ParaXTokens = orml_xtokens::Pallet<para::Runtime>;
pub type ParaRelativeTokens = orml_tokens::Pallet<para_relative_view::Runtime>;
pub type ParaRelativeXTokens = orml_xtokens::Pallet<para_relative_view::Runtime>;
pub type ParaTeleportTokens = orml_tokens::Pallet<para_teleport::Runtime>;
pub fn para_ext(para_id: u32) -> TestExternalities {
use para::{Runtime, System};
let mut t = frame_system::GenesisConfig::<Runtime>::default()
.build_storage()
.unwrap();
let parachain_info_config = parachain_info::GenesisConfig::<Runtime> {
_config: Default::default(),
parachain_id: para_id.into(),
};
parachain_info_config.assimilate_storage(&mut t).unwrap();
orml_tokens::GenesisConfig::<Runtime> {
balances: vec![(ALICE, CurrencyId::R, 1_000)],
}
.assimilate_storage(&mut t)
.unwrap();
let mut ext = TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
pub fn para_teleport_ext(para_id: u32) -> TestExternalities {
use para_teleport::{Runtime, System};
let mut t = frame_system::GenesisConfig::<Runtime>::default()
.build_storage()
.unwrap();
let parachain_info_config = parachain_info::GenesisConfig::<Runtime> {
_config: Default::default(),
parachain_id: para_id.into(),
};
parachain_info_config.assimilate_storage(&mut t).unwrap();
orml_tokens::GenesisConfig::<Runtime> {
balances: vec![(ALICE, CurrencyId::R, 1_000)],
}
.assimilate_storage(&mut t)
.unwrap();
let mut ext = TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
pub fn relay_ext() -> sp_io::TestExternalities {
use relay::{Runtime, System};
let mut t = frame_system::GenesisConfig::<Runtime>::default()
.build_storage()
.unwrap();
pallet_balances::GenesisConfig::<Runtime> {
balances: vec![(ALICE, 1_000)],
}
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
/// A trader who believes all tokens are created equal to "weight" of any chain,
/// which is not true, but good enough to mock the fee payment of XCM execution.
///
/// This mock will always trade `n` amount of weight to `n` amount of tokens.
pub struct AllTokensAreCreatedEqualToWeight(MultiLocation);
impl WeightTrader for AllTokensAreCreatedEqualToWeight {
fn new() -> Self {
Self(MultiLocation::parent())
}
fn buy_weight(&mut self, weight: Weight, payment: Assets, _context: &XcmContext) -> Result<Assets, XcmError> {
let asset_id = payment
.fungible
.iter()
.next()
.expect("Payment must be something; qed")
.0;
let required = MultiAsset {
id: asset_id.clone(),
fun: Fungible(weight.ref_time() as u128),
};
if let MultiAsset {
fun: _,
id: Concrete(ref id),
} = &required
{
self.0 = id.clone();
}
let unused = payment.checked_sub(required).map_err(|_| XcmError::TooExpensive)?;
Ok(unused)
}
fn refund_weight(&mut self, weight: Weight, _context: &XcmContext) -> Option<MultiAsset> {
if weight.is_zero() {
None
} else {
Some((self.0.clone(), weight.ref_time() as u128).into())
}
}
}
/// Allows execution from all origins taking payment into account.
///
/// Only allows for `TeleportAsset`, `WithdrawAsset`, `ClaimAsset` and
/// `ReserveAssetDeposit` XCMs because they are the only ones that place assets
/// in the Holding Register to pay for execution. This is almost equal to
/// [`xcm_builder::AllowTopLevelPaidExecutionFrom<T>`] except that it allows for
/// multiple assets and is not generic to allow all origins.
pub struct AllowTopLevelPaidExecution;
impl ShouldExecute for AllowTopLevelPaidExecution {
fn should_execute<RuntimeCall>(
_origin: &MultiLocation,
instructions: &mut [Instruction<RuntimeCall>],
max_weight: Weight,
_properties: &mut xcm_executor::traits::Properties,
) -> Result<(), ProcessMessageError> {
let end = instructions.len().min(5);
instructions[..end]
.matcher()
.match_next_inst(|inst| match inst {
ReceiveTeleportedAsset(..) | ReserveAssetDeposited(..) => Ok(()),
WithdrawAsset(..) => Ok(()),
ClaimAsset { .. } => Ok(()),
_ => Err(ProcessMessageError::BadFormat),
})?
.skip_inst_while(|inst| matches!(inst, ClearOrigin))?
.match_next_inst(|inst| {
let res = match inst {
BuyExecution {
weight_limit: Limited(ref mut weight),
..
} if weight.all_gte(max_weight) => {
*weight = max_weight;
Ok(())
}
BuyExecution {
ref mut weight_limit, ..
} if weight_limit == &Unlimited => {
*weight_limit = Limited(max_weight);
Ok(())
}
_ => Err(ProcessMessageError::Overweight(max_weight)),
};
res
})?;
Ok(())
}
}