12345678910111213141516171819use super::*;20use frame_system::Config as SystemConfig;2122use frame_support::traits::tokens::{23 DepositConsequence, WithdrawConsequence, Preservation, Fortitude, Provenance, Precision,24};25use pallet_common::CollectionHandle;26use pallet_fungible::FungibleHandle;27use pallet_common::CommonCollectionOperations;28use up_data_structs::budget::Value;29use sp_runtime::traits::{CheckedAdd, CheckedSub};3031impl<T: Config> fungibles::Inspect<<T as SystemConfig>::AccountId> for Pallet<T>32where33 T: orml_tokens::Config<CurrencyId = AssetIds>,34 BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,35 BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,36 <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,37 <T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,38{39 type AssetId = AssetIds;40 type Balance = BalanceOf<T>;4142 fn total_issuance(asset: Self::AssetId) -> Self::Balance {43 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible total_issuance");4445 match asset {46 AssetIds::NativeAssetId(NativeCurrency::Here) => {47 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::total_issuance()48 .into()49 }50 AssetIds::NativeAssetId(NativeCurrency::Parent) => {51 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::total_issuance(52 AssetIds::NativeAssetId(NativeCurrency::Parent),53 )54 .into()55 }56 AssetIds::ForeignAssetId(fid) => {57 let target_collection_id = match <AssetBinding<T>>::get(fid) {58 Some(v) => v,59 None => return Zero::zero(),60 };61 let collection_handle = match <CollectionHandle<T>>::try_get(target_collection_id) {62 Ok(v) => v,63 Err(_) => return Zero::zero(),64 };65 let collection = FungibleHandle::cast(collection_handle);66 Self::Balance::try_from(collection.total_supply()).unwrap_or(Zero::zero())67 }68 }69 }7071 fn minimum_balance(asset: Self::AssetId) -> Self::Balance {72 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible minimum_balance");73 match asset {74 AssetIds::NativeAssetId(NativeCurrency::Here) => {75 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::minimum_balance()76 .into()77 }78 AssetIds::NativeAssetId(NativeCurrency::Parent) => {79 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::minimum_balance(80 AssetIds::NativeAssetId(NativeCurrency::Parent),81 )82 .into()83 }84 AssetIds::ForeignAssetId(fid) => {85 AssetMetadatas::<T>::get(AssetIds::ForeignAssetId(fid))86 .map(|x| x.minimal_balance)87 .unwrap_or_else(Zero::zero)88 }89 }90 }9192 fn balance(asset: Self::AssetId, who: &<T as SystemConfig>::AccountId) -> Self::Balance {93 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible balance");94 match asset {95 AssetIds::NativeAssetId(NativeCurrency::Here) => {96 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::balance(who).into()97 }98 AssetIds::NativeAssetId(NativeCurrency::Parent) => {99 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::balance(100 AssetIds::NativeAssetId(NativeCurrency::Parent),101 who,102 )103 .into()104 }105 AssetIds::ForeignAssetId(fid) => {106 let target_collection_id = match <AssetBinding<T>>::get(fid) {107 Some(v) => v,108 None => return Zero::zero(),109 };110 let collection_handle = match <CollectionHandle<T>>::try_get(target_collection_id) {111 Ok(v) => v,112 Err(_) => return Zero::zero(),113 };114 let collection = FungibleHandle::cast(collection_handle);115 Self::Balance::try_from(116 collection.balance(T::CrossAccountId::from_sub(who.clone()), TokenId(0)),117 )118 .unwrap_or(Zero::zero())119 }120 }121 }122123 fn total_balance(asset: Self::AssetId, who: &<T as SystemConfig>::AccountId) -> Self::Balance {124 Self::balance(asset, who)125 }126127 fn reducible_balance(128 asset: Self::AssetId,129 who: &<T as SystemConfig>::AccountId,130 preservation: Preservation,131 fortitude: Fortitude,132 ) -> Self::Balance {133 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible reducible_balance");134135 match asset {136 AssetIds::NativeAssetId(NativeCurrency::Here) => {137 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::reducible_balance(138 who,139 preservation,140 fortitude,141 )142 .into()143 }144 AssetIds::NativeAssetId(NativeCurrency::Parent) => {145 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::reducible_balance(146 AssetIds::NativeAssetId(NativeCurrency::Parent),147 who,148 preservation,149 fortitude,150 )151 .into()152 }153 _ => Self::balance(asset, who),154 }155 }156157 fn can_deposit(158 asset: Self::AssetId,159 who: &<T as SystemConfig>::AccountId,160 amount: Self::Balance,161 provenance: Provenance,162 ) -> DepositConsequence {163 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible can_deposit");164165 match asset {166 AssetIds::NativeAssetId(NativeCurrency::Here) => {167 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::can_deposit(168 who,169 amount.into(),170 provenance,171 )172 }173 AssetIds::NativeAssetId(NativeCurrency::Parent) => {174 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_deposit(175 AssetIds::NativeAssetId(NativeCurrency::Parent),176 who,177 amount.into(),178 provenance,179 )180 }181 _ => {182 if amount.is_zero() {183 return DepositConsequence::Success;184 }185186 let extential_deposit_value = T::ExistentialDeposit::get();187 let ed_value: u128 = match extential_deposit_value.try_into() {188 Ok(val) => val,189 Err(_) => return DepositConsequence::CannotCreate,190 };191 let extential_deposit: Self::Balance = match ed_value.try_into() {192 Ok(val) => val,193 Err(_) => return DepositConsequence::CannotCreate,194 };195196 let new_total_balance = match Self::balance(asset, who).checked_add(&amount) {197 Some(x) => x,198 None => return DepositConsequence::Overflow,199 };200201 if new_total_balance < extential_deposit {202 return DepositConsequence::BelowMinimum;203 }204205 DepositConsequence::Success206 }207 }208 }209210 fn can_withdraw(211 asset: Self::AssetId,212 who: &<T as SystemConfig>::AccountId,213 amount: Self::Balance,214 ) -> WithdrawConsequence<Self::Balance> {215 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible can_withdraw");216 let value: u128 = match amount.try_into() {217 Ok(val) => val,218 Err(_) => return WithdrawConsequence::UnknownAsset,219 };220221 match asset {222 AssetIds::NativeAssetId(NativeCurrency::Here) => {223 let this_amount: <T as pallet_balances::Config>::Balance = match value.try_into() {224 Ok(val) => val,225 Err(_) => {226 return WithdrawConsequence::UnknownAsset;227 }228 };229 match <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::can_withdraw(230 who,231 this_amount,232 ) {233 WithdrawConsequence::BalanceLow => WithdrawConsequence::BalanceLow,234 WithdrawConsequence::WouldDie => WithdrawConsequence::WouldDie,235 WithdrawConsequence::UnknownAsset => WithdrawConsequence::UnknownAsset,236 WithdrawConsequence::Underflow => WithdrawConsequence::Underflow,237 WithdrawConsequence::Overflow => WithdrawConsequence::Overflow,238 WithdrawConsequence::Frozen => WithdrawConsequence::Frozen,239 WithdrawConsequence::Success => WithdrawConsequence::Success,240 _ => WithdrawConsequence::BalanceLow,241 }242 }243 AssetIds::NativeAssetId(NativeCurrency::Parent) => {244 let parent_amount: <T as orml_tokens::Config>::Balance = match value.try_into() {245 Ok(val) => val,246 Err(_) => {247 return WithdrawConsequence::UnknownAsset;248 }249 };250 match <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_withdraw(251 AssetIds::NativeAssetId(NativeCurrency::Parent),252 who,253 parent_amount,254 ) {255 WithdrawConsequence::BalanceLow => WithdrawConsequence::BalanceLow,256 WithdrawConsequence::WouldDie => WithdrawConsequence::WouldDie,257 WithdrawConsequence::UnknownAsset => WithdrawConsequence::UnknownAsset,258 WithdrawConsequence::Underflow => WithdrawConsequence::Underflow,259 WithdrawConsequence::Overflow => WithdrawConsequence::Overflow,260 WithdrawConsequence::Frozen => WithdrawConsequence::Frozen,261 WithdrawConsequence::Success => WithdrawConsequence::Success,262 _ => WithdrawConsequence::BalanceLow,263 }264 }265 _ => match Self::balance(asset, who).checked_sub(&amount) {266 Some(_) => WithdrawConsequence::Success,267 None => WithdrawConsequence::BalanceLow,268 },269 }270 }271272 fn asset_exists(asset: AssetIds) -> bool {273 match asset {274 AssetIds::NativeAssetId(_) => true,275 AssetIds::ForeignAssetId(fid) => <AssetBinding<T>>::contains_key(fid),276 }277 }278}279280impl<T: Config> fungibles::Mutate<<T as SystemConfig>::AccountId> for Pallet<T>281where282 T: orml_tokens::Config<CurrencyId = AssetIds>,283 BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,284 BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,285 <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,286 <T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,287 u128: From<BalanceOf<T>>,288{289 fn mint_into(290 asset: Self::AssetId,291 who: &<T as SystemConfig>::AccountId,292 amount: Self::Balance,293 ) -> Result<BalanceOf<T>, DispatchError> {294 295 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible mint_into {:?}", asset);296297 match asset {298 AssetIds::NativeAssetId(NativeCurrency::Here) => {299 <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::mint_into(300 who,301 amount.into(),302 )303 .map(Into::into)304 }305 AssetIds::NativeAssetId(NativeCurrency::Parent) => {306 <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::mint_into(307 AssetIds::NativeAssetId(NativeCurrency::Parent),308 who,309 amount.into(),310 )311 .map(Into::into)312 }313 AssetIds::ForeignAssetId(fid) => {314 let target_collection_id = match <AssetBinding<T>>::get(fid) {315 Some(v) => v,316 None => {317 return Err(DispatchError::Other(318 "Associated collection not found for asset",319 ))320 }321 };322 let collection =323 FungibleHandle::cast(<CollectionHandle<T>>::try_get(target_collection_id)?);324 let account = T::CrossAccountId::from_sub(who.clone());325326 let amount_data: pallet_fungible::CreateItemData<T> =327 (account.clone(), amount.into());328329 pallet_fungible::Pallet::<T>::create_item_foreign(330 &collection,331 &account,332 amount_data,333 &Value::new(0),334 )?;335336 Ok(amount)337 }338 }339 }340341 fn burn_from(342 asset: Self::AssetId,343 who: &<T as SystemConfig>::AccountId,344 amount: Self::Balance,345 precision: Precision,346 fortitude: Fortitude,347 ) -> Result<Self::Balance, DispatchError> {348 349 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible burn_from");350351 match asset {352 AssetIds::NativeAssetId(NativeCurrency::Here) => {353 <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::burn_from(354 who,355 amount.into(),356 precision,357 fortitude,358 )359 .map(Into::into)360 }361 AssetIds::NativeAssetId(NativeCurrency::Parent) => {362 <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::burn_from(363 AssetIds::NativeAssetId(NativeCurrency::Parent),364 who,365 amount.into(),366 precision,367 fortitude,368 )369 .map(Into::into)370 }371 AssetIds::ForeignAssetId(fid) => {372 let target_collection_id = match <AssetBinding<T>>::get(fid) {373 Some(v) => v,374 None => {375 return Err(DispatchError::Other(376 "Associated collection not found for asset",377 ))378 }379 };380 let collection =381 FungibleHandle::cast(<CollectionHandle<T>>::try_get(target_collection_id)?);382 pallet_fungible::Pallet::<T>::burn_foreign(383 &collection,384 &T::CrossAccountId::from_sub(who.clone()),385 amount.into(),386 )?;387388 Ok(amount)389 }390 }391 }392393 fn transfer(394 asset: Self::AssetId,395 source: &<T as SystemConfig>::AccountId,396 dest: &<T as SystemConfig>::AccountId,397 amount: Self::Balance,398 preservation: Preservation,399 ) -> Result<Self::Balance, DispatchError> {400 401 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible transfer");402403 match asset {404 AssetIds::NativeAssetId(NativeCurrency::Here) => {405 match <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::transfer(406 source,407 dest,408 amount.into(),409 preservation,410 ) {411 Ok(_) => Ok(amount),412 Err(_) => Err(DispatchError::Other(413 "Bad amount to relay chain value conversion",414 )),415 }416 }417 AssetIds::NativeAssetId(NativeCurrency::Parent) => {418 match <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::transfer(419 AssetIds::NativeAssetId(NativeCurrency::Parent),420 source,421 dest,422 amount.into(),423 preservation,424 ) {425 Ok(_) => Ok(amount),426 Err(e) => Err(e),427 }428 }429 AssetIds::ForeignAssetId(fid) => {430 let target_collection_id = match <AssetBinding<T>>::get(fid) {431 Some(v) => v,432 None => {433 return Err(DispatchError::Other(434 "Associated collection not found for asset",435 ))436 }437 };438 let collection =439 FungibleHandle::cast(<CollectionHandle<T>>::try_get(target_collection_id)?);440441 pallet_fungible::Pallet::<T>::transfer(442 &collection,443 &T::CrossAccountId::from_sub(source.clone()),444 &T::CrossAccountId::from_sub(dest.clone()),445 amount.into(),446 &Value::new(0),447 )448 .map_err(|e| e.error)?;449450 Ok(amount)451 }452 }453 }454}455456#[cfg(not(debug_assertions))]457extern "C" {458 459 460 461 462 463 464 465 466 fn unbalanced_fungible_is_called();467}468macro_rules! ensure_balanced {469 () => {{470 #[cfg(debug_assertions)]471 panic!("unbalanced fungible methods should not be used");472 #[cfg(not(debug_assertions))]473 {474 unsafe { unbalanced_fungible_is_called() };475 unreachable!();476 }477 }};478}479480impl<T: Config> fungibles::Unbalanced<<T as SystemConfig>::AccountId> for Pallet<T>481where482 T: orml_tokens::Config<CurrencyId = AssetIds>,483 BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,484 BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,485 <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,486 <T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,487 u128: From<BalanceOf<T>>,488{489 fn handle_dust(_dust: fungibles::Dust<<T as SystemConfig>::AccountId, Self>) {490 ensure_balanced!();491 }492 fn write_balance(493 _asset: Self::AssetId,494 _who: &<T as SystemConfig>::AccountId,495 _amount: Self::Balance,496 ) -> Result<Option<Self::Balance>, DispatchError> {497 ensure_balanced!();498 }499 fn set_total_issuance(_asset: Self::AssetId, _amount: Self::Balance) {500 ensure_balanced!();501 }502}