difftreelog
feat budgets
in: master
19 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -33,7 +33,7 @@
COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId, CollectionStats, MAX_TOKEN_OWNERSHIP,
CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,
- CustomDataLimit, CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit,
+ CustomDataLimit, CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit, budget::Budget,
};
pub use pallet::*;
use sp_core::H160;
@@ -763,6 +763,7 @@
to: T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo;
fn burn_from(
&self,
@@ -770,6 +771,7 @@
from: T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo;
fn set_variable_metadata(
pallets/evm-coder-substrate/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-coder-substrate/Cargo.toml
+++ b/pallets/evm-coder-substrate/Cargo.toml
@@ -17,6 +17,7 @@
frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20" }
frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20" }
frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20" }
+up-data-structs = { default-features = false, path = "../../primitives/data-structs" }
[dependencies.codec]
default-features = false
pallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -18,33 +18,43 @@
#[cfg(not(feature = "std"))]
extern crate alloc;
+#[cfg(not(feature = "std"))]
+use alloc::format;
+use frame_support::dispatch::Weight;
+
+use core::marker::PhantomData;
+use sp_std::cell::RefCell;
+use sp_std::vec::Vec;
+
+use frame_support::pallet_prelude::DispatchError;
+use frame_support::traits::PalletInfo;
+use frame_support::{ensure, sp_runtime::ModuleError};
+use up_data_structs::budget;
+use pallet_evm::{
+ ExitError, ExitRevert, ExitSucceed, GasWeightMapping, PrecompileFailure, PrecompileOutput,
+ PrecompileResult, runner::stack::MaybeMirroredLog,
+};
+use ethereum::TransactionV2;
+use sp_core::{H160, H256};
+use pallet_ethereum::EthereumTransactionSender;
// #[cfg(feature = "runtime-benchmarks")]
// pub mod benchmarking;
+use evm_coder::{
+ ToLog,
+ abi::{AbiReader, AbiWrite, AbiWriter},
+ execution::{self, Result},
+ types::{Msg, value},
+};
+
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
- #[cfg(not(feature = "std"))]
- use alloc::format;
+ use super::*;
- use evm_coder::{
- ToLog,
- abi::{AbiReader, AbiWrite, AbiWriter},
- execution::{self, Result},
- types::{Msg, value},
- };
- use frame_support::{ensure, sp_runtime::ModuleError};
- use pallet_evm::{
- ExitError, ExitRevert, ExitSucceed, GasWeightMapping, PrecompileFailure, PrecompileOutput,
- PrecompileResult, runner::stack::MaybeMirroredLog,
- };
use frame_system::ensure_signed;
pub use frame_support::dispatch::DispatchResult;
- use pallet_ethereum::EthereumTransactionSender;
- use sp_std::cell::RefCell;
- use sp_std::vec::Vec;
- use sp_core::H160;
use frame_support::{pallet_prelude::*, traits::PalletInfo};
use frame_system::pallet_prelude::*;
@@ -76,214 +86,258 @@
Ok(())
}
}
+}
- // From instabul hardfork configuration: https://github.com/rust-blockchain/evm/blob/fd4fd6acc0ca3208d6770fdb3ba407c94cdf97c6/runtime/src/lib.rs#L284
- pub const G_SLOAD_WORD: u64 = 800;
- pub const G_SSTORE_WORD: u64 = 20000;
+// From instabul hardfork configuration: https://github.com/rust-blockchain/evm/blob/fd4fd6acc0ca3208d6770fdb3ba407c94cdf97c6/runtime/src/lib.rs#L284
+pub const G_SLOAD_WORD: u64 = 800;
+pub const G_SSTORE_WORD: u64 = 20000;
- #[derive(Default)]
- pub struct SubstrateRecorder<T: Config> {
- contract: H160,
- logs: RefCell<Vec<MaybeMirroredLog>>,
- initial_gas: u64,
- gas_limit: RefCell<u64>,
- _phantom: PhantomData<*const T>,
+pub fn generate_transaction() -> TransactionV2 {
+ use ethereum::{TransactionV0, TransactionAction, TransactionSignature};
+ TransactionV2::Legacy(TransactionV0 {
+ nonce: 0.into(),
+ gas_price: 0.into(),
+ gas_limit: 0.into(),
+ action: TransactionAction::Call(H160([0; 20])),
+ value: 0.into(),
+ // zero selector, this transaction always has same sender, so all data should be acquired from logs
+ input: Vec::from([0, 0, 0, 0]),
+ // if v is not 27 - then we need to pass some other validity checks
+ signature: TransactionSignature::new(27, H256([0x88; 32]), H256([0x88; 32])).unwrap(),
+ })
+}
+
+pub struct GasCallsBudget<'r, T: Config> {
+ recorder: &'r SubstrateRecorder<T>,
+ gas_per_call: u64,
+}
+impl<T: Config> budget::Budget for GasCallsBudget<'_, T> {
+ fn consume_custom(&self, calls: u32) -> bool {
+ let (gas, overflown) = (calls as u64).overflowing_add(self.gas_per_call);
+ if overflown {
+ return false;
+ }
+ self.recorder.consume_gas(gas).is_ok()
}
+}
- impl<T: Config> SubstrateRecorder<T> {
- pub fn new(contract: H160, gas_limit: u64) -> Self {
- Self {
- contract,
- logs: RefCell::new(Vec::new()),
- initial_gas: gas_limit,
- gas_limit: RefCell::new(gas_limit),
- _phantom: PhantomData,
- }
+#[derive(Default)]
+pub struct SubstrateRecorder<T: Config> {
+ contract: H160,
+ logs: RefCell<Vec<MaybeMirroredLog>>,
+ initial_gas: u64,
+ gas_limit: RefCell<u64>,
+ _phantom: PhantomData<*const T>,
+}
+
+impl<T: Config> SubstrateRecorder<T> {
+ pub fn new(contract: H160, gas_limit: u64) -> Self {
+ Self {
+ contract,
+ logs: RefCell::new(Vec::new()),
+ initial_gas: gas_limit,
+ gas_limit: RefCell::new(gas_limit),
+ _phantom: PhantomData,
}
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.logs.borrow().is_empty()
+ }
+ // Logs emitted with log_direct appear as substrate evm.Log event
+ pub fn log_direct(&self, log: impl ToLog) {
+ self.logs
+ .borrow_mut()
+ .push(MaybeMirroredLog::direct(log.to_log(self.contract)))
+ }
+ /// If log already has substrate equivalent - then we don't need to emit evm.Log
+ pub fn log_mirrored(&self, log: impl ToLog) {
+ self.logs
+ .borrow_mut()
+ .push(MaybeMirroredLog::mirrored(log.to_log(self.contract)))
+ }
+ pub fn retrieve_logs(self) -> Vec<MaybeMirroredLog> {
+ self.logs.into_inner()
+ }
- pub fn is_empty(&self) -> bool {
- self.logs.borrow().is_empty()
- }
- // Logs emitted with log_direct appear as substrate evm.Log event
- pub fn log_direct(&self, log: impl ToLog) {
- self.logs
- .borrow_mut()
- .push(MaybeMirroredLog::direct(log.to_log(self.contract)))
- }
- /// If log already has substrate equivalent - then we don't need to emit evm.Log
- pub fn log_mirrored(&self, log: impl ToLog) {
- self.logs
- .borrow_mut()
- .push(MaybeMirroredLog::mirrored(log.to_log(self.contract)))
+ pub fn gas_left(&self) -> u64 {
+ *self.gas_limit.borrow()
+ }
+ pub fn gas_calls_budget(&self, gas_per_call: u64) -> GasCallsBudget<T> {
+ GasCallsBudget {
+ recorder: self,
+ gas_per_call,
}
- pub fn retrieve_logs(self) -> Vec<MaybeMirroredLog> {
- self.logs.into_inner()
+ }
+ pub fn weight_calls_budget(&self, weight_per_call: Weight) -> GasCallsBudget<T> {
+ GasCallsBudget {
+ recorder: self,
+ gas_per_call: T::GasWeightMapping::weight_to_gas(weight_per_call),
}
+ }
+ pub fn consume_sload_sub(&self) -> DispatchResult {
+ self.consume_gas_sub(G_SLOAD_WORD)
+ }
+ pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {
+ self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))
+ }
+ pub fn consume_sstore_sub(&self) -> DispatchResult {
+ self.consume_gas_sub(G_SSTORE_WORD)
+ }
+ pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {
+ ensure!(gas != u64::MAX, Error::<T>::OutOfGas);
+ let mut gas_limit = self.gas_limit.borrow_mut();
+ ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);
+ *gas_limit -= gas;
+ Ok(())
+ }
- pub fn gas_left(&self) -> u64 {
- *self.gas_limit.borrow()
+ pub fn consume_sload(&self) -> Result<()> {
+ self.consume_gas(G_SLOAD_WORD)
+ }
+ pub fn consume_sstore(&self) -> Result<()> {
+ self.consume_gas(G_SSTORE_WORD)
+ }
+ pub fn consume_gas(&self, gas: u64) -> Result<()> {
+ if gas == u64::MAX {
+ return Err(execution::Error::Error(ExitError::OutOfGas));
}
- pub fn consume_sload_sub(&self) -> DispatchResult {
- self.consume_gas_sub(G_SLOAD_WORD)
+ let mut gas_limit = self.gas_limit.borrow_mut();
+ if gas > *gas_limit {
+ return Err(execution::Error::Error(ExitError::OutOfGas));
}
- pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {
- self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))
- }
- pub fn consume_sstore_sub(&self) -> DispatchResult {
- self.consume_gas_sub(G_SSTORE_WORD)
- }
- pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {
- ensure!(gas != u64::MAX, Error::<T>::OutOfGas);
- let mut gas_limit = self.gas_limit.borrow_mut();
- ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);
- *gas_limit -= gas;
- Ok(())
- }
+ *gas_limit -= gas;
+ Ok(())
+ }
+ pub fn return_gas(&self, gas: u64) {
+ let mut gas_limit = self.gas_limit.borrow_mut();
+ *gas_limit += gas;
+ }
- pub fn consume_sload(&self) -> Result<()> {
- self.consume_gas(G_SLOAD_WORD)
- }
- pub fn consume_sstore(&self) -> Result<()> {
- self.consume_gas(G_SSTORE_WORD)
- }
- pub fn consume_gas(&self, gas: u64) -> Result<()> {
- if gas == u64::MAX {
- return Err(execution::Error::Error(ExitError::OutOfGas));
- }
- let mut gas_limit = self.gas_limit.borrow_mut();
- if gas > *gas_limit {
- return Err(execution::Error::Error(ExitError::OutOfGas));
- }
- *gas_limit -= gas;
- Ok(())
- }
- pub fn return_gas(&self, gas: u64) {
- let mut gas_limit = self.gas_limit.borrow_mut();
- *gas_limit += gas;
- }
+ pub fn evm_to_precompile_output(
+ self,
+ result: evm_coder::execution::Result<Option<AbiWriter>>,
+ ) -> Option<PrecompileResult> {
+ use evm_coder::execution::Error;
+ Some(match result {
+ Ok(Some(v)) => Ok(PrecompileOutput {
+ exit_status: ExitSucceed::Returned,
+ cost: self.initial_gas - self.gas_left(),
+ // TODO: preserve mirroring status
+ logs: self.retrieve_logs().into_iter().map(|l| l.log).collect(),
+ output: v.finish(),
+ }),
+ Ok(None) => return None,
+ Err(Error::Revert(e)) => {
+ let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));
+ (&e as &str).abi_write(&mut writer);
- pub fn evm_to_precompile_output(
- self,
- result: evm_coder::execution::Result<Option<AbiWriter>>,
- ) -> Option<PrecompileResult> {
- use evm_coder::execution::Error;
- Some(match result {
- Ok(Some(v)) => Ok(PrecompileOutput {
- exit_status: ExitSucceed::Returned,
+ Err(PrecompileFailure::Revert {
+ exit_status: ExitRevert::Reverted,
cost: self.initial_gas - self.gas_left(),
- // TODO: preserve mirroring status
- logs: self.retrieve_logs().into_iter().map(|l| l.log).collect(),
- output: v.finish(),
- }),
- Ok(None) => return None,
- Err(Error::Revert(e)) => {
- let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));
- (&e as &str).abi_write(&mut writer);
+ output: writer.finish(),
+ })
+ }
+ Err(Error::Fatal(f)) => Err(f.into()),
+ Err(Error::Error(e)) => Err(e.into()),
+ })
+ }
- Err(PrecompileFailure::Revert {
- exit_status: ExitRevert::Reverted,
- cost: self.initial_gas - self.gas_left(),
- output: writer.finish(),
- })
- }
- Err(Error::Fatal(f)) => Err(f.into()),
- Err(Error::Error(e)) => Err(e.into()),
- })
+ pub fn submit_logs(self) {
+ let logs = self.retrieve_logs();
+ if logs.is_empty() {
+ return;
}
+ T::EthereumTransactionSender::submit_logs_transaction(
+ Default::default(),
+ generate_transaction(),
+ logs,
+ )
+ }
+}
- pub fn submit_logs(self) {
- let logs = self.retrieve_logs();
- if logs.is_empty() {
- return;
+pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> evm_coder::execution::Error {
+ use evm_coder::execution::Error as ExError;
+ match err {
+ DispatchError::Module(ModuleError { index, error, .. })
+ if index
+ == T::PalletInfo::index::<Pallet<T>>()
+ .expect("evm-coder-substrate is a pallet, which should be added to runtime")
+ as u8 =>
+ {
+ match error {
+ v if v == Error::<T>::OutOfGas.as_u8() => ExError::Error(ExitError::OutOfGas),
+ v if v == Error::<T>::OutOfFund.as_u8() => ExError::Error(ExitError::OutOfFund),
+ _ => unreachable!("this pallet only defines two possible errors"),
}
- T::EthereumTransactionSender::submit_logs_transaction(Default::default(), logs)
}
+ DispatchError::Module(ModuleError {
+ message: Some(msg), ..
+ }) => ExError::Revert(msg.into()),
+ DispatchError::Module(ModuleError { index, error, .. }) => {
+ ExError::Revert(format!("error {} in pallet {}", error, index))
+ }
+ e => ExError::Revert(format!("substrate error: {:?}", e)),
}
+}
+
+pub trait WithRecorder<T: Config> {
+ fn recorder(&self) -> &SubstrateRecorder<T>;
+ fn into_recorder(self) -> SubstrateRecorder<T>;
+}
- pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> evm_coder::execution::Error {
- use evm_coder::execution::Error as ExError;
- match err {
- DispatchError::Module(ModuleError { index, error, .. })
- if index
- == T::PalletInfo::index::<Pallet<T>>()
- .expect("evm-coder-substrate is a pallet, which should be added to runtime")
- as u8 =>
- {
- let mut read = &error as &[u8];
- match Error::<T>::decode(&mut read) {
- Ok(Error::<T>::OutOfGas) => ExError::Error(ExitError::OutOfGas),
- Ok(Error::<T>::OutOfFund) => ExError::Error(ExitError::OutOfFund),
- _ => unreachable!("this pallet only defines two possible errors"),
- }
- }
- DispatchError::Module(ModuleError {
- message: Some(msg), ..
- }) => ExError::Revert(msg.into()),
- DispatchError::Module(ModuleError { index, error, .. }) => {
- ExError::Revert(format!("error {:?} in pallet {}", error, index))
- }
- e => ExError::Revert(format!("substrate error: {:?}", e)),
- }
- }
+/// Helper to simplify implementing bridge between evm-coder definitions and pallet-evm
+pub fn call<
+ T: Config,
+ C: evm_coder::Call + evm_coder::Weighted,
+ E: evm_coder::Callable<C> + WithRecorder<T>,
+>(
+ caller: H160,
+ mut e: E,
+ value: value,
+ input: &[u8],
+) -> Option<PrecompileResult> {
+ let result = call_internal(caller, &mut e, value, input);
+ e.into_recorder().evm_to_precompile_output(result)
+}
- pub trait WithRecorder<T: Config> {
- fn recorder(&self) -> &SubstrateRecorder<T>;
- fn into_recorder(self) -> SubstrateRecorder<T>;
+fn call_internal<
+ T: Config,
+ C: evm_coder::Call + evm_coder::Weighted,
+ E: evm_coder::Callable<C> + WithRecorder<T>,
+>(
+ caller: H160,
+ e: &mut E,
+ value: value,
+ input: &[u8],
+) -> evm_coder::execution::Result<Option<AbiWriter>> {
+ let (selector, mut reader) = AbiReader::new_call(input)?;
+ let call = C::parse(selector, &mut reader)?;
+ if call.is_none() {
+ return Ok(None);
}
+ let call = call.unwrap();
- /// Helper to simplify implementing bridge between evm-coder definitions and pallet-evm
- pub fn call<
- T: Config,
- C: evm_coder::Call + evm_coder::Weighted,
- E: evm_coder::Callable<C> + WithRecorder<T>,
- >(
- caller: H160,
- mut e: E,
- value: value,
- input: &[u8],
- ) -> Option<PrecompileResult> {
- let result = call_internal(caller, &mut e, value, input);
- e.into_recorder().evm_to_precompile_output(result)
- }
+ let dispatch_info = call.weight();
+ e.recorder()
+ .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;
- fn call_internal<
- T: Config,
- C: evm_coder::Call + evm_coder::Weighted,
- E: evm_coder::Callable<C> + WithRecorder<T>,
- >(
- caller: H160,
- e: &mut E,
- value: value,
- input: &[u8],
- ) -> evm_coder::execution::Result<Option<AbiWriter>> {
- let (selector, mut reader) = AbiReader::new_call(input)?;
- let call = C::parse(selector, &mut reader)?;
- if call.is_none() {
- return Ok(None);
+ match e.call(Msg {
+ call,
+ caller,
+ value,
+ }) {
+ Ok(v) => {
+ let unspent = v.post_info.calc_unspent(&dispatch_info);
+ e.recorder()
+ .return_gas(T::GasWeightMapping::weight_to_gas(unspent));
+ Ok(Some(v.data))
}
- let call = call.unwrap();
-
- let dispatch_info = call.weight();
- e.recorder()
- .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;
-
- match e.call(Msg {
- call,
- caller,
- value,
- }) {
- Ok(v) => {
- let unspent = v.post_info.calc_unspent(&dispatch_info);
- e.recorder()
- .return_gas(T::GasWeightMapping::weight_to_gas(unspent));
- Ok(Some(v.data))
- }
- Err(v) => {
- let unspent = v.post_info.calc_unspent(&dispatch_info);
- e.recorder()
- .return_gas(T::GasWeightMapping::weight_to_gas(unspent));
- Err(v.data)
- }
+ Err(v) => {
+ let unspent = v.post_info.calc_unspent(&dispatch_info);
+ e.recorder()
+ .return_gas(T::GasWeightMapping::weight_to_gas(unspent));
+ Err(v.data)
}
}
}
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -20,7 +20,7 @@
use sp_std::prelude::*;
use pallet_common::benchmarking::create_collection_raw;
use frame_benchmarking::{benchmarks, account};
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH};
+use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, budget::Unlimited};
use pallet_common::bench_init;
const SEED: u32 = 1;
@@ -52,7 +52,7 @@
bench_init!(to: cross_sub(i););
(to, 200)
}).collect::<BTreeMap<_, _>>().try_into().unwrap();
- }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)}
+ }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
burn_item {
bench_init!{
@@ -85,7 +85,7 @@
};
<Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200))?;
<Pallet<T>>::set_allowance(&collection, &sender, &spender, 200)?;
- }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, 100)?}
+ }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, 100, &Unlimited)?}
burn_from {
bench_init!{
@@ -94,5 +94,5 @@
};
<Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200))?;
<Pallet<T>>::set_allowance(&collection, &sender, &burner, 200)?;
- }: {<Pallet<T>>::burn_from(&collection, &burner, &sender, 100)?}
+ }: {<Pallet<T>>::burn_from(&collection, &burner, &sender, 100, &Unlimited)?}
}
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};
+use up_data_structs::{TokenId, CreateItemExData, budget::Budget};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::ArithmeticError;
use sp_std::{vec::Vec, vec};
@@ -189,6 +189,7 @@
to: T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
ensure!(
token == TokenId::default(),
@@ -196,7 +197,7 @@
);
with_weight(
- <Pallet<T>>::transfer_from(self, &sender, &from, &to, amount),
+ <Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget),
<CommonWeights<T>>::transfer_from(),
)
}
@@ -207,6 +208,7 @@
from: T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
ensure!(
token == TokenId::default(),
@@ -214,7 +216,7 @@
);
with_weight(
- <Pallet<T>>::burn_from(self, &sender, &from, amount),
+ <Pallet<T>>::burn_from(self, &sender, &from, amount, nesting_budget),
<CommonWeights<T>>::burn_from(),
)
}
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -23,6 +23,7 @@
use sp_std::vec::Vec;
use pallet_evm::account::CrossAccountId;
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
+use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
use crate::{
Allowance, Balance, Config, FungibleHandle, Pallet, SelfWeightOf, TotalSupply,
@@ -96,8 +97,11 @@
let from = T::CrossAccountId::from_eth(from);
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_from(self, &caller, &from, &to, amount)
+ <Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)
.map_err(dispatch_to_evm::<T>)?;
Ok(true)
}
@@ -127,8 +131,12 @@
let caller = T::CrossAccountId::from_eth(caller);
let from = T::CrossAccountId::from_eth(from);
let amount = amount.try_into().map_err(|_| "amount overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
- <Pallet<T>>::burn_from(self, &caller, &from, amount).map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::burn_from(self, &caller, &from, amount, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
Ok(true)
}
}
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -21,6 +21,7 @@
use pallet_evm::account::CrossAccountId;
use up_data_structs::{
AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,
+ budget::Budget,
};
use pallet_common::{
Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
@@ -361,6 +362,7 @@
spender: &T::CrossAccountId,
from: &T::CrossAccountId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> Result<Option<u128>, DispatchError> {
if spender.conv_eq(from) {
return Ok(None);
@@ -372,7 +374,12 @@
if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
// TODO: should collection owner be allowed to perform this transfer?
ensure!(
- <PalletStructure<T>>::indirectly_owned(spender.clone(), source.0, source.1, 1)?,
+ <PalletStructure<T>>::indirectly_owned(
+ spender.clone(),
+ source.0,
+ source.1,
+ nesting_budget
+ )?,
<CommonError<T>>::ApprovedValueTooLow,
);
return Ok(None);
@@ -394,8 +401,9 @@
from: &T::CrossAccountId,
to: &T::CrossAccountId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
- let allowance = Self::check_allowed(collection, spender, from, amount)?;
+ let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;
// =========
@@ -411,8 +419,9 @@
spender: &T::CrossAccountId,
from: &T::CrossAccountId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
- let allowance = Self::check_allowed(collection, spender, from, amount)?;
+ let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;
// =========
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -20,7 +20,7 @@
use sp_std::prelude::*;
use pallet_common::benchmarking::{create_collection_raw, create_data, create_var_data};
use frame_benchmarking::{benchmarks, account};
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, CUSTOM_DATA_LIMIT};
+use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, CUSTOM_DATA_LIMIT, budget::Unlimited};
use pallet_common::bench_init;
use core::convert::TryInto;
@@ -115,7 +115,7 @@
};
let item = create_max_item(&collection, &owner, sender.clone())?;
<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&spender))?;
- }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item)?}
+ }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, &Unlimited)?}
burn_from {
bench_init!{
@@ -124,7 +124,7 @@
};
let item = create_max_item(&collection, &owner, sender.clone())?;
<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&burner))?;
- }: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item)?}
+ }: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item, &Unlimited)?}
set_variable_metadata {
let b in 0..CUSTOM_DATA_LIMIT;
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/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, CustomDataLimit, CreateItemExData, CollectionId};
+use up_data_structs::{TokenId, CustomDataLimit, CreateItemExData, CollectionId, budget::Budget};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
use sp_std::vec::Vec;
@@ -192,12 +192,13 @@
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_from(self, &sender, &from, &to, token),
+ <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),
<CommonWeights<T>>::transfer_from(),
)
} else {
@@ -211,12 +212,13 @@
from: T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
if amount == 1 {
with_weight(
- <Pallet<T>>::burn_from(self, &sender, &from, token),
+ <Pallet<T>>::burn_from(self, &sender, &from, token, nesting_budget),
<CommonWeights<T>>::burn_from(),
)
} else {
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -30,6 +30,7 @@
};
use pallet_evm::account::CrossAccountId;
use pallet_evm_coder_substrate::call;
+use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
use crate::{
AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,
@@ -180,8 +181,11 @@
let from = T::CrossAccountId::from_eth(from);
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_from(self, &caller, &from, &to, token)
+ <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)
.map_err(dispatch_to_evm::<T>)?;
Ok(())
}
@@ -350,8 +354,12 @@
let caller = T::CrossAccountId::from_eth(caller);
let from = T::CrossAccountId::from_eth(from);
let token = token_id.try_into()?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
- <Pallet<T>>::burn_from(self, &caller, &from, token).map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
Ok(())
}
pallets/nonfungible/src/lib.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/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use frame_support::{BoundedVec, ensure, fail};21use up_data_structs::{22 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,23 mapping::TokenAddressMapping, NestingRule,24};25use pallet_evm::account::CrossAccountId;26use pallet_common::{27 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent,28 CollectionHandle, dispatch::CollectionDispatch,29};30use pallet_structure::Pallet as PalletStructure;31use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};32use sp_core::H160;33use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};34use sp_std::{vec::Vec, vec};35use core::ops::Deref;36use sp_std::collections::btree_map::BTreeMap;37use codec::{Encode, Decode, MaxEncodedLen};38use scale_info::TypeInfo;3940pub use pallet::*;41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod common;44pub mod erc;45pub mod weights;4647pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;48pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4950#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]51pub struct ItemData<CrossAccountId> {52 pub const_data: BoundedVec<u8, CustomDataLimit>,53 pub variable_data: BoundedVec<u8, CustomDataLimit>,54 pub owner: CrossAccountId,55}5657#[frame_support::pallet]58pub mod pallet {59 use super::*;60 use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};61 use up_data_structs::{CollectionId, TokenId};62 use super::weights::WeightInfo;6364 #[pallet::error]65 pub enum Error<T> {66 /// Not Nonfungible item data used to mint in Nonfungible collection.67 NotNonfungibleDataUsedToMintFungibleCollectionToken,68 /// Used amount > 1 with NFT69 NonfungibleItemsHaveNoAmount,70 }7172 #[pallet::config]73 pub trait Config:74 frame_system::Config + pallet_common::Config + pallet_structure::Config75 {76 type WeightInfo: WeightInfo;77 }7879 #[pallet::pallet]80 #[pallet::generate_store(pub(super) trait Store)]81 pub struct Pallet<T>(_);8283 #[pallet::storage]84 pub type TokensMinted<T: Config> =85 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;86 #[pallet::storage]87 pub type TokensBurnt<T: Config> =88 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;8990 #[pallet::storage]91 pub type TokenData<T: Config> = StorageNMap<92 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),93 Value = ItemData<T::CrossAccountId>,94 QueryKind = OptionQuery,95 >;9697 /// Used to enumerate tokens owned by account98 #[pallet::storage]99 pub type Owned<T: Config> = StorageNMap<100 Key = (101 Key<Twox64Concat, CollectionId>,102 Key<Blake2_128Concat, T::CrossAccountId>,103 Key<Twox64Concat, TokenId>,104 ),105 Value = bool,106 QueryKind = ValueQuery,107 >;108109 #[pallet::storage]110 pub type AccountBalance<T: Config> = StorageNMap<111 Key = (112 Key<Twox64Concat, CollectionId>,113 Key<Blake2_128Concat, T::CrossAccountId>,114 ),115 Value = u32,116 QueryKind = ValueQuery,117 >;118119 #[pallet::storage]120 pub type Allowance<T: Config> = StorageNMap<121 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),122 Value = T::CrossAccountId,123 QueryKind = OptionQuery,124 >;125}126127pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);128impl<T: Config> NonfungibleHandle<T> {129 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {130 Self(inner)131 }132 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {133 self.0134 }135}136impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {137 fn recorder(&self) -> &SubstrateRecorder<T> {138 self.0.recorder()139 }140 fn into_recorder(self) -> SubstrateRecorder<T> {141 self.0.into_recorder()142 }143}144impl<T: Config> Deref for NonfungibleHandle<T> {145 type Target = pallet_common::CollectionHandle<T>;146147 fn deref(&self) -> &Self::Target {148 &self.0149 }150}151152impl<T: Config> Pallet<T> {153 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {154 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)155 }156 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {157 <TokenData<T>>::contains_key((collection.id, token))158 }159}160161// unchecked calls skips any permission checks162impl<T: Config> Pallet<T> {163 pub fn init_collection(164 owner: T::AccountId,165 data: CreateCollectionData<T::AccountId>,166 ) -> Result<CollectionId, DispatchError> {167 <PalletCommon<T>>::init_collection(owner, data)168 }169 pub fn destroy_collection(170 collection: NonfungibleHandle<T>,171 sender: &T::CrossAccountId,172 ) -> DispatchResult {173 let id = collection.id;174175 // =========176177 PalletCommon::destroy_collection(collection.0, sender)?;178179 <TokenData<T>>::remove_prefix((id,), None);180 <Owned<T>>::remove_prefix((id,), None);181 <TokensMinted<T>>::remove(id);182 <TokensBurnt<T>>::remove(id);183 <Allowance<T>>::remove_prefix((id,), None);184 <AccountBalance<T>>::remove_prefix((id,), None);185 Ok(())186 }187188 pub fn burn(189 collection: &NonfungibleHandle<T>,190 sender: &T::CrossAccountId,191 token: TokenId,192 ) -> DispatchResult {193 let token_data =194 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;195 ensure!(196 &token_data.owner == sender197 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),198 <CommonError<T>>::NoPermission199 );200201 if collection.access == AccessMode::AllowList {202 collection.check_allowlist(sender)?;203 }204205 let burnt = <TokensBurnt<T>>::get(collection.id)206 .checked_add(1)207 .ok_or(ArithmeticError::Overflow)?;208209 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))210 .checked_sub(1)211 .ok_or(ArithmeticError::Overflow)?;212213 if balance == 0 {214 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));215 } else {216 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);217 }218 // =========219220 <Owned<T>>::remove((collection.id, &token_data.owner, token));221 <TokensBurnt<T>>::insert(collection.id, burnt);222 <TokenData<T>>::remove((collection.id, token));223 let old_spender = <Allowance<T>>::take((collection.id, token));224225 if let Some(old_spender) = old_spender {226 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(227 collection.id,228 token,229 sender.clone(),230 old_spender,231 0,232 ));233 }234235 collection.log_mirrored(ERC721Events::Transfer {236 from: *token_data.owner.as_eth(),237 to: H160::default(),238 token_id: token.into(),239 });240 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(241 collection.id,242 token,243 token_data.owner,244 1,245 ));246 Ok(())247 }248249 pub fn transfer(250 collection: &NonfungibleHandle<T>,251 from: &T::CrossAccountId,252 to: &T::CrossAccountId,253 token: TokenId,254 ) -> DispatchResult {255 ensure!(256 collection.limits.transfers_enabled(),257 <CommonError<T>>::TransferNotAllowed258 );259260 let token_data =261 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;262 // TODO: require sender to be token, owner, require admins to go through transfer_from263 ensure!(264 &token_data.owner == from265 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),266 <CommonError<T>>::NoPermission267 );268269 if collection.access == AccessMode::AllowList {270 collection.check_allowlist(from)?;271 collection.check_allowlist(to)?;272 }273 <PalletCommon<T>>::ensure_correct_receiver(to)?;274275 let balance_from = <AccountBalance<T>>::get((collection.id, from))276 .checked_sub(1)277 .ok_or(<CommonError<T>>::TokenValueTooLow)?;278 let balance_to = if from != to {279 let balance_to = <AccountBalance<T>>::get((collection.id, to))280 .checked_add(1)281 .ok_or(ArithmeticError::Overflow)?;282283 ensure!(284 balance_to < collection.limits.account_token_ownership_limit(),285 <CommonError<T>>::AccountTokenLimitExceeded,286 );287288 Some(balance_to)289 } else {290 None291 };292293 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {294 let handle = <CollectionHandle<T>>::try_get(target.0)?;295 let dispatch = T::CollectionDispatch::dispatch(handle);296 let dispatch = dispatch.as_dyn();297298 // =========299300 dispatch.nest_token(from.clone(), (collection.id, token), target.1)?;301 }302303 <TokenData<T>>::insert(304 (collection.id, token),305 ItemData {306 owner: to.clone(),307 ..token_data308 },309 );310311 if let Some(balance_to) = balance_to {312 // from != to313 if balance_from == 0 {314 <AccountBalance<T>>::remove((collection.id, from));315 } else {316 <AccountBalance<T>>::insert((collection.id, from), balance_from);317 }318 <AccountBalance<T>>::insert((collection.id, to), balance_to);319 <Owned<T>>::remove((collection.id, from, token));320 <Owned<T>>::insert((collection.id, to, token), true);321 }322 Self::set_allowance_unchecked(collection, from, token, None, true);323324 collection.log_mirrored(ERC721Events::Transfer {325 from: *from.as_eth(),326 to: *to.as_eth(),327 token_id: token.into(),328 });329 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(330 collection.id,331 token,332 from.clone(),333 to.clone(),334 1,335 ));336 Ok(())337 }338339 pub fn create_multiple_items(340 collection: &NonfungibleHandle<T>,341 sender: &T::CrossAccountId,342 data: Vec<CreateItemData<T>>,343 ) -> DispatchResult {344 if !collection.is_owner_or_admin(sender) {345 ensure!(346 collection.mint_mode,347 <CommonError<T>>::PublicMintingNotAllowed348 );349 collection.check_allowlist(sender)?;350351 for item in data.iter() {352 collection.check_allowlist(&item.owner)?;353 }354 }355356 for data in data.iter() {357 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;358 }359360 let first_token = <TokensMinted<T>>::get(collection.id);361 let tokens_minted = first_token362 .checked_add(data.len() as u32)363 .ok_or(ArithmeticError::Overflow)?;364 ensure!(365 tokens_minted <= collection.limits.token_limit(),366 <CommonError<T>>::CollectionTokenLimitExceeded367 );368369 let mut balances = BTreeMap::new();370 for data in &data {371 let balance = balances372 .entry(&data.owner)373 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));374 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;375376 ensure!(377 *balance <= collection.limits.account_token_ownership_limit(),378 <CommonError<T>>::AccountTokenLimitExceeded,379 );380 }381382 // =========383384 <TokensMinted<T>>::insert(collection.id, tokens_minted);385 for (account, balance) in balances {386 <AccountBalance<T>>::insert((collection.id, account), balance);387 }388 for (i, data) in data.into_iter().enumerate() {389 let token = first_token + i as u32 + 1;390391 <TokenData<T>>::insert(392 (collection.id, token),393 ItemData {394 const_data: data.const_data,395 variable_data: data.variable_data,396 owner: data.owner.clone(),397 },398 );399 <Owned<T>>::insert((collection.id, &data.owner, token), true);400401 collection.log_mirrored(ERC721Events::Transfer {402 from: H160::default(),403 to: *data.owner.as_eth(),404 token_id: token.into(),405 });406 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(407 collection.id,408 TokenId(token),409 data.owner.clone(),410 1,411 ));412 }413 Ok(())414 }415416 pub fn set_allowance_unchecked(417 collection: &NonfungibleHandle<T>,418 sender: &T::CrossAccountId,419 token: TokenId,420 spender: Option<&T::CrossAccountId>,421 assume_implicit_eth: bool,422 ) {423 if let Some(spender) = spender {424 let old_spender = <Allowance<T>>::get((collection.id, token));425 <Allowance<T>>::insert((collection.id, token), spender);426 // In ERC721 there is only one possible approved user of token, so we set427 // approved user to spender428 collection.log_mirrored(ERC721Events::Approval {429 owner: *sender.as_eth(),430 approved: *spender.as_eth(),431 token_id: token.into(),432 });433 // In Unique chain, any token can have any amount of approved users, so we need to434 // set allowance of old owner to 0, and allowance of new owner to 1435 if old_spender.as_ref() != Some(spender) {436 if let Some(old_owner) = old_spender {437 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(438 collection.id,439 token,440 sender.clone(),441 old_owner,442 0,443 ));444 }445 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(446 collection.id,447 token,448 sender.clone(),449 spender.clone(),450 1,451 ));452 }453 } else {454 let old_spender = <Allowance<T>>::take((collection.id, token));455 if !assume_implicit_eth {456 // In ERC721 there is only one possible approved user of token, so we set457 // approved user to zero address458 collection.log_mirrored(ERC721Events::Approval {459 owner: *sender.as_eth(),460 approved: H160::default(),461 token_id: token.into(),462 });463 }464 // In Unique chain, any token can have any amount of approved users, so we need to465 // set allowance of old owner to 0466 if let Some(old_spender) = old_spender {467 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(468 collection.id,469 token,470 sender.clone(),471 old_spender,472 0,473 ));474 }475 }476 }477478 pub fn set_allowance(479 collection: &NonfungibleHandle<T>,480 sender: &T::CrossAccountId,481 token: TokenId,482 spender: Option<&T::CrossAccountId>,483 ) -> DispatchResult {484 if collection.access == AccessMode::AllowList {485 collection.check_allowlist(sender)?;486 if let Some(spender) = spender {487 collection.check_allowlist(spender)?;488 }489 }490491 if let Some(spender) = spender {492 <PalletCommon<T>>::ensure_correct_receiver(spender)?;493 }494 let token_data =495 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;496 if &token_data.owner != sender {497 ensure!(498 collection.ignores_owned_amount(sender),499 <CommonError<T>>::CantApproveMoreThanOwned500 );501 }502503 // =========504505 Self::set_allowance_unchecked(collection, sender, token, spender, false);506 Ok(())507 }508509 fn check_allowed(510 collection: &NonfungibleHandle<T>,511 spender: &T::CrossAccountId,512 from: &T::CrossAccountId,513 token: TokenId,514 ) -> DispatchResult {515 if spender.conv_eq(from) {516 return Ok(());517 }518 if collection.access == AccessMode::AllowList {519 // `from`, `to` checked in [`transfer`]520 collection.check_allowlist(spender)?;521 }522 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {523 // TODO: should collection owner be allowed to perform this transfer?524 ensure!(525 <PalletStructure<T>>::indirectly_owned(spender.clone(), source.0, source.1, 1)?,526 <CommonError<T>>::ApprovedValueTooLow,527 );528 return Ok(());529 }530 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {531 return Ok(());532 }533 ensure!(534 collection.ignores_allowance(spender),535 <CommonError<T>>::ApprovedValueTooLow536 );537 Ok(())538 }539540 pub fn transfer_from(541 collection: &NonfungibleHandle<T>,542 spender: &T::CrossAccountId,543 from: &T::CrossAccountId,544 to: &T::CrossAccountId,545 token: TokenId,546 ) -> DispatchResult {547 Self::check_allowed(collection, spender, from, token)?;548549 // =========550551 // Allowance is reset in [`transfer`]552 Self::transfer(collection, from, to, token)553 }554555 pub fn burn_from(556 collection: &NonfungibleHandle<T>,557 spender: &T::CrossAccountId,558 from: &T::CrossAccountId,559 token: TokenId,560 ) -> DispatchResult {561 Self::check_allowed(collection, spender, from, token)?;562563 // =========564565 Self::burn(collection, from, token)566 }567568 pub fn set_variable_metadata(569 collection: &NonfungibleHandle<T>,570 sender: &T::CrossAccountId,571 token: TokenId,572 data: BoundedVec<u8, CustomDataLimit>,573 ) -> DispatchResult {574 let token_data =575 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;576 collection.check_can_update_meta(sender, &token_data.owner)?;577578 // =========579580 <TokenData<T>>::insert(581 (collection.id, token),582 ItemData {583 variable_data: data,584 ..token_data585 },586 );587 Ok(())588 }589590 pub fn nest_token(591 handle: &NonfungibleHandle<T>,592 sender: T::CrossAccountId,593 from: CollectionId,594 under: TokenId,595 ) -> DispatchResult {596 fn ensure_sender_allowed<T: Config>(597 collection: CollectionId,598 token: TokenId,599 sender: T::CrossAccountId,600 ) -> DispatchResult {601 ensure!(602 <TokenData<T>>::get((collection, token))603 .ok_or(<CommonError<T>>::TokenNotFound)?604 .owner605 .conv_eq(&sender),606 <CommonError<T>>::OnlyOwnerAllowedToNest,607 );608 Ok(())609 }610 match handle.limits.nesting_rule() {611 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),612 NestingRule::Owner => ensure_sender_allowed::<T>(from, under, sender)?,613 NestingRule::OwnerRestricted(whitelist) => {614 ensure!(615 whitelist.contains(&from),616 <CommonError<T>>::SourceCollectionIsNotAllowedToNest617 );618 ensure_sender_allowed::<T>(from, under, sender)?619 }620 }621 Ok(())622 }623624 /// Delegated to `create_multiple_items`625 pub fn create_item(626 collection: &NonfungibleHandle<T>,627 sender: &T::CrossAccountId,628 data: CreateItemData<T>,629 ) -> DispatchResult {630 Self::create_multiple_items(collection, sender, vec![data])631 }632}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/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use frame_support::{BoundedVec, ensure, fail};21use up_data_structs::{22 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,23 mapping::TokenAddressMapping, NestingRule, budget::Budget,24};25use pallet_evm::account::CrossAccountId;26use pallet_common::{27 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent,28 CollectionHandle, dispatch::CollectionDispatch,29};30use pallet_structure::Pallet as PalletStructure;31use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};32use sp_core::H160;33use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};34use sp_std::{vec::Vec, vec};35use core::ops::Deref;36use sp_std::collections::btree_map::BTreeMap;37use codec::{Encode, Decode, MaxEncodedLen};38use scale_info::TypeInfo;3940pub use pallet::*;41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod common;44pub mod erc;45pub mod weights;4647pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;48pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4950#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]51pub struct ItemData<CrossAccountId> {52 pub const_data: BoundedVec<u8, CustomDataLimit>,53 pub variable_data: BoundedVec<u8, CustomDataLimit>,54 pub owner: CrossAccountId,55}5657#[frame_support::pallet]58pub mod pallet {59 use super::*;60 use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};61 use up_data_structs::{CollectionId, TokenId};62 use super::weights::WeightInfo;6364 #[pallet::error]65 pub enum Error<T> {66 /// Not Nonfungible item data used to mint in Nonfungible collection.67 NotNonfungibleDataUsedToMintFungibleCollectionToken,68 /// Used amount > 1 with NFT69 NonfungibleItemsHaveNoAmount,70 }7172 #[pallet::config]73 pub trait Config:74 frame_system::Config + pallet_common::Config + pallet_structure::Config75 {76 type WeightInfo: WeightInfo;77 }7879 #[pallet::pallet]80 #[pallet::generate_store(pub(super) trait Store)]81 pub struct Pallet<T>(_);8283 #[pallet::storage]84 pub type TokensMinted<T: Config> =85 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;86 #[pallet::storage]87 pub type TokensBurnt<T: Config> =88 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;8990 #[pallet::storage]91 pub type TokenData<T: Config> = StorageNMap<92 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),93 Value = ItemData<T::CrossAccountId>,94 QueryKind = OptionQuery,95 >;9697 /// Used to enumerate tokens owned by account98 #[pallet::storage]99 pub type Owned<T: Config> = StorageNMap<100 Key = (101 Key<Twox64Concat, CollectionId>,102 Key<Blake2_128Concat, T::CrossAccountId>,103 Key<Twox64Concat, TokenId>,104 ),105 Value = bool,106 QueryKind = ValueQuery,107 >;108109 #[pallet::storage]110 pub type AccountBalance<T: Config> = StorageNMap<111 Key = (112 Key<Twox64Concat, CollectionId>,113 Key<Blake2_128Concat, T::CrossAccountId>,114 ),115 Value = u32,116 QueryKind = ValueQuery,117 >;118119 #[pallet::storage]120 pub type Allowance<T: Config> = StorageNMap<121 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),122 Value = T::CrossAccountId,123 QueryKind = OptionQuery,124 >;125}126127pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);128impl<T: Config> NonfungibleHandle<T> {129 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {130 Self(inner)131 }132 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {133 self.0134 }135}136impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {137 fn recorder(&self) -> &SubstrateRecorder<T> {138 self.0.recorder()139 }140 fn into_recorder(self) -> SubstrateRecorder<T> {141 self.0.into_recorder()142 }143}144impl<T: Config> Deref for NonfungibleHandle<T> {145 type Target = pallet_common::CollectionHandle<T>;146147 fn deref(&self) -> &Self::Target {148 &self.0149 }150}151152impl<T: Config> Pallet<T> {153 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {154 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)155 }156 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {157 <TokenData<T>>::contains_key((collection.id, token))158 }159}160161// unchecked calls skips any permission checks162impl<T: Config> Pallet<T> {163 pub fn init_collection(164 owner: T::AccountId,165 data: CreateCollectionData<T::AccountId>,166 ) -> Result<CollectionId, DispatchError> {167 <PalletCommon<T>>::init_collection(owner, data)168 }169 pub fn destroy_collection(170 collection: NonfungibleHandle<T>,171 sender: &T::CrossAccountId,172 ) -> DispatchResult {173 let id = collection.id;174175 // =========176177 PalletCommon::destroy_collection(collection.0, sender)?;178179 <TokenData<T>>::remove_prefix((id,), None);180 <Owned<T>>::remove_prefix((id,), None);181 <TokensMinted<T>>::remove(id);182 <TokensBurnt<T>>::remove(id);183 <Allowance<T>>::remove_prefix((id,), None);184 <AccountBalance<T>>::remove_prefix((id,), None);185 Ok(())186 }187188 pub fn burn(189 collection: &NonfungibleHandle<T>,190 sender: &T::CrossAccountId,191 token: TokenId,192 ) -> DispatchResult {193 let token_data =194 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;195 ensure!(196 &token_data.owner == sender197 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),198 <CommonError<T>>::NoPermission199 );200201 if collection.access == AccessMode::AllowList {202 collection.check_allowlist(sender)?;203 }204205 let burnt = <TokensBurnt<T>>::get(collection.id)206 .checked_add(1)207 .ok_or(ArithmeticError::Overflow)?;208209 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))210 .checked_sub(1)211 .ok_or(ArithmeticError::Overflow)?;212213 if balance == 0 {214 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));215 } else {216 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);217 }218 // =========219220 <Owned<T>>::remove((collection.id, &token_data.owner, token));221 <TokensBurnt<T>>::insert(collection.id, burnt);222 <TokenData<T>>::remove((collection.id, token));223 let old_spender = <Allowance<T>>::take((collection.id, token));224225 if let Some(old_spender) = old_spender {226 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(227 collection.id,228 token,229 sender.clone(),230 old_spender,231 0,232 ));233 }234235 collection.log_mirrored(ERC721Events::Transfer {236 from: *token_data.owner.as_eth(),237 to: H160::default(),238 token_id: token.into(),239 });240 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(241 collection.id,242 token,243 token_data.owner,244 1,245 ));246 Ok(())247 }248249 pub fn transfer(250 collection: &NonfungibleHandle<T>,251 from: &T::CrossAccountId,252 to: &T::CrossAccountId,253 token: TokenId,254 ) -> DispatchResult {255 ensure!(256 collection.limits.transfers_enabled(),257 <CommonError<T>>::TransferNotAllowed258 );259260 let token_data =261 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;262 // TODO: require sender to be token, owner, require admins to go through transfer_from263 ensure!(264 &token_data.owner == from265 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),266 <CommonError<T>>::NoPermission267 );268269 if collection.access == AccessMode::AllowList {270 collection.check_allowlist(from)?;271 collection.check_allowlist(to)?;272 }273 <PalletCommon<T>>::ensure_correct_receiver(to)?;274275 let balance_from = <AccountBalance<T>>::get((collection.id, from))276 .checked_sub(1)277 .ok_or(<CommonError<T>>::TokenValueTooLow)?;278 let balance_to = if from != to {279 let balance_to = <AccountBalance<T>>::get((collection.id, to))280 .checked_add(1)281 .ok_or(ArithmeticError::Overflow)?;282283 ensure!(284 balance_to < collection.limits.account_token_ownership_limit(),285 <CommonError<T>>::AccountTokenLimitExceeded,286 );287288 Some(balance_to)289 } else {290 None291 };292293 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {294 let handle = <CollectionHandle<T>>::try_get(target.0)?;295 let dispatch = T::CollectionDispatch::dispatch(handle);296 let dispatch = dispatch.as_dyn();297298 // =========299300 dispatch.nest_token(from.clone(), (collection.id, token), target.1)?;301 }302303 <TokenData<T>>::insert(304 (collection.id, token),305 ItemData {306 owner: to.clone(),307 ..token_data308 },309 );310311 if let Some(balance_to) = balance_to {312 // from != to313 if balance_from == 0 {314 <AccountBalance<T>>::remove((collection.id, from));315 } else {316 <AccountBalance<T>>::insert((collection.id, from), balance_from);317 }318 <AccountBalance<T>>::insert((collection.id, to), balance_to);319 <Owned<T>>::remove((collection.id, from, token));320 <Owned<T>>::insert((collection.id, to, token), true);321 }322 Self::set_allowance_unchecked(collection, from, token, None, true);323324 collection.log_mirrored(ERC721Events::Transfer {325 from: *from.as_eth(),326 to: *to.as_eth(),327 token_id: token.into(),328 });329 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(330 collection.id,331 token,332 from.clone(),333 to.clone(),334 1,335 ));336 Ok(())337 }338339 pub fn create_multiple_items(340 collection: &NonfungibleHandle<T>,341 sender: &T::CrossAccountId,342 data: Vec<CreateItemData<T>>,343 ) -> DispatchResult {344 if !collection.is_owner_or_admin(sender) {345 ensure!(346 collection.mint_mode,347 <CommonError<T>>::PublicMintingNotAllowed348 );349 collection.check_allowlist(sender)?;350351 for item in data.iter() {352 collection.check_allowlist(&item.owner)?;353 }354 }355356 for data in data.iter() {357 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;358 }359360 let first_token = <TokensMinted<T>>::get(collection.id);361 let tokens_minted = first_token362 .checked_add(data.len() as u32)363 .ok_or(ArithmeticError::Overflow)?;364 ensure!(365 tokens_minted <= collection.limits.token_limit(),366 <CommonError<T>>::CollectionTokenLimitExceeded367 );368369 let mut balances = BTreeMap::new();370 for data in &data {371 let balance = balances372 .entry(&data.owner)373 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));374 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;375376 ensure!(377 *balance <= collection.limits.account_token_ownership_limit(),378 <CommonError<T>>::AccountTokenLimitExceeded,379 );380 }381382 // =========383384 <TokensMinted<T>>::insert(collection.id, tokens_minted);385 for (account, balance) in balances {386 <AccountBalance<T>>::insert((collection.id, account), balance);387 }388 for (i, data) in data.into_iter().enumerate() {389 let token = first_token + i as u32 + 1;390391 <TokenData<T>>::insert(392 (collection.id, token),393 ItemData {394 const_data: data.const_data,395 variable_data: data.variable_data,396 owner: data.owner.clone(),397 },398 );399 <Owned<T>>::insert((collection.id, &data.owner, token), true);400401 collection.log_mirrored(ERC721Events::Transfer {402 from: H160::default(),403 to: *data.owner.as_eth(),404 token_id: token.into(),405 });406 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(407 collection.id,408 TokenId(token),409 data.owner.clone(),410 1,411 ));412 }413 Ok(())414 }415416 pub fn set_allowance_unchecked(417 collection: &NonfungibleHandle<T>,418 sender: &T::CrossAccountId,419 token: TokenId,420 spender: Option<&T::CrossAccountId>,421 assume_implicit_eth: bool,422 ) {423 if let Some(spender) = spender {424 let old_spender = <Allowance<T>>::get((collection.id, token));425 <Allowance<T>>::insert((collection.id, token), spender);426 // In ERC721 there is only one possible approved user of token, so we set427 // approved user to spender428 collection.log_mirrored(ERC721Events::Approval {429 owner: *sender.as_eth(),430 approved: *spender.as_eth(),431 token_id: token.into(),432 });433 // In Unique chain, any token can have any amount of approved users, so we need to434 // set allowance of old owner to 0, and allowance of new owner to 1435 if old_spender.as_ref() != Some(spender) {436 if let Some(old_owner) = old_spender {437 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(438 collection.id,439 token,440 sender.clone(),441 old_owner,442 0,443 ));444 }445 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(446 collection.id,447 token,448 sender.clone(),449 spender.clone(),450 1,451 ));452 }453 } else {454 let old_spender = <Allowance<T>>::take((collection.id, token));455 if !assume_implicit_eth {456 // In ERC721 there is only one possible approved user of token, so we set457 // approved user to zero address458 collection.log_mirrored(ERC721Events::Approval {459 owner: *sender.as_eth(),460 approved: H160::default(),461 token_id: token.into(),462 });463 }464 // In Unique chain, any token can have any amount of approved users, so we need to465 // set allowance of old owner to 0466 if let Some(old_spender) = old_spender {467 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(468 collection.id,469 token,470 sender.clone(),471 old_spender,472 0,473 ));474 }475 }476 }477478 pub fn set_allowance(479 collection: &NonfungibleHandle<T>,480 sender: &T::CrossAccountId,481 token: TokenId,482 spender: Option<&T::CrossAccountId>,483 ) -> DispatchResult {484 if collection.access == AccessMode::AllowList {485 collection.check_allowlist(sender)?;486 if let Some(spender) = spender {487 collection.check_allowlist(spender)?;488 }489 }490491 if let Some(spender) = spender {492 <PalletCommon<T>>::ensure_correct_receiver(spender)?;493 }494 let token_data =495 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;496 if &token_data.owner != sender {497 ensure!(498 collection.ignores_owned_amount(sender),499 <CommonError<T>>::CantApproveMoreThanOwned500 );501 }502503 // =========504505 Self::set_allowance_unchecked(collection, sender, token, spender, false);506 Ok(())507 }508509 fn check_allowed(510 collection: &NonfungibleHandle<T>,511 spender: &T::CrossAccountId,512 from: &T::CrossAccountId,513 token: TokenId,514 nesting_budget: &dyn Budget,515 ) -> DispatchResult {516 if spender.conv_eq(from) {517 return Ok(());518 }519 if collection.access == AccessMode::AllowList {520 // `from`, `to` checked in [`transfer`]521 collection.check_allowlist(spender)?;522 }523 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {524 // TODO: should collection owner be allowed to perform this transfer?525 ensure!(526 <PalletStructure<T>>::indirectly_owned(527 spender.clone(),528 source.0,529 source.1,530 nesting_budget531 )?,532 <CommonError<T>>::ApprovedValueTooLow,533 );534 return Ok(());535 }536 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {537 return Ok(());538 }539 ensure!(540 collection.ignores_allowance(spender),541 <CommonError<T>>::ApprovedValueTooLow542 );543 Ok(())544 }545546 pub fn transfer_from(547 collection: &NonfungibleHandle<T>,548 spender: &T::CrossAccountId,549 from: &T::CrossAccountId,550 to: &T::CrossAccountId,551 token: TokenId,552 nesting_budget: &dyn Budget,553 ) -> DispatchResult {554 Self::check_allowed(collection, spender, from, token, nesting_budget)?;555556 // =========557558 // Allowance is reset in [`transfer`]559 Self::transfer(collection, from, to, token)560 }561562 pub fn burn_from(563 collection: &NonfungibleHandle<T>,564 spender: &T::CrossAccountId,565 from: &T::CrossAccountId,566 token: TokenId,567 nesting_budget: &dyn Budget,568 ) -> DispatchResult {569 Self::check_allowed(collection, spender, from, token, nesting_budget)?;570571 // =========572573 Self::burn(collection, from, token)574 }575576 pub fn set_variable_metadata(577 collection: &NonfungibleHandle<T>,578 sender: &T::CrossAccountId,579 token: TokenId,580 data: BoundedVec<u8, CustomDataLimit>,581 ) -> DispatchResult {582 let token_data =583 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;584 collection.check_can_update_meta(sender, &token_data.owner)?;585586 // =========587588 <TokenData<T>>::insert(589 (collection.id, token),590 ItemData {591 variable_data: data,592 ..token_data593 },594 );595 Ok(())596 }597598 pub fn nest_token(599 handle: &NonfungibleHandle<T>,600 sender: T::CrossAccountId,601 from: CollectionId,602 under: TokenId,603 ) -> DispatchResult {604 fn ensure_sender_allowed<T: Config>(605 collection: CollectionId,606 token: TokenId,607 sender: T::CrossAccountId,608 ) -> DispatchResult {609 ensure!(610 <TokenData<T>>::get((collection, token))611 .ok_or(<CommonError<T>>::TokenNotFound)?612 .owner613 .conv_eq(&sender),614 <CommonError<T>>::OnlyOwnerAllowedToNest,615 );616 Ok(())617 }618 match handle.limits.nesting_rule() {619 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),620 NestingRule::Owner => ensure_sender_allowed::<T>(from, under, sender)?,621 NestingRule::OwnerRestricted(whitelist) => {622 ensure!(623 whitelist.contains(&from),624 <CommonError<T>>::SourceCollectionIsNotAllowedToNest625 );626 ensure_sender_allowed::<T>(from, under, sender)?627 }628 }629 Ok(())630 }631632 /// Delegated to `create_multiple_items`633 pub fn create_item(634 collection: &NonfungibleHandle<T>,635 sender: &T::CrossAccountId,636 data: CreateItemData<T>,637 ) -> DispatchResult {638 Self::create_multiple_items(collection, sender, vec![data])639 }640}pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -20,7 +20,7 @@
use sp_std::prelude::*;
use pallet_common::benchmarking::{create_collection_raw, create_data, create_var_data};
use frame_benchmarking::{benchmarks, account};
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, CUSTOM_DATA_LIMIT};
+use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, CUSTOM_DATA_LIMIT, budget::Unlimited};
use pallet_common::bench_init;
use core::convert::TryInto;
use core::iter::IntoIterator;
@@ -165,7 +165,7 @@
};
let item = create_max_item(&collection, &owner, [(sender.clone(), 200), (receiver.clone(), 200)])?;
<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?;
- }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 100)?}
+ }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 100, &Unlimited)?}
// Target account is created
transfer_from_creating {
bench_init!{
@@ -174,7 +174,7 @@
};
let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?;
- }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 100)?}
+ }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 100, &Unlimited)?}
// Source account is destroyed
transfer_from_removing {
bench_init!{
@@ -183,7 +183,7 @@
};
let item = create_max_item(&collection, &owner, [(sender.clone(), 200), (receiver.clone(), 200)])?;
<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 200)?;
- }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 200)?}
+ }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 200, &Unlimited)?}
// Source account destroyed, target created
transfer_from_creating_removing {
bench_init!{
@@ -192,7 +192,7 @@
};
let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 200)?;
- }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 200)?}
+ }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 200, &Unlimited)?}
// Both source account and token is destroyed
burn_from {
@@ -202,7 +202,7 @@
};
let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
<Pallet<T>>::set_allowance(&collection, &sender, &burner, item, 200)?;
- }: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item, 200)?}
+ }: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item, 200, &Unlimited)?}
set_variable_metadata {
let b in 0..CUSTOM_DATA_LIMIT;
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -18,7 +18,9 @@
use sp_std::collections::btree_map::BTreeMap;
use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight, BoundedVec};
-use up_data_structs::{TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData};
+use up_data_structs::{
+ TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData, budget::Budget,
+};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
use sp_std::{vec::Vec, vec};
@@ -210,9 +212,10 @@
to: T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
with_weight(
- <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount),
+ <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),
<CommonWeights<T>>::transfer_from(),
)
}
@@ -223,9 +226,10 @@
from: T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
with_weight(
- <Pallet<T>>::burn_from(self, &sender, &from, token, amount),
+ <Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),
<CommonWeights<T>>::burn_from(),
)
}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -19,7 +19,7 @@
use frame_support::{ensure, BoundedVec};
use up_data_structs::{
AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,
- CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping,
+ CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping, budget::Budget,
};
use pallet_evm::account::CrossAccountId;
use pallet_common::{
@@ -544,6 +544,7 @@
from: &T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> Result<Option<u128>, DispatchError> {
if spender.conv_eq(from) {
return Ok(None);
@@ -555,7 +556,12 @@
if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
// TODO: should collection owner be allowed to perform this transfer?
ensure!(
- <PalletStructure<T>>::indirectly_owned(spender.clone(), source.0, source.1, 1)?,
+ <PalletStructure<T>>::indirectly_owned(
+ spender.clone(),
+ source.0,
+ source.1,
+ nesting_budget
+ )?,
<CommonError<T>>::ApprovedValueTooLow,
);
return Ok(None);
@@ -578,8 +584,10 @@
to: &T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
- let allowance = Self::check_allowed(collection, spender, from, token, amount)?;
+ let allowance =
+ Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;
// =========
@@ -596,8 +604,10 @@
from: &T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
- let allowance = Self::check_allowed(collection, spender, from, token, amount)?;
+ let allowance =
+ Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;
// =========
pallets/structure/src/lib.rsdiffbeforeafterboth--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -6,8 +6,14 @@
use frame_support::fail;
pub use pallet::*;
use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};
-use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping};
+use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};
+#[cfg(feature = "runtime-benchmarks")]
+pub mod benchmarking;
+pub mod weights;
+
+pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;
+
#[frame_support::pallet]
pub mod pallet {
use frame_support::Parameter;
@@ -35,6 +41,7 @@
#[pallet::config]
pub trait Config: frame_system::Config + pallet_common::Config {
+ type WeightInfo: weights::WeightInfo;
type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;
type Call: Parameter + UnfilteredDispatchable<Origin = Self::Origin> + GetDispatchInfo;
}
@@ -127,10 +134,10 @@
pub fn find_topmost_owner(
collection: CollectionId,
token: TokenId,
- max_depth: u32,
+ budget: &dyn Budget,
) -> Result<T::CrossAccountId, DispatchError> {
let owner = Self::parent_chain(collection, token)
- .take(max_depth as usize)
+ .take_while(|_| budget.consume())
.find(|p| matches!(p, Ok(Parent::Normal(_) | Parent::TokenNotFound)))
.ok_or(<Error<T>>::DepthLimit)??;
@@ -145,7 +152,7 @@
user: T::CrossAccountId,
collection: CollectionId,
token: TokenId,
- max_depth: u32,
+ budget: &dyn Budget,
) -> Result<bool, DispatchError> {
let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {
Some((collection, token)) => Parent::Token(collection, token),
@@ -153,7 +160,7 @@
};
Ok(Self::parent_chain(collection, token)
- .take(max_depth as usize)
+ .take_while(|_| budget.consume())
.any(|parent| Ok(&target_parent) == parent.as_ref()))
}
}
pallets/unique/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/unique/src/benchmarking.rs
+++ b/pallets/unique/src/benchmarking.rs
@@ -19,8 +19,8 @@
use super::*;
use crate::Pallet;
use frame_system::RawOrigin;
+use frame_support::traits::{tokens::currency::Currency, Get};
use frame_benchmarking::{benchmarks, account};
-use up_data_structs::*;
use sp_runtime::DispatchError;
use pallet_common::benchmarking::{create_data, create_var_data, create_u16_data};
@@ -173,6 +173,7 @@
owner_can_transfer: Some(true),
sponsored_data_rate_limit: None,
transfers_enabled: Some(true),
+ nesting_rule: None,
};
}: set_collection_limits(RawOrigin::Signed(caller.clone()), collection, cl)
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -43,7 +43,7 @@
MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,
SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData, CustomDataLimit,
- CreateItemExData,
+ CreateItemExData, budget,
};
use pallet_evm::account::CrossAccountId;
use pallet_common::{
@@ -807,8 +807,9 @@
#[transactional]
pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, 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.burn_from(sender, from, item_id, value))
+ dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value, &budget))
}
/// Change ownership of the token.
@@ -888,8 +889,9 @@
#[transactional]
pub fn transfer_from(origin, from: T::CrossAccountId, 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_from(sender, from, recipient, item_id, value))
+ dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))
}
/// Set off-chain data schema.
primitives/data-structs/src/budget.rsdiffbeforeafterboth--- /dev/null
+++ b/primitives/data-structs/src/budget.rs
@@ -0,0 +1,38 @@
+use core::cell::Cell;
+
+pub trait Budget {
+ /// Returns true while not exceeded
+ fn consume(&self) -> bool {
+ self.consume_custom(1)
+ }
+ /// Returns true while not exceeded
+ /// Implementations should use interior mutabilitiy
+ fn consume_custom(&self, calls: u32) -> bool;
+}
+
+pub struct Unlimited;
+impl Budget for Unlimited {
+ fn consume_custom(&self, _calls: u32) -> bool {
+ true
+ }
+}
+
+pub struct Value(Cell<u32>);
+impl Value {
+ pub fn new(v: u32) -> Self {
+ Self(Cell::new(v))
+ }
+ pub fn refund(self) -> u32 {
+ self.0.get()
+ }
+}
+impl Budget for Value {
+ fn consume_custom(&self, calls: u32) -> bool {
+ let (result, overflown) = self.0.get().overflowing_sub(calls);
+ if overflown {
+ return false;
+ }
+ self.0.set(result);
+ true
+ }
+}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -35,6 +35,7 @@
use scale_info::TypeInfo;
mod bounded;
+pub mod budget;
pub mod mapping;
mod migration;