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.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -20,7 +20,7 @@
use frame_support::{BoundedVec, ensure, fail};
use up_data_structs::{
AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
- mapping::TokenAddressMapping, NestingRule,
+ mapping::TokenAddressMapping, NestingRule, budget::Budget,
};
use pallet_evm::account::CrossAccountId;
use pallet_common::{
@@ -511,6 +511,7 @@
spender: &T::CrossAccountId,
from: &T::CrossAccountId,
token: TokenId,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
if spender.conv_eq(from) {
return Ok(());
@@ -522,7 +523,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(());
@@ -543,8 +549,9 @@
from: &T::CrossAccountId,
to: &T::CrossAccountId,
token: TokenId,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
- Self::check_allowed(collection, spender, from, token)?;
+ Self::check_allowed(collection, spender, from, token, nesting_budget)?;
// =========
@@ -557,8 +564,9 @@
spender: &T::CrossAccountId,
from: &T::CrossAccountId,
token: TokenId,
+ nesting_budget: &dyn Budget,
) -> DispatchResult {
- Self::check_allowed(collection, spender, from, token)?;
+ Self::check_allowed(collection, spender, from, token, nesting_budget)?;
// =========
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.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 core::{20 convert::{TryFrom, TryInto},21 fmt,22};23use frame_support::{24 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},25};2627#[cfg(feature = "serde")]28use serde::{Serialize, Deserialize};2930use sp_core::U256;31use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};32use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};33use frame_support::{BoundedVec, traits::ConstU32};34use derivative::Derivative;35use scale_info::TypeInfo;3637mod bounded;38pub mod mapping;39mod migration;4041pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;42pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;43pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;4445pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {46 100_00047} else {48 1049};50pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {51 100_00052} else {53 1054};55pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {56 204857} else {58 1059};60pub const COLLECTION_ADMINS_LIMIT: u32 = 5;61pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;62pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {63 1_000_00064} else {65 1066};6768// Timeouts for item types in passed blocks69pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;70pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;71pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;7273pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;7475// Schema limits76pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;77pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;78pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;7980pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;81pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;82pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;8384/// How much items can be created per single85/// create_many call86pub const MAX_ITEMS_PER_BATCH: u32 = 200;8788pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;8990#[derive(91 Encode,92 Decode,93 PartialEq,94 Eq,95 PartialOrd,96 Ord,97 Clone,98 Copy,99 Debug,100 Default,101 TypeInfo,102 MaxEncodedLen,103)]104#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]105pub struct CollectionId(pub u32);106impl EncodeLike<u32> for CollectionId {}107impl EncodeLike<CollectionId> for u32 {}108109#[derive(110 Encode,111 Decode,112 PartialEq,113 Eq,114 PartialOrd,115 Ord,116 Clone,117 Copy,118 Debug,119 Default,120 TypeInfo,121 MaxEncodedLen,122)]123#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]124pub struct TokenId(pub u32);125impl EncodeLike<u32> for TokenId {}126impl EncodeLike<TokenId> for u32 {}127128impl TokenId {129 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {130 self.0131 .checked_add(1)132 .ok_or(ArithmeticError::Overflow)133 .map(Self)134 }135}136137impl From<TokenId> for U256 {138 fn from(t: TokenId) -> Self {139 t.0.into()140 }141}142143impl TryFrom<U256> for TokenId {144 type Error = &'static str;145146 fn try_from(value: U256) -> Result<Self, Self::Error> {147 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))148 }149}150151pub struct OverflowError;152impl From<OverflowError> for &'static str {153 fn from(_: OverflowError) -> Self {154 "overflow occured"155 }156}157158pub type DecimalPoints = u8;159160#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]161#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]162pub enum CollectionMode {163 NFT,164 // decimal points165 Fungible(DecimalPoints),166 ReFungible,167}168169impl CollectionMode {170 pub fn id(&self) -> u8 {171 match self {172 CollectionMode::NFT => 1,173 CollectionMode::Fungible(_) => 2,174 CollectionMode::ReFungible => 3,175 }176 }177}178179pub trait SponsoringResolve<AccountId, Call> {180 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;181}182183#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]184#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]185pub enum AccessMode {186 Normal,187 AllowList,188}189impl Default for AccessMode {190 fn default() -> Self {191 Self::Normal192 }193}194195#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]196#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]197pub enum SchemaVersion {198 ImageURL,199 Unique,200}201impl Default for SchemaVersion {202 fn default() -> Self {203 Self::ImageURL204 }205}206207#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]208#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]209pub struct Ownership<AccountId> {210 pub owner: AccountId,211 pub fraction: u128,212}213214#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]215#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]216pub enum SponsorshipState<AccountId> {217 /// The fees are applied to the transaction sender218 Disabled,219 Unconfirmed(AccountId),220 /// Transactions are sponsored by specified account221 Confirmed(AccountId),222}223224impl<AccountId> SponsorshipState<AccountId> {225 pub fn sponsor(&self) -> Option<&AccountId> {226 match self {227 Self::Confirmed(sponsor) => Some(sponsor),228 _ => None,229 }230 }231232 pub fn pending_sponsor(&self) -> Option<&AccountId> {233 match self {234 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),235 _ => None,236 }237 }238239 pub fn confirmed(&self) -> bool {240 matches!(self, Self::Confirmed(_))241 }242}243244impl<T> Default for SponsorshipState<T> {245 fn default() -> Self {246 Self::Disabled247 }248}249250#[struct_versioning::versioned(version = 2, upper)]251#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]252#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]253pub struct Collection<AccountId> {254 pub owner: AccountId,255 pub mode: CollectionMode,256 pub access: AccessMode,257 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]258 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,259 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]260 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,261 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]262 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,263 pub mint_mode: bool,264 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]265 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,266 pub schema_version: SchemaVersion,267 pub sponsorship: SponsorshipState<AccountId>,268269 #[version(..2)]270 pub limits: CollectionLimitsVersion1, // Collection private restrictions271 #[version(2.., upper(limits.into()))]272 pub limits: CollectionLimitsVersion2,273274 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]275 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,276 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]277 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,278 pub meta_update_permission: MetaUpdatePermission,279}280281#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]282#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]283#[derivative(Default(bound = ""))]284pub struct CreateCollectionData<AccountId> {285 #[derivative(Default(value = "CollectionMode::NFT"))]286 pub mode: CollectionMode,287 pub access: Option<AccessMode>,288 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]289 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,290 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]291 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,292 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]293 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,294 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]295 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,296 pub schema_version: Option<SchemaVersion>,297 pub pending_sponsor: Option<AccountId>,298 pub limits: Option<CollectionLimits>,299 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]300 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,301 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]302 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,303 pub meta_update_permission: Option<MetaUpdatePermission>,304}305306#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]307#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]308pub struct NftItemType<AccountId> {309 pub owner: AccountId,310 pub const_data: Vec<u8>,311 pub variable_data: Vec<u8>,312}313314#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]315#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]316pub struct FungibleItemType {317 pub value: u128,318}319320#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]321#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]322pub struct ReFungibleItemType<AccountId> {323 pub owner: Vec<Ownership<AccountId>>,324 pub const_data: Vec<u8>,325 pub variable_data: Vec<u8>,326}327328/// All fields are wrapped in `Option`s, where None means chain default329#[struct_versioning::versioned(version = 2, upper)]330#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]331#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]332pub struct CollectionLimits {333 pub account_token_ownership_limit: Option<u32>,334 pub sponsored_data_size: Option<u32>,335 /// None - setVariableMetadata is not sponsored336 /// Some(v) - setVariableMetadata is sponsored337 /// if there is v block between txs338 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,339 pub token_limit: Option<u32>,340341 // Timeouts for item types in passed blocks342 pub sponsor_transfer_timeout: Option<u32>,343 pub sponsor_approve_timeout: Option<u32>,344 pub owner_can_transfer: Option<bool>,345 pub owner_can_destroy: Option<bool>,346 pub transfers_enabled: Option<bool>,347348 #[version(2.., upper(None))]349 pub nesting_rule: Option<NestingRule>,350}351352impl CollectionLimits {353 pub fn account_token_ownership_limit(&self) -> u32 {354 self.account_token_ownership_limit355 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)356 .min(MAX_TOKEN_OWNERSHIP)357 }358 pub fn sponsored_data_size(&self) -> u32 {359 self.sponsored_data_size360 .unwrap_or(CUSTOM_DATA_LIMIT)361 .min(CUSTOM_DATA_LIMIT)362 }363 pub fn token_limit(&self) -> u32 {364 self.token_limit365 .unwrap_or(COLLECTION_TOKEN_LIMIT)366 .min(COLLECTION_TOKEN_LIMIT)367 }368 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {369 self.sponsor_transfer_timeout370 .unwrap_or(default)371 .min(MAX_SPONSOR_TIMEOUT)372 }373 pub fn sponsor_approve_timeout(&self) -> u32 {374 self.sponsor_approve_timeout375 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)376 .min(MAX_SPONSOR_TIMEOUT)377 }378 pub fn owner_can_transfer(&self) -> bool {379 self.owner_can_transfer.unwrap_or(true)380 }381 pub fn owner_can_destroy(&self) -> bool {382 self.owner_can_destroy.unwrap_or(true)383 }384 pub fn transfers_enabled(&self) -> bool {385 self.transfers_enabled.unwrap_or(true)386 }387 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {388 match self389 .sponsored_data_rate_limit390 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)391 {392 SponsoringRateLimit::SponsoringDisabled => None,393 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),394 }395 }396 pub fn nesting_rule(&self) -> &NestingRule {397 static DEFAULT: NestingRule = NestingRule::Owner;398 self.nesting_rule.as_ref().unwrap_or(&DEFAULT)399 }400}401402#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]403#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]404#[derivative(Debug)]405pub enum NestingRule {406 /// No one can nest tokens407 Disabled,408 /// Owner can nest any tokens409 Owner,410 /// Owner can nest tokens from specified collections411 OwnerRestricted(412 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]413 #[derivative(Debug(format_with = "bounded::set_debug"))]414 BoundedBTreeSet<CollectionId, ConstU32<16>>,415 ),416}417418#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]419#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]420pub enum SponsoringRateLimit {421 SponsoringDisabled,422 Blocks(u32),423}424425#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]426#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]427#[derivative(Debug)]428pub struct CreateNftData {429 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]430 #[derivative(Debug(format_with = "bounded::vec_debug"))]431 pub const_data: BoundedVec<u8, CustomDataLimit>,432 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]433 #[derivative(Debug(format_with = "bounded::vec_debug"))]434 pub variable_data: BoundedVec<u8, CustomDataLimit>,435}436437#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]438#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]439pub struct CreateFungibleData {440 pub value: u128,441}442443#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]444#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]445#[derivative(Debug)]446pub struct CreateReFungibleData {447 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]448 #[derivative(Debug(format_with = "bounded::vec_debug"))]449 pub const_data: BoundedVec<u8, CustomDataLimit>,450 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]451 #[derivative(Debug(format_with = "bounded::vec_debug"))]452 pub variable_data: BoundedVec<u8, CustomDataLimit>,453 pub pieces: u128,454}455456#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]457#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]458pub enum MetaUpdatePermission {459 ItemOwner,460 Admin,461 None,462}463464impl Default for MetaUpdatePermission {465 fn default() -> Self {466 Self::ItemOwner467 }468}469470#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]471#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]472pub enum CreateItemData {473 NFT(CreateNftData),474 Fungible(CreateFungibleData),475 ReFungible(CreateReFungibleData),476}477478#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]479#[derivative(Debug)]480pub struct CreateNftExData<CrossAccountId> {481 #[derivative(Debug(format_with = "bounded::vec_debug"))]482 pub const_data: BoundedVec<u8, CustomDataLimit>,483 #[derivative(Debug(format_with = "bounded::vec_debug"))]484 pub variable_data: BoundedVec<u8, CustomDataLimit>,485 pub owner: CrossAccountId,486}487488#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]489#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]490pub struct CreateRefungibleExData<CrossAccountId> {491 #[derivative(Debug(format_with = "bounded::vec_debug"))]492 pub const_data: BoundedVec<u8, CustomDataLimit>,493 #[derivative(Debug(format_with = "bounded::vec_debug"))]494 pub variable_data: BoundedVec<u8, CustomDataLimit>,495 #[derivative(Debug(format_with = "bounded::map_debug"))]496 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,497}498499#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]500#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]501pub enum CreateItemExData<CrossAccountId> {502 NFT(503 #[derivative(Debug(format_with = "bounded::vec_debug"))]504 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,505 ),506 Fungible(507 #[derivative(Debug(format_with = "bounded::map_debug"))]508 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,509 ),510 /// Many tokens, each may have only one owner511 RefungibleMultipleItems(512 #[derivative(Debug(format_with = "bounded::vec_debug"))]513 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,514 ),515 /// Single token, which may have many owners516 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),517}518519impl CreateItemData {520 pub fn data_size(&self) -> usize {521 match self {522 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),523 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),524 _ => 0,525 }526 }527}528529impl From<CreateNftData> for CreateItemData {530 fn from(item: CreateNftData) -> Self {531 CreateItemData::NFT(item)532 }533}534535impl From<CreateReFungibleData> for CreateItemData {536 fn from(item: CreateReFungibleData) -> Self {537 CreateItemData::ReFungible(item)538 }539}540541impl From<CreateFungibleData> for CreateItemData {542 fn from(item: CreateFungibleData) -> Self {543 CreateItemData::Fungible(item)544 }545}546547#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]548#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]549pub struct CollectionStats {550 pub created: u32,551 pub destroyed: u32,552 pub alive: u32,553}