difftreelog
From Karura transfers
in: master
2 files changed
README.mddiffbeforeafterboth340To get started, you need to open the hrmr channel.340To get started, you need to open the hrmr channel.341Next, we need to register our asset in Karura.341Next, we need to register our asset in Karura.342342343```343assetRegistry -> registerForeignAsset(location, metadata)344assetRegistry -> registerForeignAsset(location, metadata)344location:345location:345 V0(X2(Parent, Parachain(PARA_ID))) 346 V0(X2(Parent, Parachain(PARA_ID))) 348 symbol OPL349 symbol OPL349 decimals 15350 decimals 15350minimalBalance 1351minimalBalance 1352```351353352Next, we can send tokens of our chain:354Next, we can send tokens of our chain:355```353polkadotXcm -> reserveTransferAssets356polkadotXcm -> reserveTransferAssets354dest:357dest:355 V0(X2(Parent, Parachain(KARURA_PARA_ID))) 358 V0(X2(Parent, Parachain(<KARURA_PARA_ID>))) 356beneficiary:359beneficiary:357 X1(AccountId(Any, ACCOUNT))360 X1(AccountId(Any, <ACCOUNT>))358assets:361assets:359 V1(Concrete(0,Here), Fungible(AMOUNT))362 V1(Concrete(0,Here), Fungible(<AMOUNT>))360feeAssetItem: 363feeAssetItem: 361 0 364 0 362weightLimit:365weightLimit:363 Limit366 <LIMIT>364 367``` 365368366The result will be displayed in ChainState 369The result will be displayed in ChainState 367tokens -> accounts 370tokens -> accounts 368371372373To send tokens from karura:374375```376xtokens -> transfer377378currencyId:379 ForeingAsset380 <TOKEN_ID>381382amount:383 <AMOUNT>384dest:385 V1386 (387 Parents:1, 388 X2(Parachain(<KARURA_PARA_ID>), AccountId(Any, <ACCOUNT>)389 )390destWeight:391 <WEIGHT>392 393394```runtime/src/lib.rsdiffbeforeafterboth24 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,25 traits::{25 traits::{26 AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify, AccountIdConversion,26 AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify,27 AccountIdConversion, Zero,27 },28 },28 transaction_validity::{TransactionSource, TransactionValidity},29 transaction_validity::{TransactionSource, TransactionValidity},29 ApplyExtrinsicResult, MultiSignature, RuntimeAppPublic,30 ApplyExtrinsicResult, MultiSignature, RuntimeAppPublic,45 dispatch::DispatchResult,46 dispatch::DispatchResult,46 PalletId, parameter_types, StorageValue, ConsensusEngineId,47 PalletId, parameter_types, StorageValue, ConsensusEngineId,47 traits::{48 traits::{48 Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,49 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,49 LockIdentifier, OnUnbalanced, Randomness, FindAuthor,50 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,51 OnUnbalanced, Randomness, FindAuthor,50 },52 },69use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};71use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};70use fp_rpc::TransactionStatus;72use fp_rpc::TransactionStatus;71use sp_runtime::{73use sp_runtime::{72 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},74 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},73 transaction_validity::TransactionValidityError,75 transaction_validity::TransactionValidityError,76 SaturatedConversion,74};77};757876// pub use pallet_timestamp::Call as TimestampCall;79// pub use pallet_timestamp::Call as TimestampCall;85 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset,88 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,86 ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,89 ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,87 SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,90 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,88 SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,89};91};90use xcm_executor::{Config, XcmExecutor};92use xcm_executor::{Config, XcmExecutor, Assets};9192use log::{debug};93use sp_std::{borrow::Borrow, marker::PhantomData};93use sp_std::{marker::PhantomData};949495use xcm::latest::{95use xcm::latest::{96// Xcm, 96 // Xcm,97 AssetId::{Concrete},97 AssetId::{Concrete},98 Fungibility::Fungible as XcmFungible,98 Fungibility::Fungible as XcmFungible,99 MultiAsset99 MultiAsset,100 Error as XcmError,100};101};101use xcm_executor::traits::{ShouldExecute, WeightBounds, MatchesFungible, WeightTrader, Convert};102use xcm_executor::traits::{MatchesFungible, WeightTrader};102//use xcm_executor::traits::MatchesFungible;103//use xcm_executor::traits::MatchesFungible;103use sp_runtime::traits::CheckedConversion;104use sp_runtime::traits::CheckedConversion;104105606 type XcmpMessageHandler = XcmpQueue;607 type XcmpMessageHandler = XcmpQueue;607}608}608609pub struct SiblingParachainConvertsVia2<ParaId, AccountId>(PhantomData<(ParaId, AccountId)>);610impl<ParaId: From<u32> + Into<u32> + AccountIdConversion<AccountId>, AccountId: Clone + core::fmt::Debug>611 Convert<MultiLocation, AccountId> for SiblingParachainConvertsVia2<ParaId, AccountId>612{613 fn convert_ref(location: impl Borrow<MultiLocation>) -> Result<AccountId, ()> {614615616617 match location.borrow() {618 MultiLocation { parents: 1, interior: X1(Parachain(id)) } => {619 log::debug!(620 target: "xcm::converter",621 "SiblingParachainConvertsVia2 accountId: {:?}",622 ParaId::from(*id).into_account(),623 );624 Ok(ParaId::from(*id).into_account())625 }626 _ => Err(()),627 }628 }629630 fn reverse_ref(who: impl Borrow<AccountId>) -> Result<MultiLocation, ()> {631 if let Some(id) = ParaId::try_from_account(who.borrow()) {632 Ok(MultiLocation::new(1, X1(Parachain(id.into()))))633 } else {634 Err(())635 }636 }637}638639609640impl parachain_info::Config for Runtime {}610impl parachain_info::Config for Runtime {}655 // The parent (Relay-chain) origin converts to the default `AccountId`.625 // The parent (Relay-chain) origin converts to the default `AccountId`.656 ParentIsDefault<AccountId>,626 ParentIsDefault<AccountId>,657 // Sibling parachain origins convert to AccountId via the `ParaId::into`.627 // Sibling parachain origins convert to AccountId via the `ParaId::into`.658 SiblingParachainConvertsVia2<Sibling, AccountId>,628 SiblingParachainConvertsVia<Sibling, AccountId>,659 // Straight up local `AccountId32` origins just alias directly to `AccountId`.629 // Straight up local `AccountId32` origins just alias directly to `AccountId`.660 AccountId32Aliases<RelayNetwork, AccountId>,630 AccountId32Aliases<RelayNetwork, AccountId>,661);631);733 // ^^^ Parent & its unit plurality gets free execution701 // ^^^ Parent & its unit plurality gets free execution734);702);703704pub struct UsingOnlySelfCurrencyComponents<705 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,706 AssetId: Get<MultiLocation>,707 AccountId,708 Currency: CurrencyT<AccountId>,709 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,710>(711 Weight,712 Currency::Balance,713 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,714);715impl<716 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,717 AssetId: Get<MultiLocation>,718 AccountId,719 Currency: CurrencyT<AccountId>,720 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,721 > WeightTrader722 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>723{724 fn new() -> Self {725 Self(0, Zero::zero(), PhantomData)726 }727728 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {729 let amount = WeightToFee::calc(&weight);730 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;731732 // location to this parachain through relay chain733 let option1: xcm::v1::AssetId = Concrete(MultiLocation {734 parents: 1,735 interior: X1(Parachain(ParachainInfo::parachain_id().into())),736 });737 // direct location738 let option2: xcm::v1::AssetId = Concrete(MultiLocation {739 parents: 0,740 interior: Here,741 });742743 let required = if payment.fungible.contains_key(&option1) {744 (option1, u128_amount).into()745 } else if payment.fungible.contains_key(&option2) {746 (option2, u128_amount).into()747 } else {748 (Concrete(MultiLocation::default()), u128_amount).into()749 };750751 let unused = payment752 .checked_sub(required)753 .map_err(|_| XcmError::TooExpensive)?;754 self.0 = self.0.saturating_add(weight);755 self.1 = self.1.saturating_add(amount);756 Ok(unused)757 }758759 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {760 let weight = weight.min(self.0);761 let amount = WeightToFee::calc(&weight);762 self.0 -= weight;763 self.1 = self.1.saturating_sub(amount);764 let amount: u128 = amount.saturated_into();765 if amount > 0 {766 Some((AssetId::get(), amount).into())767 } else {768 None769 }770 }771}772impl<773 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,774 AssetId: Get<MultiLocation>,775 AccountId,776 Currency: CurrencyT<AccountId>,777 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,778 > Drop779 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>780{781 fn drop(&mut self) {782 OnUnbalanced::on_unbalanced(Currency::issue(self.1));783 }784}735785736pub struct XcmConfig;786pub struct XcmConfig;737impl Config for XcmConfig {787impl Config for XcmConfig {745 type LocationInverter = LocationInverter<Ancestry>;795 type LocationInverter = LocationInverter<Ancestry>;746 type Barrier = Barrier;796 type Barrier = Barrier;747 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;797 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;748 type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;798 type Trader = UsingOnlySelfCurrencyComponents<799 IdentityFee<Balance>,800 RelayLocation,801 AccountId,802 Balances,803 (),804 >;749 type ResponseHandler = (); // Don't handle responses for now.805 type ResponseHandler = (); // Don't handle responses for now.750 type SubscriptionService = PolkadotXcm;806 type SubscriptionService = PolkadotXcm;