difftreelog
feat nest on create/transfer
in: master
12 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -723,17 +723,20 @@
sender: T::CrossAccountId,
to: T::CrossAccountId,
data: CreateItemData,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo;
fn create_multiple_items(
&self,
sender: T::CrossAccountId,
to: T::CrossAccountId,
data: Vec<CreateItemData>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo;
fn create_multiple_items_ex(
&self,
sender: T::CrossAccountId,
data: CreateItemExData<T::CrossAccountId>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo;
fn burn_item(
&self,
@@ -748,6 +751,7 @@
to: T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo;
fn approve(
&self,
@@ -781,11 +785,12 @@
data: BoundedVec<u8, CustomDataLimit>,
) -> DispatchResultWithPostInfo;
- fn nest_token(
+ fn check_nesting(
&self,
sender: T::CrossAccountId,
- from: (CollectionId, TokenId),
+ from: CollectionId,
under: TokenId,
+ budget: &dyn Budget,
) -> DispatchResult;
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;
pallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -55,7 +55,6 @@
use frame_system::ensure_signed;
pub use frame_support::dispatch::DispatchResult;
- use frame_support::{pallet_prelude::*, traits::PalletInfo};
use frame_system::pallet_prelude::*;
/// DispatchError is opaque, but we need to somehow extract correct error in case of OutOfGas failure
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -17,7 +17,7 @@
use core::marker::PhantomData;
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};
-use up_data_structs::{TokenId, CreateItemExData, budget::Budget};
+use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::ArithmeticError;
use sp_std::{vec::Vec, vec};
@@ -78,10 +78,11 @@
sender: T::CrossAccountId,
to: T::CrossAccountId,
data: up_data_structs::CreateItemData,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
match data {
up_data_structs::CreateItemData::Fungible(data) => with_weight(
- <Pallet<T>>::create_item(self, &sender, (to, data.value)),
+ <Pallet<T>>::create_item(self, &sender, (to, data.value), nesting_budget),
<CommonWeights<T>>::create_item(),
),
_ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
@@ -93,6 +94,7 @@
sender: T::CrossAccountId,
to: T::CrossAccountId,
data: Vec<up_data_structs::CreateItemData>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
let mut sum: u128 = 0;
for data in data {
@@ -107,7 +109,7 @@
}
with_weight(
- <Pallet<T>>::create_item(self, &sender, (to, sum)),
+ <Pallet<T>>::create_item(self, &sender, (to, sum), nesting_budget),
<CommonWeights<T>>::create_item(),
)
}
@@ -116,6 +118,7 @@
&self,
sender: <T>::CrossAccountId,
data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);
let data = match data {
@@ -124,7 +127,7 @@
};
with_weight(
- <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner()),
+ <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),
weight,
)
}
@@ -152,6 +155,7 @@
to: T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
ensure!(
token == TokenId::default(),
@@ -159,7 +163,7 @@
);
with_weight(
- <Pallet<T>>::transfer(self, &from, &to, amount),
+ <Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget),
<CommonWeights<T>>::transfer(),
)
}
@@ -230,11 +234,12 @@
fail!(<Error<T>>::FungibleItemsDontHaveData)
}
- fn nest_token(
+ fn check_nesting(
&self,
_sender: <T>::CrossAccountId,
- _from: (up_data_structs::CollectionId, TokenId),
+ _from: CollectionId,
_under: TokenId,
+ _budget: &dyn Budget,
) -> sp_runtime::DispatchResult {
fail!(<Error<T>>::FungibleDisallowsNesting)
}
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -81,8 +81,11 @@
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
let amount = amount.try_into().map_err(|_| "amount overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
- <Pallet<T>>::transfer(self, &caller, &to, amount).map_err(|_| "transfer error")?;
+ <Pallet<T>>::transfer(self, &caller, &to, amount, &budget).map_err(|_| "transfer error")?;
Ok(true)
}
#[weight(<SelfWeightOf<T>>::transfer_from())]
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -193,6 +193,7 @@
from: &T::CrossAccountId,
to: &T::CrossAccountId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
ensure!(
collection.limits.transfers_enabled(),
@@ -222,12 +223,12 @@
let handle = <CollectionHandle<T>>::try_get(target.0)?;
let dispatch = T::CollectionDispatch::dispatch(handle);
let dispatch = dispatch.as_dyn();
-
- // =========
- dispatch.nest_token(from.clone(), (collection.id, TokenId::default()), target.1)?;
+ dispatch.check_nesting(from.clone(), collection.id, target.1, nesting_budget)?;
}
+ // =========
+
if let Some(balance_to) = balance_to {
// from != to
if balance_from == 0 {
@@ -257,6 +258,7 @@
collection: &FungibleHandle<T>,
sender: &T::CrossAccountId,
data: BTreeMap<T::CrossAccountId, u128>,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
if !collection.is_owner_or_admin(sender) {
ensure!(
@@ -285,6 +287,16 @@
.ok_or(ArithmeticError::Overflow)?;
}
+ for (to, _) in balances.iter() {
+ if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
+ let handle = <CollectionHandle<T>>::try_get(target.0)?;
+ let dispatch = T::CollectionDispatch::dispatch(handle);
+ let dispatch = dispatch.as_dyn();
+
+ dispatch.check_nesting(sender.clone(), collection.id, target.1, nesting_budget)?;
+ }
+ }
+
// =========
<TotalSupply<T>>::insert(collection.id, total_supply);
@@ -407,7 +419,7 @@
// =========
- Self::transfer(collection, from, to, amount)?;
+ Self::transfer(collection, from, to, amount, nesting_budget)?;
if let Some(allowance) = allowance {
Self::set_allowance_unchecked(collection, from, spender, allowance);
}
@@ -437,7 +449,13 @@
collection: &FungibleHandle<T>,
sender: &T::CrossAccountId,
data: CreateItemData<T>,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
- Self::create_multiple_items(collection, sender, [(data.0, data.1)].into_iter().collect())
+ Self::create_multiple_items(
+ collection,
+ sender,
+ [(data.0, data.1)].into_iter().collect(),
+ nesting_budget,
+ )
}
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -89,9 +89,15 @@
sender: T::CrossAccountId,
to: T::CrossAccountId,
data: up_data_structs::CreateItemData,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
with_weight(
- <Pallet<T>>::create_item(self, &sender, map_create_data::<T>(data, &to)?),
+ <Pallet<T>>::create_item(
+ self,
+ &sender,
+ map_create_data::<T>(data, &to)?,
+ nesting_budget,
+ ),
<CommonWeights<T>>::create_item(),
)
}
@@ -101,6 +107,7 @@
sender: T::CrossAccountId,
to: T::CrossAccountId,
data: Vec<up_data_structs::CreateItemData>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
let data = data
.into_iter()
@@ -109,7 +116,7 @@
let amount = data.len();
with_weight(
- <Pallet<T>>::create_multiple_items(self, &sender, data),
+ <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),
<CommonWeights<T>>::create_multiple_items(amount as u32),
)
}
@@ -118,6 +125,7 @@
&self,
sender: <T>::CrossAccountId,
data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);
let data = match data {
@@ -126,7 +134,7 @@
};
with_weight(
- <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner()),
+ <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),
weight,
)
}
@@ -154,11 +162,12 @@
to: T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
if amount == 1 {
with_weight(
- <Pallet<T>>::transfer(self, &from, &to, token),
+ <Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),
<CommonWeights<T>>::transfer(),
)
} else {
@@ -239,13 +248,14 @@
)
}
- fn nest_token(
+ fn check_nesting(
&self,
sender: T::CrossAccountId,
- (from, _): (CollectionId, TokenId),
+ from: CollectionId,
under: TokenId,
+ budget: &dyn Budget,
) -> sp_runtime::DispatchResult {
- <Pallet<T>>::nest_token(self, sender, from, under)
+ <Pallet<T>>::check_nesting(self, sender, from, under, budget)
}
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -256,6 +256,10 @@
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
let token_id: u32 = token_id.try_into()?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
if <TokensMinted<T>>::get(self.id)
.checked_add(1)
.ok_or("item id overflow")?
@@ -272,6 +276,7 @@
variable_data: BoundedVec::default(),
owner: to,
},
+ &budget,
)
.map_err(dispatch_to_evm::<T>)?;
@@ -296,6 +301,10 @@
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
if <TokensMinted<T>>::get(self.id)
.checked_add(1)
.ok_or("item id overflow")?
@@ -314,6 +323,7 @@
variable_data: BoundedVec::default(),
owner: to,
},
+ &budget,
)
.map_err(dispatch_to_evm::<T>)?;
Ok(true)
@@ -338,8 +348,11 @@
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
let token = token_id.try_into()?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
- <Pallet<T>>::transfer(self, &caller, &to, token).map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
@@ -409,6 +422,9 @@
let mut expected_index = <TokensMinted<T>>::get(self.id)
.checked_add(1)
.ok_or("item id overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
let total_tokens = token_ids.len();
for id in token_ids.into_iter() {
@@ -426,7 +442,8 @@
})
.collect();
- <Pallet<T>>::create_multiple_items(self, &caller, data).map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
Ok(true)
}
@@ -447,6 +464,9 @@
let mut expected_index = <TokensMinted<T>>::get(self.id)
.checked_add(1)
.ok_or("item id overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
let mut data = Vec::with_capacity(tokens.len());
for (id, token_uri) in tokens {
@@ -465,7 +485,8 @@
});
}
- <Pallet<T>>::create_multiple_items(self, &caller, data).map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
Ok(true)
}
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -251,6 +251,7 @@
from: &T::CrossAccountId,
to: &T::CrossAccountId,
token: TokenId,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
ensure!(
collection.limits.transfers_enabled(),
@@ -294,12 +295,12 @@
let handle = <CollectionHandle<T>>::try_get(target.0)?;
let dispatch = T::CollectionDispatch::dispatch(handle);
let dispatch = dispatch.as_dyn();
-
- // =========
- dispatch.nest_token(from.clone(), (collection.id, token), target.1)?;
+ dispatch.check_nesting(from.clone(), collection.id, target.1, nesting_budget)?;
}
+ // =========
+
<TokenData<T>>::insert(
(collection.id, token),
ItemData {
@@ -340,6 +341,7 @@
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,
data: Vec<CreateItemData<T>>,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
if !collection.is_owner_or_admin(sender) {
ensure!(
@@ -379,6 +381,16 @@
);
}
+ for (to, _) in balances.iter() {
+ if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
+ let handle = <CollectionHandle<T>>::try_get(target.0)?;
+ let dispatch = T::CollectionDispatch::dispatch(handle);
+ let dispatch = dispatch.as_dyn();
+
+ dispatch.check_nesting(sender.clone(), collection.id, target.1, nesting_budget)?;
+ }
+ }
+
// =========
<TokensMinted<T>>::insert(collection.id, tokens_minted);
@@ -556,7 +568,7 @@
// =========
// Allowance is reset in [`transfer`]
- Self::transfer(collection, from, to, token)
+ Self::transfer(collection, from, to, token, nesting_budget)
}
pub fn burn_from(
@@ -595,35 +607,34 @@
Ok(())
}
- pub fn nest_token(
+ pub fn check_nesting(
handle: &NonfungibleHandle<T>,
sender: T::CrossAccountId,
from: CollectionId,
under: TokenId,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
fn ensure_sender_allowed<T: Config>(
collection: CollectionId,
token: TokenId,
sender: T::CrossAccountId,
+ budget: &dyn Budget,
) -> DispatchResult {
ensure!(
- <TokenData<T>>::get((collection, token))
- .ok_or(<CommonError<T>>::TokenNotFound)?
- .owner
- .conv_eq(&sender),
+ <PalletStructure<T>>::indirectly_owned(sender, collection, token, budget)?,
<CommonError<T>>::OnlyOwnerAllowedToNest,
);
Ok(())
}
match handle.limits.nesting_rule() {
NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),
- NestingRule::Owner => ensure_sender_allowed::<T>(from, under, sender)?,
+ NestingRule::Owner => ensure_sender_allowed::<T>(from, under, sender, nesting_budget)?,
NestingRule::OwnerRestricted(whitelist) => {
ensure!(
whitelist.contains(&from),
<CommonError<T>>::SourceCollectionIsNotAllowedToNest
);
- ensure_sender_allowed::<T>(from, under, sender)?
+ ensure_sender_allowed::<T>(from, under, sender, nesting_budget)?
}
}
Ok(())
@@ -634,7 +645,8 @@
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,
data: CreateItemData<T>,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
- Self::create_multiple_items(collection, sender, vec![data])
+ Self::create_multiple_items(collection, sender, vec![data], nesting_budget)
}
}
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -19,7 +19,8 @@
use sp_std::collections::btree_map::BTreeMap;
use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight, BoundedVec};
use up_data_structs::{
- TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData, budget::Budget,
+ CollectionId, TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData,
+ budget::Budget,
};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
@@ -120,9 +121,15 @@
sender: T::CrossAccountId,
to: T::CrossAccountId,
data: up_data_structs::CreateItemData,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
with_weight(
- <Pallet<T>>::create_item(self, &sender, map_create_data::<T>(data, &to)?),
+ <Pallet<T>>::create_item(
+ self,
+ &sender,
+ map_create_data::<T>(data, &to)?,
+ nesting_budget,
+ ),
<CommonWeights<T>>::create_item(),
)
}
@@ -132,6 +139,7 @@
sender: T::CrossAccountId,
to: T::CrossAccountId,
data: Vec<up_data_structs::CreateItemData>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
let data = data
.into_iter()
@@ -140,7 +148,7 @@
let amount = data.len();
with_weight(
- <Pallet<T>>::create_multiple_items(self, &sender, data),
+ <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),
<CommonWeights<T>>::create_multiple_items(amount as u32),
)
}
@@ -149,6 +157,7 @@
&self,
sender: <T>::CrossAccountId,
data: CreateItemExData<T::CrossAccountId>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);
let data = match data {
@@ -162,7 +171,7 @@
};
with_weight(
- <Pallet<T>>::create_multiple_items(self, &sender, data),
+ <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),
weight,
)
}
@@ -185,9 +194,10 @@
to: T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
with_weight(
- <Pallet<T>>::transfer(self, &from, &to, token, amount),
+ <Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),
<CommonWeights<T>>::transfer(),
)
}
@@ -247,11 +257,12 @@
)
}
- fn nest_token(
+ fn check_nesting(
&self,
_sender: <T>::CrossAccountId,
- _from: (up_data_structs::CollectionId, TokenId),
+ _from: CollectionId,
_under: TokenId,
+ _budget: &dyn Budget,
) -> sp_runtime::DispatchResult {
fail!(<Error<T>>::RefungibleDisallowsNesting)
}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -289,6 +289,7 @@
to: &T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
ensure!(
collection.limits.transfers_enabled(),
@@ -351,10 +352,10 @@
let dispatch = T::CollectionDispatch::dispatch(handle);
let dispatch = dispatch.as_dyn();
- // =========
+ dispatch.check_nesting(from.clone(), collection.id, target.1, nesting_budget)?;
+ }
- dispatch.nest_token(from.clone(), (collection.id, token), target.1)?;
- }
+ // =========
if let Some(balance_to) = balance_to {
// from != to
@@ -389,6 +390,7 @@
collection: &RefungibleHandle<T>,
sender: &T::CrossAccountId,
data: Vec<CreateRefungibleExData<T::CrossAccountId>>,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
if !collection.is_owner_or_admin(sender) {
ensure!(
@@ -453,6 +455,23 @@
}
}
+ for token in data.iter() {
+ for (to, _) in token.users.iter() {
+ if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
+ let handle = <CollectionHandle<T>>::try_get(target.0)?;
+ let dispatch = T::CollectionDispatch::dispatch(handle);
+ let dispatch = dispatch.as_dyn();
+
+ dispatch.check_nesting(
+ sender.clone(),
+ collection.id,
+ target.1,
+ nesting_budget,
+ )?;
+ }
+ }
+ }
+
// =========
<TokensMinted<T>>::insert(collection.id, tokens_minted);
@@ -591,7 +610,7 @@
// =========
- Self::transfer(collection, from, to, token, amount)?;
+ Self::transfer(collection, from, to, token, amount, nesting_budget)?;
if let Some(allowance) = allowance {
Self::set_allowance_unchecked(collection, from, spender, token, allowance);
}
@@ -648,7 +667,8 @@
collection: &RefungibleHandle<T>,
sender: &T::CrossAccountId,
data: CreateRefungibleExData<T::CrossAccountId>,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
- Self::create_multiple_items(collection, sender, vec![data])
+ Self::create_multiple_items(collection, sender, vec![data], nesting_budget)
}
}
pallets/structure/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use sp_std::collections::btree_set::BTreeSet;45use frame_support::dispatch::DispatchError;6use frame_support::fail;7pub use pallet::*;8use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};9use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};1011#[cfg(feature = "runtime-benchmarks")]12pub mod benchmarking;13pub mod weights;1415pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;1617#[frame_support::pallet]18pub mod pallet {19 use frame_support::Parameter;20 use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};21 use frame_support::pallet_prelude::*;22 use frame_system::pallet_prelude::*;2324 use super::*;2526 #[pallet::error]27 pub enum Error<T> {28 /// While searched for owner, got already checked account29 OuroborosDetected,30 /// While searched for owner, encountered depth limit31 DepthLimit,32 /// While searched for owner, found token owner by not-yet-existing token33 TokenNotFound,34 }3536 #[pallet::event]37 pub enum Event<T> {38 /// Executed call on behalf of token39 Executed(DispatchResult),40 }4142 #[pallet::config]43 pub trait Config: frame_system::Config + pallet_common::Config {44 type WeightInfo: weights::WeightInfo;45 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;46 type Call: Parameter + UnfilteredDispatchable<Origin = Self::Origin> + GetDispatchInfo;47 }4849 #[pallet::pallet]50 pub struct Pallet<T>(_);5152 #[pallet::call]53 impl<T: Config> Pallet<T> {54 // #[pallet::weight({55 // let dispatch_info = call.get_dispatch_info();5657 // (58 // dispatch_info.weight59 // // Cost of dereferencing parent60 // .saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))61 // .saturating_add(4000 * *max_depth as Weight),62 // dispatch_info.class)63 // })]64 // pub fn execute(65 // origin: OriginFor<T>,66 // call: Box<<T as Config>::Call>,67 // max_depth: u32,68 // ) -> DispatchResult {69 }70}7172#[derive(PartialEq)]73pub enum Parent<CrossAccountId> {74 /// Token owned by normal account75 Normal(CrossAccountId),76 /// Passed token not found77 TokenNotFound,78 /// Token owner is another token (target token still may not exist)79 Token(CollectionId, TokenId),80}8182impl<T: Config> Pallet<T> {83 pub fn find_parent(84 collection: CollectionId,85 token: TokenId,86 ) -> Result<Parent<T::CrossAccountId>, DispatchError> {87 // TODO: Reduce cost by not reading collection config88 let handle = match CollectionHandle::try_get(collection) {89 Ok(v) => v,90 Err(_) => return Ok(Parent::TokenNotFound),91 };92 let handle = T::CollectionDispatch::dispatch(handle);93 let handle = handle.as_dyn();9495 Ok(match handle.token_owner(token) {96 Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {97 Some((collection, token)) => Parent::Token(collection, token),98 None => Parent::Normal(owner),99 },100 None => Parent::TokenNotFound,101 })102 }103104 pub fn parent_chain(105 mut collection: CollectionId,106 mut token: TokenId,107 ) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {108 let mut finished = false;109 let mut visited = BTreeSet::new();110 visited.insert((collection, token));111 core::iter::from_fn(move || {112 if finished {113 return None;114 }115 let parent = Self::find_parent(collection, token);116 match parent {117 Ok(Parent::Token(new_collection, new_token)) => {118 collection = new_collection;119 token = new_token;120 if !visited.insert((new_collection, new_token)) {121 finished = true;122 return Some(Err(<Error<T>>::OuroborosDetected.into()));123 }124 }125 _ => finished = true,126 }127 Some(parent as Result<_, DispatchError>)128 })129 }130131 /// Try to dereference address, until finding top level owner132 ///133 /// May return token address if parent token not yet exists134 pub fn find_topmost_owner(135 collection: CollectionId,136 token: TokenId,137 budget: &dyn Budget,138 ) -> Result<T::CrossAccountId, DispatchError> {139 let owner = Self::parent_chain(collection, token)140 .take_while(|_| budget.consume())141 .find(|p| matches!(p, Ok(Parent::Normal(_) | Parent::TokenNotFound)))142 .ok_or(<Error<T>>::DepthLimit)??;143144 Ok(match owner {145 Parent::Normal(v) => v,146 _ => fail!(<Error<T>>::TokenNotFound),147 })148 }149150 /// Check if token indirectly owned by specified user151 pub fn indirectly_owned(152 user: T::CrossAccountId,153 collection: CollectionId,154 token: TokenId,155 budget: &dyn Budget,156 ) -> Result<bool, DispatchError> {157 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {158 Some((collection, token)) => Parent::Token(collection, token),159 None => Parent::Normal(user),160 };161162 Ok(Self::parent_chain(collection, token)163 .take_while(|_| budget.consume())164 .any(|parent| Ok(&target_parent) == parent.as_ref()))165 }166}1#![cfg_attr(not(feature = "std"), no_std)]23use sp_std::collections::btree_set::BTreeSet;45use frame_support::dispatch::DispatchError;6use frame_support::fail;7pub use pallet::*;8use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};9use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};1011#[cfg(feature = "runtime-benchmarks")]12pub mod benchmarking;13pub mod weights;1415pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;1617#[frame_support::pallet]18pub mod pallet {19 use frame_support::Parameter;20 use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};21 use frame_support::pallet_prelude::*;2223 use super::*;2425 #[pallet::error]26 pub enum Error<T> {27 /// While searched for owner, got already checked account28 OuroborosDetected,29 /// While searched for owner, encountered depth limit30 DepthLimit,31 /// While searched for owner, found token owner by not-yet-existing token32 TokenNotFound,33 }3435 #[pallet::event]36 pub enum Event<T> {37 /// Executed call on behalf of token38 Executed(DispatchResult),39 }4041 #[pallet::config]42 pub trait Config: frame_system::Config + pallet_common::Config {43 type WeightInfo: weights::WeightInfo;44 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;45 type Call: Parameter + UnfilteredDispatchable<Origin = Self::Origin> + GetDispatchInfo;46 }4748 #[pallet::pallet]49 pub struct Pallet<T>(_);5051 #[pallet::call]52 impl<T: Config> Pallet<T> {53 // #[pallet::weight({54 // let dispatch_info = call.get_dispatch_info();5556 // (57 // dispatch_info.weight58 // // Cost of dereferencing parent59 // .saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))60 // .saturating_add(4000 * *max_depth as Weight),61 // dispatch_info.class)62 // })]63 // pub fn execute(64 // origin: OriginFor<T>,65 // call: Box<<T as Config>::Call>,66 // max_depth: u32,67 // ) -> DispatchResult {68 }69}7071#[derive(PartialEq)]72pub enum Parent<CrossAccountId> {73 /// Token owned by normal account74 Normal(CrossAccountId),75 /// Passed token not found76 TokenNotFound,77 /// Token owner is another token (target token still may not exist)78 Token(CollectionId, TokenId),79}8081impl<T: Config> Pallet<T> {82 pub fn find_parent(83 collection: CollectionId,84 token: TokenId,85 ) -> Result<Parent<T::CrossAccountId>, DispatchError> {86 // TODO: Reduce cost by not reading collection config87 let handle = match CollectionHandle::try_get(collection) {88 Ok(v) => v,89 Err(_) => return Ok(Parent::TokenNotFound),90 };91 let handle = T::CollectionDispatch::dispatch(handle);92 let handle = handle.as_dyn();9394 Ok(match handle.token_owner(token) {95 Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {96 Some((collection, token)) => Parent::Token(collection, token),97 None => Parent::Normal(owner),98 },99 None => Parent::TokenNotFound,100 })101 }102103 pub fn parent_chain(104 mut collection: CollectionId,105 mut token: TokenId,106 ) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {107 let mut finished = false;108 let mut visited = BTreeSet::new();109 visited.insert((collection, token));110 core::iter::from_fn(move || {111 if finished {112 return None;113 }114 let parent = Self::find_parent(collection, token);115 match parent {116 Ok(Parent::Token(new_collection, new_token)) => {117 collection = new_collection;118 token = new_token;119 if !visited.insert((new_collection, new_token)) {120 finished = true;121 return Some(Err(<Error<T>>::OuroborosDetected.into()));122 }123 }124 _ => finished = true,125 }126 Some(parent as Result<_, DispatchError>)127 })128 }129130 /// Try to dereference address, until finding top level owner131 ///132 /// May return token address if parent token not yet exists133 pub fn find_topmost_owner(134 collection: CollectionId,135 token: TokenId,136 budget: &dyn Budget,137 ) -> Result<T::CrossAccountId, DispatchError> {138 let owner = Self::parent_chain(collection, token)139 .take_while(|_| budget.consume())140 .find(|p| matches!(p, Ok(Parent::Normal(_) | Parent::TokenNotFound)))141 .ok_or(<Error<T>>::DepthLimit)??;142143 Ok(match owner {144 Parent::Normal(v) => v,145 _ => fail!(<Error<T>>::TokenNotFound),146 })147 }148149 /// Check if token indirectly owned by specified user150 pub fn indirectly_owned(151 user: T::CrossAccountId,152 collection: CollectionId,153 token: TokenId,154 budget: &dyn Budget,155 ) -> Result<bool, DispatchError> {156 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {157 Some((collection, token)) => Parent::Token(collection, token),158 None => Parent::Normal(user),159 };160161 Ok(Self::parent_chain(collection, token)162 .take_while(|_| budget.consume())163 .any(|parent| Ok(&target_parent) == parent.as_ref()))164 }165}pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -693,8 +693,9 @@
#[transactional]
pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+ let budget = budget::Value::new(2);
- dispatch_call::<T, _>(collection_id, |d| d.create_item(sender, owner, data))
+ dispatch_call::<T, _>(collection_id, |d| d.create_item(sender, owner, data, &budget))
}
/// This method creates multiple items in a collection created with CreateCollection method.
@@ -720,16 +721,18 @@
pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResultWithPostInfo {
ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+ let budget = budget::Value::new(2);
- dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data))
+ dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data, &budget))
}
#[weight = <CommonWeights<T>>::create_multiple_items_ex(&data)]
#[transactional]
pub fn create_multiple_items_ex(origin, collection_id: CollectionId, data: CreateItemExData<T::CrossAccountId>) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+ let budget = budget::Value::new(2);
- dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items_ex(sender, data))
+ dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items_ex(sender, data, &budget))
}
// TODO! transaction weight
@@ -839,8 +842,9 @@
#[transactional]
pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+ let budget = budget::Value::new(2);
- dispatch_call::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value))
+ dispatch_call::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value, &budget))
}
/// Set, change, or remove approved address to transfer the ownership of the NFT.