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.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)]1819#[cfg(not(feature = "std"))]20extern crate alloc;21// #[cfg(feature = "runtime-benchmarks")]22// pub mod benchmarking;2324pub use pallet::*;2526#[frame_support::pallet]27pub mod pallet {28 #[cfg(not(feature = "std"))]29 use alloc::format;3031 use evm_coder::{32 ToLog,33 abi::{AbiReader, AbiWrite, AbiWriter},34 execution::{self, Result},35 types::{Msg, value},36 };37 use frame_support::{ensure, sp_runtime::ModuleError};38 use pallet_evm::{39 ExitError, ExitRevert, ExitSucceed, GasWeightMapping, PrecompileFailure, PrecompileOutput,40 PrecompileResult, runner::stack::MaybeMirroredLog,41 };42 use frame_system::ensure_signed;43 pub use frame_support::dispatch::DispatchResult;44 use pallet_ethereum::EthereumTransactionSender;45 use sp_std::cell::RefCell;46 use sp_std::vec::Vec;47 use sp_core::H160;48 use frame_support::{pallet_prelude::*, traits::PalletInfo};49 use frame_system::pallet_prelude::*;5051 /// DispatchError is opaque, but we need to somehow extract correct error in case of OutOfGas failure52 /// So we have this pallet, which defines OutOfGas error, and knews its own id to check if DispatchError53 /// is thrown because of it54 ///55 /// These errors shouldn't end in extrinsic results, as they only used in evm execution path56 #[pallet::error]57 pub enum Error<T> {58 OutOfGas,59 OutOfFund,60 }6162 #[pallet::config]63 pub trait Config: frame_system::Config {64 type EthereumTransactionSender: pallet_ethereum::EthereumTransactionSender;65 type GasWeightMapping: pallet_evm::GasWeightMapping;66 }6768 #[pallet::pallet]69 pub struct Pallet<T>(_);7071 #[pallet::call]72 impl<T: Config> Pallet<T> {73 #[pallet::weight(0)]74 pub fn empty_call(origin: OriginFor<T>) -> DispatchResult {75 let _sender = ensure_signed(origin)?;76 Ok(())77 }78 }7980 // From instabul hardfork configuration: https://github.com/rust-blockchain/evm/blob/fd4fd6acc0ca3208d6770fdb3ba407c94cdf97c6/runtime/src/lib.rs#L28481 pub const G_SLOAD_WORD: u64 = 800;82 pub const G_SSTORE_WORD: u64 = 20000;8384 #[derive(Default)]85 pub struct SubstrateRecorder<T: Config> {86 contract: H160,87 logs: RefCell<Vec<MaybeMirroredLog>>,88 initial_gas: u64,89 gas_limit: RefCell<u64>,90 _phantom: PhantomData<*const T>,91 }9293 impl<T: Config> SubstrateRecorder<T> {94 pub fn new(contract: H160, gas_limit: u64) -> Self {95 Self {96 contract,97 logs: RefCell::new(Vec::new()),98 initial_gas: gas_limit,99 gas_limit: RefCell::new(gas_limit),100 _phantom: PhantomData,101 }102 }103104 pub fn is_empty(&self) -> bool {105 self.logs.borrow().is_empty()106 }107 // Logs emitted with log_direct appear as substrate evm.Log event108 pub fn log_direct(&self, log: impl ToLog) {109 self.logs110 .borrow_mut()111 .push(MaybeMirroredLog::direct(log.to_log(self.contract)))112 }113 /// If log already has substrate equivalent - then we don't need to emit evm.Log114 pub fn log_mirrored(&self, log: impl ToLog) {115 self.logs116 .borrow_mut()117 .push(MaybeMirroredLog::mirrored(log.to_log(self.contract)))118 }119 pub fn retrieve_logs(self) -> Vec<MaybeMirroredLog> {120 self.logs.into_inner()121 }122123 pub fn gas_left(&self) -> u64 {124 *self.gas_limit.borrow()125 }126 pub fn consume_sload_sub(&self) -> DispatchResult {127 self.consume_gas_sub(G_SLOAD_WORD)128 }129 pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {130 self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))131 }132 pub fn consume_sstore_sub(&self) -> DispatchResult {133 self.consume_gas_sub(G_SSTORE_WORD)134 }135 pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {136 ensure!(gas != u64::MAX, Error::<T>::OutOfGas);137 let mut gas_limit = self.gas_limit.borrow_mut();138 ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);139 *gas_limit -= gas;140 Ok(())141 }142143 pub fn consume_sload(&self) -> Result<()> {144 self.consume_gas(G_SLOAD_WORD)145 }146 pub fn consume_sstore(&self) -> Result<()> {147 self.consume_gas(G_SSTORE_WORD)148 }149 pub fn consume_gas(&self, gas: u64) -> Result<()> {150 if gas == u64::MAX {151 return Err(execution::Error::Error(ExitError::OutOfGas));152 }153 let mut gas_limit = self.gas_limit.borrow_mut();154 if gas > *gas_limit {155 return Err(execution::Error::Error(ExitError::OutOfGas));156 }157 *gas_limit -= gas;158 Ok(())159 }160 pub fn return_gas(&self, gas: u64) {161 let mut gas_limit = self.gas_limit.borrow_mut();162 *gas_limit += gas;163 }164165 pub fn evm_to_precompile_output(166 self,167 result: evm_coder::execution::Result<Option<AbiWriter>>,168 ) -> Option<PrecompileResult> {169 use evm_coder::execution::Error;170 Some(match result {171 Ok(Some(v)) => Ok(PrecompileOutput {172 exit_status: ExitSucceed::Returned,173 cost: self.initial_gas - self.gas_left(),174 // TODO: preserve mirroring status175 logs: self.retrieve_logs().into_iter().map(|l| l.log).collect(),176 output: v.finish(),177 }),178 Ok(None) => return None,179 Err(Error::Revert(e)) => {180 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));181 (&e as &str).abi_write(&mut writer);182183 Err(PrecompileFailure::Revert {184 exit_status: ExitRevert::Reverted,185 cost: self.initial_gas - self.gas_left(),186 output: writer.finish(),187 })188 }189 Err(Error::Fatal(f)) => Err(f.into()),190 Err(Error::Error(e)) => Err(e.into()),191 })192 }193194 pub fn submit_logs(self) {195 let logs = self.retrieve_logs();196 if logs.is_empty() {197 return;198 }199 T::EthereumTransactionSender::submit_logs_transaction(Default::default(), logs)200 }201 }202203 pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> evm_coder::execution::Error {204 use evm_coder::execution::Error as ExError;205 match err {206 DispatchError::Module(ModuleError { index, error, .. })207 if index208 == T::PalletInfo::index::<Pallet<T>>()209 .expect("evm-coder-substrate is a pallet, which should be added to runtime")210 as u8 =>211 {212 let mut read = &error as &[u8];213 match Error::<T>::decode(&mut read) {214 Ok(Error::<T>::OutOfGas) => ExError::Error(ExitError::OutOfGas),215 Ok(Error::<T>::OutOfFund) => ExError::Error(ExitError::OutOfFund),216 _ => unreachable!("this pallet only defines two possible errors"),217 }218 }219 DispatchError::Module(ModuleError {220 message: Some(msg), ..221 }) => ExError::Revert(msg.into()),222 DispatchError::Module(ModuleError { index, error, .. }) => {223 ExError::Revert(format!("error {:?} in pallet {}", error, index))224 }225 e => ExError::Revert(format!("substrate error: {:?}", e)),226 }227 }228229 pub trait WithRecorder<T: Config> {230 fn recorder(&self) -> &SubstrateRecorder<T>;231 fn into_recorder(self) -> SubstrateRecorder<T>;232 }233234 /// Helper to simplify implementing bridge between evm-coder definitions and pallet-evm235 pub fn call<236 T: Config,237 C: evm_coder::Call + evm_coder::Weighted,238 E: evm_coder::Callable<C> + WithRecorder<T>,239 >(240 caller: H160,241 mut e: E,242 value: value,243 input: &[u8],244 ) -> Option<PrecompileResult> {245 let result = call_internal(caller, &mut e, value, input);246 e.into_recorder().evm_to_precompile_output(result)247 }248249 fn call_internal<250 T: Config,251 C: evm_coder::Call + evm_coder::Weighted,252 E: evm_coder::Callable<C> + WithRecorder<T>,253 >(254 caller: H160,255 e: &mut E,256 value: value,257 input: &[u8],258 ) -> evm_coder::execution::Result<Option<AbiWriter>> {259 let (selector, mut reader) = AbiReader::new_call(input)?;260 let call = C::parse(selector, &mut reader)?;261 if call.is_none() {262 return Ok(None);263 }264 let call = call.unwrap();265266 let dispatch_info = call.weight();267 e.recorder()268 .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;269270 match e.call(Msg {271 call,272 caller,273 value,274 }) {275 Ok(v) => {276 let unspent = v.post_info.calc_unspent(&dispatch_info);277 e.recorder()278 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));279 Ok(Some(v.data))280 }281 Err(v) => {282 let unspent = v.post_info.calc_unspent(&dispatch_info);283 e.recorder()284 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));285 Err(v.data)286 }287 }288 }289}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)]1819#[cfg(not(feature = "std"))]20extern crate alloc;21#[cfg(not(feature = "std"))]22use alloc::format;23use frame_support::dispatch::Weight;2425use core::marker::PhantomData;26use sp_std::cell::RefCell;27use sp_std::vec::Vec;2829use frame_support::pallet_prelude::DispatchError;30use frame_support::traits::PalletInfo;31use frame_support::{ensure, sp_runtime::ModuleError};32use up_data_structs::budget;33use pallet_evm::{34 ExitError, ExitRevert, ExitSucceed, GasWeightMapping, PrecompileFailure, PrecompileOutput,35 PrecompileResult, runner::stack::MaybeMirroredLog,36};37use ethereum::TransactionV2;38use sp_core::{H160, H256};39use pallet_ethereum::EthereumTransactionSender;40// #[cfg(feature = "runtime-benchmarks")]41// pub mod benchmarking;4243use evm_coder::{44 ToLog,45 abi::{AbiReader, AbiWrite, AbiWriter},46 execution::{self, Result},47 types::{Msg, value},48};4950pub use pallet::*;5152#[frame_support::pallet]53pub mod pallet {54 use super::*;5556 use frame_system::ensure_signed;57 pub use frame_support::dispatch::DispatchResult;58 use frame_support::{pallet_prelude::*, traits::PalletInfo};59 use frame_system::pallet_prelude::*;6061 /// DispatchError is opaque, but we need to somehow extract correct error in case of OutOfGas failure62 /// So we have this pallet, which defines OutOfGas error, and knews its own id to check if DispatchError63 /// is thrown because of it64 ///65 /// These errors shouldn't end in extrinsic results, as they only used in evm execution path66 #[pallet::error]67 pub enum Error<T> {68 OutOfGas,69 OutOfFund,70 }7172 #[pallet::config]73 pub trait Config: frame_system::Config {74 type EthereumTransactionSender: pallet_ethereum::EthereumTransactionSender;75 type GasWeightMapping: pallet_evm::GasWeightMapping;76 }7778 #[pallet::pallet]79 pub struct Pallet<T>(_);8081 #[pallet::call]82 impl<T: Config> Pallet<T> {83 #[pallet::weight(0)]84 pub fn empty_call(origin: OriginFor<T>) -> DispatchResult {85 let _sender = ensure_signed(origin)?;86 Ok(())87 }88 }89}9091// From instabul hardfork configuration: https://github.com/rust-blockchain/evm/blob/fd4fd6acc0ca3208d6770fdb3ba407c94cdf97c6/runtime/src/lib.rs#L28492pub const G_SLOAD_WORD: u64 = 800;93pub const G_SSTORE_WORD: u64 = 20000;9495pub fn generate_transaction() -> TransactionV2 {96 use ethereum::{TransactionV0, TransactionAction, TransactionSignature};97 TransactionV2::Legacy(TransactionV0 {98 nonce: 0.into(),99 gas_price: 0.into(),100 gas_limit: 0.into(),101 action: TransactionAction::Call(H160([0; 20])),102 value: 0.into(),103 // zero selector, this transaction always has same sender, so all data should be acquired from logs104 input: Vec::from([0, 0, 0, 0]),105 // if v is not 27 - then we need to pass some other validity checks106 signature: TransactionSignature::new(27, H256([0x88; 32]), H256([0x88; 32])).unwrap(),107 })108}109110pub struct GasCallsBudget<'r, T: Config> {111 recorder: &'r SubstrateRecorder<T>,112 gas_per_call: u64,113}114impl<T: Config> budget::Budget for GasCallsBudget<'_, T> {115 fn consume_custom(&self, calls: u32) -> bool {116 let (gas, overflown) = (calls as u64).overflowing_add(self.gas_per_call);117 if overflown {118 return false;119 }120 self.recorder.consume_gas(gas).is_ok()121 }122}123124#[derive(Default)]125pub struct SubstrateRecorder<T: Config> {126 contract: H160,127 logs: RefCell<Vec<MaybeMirroredLog>>,128 initial_gas: u64,129 gas_limit: RefCell<u64>,130 _phantom: PhantomData<*const T>,131}132133impl<T: Config> SubstrateRecorder<T> {134 pub fn new(contract: H160, gas_limit: u64) -> Self {135 Self {136 contract,137 logs: RefCell::new(Vec::new()),138 initial_gas: gas_limit,139 gas_limit: RefCell::new(gas_limit),140 _phantom: PhantomData,141 }142 }143144 pub fn is_empty(&self) -> bool {145 self.logs.borrow().is_empty()146 }147 // Logs emitted with log_direct appear as substrate evm.Log event148 pub fn log_direct(&self, log: impl ToLog) {149 self.logs150 .borrow_mut()151 .push(MaybeMirroredLog::direct(log.to_log(self.contract)))152 }153 /// If log already has substrate equivalent - then we don't need to emit evm.Log154 pub fn log_mirrored(&self, log: impl ToLog) {155 self.logs156 .borrow_mut()157 .push(MaybeMirroredLog::mirrored(log.to_log(self.contract)))158 }159 pub fn retrieve_logs(self) -> Vec<MaybeMirroredLog> {160 self.logs.into_inner()161 }162163 pub fn gas_left(&self) -> u64 {164 *self.gas_limit.borrow()165 }166 pub fn gas_calls_budget(&self, gas_per_call: u64) -> GasCallsBudget<T> {167 GasCallsBudget {168 recorder: self,169 gas_per_call,170 }171 }172 pub fn weight_calls_budget(&self, weight_per_call: Weight) -> GasCallsBudget<T> {173 GasCallsBudget {174 recorder: self,175 gas_per_call: T::GasWeightMapping::weight_to_gas(weight_per_call),176 }177 }178 pub fn consume_sload_sub(&self) -> DispatchResult {179 self.consume_gas_sub(G_SLOAD_WORD)180 }181 pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {182 self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))183 }184 pub fn consume_sstore_sub(&self) -> DispatchResult {185 self.consume_gas_sub(G_SSTORE_WORD)186 }187 pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {188 ensure!(gas != u64::MAX, Error::<T>::OutOfGas);189 let mut gas_limit = self.gas_limit.borrow_mut();190 ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);191 *gas_limit -= gas;192 Ok(())193 }194195 pub fn consume_sload(&self) -> Result<()> {196 self.consume_gas(G_SLOAD_WORD)197 }198 pub fn consume_sstore(&self) -> Result<()> {199 self.consume_gas(G_SSTORE_WORD)200 }201 pub fn consume_gas(&self, gas: u64) -> Result<()> {202 if gas == u64::MAX {203 return Err(execution::Error::Error(ExitError::OutOfGas));204 }205 let mut gas_limit = self.gas_limit.borrow_mut();206 if gas > *gas_limit {207 return Err(execution::Error::Error(ExitError::OutOfGas));208 }209 *gas_limit -= gas;210 Ok(())211 }212 pub fn return_gas(&self, gas: u64) {213 let mut gas_limit = self.gas_limit.borrow_mut();214 *gas_limit += gas;215 }216217 pub fn evm_to_precompile_output(218 self,219 result: evm_coder::execution::Result<Option<AbiWriter>>,220 ) -> Option<PrecompileResult> {221 use evm_coder::execution::Error;222 Some(match result {223 Ok(Some(v)) => Ok(PrecompileOutput {224 exit_status: ExitSucceed::Returned,225 cost: self.initial_gas - self.gas_left(),226 // TODO: preserve mirroring status227 logs: self.retrieve_logs().into_iter().map(|l| l.log).collect(),228 output: v.finish(),229 }),230 Ok(None) => return None,231 Err(Error::Revert(e)) => {232 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));233 (&e as &str).abi_write(&mut writer);234235 Err(PrecompileFailure::Revert {236 exit_status: ExitRevert::Reverted,237 cost: self.initial_gas - self.gas_left(),238 output: writer.finish(),239 })240 }241 Err(Error::Fatal(f)) => Err(f.into()),242 Err(Error::Error(e)) => Err(e.into()),243 })244 }245246 pub fn submit_logs(self) {247 let logs = self.retrieve_logs();248 if logs.is_empty() {249 return;250 }251 T::EthereumTransactionSender::submit_logs_transaction(252 Default::default(),253 generate_transaction(),254 logs,255 )256 }257}258259pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> evm_coder::execution::Error {260 use evm_coder::execution::Error as ExError;261 match err {262 DispatchError::Module(ModuleError { index, error, .. })263 if index264 == T::PalletInfo::index::<Pallet<T>>()265 .expect("evm-coder-substrate is a pallet, which should be added to runtime")266 as u8 =>267 {268 match error {269 v if v == Error::<T>::OutOfGas.as_u8() => ExError::Error(ExitError::OutOfGas),270 v if v == Error::<T>::OutOfFund.as_u8() => ExError::Error(ExitError::OutOfFund),271 _ => unreachable!("this pallet only defines two possible errors"),272 }273 }274 DispatchError::Module(ModuleError {275 message: Some(msg), ..276 }) => ExError::Revert(msg.into()),277 DispatchError::Module(ModuleError { index, error, .. }) => {278 ExError::Revert(format!("error {} in pallet {}", error, index))279 }280 e => ExError::Revert(format!("substrate error: {:?}", e)),281 }282}283284pub trait WithRecorder<T: Config> {285 fn recorder(&self) -> &SubstrateRecorder<T>;286 fn into_recorder(self) -> SubstrateRecorder<T>;287}288289/// Helper to simplify implementing bridge between evm-coder definitions and pallet-evm290pub fn call<291 T: Config,292 C: evm_coder::Call + evm_coder::Weighted,293 E: evm_coder::Callable<C> + WithRecorder<T>,294>(295 caller: H160,296 mut e: E,297 value: value,298 input: &[u8],299) -> Option<PrecompileResult> {300 let result = call_internal(caller, &mut e, value, input);301 e.into_recorder().evm_to_precompile_output(result)302}303304fn call_internal<305 T: Config,306 C: evm_coder::Call + evm_coder::Weighted,307 E: evm_coder::Callable<C> + WithRecorder<T>,308>(309 caller: H160,310 e: &mut E,311 value: value,312 input: &[u8],313) -> evm_coder::execution::Result<Option<AbiWriter>> {314 let (selector, mut reader) = AbiReader::new_call(input)?;315 let call = C::parse(selector, &mut reader)?;316 if call.is_none() {317 return Ok(None);318 }319 let call = call.unwrap();320321 let dispatch_info = call.weight();322 e.recorder()323 .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;324325 match e.call(Msg {326 call,327 caller,328 value,329 }) {330 Ok(v) => {331 let unspent = v.post_info.calc_unspent(&dispatch_info);332 e.recorder()333 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));334 Ok(Some(v.data))335 }336 Err(v) => {337 let unspent = v.post_info.calc_unspent(&dispatch_info);338 e.recorder()339 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));340 Err(v.data)341 }342 }343}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.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;