difftreelog
Merge pull request #848 from UniqueNetwork/fix/find-parent
in: master
15 files changed
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -28,8 +28,8 @@
use sp_std::{vec, vec::Vec};
use sp_core::U256;
use up_data_structs::{
- AccessMode, CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property,
- SponsoringRateLimit, SponsorshipState,
+ CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property, SponsoringRateLimit,
+ SponsorshipState,
};
use crate::{
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -80,10 +80,7 @@
if cross_account_id.is_canonical_substrate() {
Self::from_sub::<T>(cross_account_id.as_sub())
} else {
- Self {
- eth: *cross_account_id.as_eth(),
- sub: Default::default(),
- }
+ Self::from_eth(*cross_account_id.as_eth())
}
}
/// Creates [`CrossAddress`] from Substrate account.
@@ -97,6 +94,13 @@
sub: U256::from_big_endian(account_id.as_ref()),
}
}
+ /// Creates [`CrossAddress`] from Ethereum account.
+ pub fn from_eth(address: Address) -> Self {
+ Self {
+ eth: address,
+ sub: Default::default(),
+ }
+ }
/// Converts [`CrossAddress`] to `CrossAccountId`.
pub fn into_sub_cross_account<T>(&self) -> evm_coder::execution::Result<T::CrossAccountId>
where
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -100,6 +100,7 @@
PropertyValue,
PropertyPermission,
PropertiesError,
+ TokenOwnerError,
PropertyKeyPermission,
TokenData,
TrySetProperty,
@@ -2134,7 +2135,7 @@
/// Get the owner of the token.
///
/// * `token` - The token for which you need to find out the owner.
- fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;
+ fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;
/// Returns 10 tokens owners in no particular order.
///
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -17,7 +17,9 @@
use core::marker::PhantomData;
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};
-use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData};
+use up_data_structs::{
+ TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData, TokenOwnerError,
+};
use pallet_common::{
CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
weights::WeightInfo as _,
@@ -404,8 +406,8 @@
TokenId::default()
}
- fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {
- None
+ fn token_owner(&self, _token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {
+ Err(TokenOwnerError::MultipleOwners)
}
/// Returns 10 tokens owners in no particular order.
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -19,7 +19,7 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use up_data_structs::{
TokenId, CreateItemExData, CollectionId, budget::Budget, Property, PropertyKey,
- PropertyKeyPermission, PropertyValue,
+ PropertyKeyPermission, PropertyValue, TokenOwnerError,
};
use pallet_common::{
CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
@@ -460,13 +460,15 @@
TokenId(<TokensMinted<T>>::get(self.id))
}
- fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {
- <TokenData<T>>::get((self.id, token)).map(|t| t.owner)
+ fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {
+ <TokenData<T>>::get((self.id, token))
+ .map(|t| t.owner)
+ .ok_or(TokenOwnerError::NotFound)
}
/// Returns token owners.
fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {
- self.token_owner(token).map_or_else(|| vec![], |t| vec![t])
+ self.token_owner(token).map_or_else(|_| vec![], |t| vec![t])
}
fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -728,7 +728,7 @@
fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {
Self::token_owner(&self, token_id.try_into()?)
.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))
- .ok_or(Error::Revert("key too large".into()))
+ .map_err(|_| Error::Revert("token not found".into()))
}
/// Returns the token properties.
pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -741,7 +741,8 @@
Some((collection_id, nft_id)),
&target_nft_budget,
)
- .map_err(Self::map_unique_err_to_proxy)?;
+ .map_err(Self::map_unique_err_to_proxy)?
+ .ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
approval_required = cross_sender != target_nft_owner;
@@ -989,7 +990,8 @@
let nft_owner =
<PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)
- .map_err(|_| <Error<T>>::ResourceDoesntExist)?;
+ .map_err(|_| <Error<T>>::ResourceDoesntExist)?
+ .ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
Self::try_mutate_resource_info(collection_id, nft_id, resource_id, |res| {
ensure!(res.pending, <Error<T>>::ResourceNotPending);
@@ -1044,7 +1046,8 @@
let nft_owner =
<PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)
- .map_err(|_| <Error<T>>::ResourceDoesntExist)?;
+ .map_err(|_| <Error<T>>::ResourceDoesntExist)?
+ .ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
ensure!(cross_sender == nft_owner, <Error<T>>::NoPermission);
@@ -1666,7 +1669,8 @@
let budget = budget::Value::new(NESTING_BUDGET);
let nft_owner = <PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)
- .map_err(Self::map_unique_err_to_proxy)?;
+ .map_err(Self::map_unique_err_to_proxy)?
+ .ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
let pending = sender != nft_owner;
@@ -1720,7 +1724,8 @@
let budget = up_data_structs::budget::Value::new(NESTING_BUDGET);
let topmost_owner =
- <PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)?;
+ <PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)?
+ .ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
let sender = T::CrossAccountId::from_sub(sender);
if topmost_owner == sender {
pallets/proxy-rmrk-core/src/rpc.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/rpc.rs
+++ b/pallets/proxy-rmrk-core/src/rpc.rs
@@ -68,7 +68,7 @@
}
let owner = match collection.token_owner(nft_id) {
- Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
+ Ok(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
Some((col, tok)) => {
let rmrk_collection = <Pallet<T>>::rmrk_collection_id(col)?;
@@ -76,7 +76,7 @@
}
None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone()),
},
- None => return Ok(None),
+ _ => return Ok(None),
};
Ok(Some(RmrkInstanceInfo {
pallets/refungible/src/common.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use core::marker::PhantomData;1819use sp_std::collections::btree_map::BTreeMap;20use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};21use up_data_structs::{22 CollectionId, TokenId, CreateItemExData, budget::Budget, Property, PropertyKey, PropertyValue,23 PropertyKeyPermission, CollectionPropertiesVec, CreateRefungibleExMultipleOwners,24 CreateRefungibleExSingleOwner,25};26use pallet_common::{27 CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,28 weights::WeightInfo as _,29};30use pallet_structure::Error as StructureError;31use sp_runtime::{DispatchError};32use sp_std::{vec::Vec, vec};3334use crate::{35 AccountBalance, Allowance, Balance, Config, Error, Owned, Pallet, RefungibleHandle,36 SelfWeightOf, weights::WeightInfo, TokensMinted, TotalSupply, CreateItemData,37};3839macro_rules! max_weight_of {40 ($($method:ident ($($args:tt)*)),*) => {41 Weight::zero()42 $(43 .max(<SelfWeightOf<T>>::$method($($args)*))44 )*45 };46}4748fn properties_weight<T: Config>(properties: &CollectionPropertiesVec) -> Weight {49 if properties.len() > 0 {50 <CommonWeights<T>>::set_token_properties(properties.len() as u32)51 } else {52 Weight::zero()53 }54}5556pub struct CommonWeights<T: Config>(PhantomData<T>);57impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {58 fn create_item() -> Weight {59 <SelfWeightOf<T>>::create_item()60 }6162 fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {63 <SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(64 data.iter()65 .map(|data| match data {66 up_data_structs::CreateItemData::ReFungible(rft_data) => {67 properties_weight::<T>(&rft_data.properties)68 }69 _ => Weight::zero(),70 })71 .fold(Weight::zero(), |a, b| a.saturating_add(b)),72 )73 }7475 fn create_multiple_items_ex(call: &CreateItemExData<T::CrossAccountId>) -> Weight {76 match call {77 CreateItemExData::RefungibleMultipleOwners(i) => {78 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32)79 .saturating_add(properties_weight::<T>(&i.properties))80 }81 CreateItemExData::RefungibleMultipleItems(i) => {82 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32)83 .saturating_add(84 i.iter()85 .map(|d| properties_weight::<T>(&d.properties))86 .fold(Weight::zero(), |a, b| a.saturating_add(b)),87 )88 }89 _ => Weight::zero(),90 }91 }9293 fn burn_item() -> Weight {94 max_weight_of!(burn_item_partial(), burn_item_fully())95 }9697 fn set_collection_properties(amount: u32) -> Weight {98 <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)99 }100101 fn delete_collection_properties(amount: u32) -> Weight {102 <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)103 }104105 fn set_token_properties(amount: u32) -> Weight {106 <SelfWeightOf<T>>::set_token_properties(amount)107 }108109 fn delete_token_properties(amount: u32) -> Weight {110 <SelfWeightOf<T>>::delete_token_properties(amount)111 }112113 fn set_token_property_permissions(amount: u32) -> Weight {114 <SelfWeightOf<T>>::set_token_property_permissions(amount)115 }116117 fn transfer() -> Weight {118 max_weight_of!(119 transfer_normal(),120 transfer_creating(),121 transfer_removing(),122 transfer_creating_removing()123 )124 }125126 fn approve() -> Weight {127 <SelfWeightOf<T>>::approve()128 }129130 fn approve_from() -> Weight {131 <SelfWeightOf<T>>::approve_from()132 }133134 fn transfer_from() -> Weight {135 max_weight_of!(136 transfer_from_normal(),137 transfer_from_creating(),138 transfer_from_removing(),139 transfer_from_creating_removing()140 )141 }142143 fn burn_from() -> Weight {144 <SelfWeightOf<T>>::burn_from()145 }146147 fn burn_recursively_self_raw() -> Weight {148 // Read to get total balance149 Self::burn_item() + T::DbWeight::get().reads(1)150 }151 fn burn_recursively_breadth_raw(_amount: u32) -> Weight {152 // Refungible token can't have children153 Weight::zero()154 }155156 fn token_owner() -> Weight {157 <SelfWeightOf<T>>::token_owner()158 }159160 fn set_allowance_for_all() -> Weight {161 <SelfWeightOf<T>>::set_allowance_for_all()162 }163164 fn force_repair_item() -> Weight {165 <SelfWeightOf<T>>::repair_item()166 }167}168169fn map_create_data<T: Config>(170 data: up_data_structs::CreateItemData,171 to: &T::CrossAccountId,172) -> Result<CreateItemData<T>, DispatchError> {173 match data {174 up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateItemData::<T> {175 users: {176 let mut out = BTreeMap::new();177 out.insert(to.clone(), data.pieces);178 out.try_into().expect("limit > 0")179 },180 properties: data.properties,181 }),182 _ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),183 }184}185186/// Implementation of `CommonCollectionOperations` for `RefungibleHandle`. It wraps Refungible Pallete187/// methods and adds weight info.188impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {189 fn create_item(190 &self,191 sender: T::CrossAccountId,192 to: T::CrossAccountId,193 data: up_data_structs::CreateItemData,194 nesting_budget: &dyn Budget,195 ) -> DispatchResultWithPostInfo {196 with_weight(197 <Pallet<T>>::create_item(198 self,199 &sender,200 map_create_data::<T>(data, &to)?,201 nesting_budget,202 ),203 <CommonWeights<T>>::create_item(),204 )205 }206207 fn create_multiple_items(208 &self,209 sender: T::CrossAccountId,210 to: T::CrossAccountId,211 data: Vec<up_data_structs::CreateItemData>,212 nesting_budget: &dyn Budget,213 ) -> DispatchResultWithPostInfo {214 let weight = <CommonWeights<T>>::create_multiple_items(&data);215 let data = data216 .into_iter()217 .map(|d| map_create_data::<T>(d, &to))218 .collect::<Result<Vec<_>, DispatchError>>()?;219220 with_weight(221 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),222 weight,223 )224 }225226 fn create_multiple_items_ex(227 &self,228 sender: <T>::CrossAccountId,229 data: CreateItemExData<T::CrossAccountId>,230 nesting_budget: &dyn Budget,231 ) -> DispatchResultWithPostInfo {232 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);233 let data = match data {234 CreateItemExData::RefungibleMultipleOwners(CreateRefungibleExMultipleOwners {235 users,236 properties,237 }) => vec![CreateItemData::<T> { users, properties }],238 CreateItemExData::RefungibleMultipleItems(r) => r239 .into_inner()240 .into_iter()241 .map(242 |CreateRefungibleExSingleOwner {243 user,244 pieces,245 properties,246 }| CreateItemData::<T> {247 users: BTreeMap::from([(user, pieces)])248 .try_into()249 .expect("limit >= 1"),250 properties,251 },252 )253 .collect(),254 _ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),255 };256257 with_weight(258 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),259 weight,260 )261 }262263 fn burn_item(264 &self,265 sender: T::CrossAccountId,266 token: TokenId,267 amount: u128,268 ) -> DispatchResultWithPostInfo {269 with_weight(270 <Pallet<T>>::burn(self, &sender, token, amount),271 <CommonWeights<T>>::burn_item(),272 )273 }274275 fn burn_item_recursively(276 &self,277 sender: T::CrossAccountId,278 token: TokenId,279 self_budget: &dyn Budget,280 _breadth_budget: &dyn Budget,281 ) -> DispatchResultWithPostInfo {282 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);283 with_weight(284 <Pallet<T>>::burn(285 self,286 &sender,287 token,288 <Balance<T>>::get((self.id, token, &sender)),289 ),290 <CommonWeights<T>>::burn_recursively_self_raw(),291 )292 }293294 fn transfer(295 &self,296 from: T::CrossAccountId,297 to: T::CrossAccountId,298 token: TokenId,299 amount: u128,300 nesting_budget: &dyn Budget,301 ) -> DispatchResultWithPostInfo {302 with_weight(303 <Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),304 <CommonWeights<T>>::transfer(),305 )306 }307308 fn approve(309 &self,310 sender: T::CrossAccountId,311 spender: T::CrossAccountId,312 token: TokenId,313 amount: u128,314 ) -> DispatchResultWithPostInfo {315 with_weight(316 <Pallet<T>>::set_allowance(self, &sender, &spender, token, amount),317 <CommonWeights<T>>::approve(),318 )319 }320321 fn approve_from(322 &self,323 sender: T::CrossAccountId,324 from: T::CrossAccountId,325 to: T::CrossAccountId,326 token_id: TokenId,327 amount: u128,328 ) -> DispatchResultWithPostInfo {329 with_weight(330 <Pallet<T>>::set_allowance_from(self, &sender, &from, &to, token_id, amount),331 <CommonWeights<T>>::approve_from(),332 )333 }334335 fn transfer_from(336 &self,337 sender: T::CrossAccountId,338 from: T::CrossAccountId,339 to: T::CrossAccountId,340 token: TokenId,341 amount: u128,342 nesting_budget: &dyn Budget,343 ) -> DispatchResultWithPostInfo {344 with_weight(345 <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),346 <CommonWeights<T>>::transfer_from(),347 )348 }349350 fn burn_from(351 &self,352 sender: T::CrossAccountId,353 from: T::CrossAccountId,354 token: TokenId,355 amount: u128,356 nesting_budget: &dyn Budget,357 ) -> DispatchResultWithPostInfo {358 with_weight(359 <Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),360 <CommonWeights<T>>::burn_from(),361 )362 }363364 fn set_collection_properties(365 &self,366 sender: T::CrossAccountId,367 properties: Vec<Property>,368 ) -> DispatchResultWithPostInfo {369 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);370371 with_weight(372 <Pallet<T>>::set_collection_properties(self, &sender, properties),373 weight,374 )375 }376377 fn delete_collection_properties(378 &self,379 sender: &T::CrossAccountId,380 property_keys: Vec<PropertyKey>,381 ) -> DispatchResultWithPostInfo {382 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);383384 with_weight(385 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),386 weight,387 )388 }389390 fn set_token_properties(391 &self,392 sender: T::CrossAccountId,393 token_id: TokenId,394 properties: Vec<Property>,395 nesting_budget: &dyn Budget,396 ) -> DispatchResultWithPostInfo {397 let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);398399 with_weight(400 <Pallet<T>>::set_token_properties(401 self,402 &sender,403 token_id,404 properties.into_iter(),405 false,406 nesting_budget,407 ),408 weight,409 )410 }411412 fn set_token_property_permissions(413 &self,414 sender: &T::CrossAccountId,415 property_permissions: Vec<PropertyKeyPermission>,416 ) -> DispatchResultWithPostInfo {417 let weight =418 <CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);419420 with_weight(421 <Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),422 weight,423 )424 }425426 fn delete_token_properties(427 &self,428 sender: T::CrossAccountId,429 token_id: TokenId,430 property_keys: Vec<PropertyKey>,431 nesting_budget: &dyn Budget,432 ) -> DispatchResultWithPostInfo {433 let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);434435 with_weight(436 <Pallet<T>>::delete_token_properties(437 self,438 &sender,439 token_id,440 property_keys.into_iter(),441 nesting_budget,442 ),443 weight,444 )445 }446447 fn check_nesting(448 &self,449 _sender: <T>::CrossAccountId,450 _from: (CollectionId, TokenId),451 _under: TokenId,452 _nesting_budget: &dyn Budget,453 ) -> sp_runtime::DispatchResult {454 fail!(<Error<T>>::RefungibleDisallowsNesting)455 }456457 fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}458459 fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}460461 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {462 <Owned<T>>::iter_prefix((self.id, account))463 .map(|(id, _)| id)464 .collect()465 }466467 fn collection_tokens(&self) -> Vec<TokenId> {468 <TotalSupply<T>>::iter_prefix((self.id,))469 .map(|(id, _)| id)470 .collect()471 }472473 fn token_exists(&self, token: TokenId) -> bool {474 <Pallet<T>>::token_exists(self, token)475 }476477 fn last_token_id(&self) -> TokenId {478 TokenId(<TokensMinted<T>>::get(self.id))479 }480481 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {482 <Pallet<T>>::token_owner(self.id, token)483 }484485 /// Returns 10 token in no particular order.486 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {487 <Pallet<T>>::token_owners(self.id, token).unwrap_or_default()488 }489490 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {491 <Pallet<T>>::token_properties((self.id, token_id))492 .get(key)493 .cloned()494 }495496 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {497 let properties = <Pallet<T>>::token_properties((self.id, token_id));498499 keys.map(|keys| {500 keys.into_iter()501 .filter_map(|key| {502 properties.get(&key).map(|value| Property {503 key,504 value: value.clone(),505 })506 })507 .collect()508 })509 .unwrap_or_else(|| {510 properties511 .into_iter()512 .map(|(key, value)| Property { key, value })513 .collect()514 })515 }516517 fn total_supply(&self) -> u32 {518 <Pallet<T>>::total_supply(self)519 }520521 fn account_balance(&self, account: T::CrossAccountId) -> u32 {522 <AccountBalance<T>>::get((self.id, account))523 }524525 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {526 <Balance<T>>::get((self.id, token, account))527 }528529 fn allowance(530 &self,531 sender: T::CrossAccountId,532 spender: T::CrossAccountId,533 token: TokenId,534 ) -> u128 {535 <Allowance<T>>::get((self.id, token, sender, spender))536 }537538 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {539 Some(self)540 }541542 fn total_pieces(&self, token: TokenId) -> Option<u128> {543 <Pallet<T>>::total_pieces(self.id, token)544 }545546 fn set_allowance_for_all(547 &self,548 owner: T::CrossAccountId,549 operator: T::CrossAccountId,550 approve: bool,551 ) -> DispatchResultWithPostInfo {552 with_weight(553 <Pallet<T>>::set_allowance_for_all(self, &owner, &operator, approve),554 <CommonWeights<T>>::set_allowance_for_all(),555 )556 }557558 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {559 <Pallet<T>>::allowance_for_all(self, &owner, &operator)560 }561562 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {563 with_weight(564 <Pallet<T>>::repair_item(self, token),565 <CommonWeights<T>>::force_repair_item(),566 )567 }568}569570impl<T: Config> RefungibleExtensions<T> for RefungibleHandle<T> {571 fn repartition(572 &self,573 owner: &T::CrossAccountId,574 token: TokenId,575 amount: u128,576 ) -> DispatchResultWithPostInfo {577 with_weight(578 <Pallet<T>>::repartition(self, owner, token, amount),579 <SelfWeightOf<T>>::repartition_item(),580 )581 }582}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use core::marker::PhantomData;1819use sp_std::collections::btree_map::BTreeMap;20use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};21use up_data_structs::{22 CollectionId, TokenId, CreateItemExData, budget::Budget, Property, PropertyKey, PropertyValue,23 PropertyKeyPermission, CollectionPropertiesVec, CreateRefungibleExMultipleOwners,24 CreateRefungibleExSingleOwner, TokenOwnerError,25};26use pallet_common::{27 CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,28 weights::WeightInfo as _,29};30use pallet_structure::Error as StructureError;31use sp_runtime::{DispatchError};32use sp_std::{vec::Vec, vec};3334use crate::{35 AccountBalance, Allowance, Balance, Config, Error, Owned, Pallet, RefungibleHandle,36 SelfWeightOf, weights::WeightInfo, TokensMinted, TotalSupply, CreateItemData,37};3839macro_rules! max_weight_of {40 ($($method:ident ($($args:tt)*)),*) => {41 Weight::zero()42 $(43 .max(<SelfWeightOf<T>>::$method($($args)*))44 )*45 };46}4748fn properties_weight<T: Config>(properties: &CollectionPropertiesVec) -> Weight {49 if properties.len() > 0 {50 <CommonWeights<T>>::set_token_properties(properties.len() as u32)51 } else {52 Weight::zero()53 }54}5556pub struct CommonWeights<T: Config>(PhantomData<T>);57impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {58 fn create_item() -> Weight {59 <SelfWeightOf<T>>::create_item()60 }6162 fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {63 <SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(64 data.iter()65 .map(|data| match data {66 up_data_structs::CreateItemData::ReFungible(rft_data) => {67 properties_weight::<T>(&rft_data.properties)68 }69 _ => Weight::zero(),70 })71 .fold(Weight::zero(), |a, b| a.saturating_add(b)),72 )73 }7475 fn create_multiple_items_ex(call: &CreateItemExData<T::CrossAccountId>) -> Weight {76 match call {77 CreateItemExData::RefungibleMultipleOwners(i) => {78 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32)79 .saturating_add(properties_weight::<T>(&i.properties))80 }81 CreateItemExData::RefungibleMultipleItems(i) => {82 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32)83 .saturating_add(84 i.iter()85 .map(|d| properties_weight::<T>(&d.properties))86 .fold(Weight::zero(), |a, b| a.saturating_add(b)),87 )88 }89 _ => Weight::zero(),90 }91 }9293 fn burn_item() -> Weight {94 max_weight_of!(burn_item_partial(), burn_item_fully())95 }9697 fn set_collection_properties(amount: u32) -> Weight {98 <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)99 }100101 fn delete_collection_properties(amount: u32) -> Weight {102 <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)103 }104105 fn set_token_properties(amount: u32) -> Weight {106 <SelfWeightOf<T>>::set_token_properties(amount)107 }108109 fn delete_token_properties(amount: u32) -> Weight {110 <SelfWeightOf<T>>::delete_token_properties(amount)111 }112113 fn set_token_property_permissions(amount: u32) -> Weight {114 <SelfWeightOf<T>>::set_token_property_permissions(amount)115 }116117 fn transfer() -> Weight {118 max_weight_of!(119 transfer_normal(),120 transfer_creating(),121 transfer_removing(),122 transfer_creating_removing()123 )124 }125126 fn approve() -> Weight {127 <SelfWeightOf<T>>::approve()128 }129130 fn approve_from() -> Weight {131 <SelfWeightOf<T>>::approve_from()132 }133134 fn transfer_from() -> Weight {135 max_weight_of!(136 transfer_from_normal(),137 transfer_from_creating(),138 transfer_from_removing(),139 transfer_from_creating_removing()140 )141 }142143 fn burn_from() -> Weight {144 <SelfWeightOf<T>>::burn_from()145 }146147 fn burn_recursively_self_raw() -> Weight {148 // Read to get total balance149 Self::burn_item() + T::DbWeight::get().reads(1)150 }151 fn burn_recursively_breadth_raw(_amount: u32) -> Weight {152 // Refungible token can't have children153 Weight::zero()154 }155156 fn token_owner() -> Weight {157 <SelfWeightOf<T>>::token_owner()158 }159160 fn set_allowance_for_all() -> Weight {161 <SelfWeightOf<T>>::set_allowance_for_all()162 }163164 fn force_repair_item() -> Weight {165 <SelfWeightOf<T>>::repair_item()166 }167}168169fn map_create_data<T: Config>(170 data: up_data_structs::CreateItemData,171 to: &T::CrossAccountId,172) -> Result<CreateItemData<T>, DispatchError> {173 match data {174 up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateItemData::<T> {175 users: {176 let mut out = BTreeMap::new();177 out.insert(to.clone(), data.pieces);178 out.try_into().expect("limit > 0")179 },180 properties: data.properties,181 }),182 _ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),183 }184}185186/// Implementation of `CommonCollectionOperations` for `RefungibleHandle`. It wraps Refungible Pallete187/// methods and adds weight info.188impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {189 fn create_item(190 &self,191 sender: T::CrossAccountId,192 to: T::CrossAccountId,193 data: up_data_structs::CreateItemData,194 nesting_budget: &dyn Budget,195 ) -> DispatchResultWithPostInfo {196 with_weight(197 <Pallet<T>>::create_item(198 self,199 &sender,200 map_create_data::<T>(data, &to)?,201 nesting_budget,202 ),203 <CommonWeights<T>>::create_item(),204 )205 }206207 fn create_multiple_items(208 &self,209 sender: T::CrossAccountId,210 to: T::CrossAccountId,211 data: Vec<up_data_structs::CreateItemData>,212 nesting_budget: &dyn Budget,213 ) -> DispatchResultWithPostInfo {214 let weight = <CommonWeights<T>>::create_multiple_items(&data);215 let data = data216 .into_iter()217 .map(|d| map_create_data::<T>(d, &to))218 .collect::<Result<Vec<_>, DispatchError>>()?;219220 with_weight(221 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),222 weight,223 )224 }225226 fn create_multiple_items_ex(227 &self,228 sender: <T>::CrossAccountId,229 data: CreateItemExData<T::CrossAccountId>,230 nesting_budget: &dyn Budget,231 ) -> DispatchResultWithPostInfo {232 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);233 let data = match data {234 CreateItemExData::RefungibleMultipleOwners(CreateRefungibleExMultipleOwners {235 users,236 properties,237 }) => vec![CreateItemData::<T> { users, properties }],238 CreateItemExData::RefungibleMultipleItems(r) => r239 .into_inner()240 .into_iter()241 .map(242 |CreateRefungibleExSingleOwner {243 user,244 pieces,245 properties,246 }| CreateItemData::<T> {247 users: BTreeMap::from([(user, pieces)])248 .try_into()249 .expect("limit >= 1"),250 properties,251 },252 )253 .collect(),254 _ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),255 };256257 with_weight(258 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),259 weight,260 )261 }262263 fn burn_item(264 &self,265 sender: T::CrossAccountId,266 token: TokenId,267 amount: u128,268 ) -> DispatchResultWithPostInfo {269 with_weight(270 <Pallet<T>>::burn(self, &sender, token, amount),271 <CommonWeights<T>>::burn_item(),272 )273 }274275 fn burn_item_recursively(276 &self,277 sender: T::CrossAccountId,278 token: TokenId,279 self_budget: &dyn Budget,280 _breadth_budget: &dyn Budget,281 ) -> DispatchResultWithPostInfo {282 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);283 with_weight(284 <Pallet<T>>::burn(285 self,286 &sender,287 token,288 <Balance<T>>::get((self.id, token, &sender)),289 ),290 <CommonWeights<T>>::burn_recursively_self_raw(),291 )292 }293294 fn transfer(295 &self,296 from: T::CrossAccountId,297 to: T::CrossAccountId,298 token: TokenId,299 amount: u128,300 nesting_budget: &dyn Budget,301 ) -> DispatchResultWithPostInfo {302 with_weight(303 <Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),304 <CommonWeights<T>>::transfer(),305 )306 }307308 fn approve(309 &self,310 sender: T::CrossAccountId,311 spender: T::CrossAccountId,312 token: TokenId,313 amount: u128,314 ) -> DispatchResultWithPostInfo {315 with_weight(316 <Pallet<T>>::set_allowance(self, &sender, &spender, token, amount),317 <CommonWeights<T>>::approve(),318 )319 }320321 fn approve_from(322 &self,323 sender: T::CrossAccountId,324 from: T::CrossAccountId,325 to: T::CrossAccountId,326 token_id: TokenId,327 amount: u128,328 ) -> DispatchResultWithPostInfo {329 with_weight(330 <Pallet<T>>::set_allowance_from(self, &sender, &from, &to, token_id, amount),331 <CommonWeights<T>>::approve_from(),332 )333 }334335 fn transfer_from(336 &self,337 sender: T::CrossAccountId,338 from: T::CrossAccountId,339 to: T::CrossAccountId,340 token: TokenId,341 amount: u128,342 nesting_budget: &dyn Budget,343 ) -> DispatchResultWithPostInfo {344 with_weight(345 <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),346 <CommonWeights<T>>::transfer_from(),347 )348 }349350 fn burn_from(351 &self,352 sender: T::CrossAccountId,353 from: T::CrossAccountId,354 token: TokenId,355 amount: u128,356 nesting_budget: &dyn Budget,357 ) -> DispatchResultWithPostInfo {358 with_weight(359 <Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),360 <CommonWeights<T>>::burn_from(),361 )362 }363364 fn set_collection_properties(365 &self,366 sender: T::CrossAccountId,367 properties: Vec<Property>,368 ) -> DispatchResultWithPostInfo {369 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);370371 with_weight(372 <Pallet<T>>::set_collection_properties(self, &sender, properties),373 weight,374 )375 }376377 fn delete_collection_properties(378 &self,379 sender: &T::CrossAccountId,380 property_keys: Vec<PropertyKey>,381 ) -> DispatchResultWithPostInfo {382 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);383384 with_weight(385 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),386 weight,387 )388 }389390 fn set_token_properties(391 &self,392 sender: T::CrossAccountId,393 token_id: TokenId,394 properties: Vec<Property>,395 nesting_budget: &dyn Budget,396 ) -> DispatchResultWithPostInfo {397 let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);398399 with_weight(400 <Pallet<T>>::set_token_properties(401 self,402 &sender,403 token_id,404 properties.into_iter(),405 false,406 nesting_budget,407 ),408 weight,409 )410 }411412 fn set_token_property_permissions(413 &self,414 sender: &T::CrossAccountId,415 property_permissions: Vec<PropertyKeyPermission>,416 ) -> DispatchResultWithPostInfo {417 let weight =418 <CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);419420 with_weight(421 <Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),422 weight,423 )424 }425426 fn delete_token_properties(427 &self,428 sender: T::CrossAccountId,429 token_id: TokenId,430 property_keys: Vec<PropertyKey>,431 nesting_budget: &dyn Budget,432 ) -> DispatchResultWithPostInfo {433 let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);434435 with_weight(436 <Pallet<T>>::delete_token_properties(437 self,438 &sender,439 token_id,440 property_keys.into_iter(),441 nesting_budget,442 ),443 weight,444 )445 }446447 fn check_nesting(448 &self,449 _sender: <T>::CrossAccountId,450 _from: (CollectionId, TokenId),451 _under: TokenId,452 _nesting_budget: &dyn Budget,453 ) -> sp_runtime::DispatchResult {454 fail!(<Error<T>>::RefungibleDisallowsNesting)455 }456457 fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}458459 fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}460461 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {462 <Owned<T>>::iter_prefix((self.id, account))463 .map(|(id, _)| id)464 .collect()465 }466467 fn collection_tokens(&self) -> Vec<TokenId> {468 <TotalSupply<T>>::iter_prefix((self.id,))469 .map(|(id, _)| id)470 .collect()471 }472473 fn token_exists(&self, token: TokenId) -> bool {474 <Pallet<T>>::token_exists(self, token)475 }476477 fn last_token_id(&self) -> TokenId {478 TokenId(<TokensMinted<T>>::get(self.id))479 }480481 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {482 <Pallet<T>>::token_owner(self.id, token)483 }484485 /// Returns 10 token in no particular order.486 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {487 <Pallet<T>>::token_owners(self.id, token).unwrap_or_default()488 }489490 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {491 <Pallet<T>>::token_properties((self.id, token_id))492 .get(key)493 .cloned()494 }495496 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {497 let properties = <Pallet<T>>::token_properties((self.id, token_id));498499 keys.map(|keys| {500 keys.into_iter()501 .filter_map(|key| {502 properties.get(&key).map(|value| Property {503 key,504 value: value.clone(),505 })506 })507 .collect()508 })509 .unwrap_or_else(|| {510 properties511 .into_iter()512 .map(|(key, value)| Property { key, value })513 .collect()514 })515 }516517 fn total_supply(&self) -> u32 {518 <Pallet<T>>::total_supply(self)519 }520521 fn account_balance(&self, account: T::CrossAccountId) -> u32 {522 <AccountBalance<T>>::get((self.id, account))523 }524525 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {526 <Balance<T>>::get((self.id, token, account))527 }528529 fn allowance(530 &self,531 sender: T::CrossAccountId,532 spender: T::CrossAccountId,533 token: TokenId,534 ) -> u128 {535 <Allowance<T>>::get((self.id, token, sender, spender))536 }537538 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {539 Some(self)540 }541542 fn total_pieces(&self, token: TokenId) -> Option<u128> {543 <Pallet<T>>::total_pieces(self.id, token)544 }545546 fn set_allowance_for_all(547 &self,548 owner: T::CrossAccountId,549 operator: T::CrossAccountId,550 approve: bool,551 ) -> DispatchResultWithPostInfo {552 with_weight(553 <Pallet<T>>::set_allowance_for_all(self, &owner, &operator, approve),554 <CommonWeights<T>>::set_allowance_for_all(),555 )556 }557558 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {559 <Pallet<T>>::allowance_for_all(self, &owner, &operator)560 }561562 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {563 with_weight(564 <Pallet<T>>::repair_item(self, token),565 <CommonWeights<T>>::force_repair_item(),566 )567 }568}569570impl<T: Config> RefungibleExtensions<T> for RefungibleHandle<T> {571 fn repartition(572 &self,573 owner: &T::CrossAccountId,574 token: TokenId,575 amount: u128,576 ) -> DispatchResultWithPostInfo {577 with_weight(578 <Pallet<T>>::repartition(self, owner, token, amount),579 <SelfWeightOf<T>>::repartition_item(),580 )581 }582}pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -43,7 +43,7 @@
use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};
use up_data_structs::{
CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,
- PropertyKeyPermission, PropertyPermission, TokenId,
+ PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,
};
use crate::{
@@ -411,9 +411,12 @@
self.consume_store_reads(2)?;
let token = token_id.try_into()?;
let owner = <Pallet<T>>::token_owner(self.id, token);
- Ok(owner
+ owner
.map(|address| *address.as_eth())
- .unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))
+ .or_else(|err| match err {
+ TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),
+ TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),
+ })
}
/// @dev Not implemented
@@ -766,7 +769,12 @@
fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {
Self::token_owner(&self, token_id.try_into()?)
.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))
- .ok_or(Error::Revert("key too large".into()))
+ .or_else(|err| match err {
+ TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),
+ TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(
+ ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,
+ )),
+ })
}
/// Returns the token properties.
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -107,7 +107,7 @@
AccessMode, budget::Budget, CollectionId, CollectionFlags, CreateCollectionData,
mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, Property, PropertyKey,
PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue, TokenId,
- TrySetProperty, PropertiesPermissionMap, CreateRefungibleExMultipleOwners,
+ TrySetProperty, PropertiesPermissionMap, CreateRefungibleExMultipleOwners, TokenOwnerError,
};
pub use pallet::*;
@@ -480,7 +480,7 @@
<Balance<T>>::remove((collection.id, token, owner));
<AccountBalance<T>>::insert((collection.id, owner), account_balance);
- if let Some(user) = Self::token_owner(collection.id, token) {
+ if let Ok(user) = Self::token_owner(collection.id, token) {
<PalletEvm<T>>::deposit_log(
ERC721Events::Transfer {
from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,
@@ -1365,17 +1365,20 @@
Ok(())
}
- fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {
+ fn token_owner(
+ collection_id: CollectionId,
+ token_id: TokenId,
+ ) -> Result<T::CrossAccountId, TokenOwnerError> {
let mut owner = None;
let mut count = 0;
for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {
count += 1;
if count > 1 {
- return None;
+ return Err(TokenOwnerError::MultipleOwners);
}
owner = Some(key);
}
- owner
+ owner.ok_or(TokenOwnerError::NotFound)
}
fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {
pallets/structure/src/lib.rsdiffbeforeafterboth--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -61,7 +61,9 @@
use frame_support::fail;
pub use pallet::*;
use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};
-use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};
+use up_data_structs::{
+ CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget, TokenOwnerError,
+};
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
@@ -135,6 +137,8 @@
User(CrossAccountId),
/// Could not find the token provided as the owner.
TokenNotFound,
+ /// Nested token has multiple owners.
+ MultipleOwners,
/// Token owner is another token (still, the target token may not exist).
Token(CollectionId, TokenId),
}
@@ -159,11 +163,12 @@
let handle = handle.as_dyn();
Ok(match handle.token_owner(token) {
- Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
+ Ok(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
Some((collection, token)) => Parent::Token(collection, token),
None => Parent::User(owner),
},
- None => Parent::TokenNotFound,
+ Err(TokenOwnerError::MultipleOwners) => Parent::MultipleOwners,
+ Err(TokenOwnerError::NotFound) => Parent::TokenNotFound,
})
}
@@ -203,19 +208,27 @@
///
/// May return token address if parent token not yet exists
///
+ /// Returns `None` if the token has multiple owners.
+ ///
/// - `budget`: Limit for searching parents in depth.
pub fn find_topmost_owner(
collection: CollectionId,
token: TokenId,
budget: &dyn Budget,
- ) -> Result<T::CrossAccountId, DispatchError> {
+ ) -> Result<Option<T::CrossAccountId>, DispatchError> {
let owner = Self::parent_chain(collection, token)
.take_while(|_| budget.consume())
- .find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))
+ .find(|p| {
+ matches!(
+ p,
+ Ok(Parent::User(_) | Parent::TokenNotFound | Parent::MultipleOwners)
+ )
+ })
.ok_or(<Error<T>>::DepthLimit)??;
Ok(match owner {
- Parent::User(v) => v,
+ Parent::User(v) => Some(v),
+ Parent::MultipleOwners => None,
_ => fail!(<Error<T>>::TokenNotFound),
})
}
@@ -223,13 +236,15 @@
/// Find the topmost parent and check that assigning `for_nest` token as a child for
/// `token` wouldn't create a cycle.
///
+ /// Returns `None` if the token has multiple owners.
+ ///
/// - `budget`: Limit for searching parents in depth.
pub fn get_checked_topmost_owner(
collection: CollectionId,
token: TokenId,
for_nest: Option<(CollectionId, TokenId)>,
budget: &dyn Budget,
- ) -> Result<T::CrossAccountId, DispatchError> {
+ ) -> Result<Option<T::CrossAccountId>, DispatchError> {
// Tried to nest token in itself
if Some((collection, token)) == for_nest {
return Err(<Error<T>>::OuroborosDetected.into());
@@ -242,8 +257,9 @@
return Err(<Error<T>>::OuroborosDetected.into())
}
// Token is owned by other user
- Parent::User(user) => return Ok(user),
+ Parent::User(user) => return Ok(Some(user)),
Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),
+ Parent::MultipleOwners => return Ok(None),
// Continue parent chain
Parent::Token(_, _) => {}
}
@@ -284,12 +300,17 @@
budget: &dyn Budget,
) -> Result<bool, DispatchError> {
let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {
- Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,
+ Some((collection, token)) => match Self::find_topmost_owner(collection, token, budget)?
+ {
+ Some(topmost_owner) => topmost_owner,
+ None => return Ok(false),
+ },
None => user,
};
- Self::get_checked_topmost_owner(collection, token, for_nest, budget)
- .map(|indirect_owner| indirect_owner == target_parent)
+ Self::get_checked_topmost_owner(collection, token, for_nest, budget).map(|indirect_owner| {
+ indirect_owner.map_or(false, |indirect_owner| indirect_owner == target_parent)
+ })
}
/// Checks that `under` is valid token and that `token_id` could be nested under it
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1099,6 +1099,13 @@
EmptyPropertyKey,
}
+/// Token owner error: it could be either `NotFound` ot `MultipleOwners`.
+#[derive(Debug)]
+pub enum TokenOwnerError {
+ NotFound,
+ MultipleOwners,
+}
+
/// Marker for scope of property.
///
/// Scoped property can't be changed by user. Used for external collections.
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -16,11 +16,11 @@
#[macro_export]
macro_rules! dispatch_unique_runtime {
- ($collection:ident.$method:ident($($name:ident),*)) => {{
+ ($collection:ident.$method:ident($($name:ident),*) $($rest:tt)*) => {{
let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
let dispatch = collection.as_dyn();
- Ok::<_, DispatchError>(dispatch.$method($($name),*))
+ Ok::<_, DispatchError>(dispatch.$method($($name),*) $($rest)*)
}};
}
@@ -73,7 +73,7 @@
}
fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
- dispatch_unique_runtime!(collection.token_owner(token))
+ dispatch_unique_runtime!(collection.token_owner(token).ok())
}
fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec::<CrossAccountId>, DispatchError> {
@@ -83,7 +83,7 @@
fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
let budget = up_data_structs::budget::Value::new(10);
- Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))
+ Ok(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?)
}
fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {
Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))
tests/src/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -15,7 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {expect, itSub, usingPlaygrounds} from '../util';
+import {expect, itSub, Pallets, usingPlaygrounds} from '../util';
describe('Integration Test: Composite nesting tests', () => {
let alice: IKeyringPair;
@@ -138,7 +138,7 @@
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([50n, 10n, 10n], donor);
+ [alice, bob, charlie] = await helper.arrange.createAccounts([200n, 10n, 10n], donor);
});
});
@@ -288,6 +288,38 @@
await collectionFT.transfer(charlie, targetToken.nestingAccount(), 2n);
expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(7n);
});
+
+ itSub.ifWithPallets('ReFungible: getTopmostOwner works correctly with Nesting', [Pallets.ReFungible], async({helper}) => {
+ const collectionNFT = await helper.nft.mintCollection(alice, {
+ permissions: {
+ nesting: {
+ tokenOwner: true,
+ },
+ },
+ });
+ const collectionRFT = await helper.rft.mintCollection(alice);
+
+ const nft = await collectionNFT.mintToken(alice, {Substrate: alice.address});
+ const rft = await collectionRFT.mintToken(alice, 100n, {Substrate: alice.address});
+
+ expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});
+
+ await rft.transfer(alice, nft.nestingAccount(), 40n);
+
+ expect(await rft.getTopmostOwner()).deep.equal(null);
+
+ await rft.transfer(alice, nft.nestingAccount(), 60n);
+
+ expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});
+
+ await rft.transferFrom(alice, nft.nestingAccount(), {Substrate: alice.address}, 30n);
+
+ expect(await rft.getTopmostOwner()).deep.equal(null);
+
+ await rft.transferFrom(alice, nft.nestingAccount(), {Substrate: alice.address}, 70n);
+
+ expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});
+ });
});
describe('Negative Test: Nesting', () => {