git.delta.rocks / unique-network / refs/commits / 44992fca8f8c

difftreelog

feat burn_from

Yaroslav Bolyukin2021-11-02parent: #283713e.patch.diff
in: master

12 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -459,6 +459,7 @@
 	fn transfer() -> Weight;
 	fn approve() -> Weight;
 	fn transfer_from() -> Weight;
+	fn burn_from() -> Weight;
 	fn set_variable_metadata(bytes: u32) -> Weight;
 }
 
@@ -504,6 +505,13 @@
 		token: TokenId,
 		amount: u128,
 	) -> DispatchResultWithPostInfo;
+	fn burn_from(
+		&self,
+		sender: T::CrossAccountId,
+		from: T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResultWithPostInfo;
 
 	fn set_variable_metadata(
 		&self,
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -38,6 +38,10 @@
 		<SelfWeightOf<T>>::transfer_from()
 	}
 
+	fn burn_from() -> Weight {
+		0
+	}
+
 	fn set_variable_metadata(_bytes: u32) -> Weight {
 		// Error
 		0
@@ -156,6 +160,24 @@
 		)
 	}
 
+	fn burn_from(
+		&self,
+		sender: T::CrossAccountId,
+		from: T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResultWithPostInfo {
+		ensure!(
+			token == TokenId::default(),
+			<Error<T>>::FungibleItemsHaveNoId
+		);
+
+		with_weight(
+			<Pallet<T>>::burn_from(&self, &sender, &from, amount),
+			<CommonWeights<T>>::burn_from(),
+		)
+	}
+
 	fn set_variable_metadata(
 		&self,
 		_sender: T::CrossAccountId,
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -96,6 +96,18 @@
 	}
 }
 
+#[solidity_interface(name = "ERC20UniqueExtensions")]
+impl<T: Config> FungibleHandle<T> {
+	fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		let from = T::CrossAccountId::from_eth(from);
+		let amount = amount.try_into().map_err(|_| "amount overflow")?;
+
+		<Pallet<T>>::burn_from(self, &caller, &from, amount).map_err(dispatch_to_evm::<T>)?;
+		Ok(true)
+	}
+}
+
 #[solidity_interface(name = "UniqueFungible", is(ERC20))]
 impl<T: Config> FungibleHandle<T> {}
 
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
before · pallets/fungible/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use core::ops::Deref;4use frame_support::{ensure};5use nft_data_structs::{AccessMode, Collection, CollectionId, TokenId};6use pallet_common::{7	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,8};9use sp_core::H160;10use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};11use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};1213pub use pallet::*;1415use crate::erc::ERC20Events;16#[cfg(feature = "runtime-benchmarks")]17pub mod benchmarking;18pub mod common;19pub mod erc;20pub mod weights;2122pub type CreateItemData<T> = (<T as pallet_common::Config>::CrossAccountId, u128);23pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2425#[frame_support::pallet]26pub mod pallet {27	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};28	use nft_data_structs::CollectionId;29	use super::weights::WeightInfo;3031	#[pallet::error]32	pub enum Error<T> {33		/// Not Fungible item data used to mint in Fungible collection.34		NotFungibleDataUsedToMintFungibleCollectionToken,35		/// Not default id passed as TokenId argument36		FungibleItemsHaveNoId,37		/// Tried to set data for fungible item38		FungibleItemsHaveData,39	}4041	#[pallet::config]42	pub trait Config: frame_system::Config + pallet_common::Config {43		type WeightInfo: WeightInfo;44	}4546	#[pallet::pallet]47	#[pallet::generate_store(pub(super) trait Store)]48	pub struct Pallet<T>(_);4950	#[pallet::storage]51	pub(super) type TotalSupply<T: Config> =52		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;5354	#[pallet::storage]55	pub(super) type Balance<T: Config> = StorageNMap<56		Key = (57			Key<Twox64Concat, CollectionId>,58			Key<Blake2_128Concat, T::AccountId>,59		),60		Value = u128,61		QueryKind = ValueQuery,62	>;6364	#[pallet::storage]65	pub(super) type Allowance<T: Config> = StorageNMap<66		Key = (67			Key<Twox64Concat, CollectionId>,68			Key<Blake2_128, T::AccountId>,69			Key<Blake2_128Concat, T::AccountId>,70		),71		Value = u128,72		QueryKind = ValueQuery,73	>;74}7576pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);77impl<T: Config> FungibleHandle<T> {78	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {79		Self(inner)80	}81	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {82		self.083	}84}85impl<T: Config> Deref for FungibleHandle<T> {86	type Target = pallet_common::CollectionHandle<T>;8788	fn deref(&self) -> &Self::Target {89		&self.090	}91}9293impl<T: Config> Pallet<T> {94	pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {95		PalletCommon::init_collection(data)96	}97	pub fn destroy_collection(98		collection: FungibleHandle<T>,99		sender: &T::CrossAccountId,100	) -> DispatchResult {101		let id = collection.id;102103		// =========104105		PalletCommon::destroy_collection(collection.0, sender)?;106107		<TotalSupply<T>>::remove(id);108		<Balance<T>>::remove_prefix((id,), None);109		<Allowance<T>>::remove_prefix((id,), None);110		Ok(())111	}112113	pub fn burn(114		collection: &FungibleHandle<T>,115		owner: &T::CrossAccountId,116		amount: u128,117	) -> DispatchResult {118		let total_supply = <TotalSupply<T>>::get(collection.id)119			.checked_sub(amount)120			.ok_or(<CommonError<T>>::TokenValueTooLow)?;121122		let balance = <Balance<T>>::get((collection.id, owner.as_sub()))123			.checked_sub(amount)124			.ok_or(<CommonError<T>>::TokenValueTooLow)?;125126		if collection.access == AccessMode::WhiteList {127			collection.check_allowlist(owner)?;128		}129130		// =========131132		if balance == 0 {133			<Balance<T>>::remove((collection.id, owner.as_sub()));134		} else {135			<Balance<T>>::insert((collection.id, owner.as_sub()), balance);136		}137		<TotalSupply<T>>::insert(collection.id, total_supply);138139		collection.log_infallible(ERC20Events::Transfer {140			from: *owner.as_eth(),141			to: H160::default(),142			value: amount.into(),143		});144		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(145			collection.id,146			TokenId::default(),147			owner.clone(),148			amount,149		));150		Ok(())151	}152153	pub fn transfer(154		collection: &FungibleHandle<T>,155		from: &T::CrossAccountId,156		to: &T::CrossAccountId,157		amount: u128,158	) -> DispatchResult {159		ensure!(160			collection.transfers_enabled,161			<CommonError<T>>::TransferNotAllowed162		);163164		if collection.access == AccessMode::WhiteList {165			collection.check_allowlist(from)?;166			collection.check_allowlist(to)?;167		}168		<PalletCommon<T>>::ensure_correct_receiver(to)?;169170		let balance_from = <Balance<T>>::get((collection.id, from.as_sub()))171			.checked_sub(amount)172			.ok_or(<CommonError<T>>::TokenValueTooLow)?;173		let balance_to = if from != to {174			Some(175				<Balance<T>>::get((collection.id, to.as_sub()))176					.checked_add(amount)177					.ok_or(ArithmeticError::Overflow)?,178			)179		} else {180			None181		};182183		collection.consume_sstore()?;184		collection.consume_sstore()?;185		collection.consume_log(2, 32)?;186		collection.consume_sstore()?;187188		// =========189190		if let Some(balance_to) = balance_to {191			// from != to192			if balance_from == 0 {193				<Balance<T>>::remove((collection.id, from.as_sub()));194			} else {195				<Balance<T>>::insert((collection.id, from.as_sub()), balance_from);196			}197			<Balance<T>>::insert((collection.id, to.as_sub()), balance_to);198		}199200		collection.log_infallible(ERC20Events::Transfer {201			from: *from.as_eth(),202			to: *to.as_eth(),203			value: amount.into(),204		});205		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(206			collection.id,207			TokenId::default(),208			from.clone(),209			to.clone(),210			amount,211		));212		Ok(())213	}214215	pub fn create_multiple_items(216		collection: &FungibleHandle<T>,217		sender: &T::CrossAccountId,218		data: Vec<CreateItemData<T>>,219	) -> DispatchResult {220		let unrestricted_minting = collection.is_owner_or_admin(sender)?;221		if !unrestricted_minting {222			ensure!(223				collection.mint_mode,224				<CommonError<T>>::PublicMintingNotAllowed225			);226			collection.check_allowlist(sender)?;227228			for (owner, _) in data.iter() {229				collection.check_allowlist(owner)?;230			}231		}232233		let mut balances = BTreeMap::new();234235		let total_supply = data236			.iter()237			.map(|u| u.1)238			.try_fold(0u128, |acc, v| acc.checked_add(v))239			.ok_or(ArithmeticError::Overflow)?;240241		for (user, amount) in data.into_iter() {242			collection.consume_sload()?;243			let balance = balances244				.entry(user.clone())245				.or_insert_with(|| <Balance<T>>::get((collection.id, user.as_sub())));246			*balance = (*balance)247				.checked_add(amount)248				.ok_or(ArithmeticError::Overflow)?;249		}250251		collection.consume_sstore()?;252		for _ in &balances {253			collection.consume_sstore()?;254			collection.consume_log(2, 32)?;255			collection.consume_sstore()?;256		}257258		// =========259260		<TotalSupply<T>>::insert(collection.id, total_supply);261		for (user, amount) in balances {262			<Balance<T>>::insert((collection.id, user.as_sub()), amount);263264			collection.log_infallible(ERC20Events::Transfer {265				from: H160::default(),266				to: *user.as_eth(),267				value: amount.into(),268			});269			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(270				collection.id,271				TokenId::default(),272				user.clone(),273				amount,274			));275		}276277		Ok(())278	}279280	fn set_allowance_unchecked(281		collection: &FungibleHandle<T>,282		owner: &T::CrossAccountId,283		spender: &T::CrossAccountId,284		amount: u128,285	) {286		<Allowance<T>>::insert((collection.id, owner.as_sub(), spender.as_sub()), amount);287288		collection.log_infallible(ERC20Events::Approval {289			owner: *owner.as_eth(),290			spender: *spender.as_eth(),291			value: amount.into(),292		});293		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(294			collection.id,295			TokenId(0),296			owner.clone(),297			spender.clone(),298			amount,299		));300	}301302	pub fn set_allowance(303		collection: &FungibleHandle<T>,304		owner: &T::CrossAccountId,305		spender: &T::CrossAccountId,306		amount: u128,307	) -> DispatchResult {308		if collection.access == AccessMode::WhiteList {309			collection.check_allowlist(&owner)?;310			collection.check_allowlist(&spender)?;311		}312313		if <Balance<T>>::get((collection.id, owner.as_sub())) < amount {314			ensure!(315				collection.ignores_owned_amount(owner)?,316				<CommonError<T>>::CantApproveMoreThanOwned317			);318		}319320		// =========321322		Self::set_allowance_unchecked(collection, owner, spender, amount);323		Ok(())324	}325326	pub fn transfer_from(327		collection: &FungibleHandle<T>,328		spender: &T::CrossAccountId,329		from: &T::CrossAccountId,330		to: &T::CrossAccountId,331		amount: u128,332	) -> DispatchResult {333		if spender == from {334			return Self::transfer(collection, from, to, amount);335		}336		if collection.access == AccessMode::WhiteList {337			// `from`, `to` checked in [`transfer`]338			collection.check_allowlist(spender)?;339		}340341		let allowance = <Allowance<T>>::get((collection.id, from.as_sub(), spender.as_sub()))342			.checked_sub(amount);343		if allowance.is_none() {344			ensure!(345				collection.ignores_allowance(spender)?,346				<CommonError<T>>::TokenValueNotEnough347			);348		}349350		// =========351352		Self::transfer(collection, from, to, amount)?;353		if let Some(allowance) = allowance {354			Self::set_allowance_unchecked(collection, from, spender, allowance);355		}356		Ok(())357	}358359	/// Delegated to `create_multiple_items`360	pub fn create_item(361		collection: &FungibleHandle<T>,362		sender: &T::CrossAccountId,363		data: CreateItemData<T>,364	) -> DispatchResult {365		Self::create_multiple_items(collection, sender, vec![data])366	}367}
modifiedpallets/nft/src/common.rsdiffbeforeafterboth
--- a/pallets/nft/src/common.rs
+++ b/pallets/nft/src/common.rs
@@ -45,4 +45,8 @@
 	fn set_variable_metadata(bytes: u32) -> nft_data_structs::Weight {
 		dispatch_weight::<T>() + max_weight_of!(set_variable_metadata(bytes))
 	}
+
+	fn burn_from() -> Weight {
+		dispatch_weight::<T>() + max_weight_of!(burn_from())
+	}
 }
modifiedpallets/nft/src/eth/sponsoring.rsdiffbeforeafterboth
--- a/pallets/nft/src/eth/sponsoring.rs
+++ b/pallets/nft/src/eth/sponsoring.rs
@@ -35,9 +35,10 @@
 				.map_err(|_| AnyError)?
 				.ok_or(AnyError)?;
 			match call {
-				UniqueNFTCall::ERC721UniqueExtensions(
-					ERC721UniqueExtensionsCall::TransferNft { token_id, .. },
-				)
+				UniqueNFTCall::ERC721UniqueExtensions(ERC721UniqueExtensionsCall::Transfer {
+					token_id,
+					..
+				})
 				| UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, .. }) => {
 					let token_id: u32 = token_id.try_into().map_err(|_| AnyError)?;
 					let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -623,14 +623,13 @@
 		/// * item_id: ID of NFT to burn.
 		///
 		/// * from: owner of item
-		// #[weight = 0]
-		// #[transactional]
-		// pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> PostDispatchInfo {
-		// 	let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+		#[weight = <CommonWeights<T>>::burn_from()]
+		#[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)?);
 
-		// 	// dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value))
-		// 	todo!()
-		// }
+			dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value))
+		}
 
 		/// Change ownership of the token.
 		///
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -39,6 +39,10 @@
 		<SelfWeightOf<T>>::transfer_from()
 	}
 
+	fn burn_from() -> Weight {
+		0
+	}
+
 	fn set_variable_metadata(bytes: u32) -> Weight {
 		<SelfWeightOf<T>>::set_variable_metadata(bytes)
 	}
@@ -163,6 +167,25 @@
 		}
 	}
 
+	fn burn_from(
+		&self,
+		sender: T::CrossAccountId,
+		from: T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResultWithPostInfo {
+		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
+
+		if amount == 1 {
+			with_weight(
+				<Pallet<T>>::burn_from(&self, &sender, &from, token),
+				<CommonWeights<T>>::burn_from(),
+			)
+		} else {
+			Ok(().into())
+		}
+	}
+
 	fn set_variable_metadata(
 		&self,
 		sender: T::CrossAccountId,
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -264,8 +264,7 @@
 
 #[solidity_interface(name = "ERC721UniqueExtensions")]
 impl<T: Config> NonfungibleHandle<T> {
-	#[solidity(rename_selector = "transfer")]
-	fn transfer_nft(
+	fn transfer(
 		&mut self,
 		caller: caller,
 		to: address,
@@ -280,6 +279,21 @@
 		Ok(())
 	}
 
+	fn burn_from(
+		&mut self,
+		caller: caller,
+		from: address,
+		token_id: uint256,
+		_value: value,
+	) -> Result<void> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		let from = T::CrossAccountId::from_eth(from);
+		let token = token_id.try_into()?;
+
+		<Pallet<T>>::burn_from(self, &caller, &from, token).map_err(dispatch_to_evm::<T>)?;
+		Ok(())
+	}
+
 	fn next_token_id(&self) -> Result<uint256> {
 		Ok(<TokensMinted<T>>::get(self.id)
 			.checked_add(1)
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -499,6 +499,32 @@
 		Ok(())
 	}
 
+	pub fn burn_from(
+		collection: &NonfungibleHandle<T>,
+		spender: &T::CrossAccountId,
+		from: &T::CrossAccountId,
+		token: TokenId,
+	) -> DispatchResult {
+		if spender == from {
+			return Self::burn(collection, from, token);
+		}
+		if collection.access == AccessMode::WhiteList {
+			// `from` checked in [`burn`]
+			collection.check_allowlist(spender)?;
+		}
+
+		if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {
+			ensure!(
+				collection.ignores_allowance(spender)?,
+				<CommonError<T>>::TokenValueNotEnough
+			);
+		}
+
+		// =========
+
+		Self::burn(collection, &from, token)
+	}
+
 	pub fn set_variable_metadata(
 		collection: &NonfungibleHandle<T>,
 		sender: &T::CrossAccountId,
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -59,6 +59,10 @@
 		)
 	}
 
+	fn burn_from() -> Weight {
+		0
+	}
+
 	fn set_variable_metadata(bytes: u32) -> Weight {
 		<SelfWeightOf<T>>::set_variable_metadata(bytes)
 	}
@@ -161,7 +165,20 @@
 	) -> DispatchResultWithPostInfo {
 		with_weight(
 			<Pallet<T>>::transfer_from(&self, &sender, &from, &to, token, amount),
-			<CommonWeights<T>>::approve(),
+			<CommonWeights<T>>::transfer_from(),
+		)
+	}
+
+	fn burn_from(
+		&self,
+		sender: T::CrossAccountId,
+		from: T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResultWithPostInfo {
+		with_weight(
+			<Pallet<T>>::burn_from(&self, &sender, &from, token, amount),
+			<CommonWeights<T>>::burn_from(),
 		)
 	}
 
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -537,6 +537,39 @@
 		Ok(())
 	}
 
+	pub fn burn_from(
+		collection: &RefungibleHandle<T>,
+		spender: &T::CrossAccountId,
+		from: &T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResult {
+		if spender == from {
+			return Self::burn(collection, from, token, amount);
+		}
+		if collection.access == AccessMode::WhiteList {
+			// `from` checked in [`burn`]
+			collection.check_allowlist(spender)?;
+		}
+
+		let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))
+			.checked_sub(amount);
+		if allowance.is_none() {
+			ensure!(
+				collection.ignores_allowance(spender)?,
+				<CommonError<T>>::TokenValueNotEnough
+			);
+		}
+
+		// =========
+
+		Self::burn(collection, from, token, amount)?;
+		if let Some(allowance) = allowance {
+			Self::set_allowance_unchecked(collection, from, spender, token, allowance);
+		}
+		Ok(())
+	}
+
 	pub fn set_variable_metadata(
 		collection: &RefungibleHandle<T>,
 		sender: &T::CrossAccountId,