-
Notifications
You must be signed in to change notification settings - Fork 700
/
tests.rs
1448 lines (1289 loc) · 46.5 KB
/
tests.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
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
// This file is part of Cumulus.
// 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.
//! Tests for the Westmint (Westend Assets Hub) chain.
use asset_hub_westend_runtime::{
xcm_config,
xcm_config::{
bridging, AssetFeeAsExistentialDepositMultiplierFeeCharger, CheckingAccount,
ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger, LocationToAccountId, StakingPot,
TrustBackedAssetsPalletLocation, WestendLocation, XcmConfig,
},
AllPalletsWithoutSystem, Assets, Balances, ExistentialDeposit, ForeignAssets,
ForeignAssetsInstance, MetadataDepositBase, MetadataDepositPerByte, ParachainSystem,
PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, SessionKeys,
TrustBackedAssetsInstance, XcmpQueue,
};
pub use asset_hub_westend_runtime::{AssetConversion, AssetDeposit, CollatorSelection, System};
use asset_test_utils::{
test_cases_over_bridge::TestBridgingConfig, CollatorSessionKey, CollatorSessionKeys,
ExtBuilder, SlotDurations,
};
use codec::{Decode, Encode};
use cumulus_primitives_utility::ChargeWeightInFungibles;
use frame_support::{
assert_noop, assert_ok,
traits::{
fungible::{Inspect, Mutate},
fungibles::{
Create, Inspect as FungiblesInspect, InspectEnumerable, Mutate as FungiblesMutate,
},
},
weights::{Weight, WeightToFee as WeightToFeeT},
};
use parachains_common::{AccountId, AssetIdForTrustBackedAssets, AuraId, Balance};
use sp_consensus_aura::SlotDuration;
use sp_core::crypto::Ss58Codec;
use sp_runtime::traits::MaybeEquivalence;
use std::{convert::Into, ops::Mul};
use testnet_parachains_constants::westend::{consensus::*, currency::UNITS, fee::WeightToFee};
use xcm::latest::{
prelude::{Assets as XcmAssets, *},
ROCOCO_GENESIS_HASH,
};
use xcm_builder::WithLatestLocationConverter;
use xcm_executor::traits::{ConvertLocation, JustTry, WeightTrader};
use xcm_runtime_apis::conversions::LocationToAccountHelper;
const ALICE: [u8; 32] = [1u8; 32];
const SOME_ASSET_ADMIN: [u8; 32] = [5u8; 32];
type AssetIdForTrustBackedAssetsConvert =
assets_common::AssetIdForTrustBackedAssetsConvert<TrustBackedAssetsPalletLocation>;
type RuntimeHelper = asset_test_utils::RuntimeHelper<Runtime, AllPalletsWithoutSystem>;
fn collator_session_key(account: [u8; 32]) -> CollatorSessionKey<Runtime> {
CollatorSessionKey::new(
AccountId::from(account),
AccountId::from(account),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(account)) },
)
}
fn collator_session_keys() -> CollatorSessionKeys<Runtime> {
CollatorSessionKeys::default().add(collator_session_key(ALICE))
}
fn slot_durations() -> SlotDurations {
SlotDurations {
relay: SlotDuration::from_millis(RELAY_CHAIN_SLOT_DURATION_MILLIS.into()),
para: SlotDuration::from_millis(SLOT_DURATION),
}
}
fn setup_pool_for_paying_fees_with_foreign_assets(
(foreign_asset_owner, foreign_asset_id_location, foreign_asset_id_minimum_balance): (
AccountId,
xcm::v5::Location,
Balance,
),
) {
let existential_deposit = ExistentialDeposit::get();
// setup a pool to pay fees with `foreign_asset_id_location` tokens
let pool_owner: AccountId = [14u8; 32].into();
let native_asset = xcm::v5::Location::parent();
let pool_liquidity: Balance =
existential_deposit.max(foreign_asset_id_minimum_balance).mul(100_000);
let _ = Balances::force_set_balance(
RuntimeOrigin::root(),
pool_owner.clone().into(),
(existential_deposit + pool_liquidity).mul(2).into(),
);
assert_ok!(ForeignAssets::mint(
RuntimeOrigin::signed(foreign_asset_owner),
foreign_asset_id_location.clone().into(),
pool_owner.clone().into(),
(foreign_asset_id_minimum_balance + pool_liquidity).mul(2).into(),
));
assert_ok!(AssetConversion::create_pool(
RuntimeOrigin::signed(pool_owner.clone()),
Box::new(native_asset.clone().into()),
Box::new(foreign_asset_id_location.clone().into())
));
assert_ok!(AssetConversion::add_liquidity(
RuntimeOrigin::signed(pool_owner.clone()),
Box::new(native_asset.into()),
Box::new(foreign_asset_id_location.into()),
pool_liquidity,
pool_liquidity,
1,
1,
pool_owner,
));
}
#[test]
fn test_buy_and_refund_weight_in_native() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
let bob: AccountId = SOME_ASSET_ADMIN.into();
let staking_pot = CollatorSelection::account_id();
let native_location = WestendLocation::get();
let initial_balance = 200 * UNITS;
assert_ok!(Balances::mint_into(&bob, initial_balance));
assert_ok!(Balances::mint_into(&staking_pot, initial_balance));
// keep initial total issuance to assert later.
let total_issuance = Balances::total_issuance();
// prepare input to buy weight.
let weight = Weight::from_parts(4_000_000_000, 0);
let fee = WeightToFee::weight_to_fee(&weight);
let extra_amount = 100;
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
let payment: Asset = (native_location.clone(), fee + extra_amount).into();
// init trader and buy weight.
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
let unused_asset =
trader.buy_weight(weight, payment.into(), &ctx).expect("Expected Ok");
// assert.
let unused_amount =
unused_asset.fungible.get(&native_location.clone().into()).map_or(0, |a| *a);
assert_eq!(unused_amount, extra_amount);
assert_eq!(Balances::total_issuance(), total_issuance);
// prepare input to refund weight.
let refund_weight = Weight::from_parts(1_000_000_000, 0);
let refund = WeightToFee::weight_to_fee(&refund_weight);
// refund.
let actual_refund = trader.refund_weight(refund_weight, &ctx).unwrap();
assert_eq!(actual_refund, (native_location, refund).into());
// assert.
assert_eq!(Balances::balance(&staking_pot), initial_balance);
// only after `trader` is dropped we expect the fee to be resolved into the treasury
// account.
drop(trader);
assert_eq!(Balances::balance(&staking_pot), initial_balance + fee - refund);
assert_eq!(Balances::total_issuance(), total_issuance + fee - refund);
})
}
#[test]
fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
let bob: AccountId = SOME_ASSET_ADMIN.into();
let staking_pot = CollatorSelection::account_id();
let asset_1: u32 = 1;
let native_location = WestendLocation::get();
let asset_1_location =
AssetIdForTrustBackedAssetsConvert::convert_back(&asset_1).unwrap();
// bob's initial balance for native and `asset1` assets.
let initial_balance = 200 * UNITS;
// liquidity for both arms of (native, asset1) pool.
let pool_liquidity = 100 * UNITS;
// init asset, balances and pool.
assert_ok!(<Assets as Create<_>>::create(asset_1, bob.clone(), true, 10));
assert_ok!(Assets::mint_into(asset_1, &bob, initial_balance));
assert_ok!(Balances::mint_into(&bob, initial_balance));
assert_ok!(Balances::mint_into(&staking_pot, initial_balance));
assert_ok!(AssetConversion::create_pool(
RuntimeHelper::origin_of(bob.clone()),
Box::new(
xcm::v5::Location::try_from(native_location.clone()).expect("conversion works")
),
Box::new(
xcm::v5::Location::try_from(asset_1_location.clone())
.expect("conversion works")
)
));
assert_ok!(AssetConversion::add_liquidity(
RuntimeHelper::origin_of(bob.clone()),
Box::new(
xcm::v5::Location::try_from(native_location.clone()).expect("conversion works")
),
Box::new(
xcm::v5::Location::try_from(asset_1_location.clone())
.expect("conversion works")
),
pool_liquidity,
pool_liquidity,
1,
1,
bob,
));
// keep initial total issuance to assert later.
let asset_total_issuance = Assets::total_issuance(asset_1);
let native_total_issuance = Balances::total_issuance();
// prepare input to buy weight.
let weight = Weight::from_parts(4_000_000_000, 0);
let fee = WeightToFee::weight_to_fee(&weight);
let asset_fee =
AssetConversion::get_amount_in(&fee, &pool_liquidity, &pool_liquidity).unwrap();
let extra_amount = 100;
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
let payment: Asset = (asset_1_location.clone(), asset_fee + extra_amount).into();
// init trader and buy weight.
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
let unused_asset =
trader.buy_weight(weight, payment.into(), &ctx).expect("Expected Ok");
// assert.
let unused_amount =
unused_asset.fungible.get(&asset_1_location.clone().into()).map_or(0, |a| *a);
assert_eq!(unused_amount, extra_amount);
assert_eq!(Assets::total_issuance(asset_1), asset_total_issuance + asset_fee);
// prepare input to refund weight.
let refund_weight = Weight::from_parts(1_000_000_000, 0);
let refund = WeightToFee::weight_to_fee(&refund_weight);
let (reserve1, reserve2) = AssetConversion::get_reserves(
xcm::v5::Location::try_from(native_location).expect("conversion works"),
xcm::v5::Location::try_from(asset_1_location.clone()).expect("conversion works"),
)
.unwrap();
let asset_refund =
AssetConversion::get_amount_out(&refund, &reserve1, &reserve2).unwrap();
// refund.
let actual_refund = trader.refund_weight(refund_weight, &ctx).unwrap();
assert_eq!(actual_refund, (asset_1_location, asset_refund).into());
// assert.
assert_eq!(Balances::balance(&staking_pot), initial_balance);
// only after `trader` is dropped we expect the fee to be resolved into the treasury
// account.
drop(trader);
assert_eq!(Balances::balance(&staking_pot), initial_balance + fee - refund);
assert_eq!(
Assets::total_issuance(asset_1),
asset_total_issuance + asset_fee - asset_refund
);
assert_eq!(Balances::total_issuance(), native_total_issuance);
})
}
#[test]
fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
let bob: AccountId = SOME_ASSET_ADMIN.into();
let staking_pot = CollatorSelection::account_id();
let native_location =
xcm::v5::Location::try_from(WestendLocation::get()).expect("conversion works");
let foreign_location = xcm::v5::Location {
parents: 1,
interior: (
xcm::v5::Junction::Parachain(1234),
xcm::v5::Junction::GeneralIndex(12345),
)
.into(),
};
// bob's initial balance for native and `asset1` assets.
let initial_balance = 200 * UNITS;
// liquidity for both arms of (native, asset1) pool.
let pool_liquidity = 100 * UNITS;
// init asset, balances and pool.
assert_ok!(<ForeignAssets as Create<_>>::create(
foreign_location.clone(),
bob.clone(),
true,
10
));
assert_ok!(ForeignAssets::mint_into(foreign_location.clone(), &bob, initial_balance));
assert_ok!(Balances::mint_into(&bob, initial_balance));
assert_ok!(Balances::mint_into(&staking_pot, initial_balance));
assert_ok!(AssetConversion::create_pool(
RuntimeHelper::origin_of(bob.clone()),
Box::new(native_location.clone()),
Box::new(foreign_location.clone())
));
assert_ok!(AssetConversion::add_liquidity(
RuntimeHelper::origin_of(bob.clone()),
Box::new(native_location.clone()),
Box::new(foreign_location.clone()),
pool_liquidity,
pool_liquidity,
1,
1,
bob,
));
// keep initial total issuance to assert later.
let asset_total_issuance = ForeignAssets::total_issuance(foreign_location.clone());
let native_total_issuance = Balances::total_issuance();
// prepare input to buy weight.
let weight = Weight::from_parts(4_000_000_000, 0);
let fee = WeightToFee::weight_to_fee(&weight);
let asset_fee =
AssetConversion::get_amount_in(&fee, &pool_liquidity, &pool_liquidity).unwrap();
let extra_amount = 100;
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
let payment: Asset = (foreign_location.clone(), asset_fee + extra_amount).into();
// init trader and buy weight.
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
let unused_asset =
trader.buy_weight(weight, payment.into(), &ctx).expect("Expected Ok");
// assert.
let unused_amount =
unused_asset.fungible.get(&foreign_location.clone().into()).map_or(0, |a| *a);
assert_eq!(unused_amount, extra_amount);
assert_eq!(
ForeignAssets::total_issuance(foreign_location.clone()),
asset_total_issuance + asset_fee
);
// prepare input to refund weight.
let refund_weight = Weight::from_parts(1_000_000_000, 0);
let refund = WeightToFee::weight_to_fee(&refund_weight);
let (reserve1, reserve2) =
AssetConversion::get_reserves(native_location, foreign_location.clone()).unwrap();
let asset_refund =
AssetConversion::get_amount_out(&refund, &reserve1, &reserve2).unwrap();
// refund.
let actual_refund = trader.refund_weight(refund_weight, &ctx).unwrap();
assert_eq!(actual_refund, (foreign_location.clone(), asset_refund).into());
// assert.
assert_eq!(Balances::balance(&staking_pot), initial_balance);
// only after `trader` is dropped we expect the fee to be resolved into the treasury
// account.
drop(trader);
assert_eq!(Balances::balance(&staking_pot), initial_balance + fee - refund);
assert_eq!(
ForeignAssets::total_issuance(foreign_location),
asset_total_issuance + asset_fee - asset_refund
);
assert_eq!(Balances::total_issuance(), native_total_issuance);
})
}
#[test]
fn test_asset_xcm_take_first_trader() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
// We need root origin to create a sufficient asset
let minimum_asset_balance = 3333333_u128;
let local_asset_id = 1;
assert_ok!(Assets::force_create(
RuntimeHelper::root_origin(),
local_asset_id.into(),
AccountId::from(ALICE).into(),
true,
minimum_asset_balance
));
// We first mint enough asset for the account to exist for assets
assert_ok!(Assets::mint(
RuntimeHelper::origin_of(AccountId::from(ALICE)),
local_asset_id.into(),
AccountId::from(ALICE).into(),
minimum_asset_balance
));
// get asset id as location
let asset_location =
AssetIdForTrustBackedAssetsConvert::convert_back(&local_asset_id).unwrap();
// Set Alice as block author, who will receive fees
RuntimeHelper::run_to_block(2, AccountId::from(ALICE));
// We are going to buy 4e9 weight
let bought = Weight::from_parts(4_000_000_000u64, 0);
// Lets calculate amount needed
let asset_amount_needed =
AssetFeeAsExistentialDepositMultiplierFeeCharger::charge_weight_in_fungibles(
local_asset_id,
bought,
)
.expect("failed to compute");
// Lets pay with: asset_amount_needed + asset_amount_extra
let asset_amount_extra = 100_u128;
let asset: Asset =
(asset_location.clone(), asset_amount_needed + asset_amount_extra).into();
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
// Lets buy_weight and make sure buy_weight does not return an error
let unused_assets = trader.buy_weight(bought, asset.into(), &ctx).expect("Expected Ok");
// Check whether a correct amount of unused assets is returned
assert_ok!(unused_assets.ensure_contains(&(asset_location, asset_amount_extra).into()));
// Drop trader
drop(trader);
// Make sure author(Alice) has received the amount
assert_eq!(
Assets::balance(local_asset_id, AccountId::from(ALICE)),
minimum_asset_balance + asset_amount_needed
);
// We also need to ensure the total supply increased
assert_eq!(
Assets::total_supply(local_asset_id),
minimum_asset_balance + asset_amount_needed
);
});
}
#[test]
fn test_foreign_asset_xcm_take_first_trader() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
// We need root origin to create a sufficient asset
let minimum_asset_balance = 3333333_u128;
let foreign_location = xcm::v5::Location {
parents: 1,
interior: (
xcm::v5::Junction::Parachain(1234),
xcm::v5::Junction::GeneralIndex(12345),
)
.into(),
};
assert_ok!(ForeignAssets::force_create(
RuntimeHelper::root_origin(),
foreign_location.clone().into(),
AccountId::from(ALICE).into(),
true,
minimum_asset_balance
));
// We first mint enough asset for the account to exist for assets
assert_ok!(ForeignAssets::mint(
RuntimeHelper::origin_of(AccountId::from(ALICE)),
foreign_location.clone().into(),
AccountId::from(ALICE).into(),
minimum_asset_balance
));
let asset_location_v5: Location = foreign_location.clone().try_into().unwrap();
// Set Alice as block author, who will receive fees
RuntimeHelper::run_to_block(2, AccountId::from(ALICE));
// We are going to buy 4e9 weight
let bought = Weight::from_parts(4_000_000_000u64, 0);
// Lets calculate amount needed
let asset_amount_needed = ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger::charge_weight_in_fungibles(foreign_location.clone(), bought)
.expect("failed to compute");
// Lets pay with: asset_amount_needed + asset_amount_extra
let asset_amount_extra = 100_u128;
let asset: Asset =
(asset_location_v5.clone(), asset_amount_needed + asset_amount_extra).into();
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
// Lets buy_weight and make sure buy_weight does not return an error
let unused_assets = trader.buy_weight(bought, asset.into(), &ctx).expect("Expected Ok");
// Check whether a correct amount of unused assets is returned
assert_ok!(
unused_assets.ensure_contains(&(asset_location_v5, asset_amount_extra).into())
);
// Drop trader
drop(trader);
// Make sure author(Alice) has received the amount
assert_eq!(
ForeignAssets::balance(foreign_location.clone(), AccountId::from(ALICE)),
minimum_asset_balance + asset_amount_needed
);
// We also need to ensure the total supply increased
assert_eq!(
ForeignAssets::total_supply(foreign_location),
minimum_asset_balance + asset_amount_needed
);
});
}
#[test]
fn test_asset_xcm_take_first_trader_with_refund() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
// We need root origin to create a sufficient asset
// We set existential deposit to be identical to the one for Balances first
assert_ok!(Assets::force_create(
RuntimeHelper::root_origin(),
1.into(),
AccountId::from(ALICE).into(),
true,
ExistentialDeposit::get()
));
// We first mint enough asset for the account to exist for assets
assert_ok!(Assets::mint(
RuntimeHelper::origin_of(AccountId::from(ALICE)),
1.into(),
AccountId::from(ALICE).into(),
ExistentialDeposit::get()
));
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
// Set Alice as block author, who will receive fees
RuntimeHelper::run_to_block(2, AccountId::from(ALICE));
// We are going to buy 4e9 weight
let bought = Weight::from_parts(4_000_000_000u64, 0);
let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap();
// lets calculate amount needed
let amount_bought = WeightToFee::weight_to_fee(&bought);
let asset: Asset = (asset_location.clone(), amount_bought).into();
// Make sure buy_weight does not return an error
assert_ok!(trader.buy_weight(bought, asset.clone().into(), &ctx));
// Make sure again buy_weight does return an error
// This assert relies on the fact, that we use `TakeFirstAssetTrader` in `WeightTrader`
// tuple chain, which cannot be called twice
assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive);
// We actually use half of the weight
let weight_used = bought / 2;
// Make sure refund works.
let amount_refunded = WeightToFee::weight_to_fee(&(bought - weight_used));
assert_eq!(
trader.refund_weight(bought - weight_used, &ctx),
Some((asset_location, amount_refunded).into())
);
// Drop trader
drop(trader);
// We only should have paid for half of the bought weight
let fees_paid = WeightToFee::weight_to_fee(&weight_used);
assert_eq!(
Assets::balance(1, AccountId::from(ALICE)),
ExistentialDeposit::get() + fees_paid
);
// We also need to ensure the total supply increased
assert_eq!(Assets::total_supply(1), ExistentialDeposit::get() + fees_paid);
});
}
#[test]
fn test_asset_xcm_take_first_trader_refund_not_possible_since_amount_less_than_ed() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
// We need root origin to create a sufficient asset
// We set existential deposit to be identical to the one for Balances first
assert_ok!(Assets::force_create(
RuntimeHelper::root_origin(),
1.into(),
AccountId::from(ALICE).into(),
true,
ExistentialDeposit::get()
));
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
// Set Alice as block author, who will receive fees
RuntimeHelper::run_to_block(2, AccountId::from(ALICE));
// We are going to buy small amount
let bought = Weight::from_parts(500_000_000u64, 0);
let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap();
let amount_bought = WeightToFee::weight_to_fee(&bought);
assert!(
amount_bought < ExistentialDeposit::get(),
"we are testing what happens when the amount does not exceed ED"
);
let asset: Asset = (asset_location, amount_bought).into();
// Buy weight should return an error
assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive);
// not credited since the ED is higher than this value
assert_eq!(Assets::balance(1, AccountId::from(ALICE)), 0);
// We also need to ensure the total supply did not increase
assert_eq!(Assets::total_supply(1), 0);
});
}
#[test]
fn test_that_buying_ed_refund_does_not_refund_for_take_first_trader() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
// We need root origin to create a sufficient asset
// We set existential deposit to be identical to the one for Balances first
assert_ok!(Assets::force_create(
RuntimeHelper::root_origin(),
1.into(),
AccountId::from(ALICE).into(),
true,
ExistentialDeposit::get()
));
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
// Set Alice as block author, who will receive fees
RuntimeHelper::run_to_block(2, AccountId::from(ALICE));
let bought = Weight::from_parts(500_000_000u64, 0);
let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap();
let amount_bought = WeightToFee::weight_to_fee(&bought);
assert!(
amount_bought < ExistentialDeposit::get(),
"we are testing what happens when the amount does not exceed ED"
);
// We know we will have to buy at least ED, so lets make sure first it will
// fail with a payment of less than ED
let asset: Asset = (asset_location.clone(), amount_bought).into();
assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive);
// Now lets buy ED at least
let asset: Asset = (asset_location.clone(), ExistentialDeposit::get()).into();
// Buy weight should work
assert_ok!(trader.buy_weight(bought, asset.into(), &ctx));
// Should return None. We have a specific check making sure we don't go below ED for
// drop payment
assert_eq!(trader.refund_weight(bought, &ctx), None);
// Drop trader
drop(trader);
// Make sure author(Alice) has received the amount
assert_eq!(Assets::balance(1, AccountId::from(ALICE)), ExistentialDeposit::get());
// We also need to ensure the total supply increased
assert_eq!(Assets::total_supply(1), ExistentialDeposit::get());
});
}
#[test]
fn test_asset_xcm_take_first_trader_not_possible_for_non_sufficient_assets() {
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
// Create a non-sufficient asset with specific existential deposit
let minimum_asset_balance = 1_000_000_u128;
assert_ok!(Assets::force_create(
RuntimeHelper::root_origin(),
1.into(),
AccountId::from(ALICE).into(),
false,
minimum_asset_balance
));
// We first mint enough asset for the account to exist for assets
assert_ok!(Assets::mint(
RuntimeHelper::origin_of(AccountId::from(ALICE)),
1.into(),
AccountId::from(ALICE).into(),
minimum_asset_balance
));
let mut trader = <XcmConfig as xcm_executor::Config>::Trader::new();
let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
// Set Alice as block author, who will receive fees
RuntimeHelper::run_to_block(2, AccountId::from(ALICE));
// We are going to buy 4e9 weight
let bought = Weight::from_parts(4_000_000_000u64, 0);
// lets calculate amount needed
let asset_amount_needed = WeightToFee::weight_to_fee(&bought);
let asset_location = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap();
let asset: Asset = (asset_location, asset_amount_needed).into();
// Make sure again buy_weight does return an error
assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive);
// Drop trader
drop(trader);
// Make sure author(Alice) has NOT received the amount
assert_eq!(Assets::balance(1, AccountId::from(ALICE)), minimum_asset_balance);
// We also need to ensure the total supply NOT increased
assert_eq!(Assets::total_supply(1), minimum_asset_balance);
});
}
#[test]
fn test_assets_balances_api_works() {
use assets_common::runtime_api::runtime_decl_for_fungibles_api::FungiblesApi;
ExtBuilder::<Runtime>::default()
.with_collators(vec![AccountId::from(ALICE)])
.with_session_keys(vec![(
AccountId::from(ALICE),
AccountId::from(ALICE),
SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) },
)])
.build()
.execute_with(|| {
let local_asset_id = 1;
let foreign_asset_id_location = xcm::v5::Location {
parents: 1,
interior: [
xcm::v5::Junction::Parachain(1234),
xcm::v5::Junction::GeneralIndex(12345),
]
.into(),
};
// check before
assert_eq!(Assets::balance(local_asset_id, AccountId::from(ALICE)), 0);
assert_eq!(
ForeignAssets::balance(foreign_asset_id_location.clone(), AccountId::from(ALICE)),
0
);
assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 0);
assert!(Runtime::query_account_balances(AccountId::from(ALICE))
.unwrap()
.try_as::<XcmAssets>()
.unwrap()
.is_none());
// Drip some balance
use frame_support::traits::fungible::Mutate;
let some_currency = ExistentialDeposit::get();
Balances::mint_into(&AccountId::from(ALICE), some_currency).unwrap();
// We need root origin to create a sufficient asset
let minimum_asset_balance = 3333333_u128;
assert_ok!(Assets::force_create(
RuntimeHelper::root_origin(),
local_asset_id.into(),
AccountId::from(ALICE).into(),
true,
minimum_asset_balance
));
// We first mint enough asset for the account to exist for assets
assert_ok!(Assets::mint(
RuntimeHelper::origin_of(AccountId::from(ALICE)),
local_asset_id.into(),
AccountId::from(ALICE).into(),
minimum_asset_balance
));
// create foreign asset
let foreign_asset_minimum_asset_balance = 3333333_u128;
assert_ok!(ForeignAssets::force_create(
RuntimeHelper::root_origin(),
foreign_asset_id_location.clone(),
AccountId::from(SOME_ASSET_ADMIN).into(),
false,
foreign_asset_minimum_asset_balance
));
// We first mint enough asset for the account to exist for assets
assert_ok!(ForeignAssets::mint(
RuntimeHelper::origin_of(AccountId::from(SOME_ASSET_ADMIN)),
foreign_asset_id_location.clone(),
AccountId::from(ALICE).into(),
6 * foreign_asset_minimum_asset_balance
));
// check after
assert_eq!(
Assets::balance(local_asset_id, AccountId::from(ALICE)),
minimum_asset_balance
);
assert_eq!(
ForeignAssets::balance(foreign_asset_id_location.clone(), AccountId::from(ALICE)),
6 * minimum_asset_balance
);
assert_eq!(Balances::free_balance(AccountId::from(ALICE)), some_currency);
let result: XcmAssets = Runtime::query_account_balances(AccountId::from(ALICE))
.unwrap()
.try_into()
.unwrap();
assert_eq!(result.len(), 3);
// check currency
assert!(result.inner().iter().any(|asset| asset.eq(
&assets_common::fungible_conversion::convert_balance::<WestendLocation, Balance>(
some_currency
)
.unwrap()
)));
// check trusted asset
assert!(result.inner().iter().any(|asset| asset.eq(&(
AssetIdForTrustBackedAssetsConvert::convert_back(&local_asset_id).unwrap(),
minimum_asset_balance
)
.into())));
// check foreign asset
assert!(result.inner().iter().any(|asset| asset.eq(&(
WithLatestLocationConverter::<xcm::v5::Location>::convert_back(
&foreign_asset_id_location
)
.unwrap(),
6 * foreign_asset_minimum_asset_balance
)
.into())));
});
}
asset_test_utils::include_teleports_for_native_asset_works!(
Runtime,
AllPalletsWithoutSystem,
XcmConfig,
CheckingAccount,
WeightToFee,
ParachainSystem,
collator_session_keys(),
slot_durations(),
ExistentialDeposit::get(),
Box::new(|runtime_event_encoded: Vec<u8>| {
match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) {
Ok(RuntimeEvent::PolkadotXcm(event)) => Some(event),
_ => None,
}
}),
1000
);
asset_test_utils::include_teleports_for_foreign_assets_works!(
Runtime,
AllPalletsWithoutSystem,
XcmConfig,
CheckingAccount,
WeightToFee,
ParachainSystem,
LocationToAccountId,
ForeignAssetsInstance,
collator_session_keys(),
slot_durations(),
ExistentialDeposit::get(),
Box::new(|runtime_event_encoded: Vec<u8>| {
match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) {
Ok(RuntimeEvent::PolkadotXcm(event)) => Some(event),
_ => None,
}
}),
Box::new(|runtime_event_encoded: Vec<u8>| {
match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) {
Ok(RuntimeEvent::XcmpQueue(event)) => Some(event),
_ => None,
}
})
);
asset_test_utils::include_asset_transactor_transfer_with_local_consensus_currency_works!(
Runtime,
XcmConfig,
collator_session_keys(),
ExistentialDeposit::get(),
Box::new(|| {
assert!(Assets::asset_ids().collect::<Vec<_>>().is_empty());
assert!(ForeignAssets::asset_ids().collect::<Vec<_>>().is_empty());
}),
Box::new(|| {
assert!(Assets::asset_ids().collect::<Vec<_>>().is_empty());