git.delta.rocks / unique-network / refs/commits / 0660dd124ff7

difftreelog

fix code style

Igor Kozyrev2022-02-17parent: #c091cef.patch.diff
in: master

4 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -13,9 +13,8 @@
 use pallet_evm::GasWeightMapping;
 use up_data_structs::{
 	COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
-	MAX_TOKEN_PREFIX_LENGTH,
-	COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,
-	WithdrawReasons, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode,
+	MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo,
+	TokenId, Weight, WithdrawReasons, 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,
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
before · pallets/nonfungible/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use erc::ERC721Events;4use frame_support::{BoundedVec, ensure};5use up_data_structs::{6	AccessMode, Collection, CollectionId, CustomDataLimit, TokenId,7	CreateCollectionData,8};9use pallet_common::{10	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,11};12use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};13use sp_core::H160;14use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};15use sp_std::{vec::Vec, vec};16use core::ops::Deref;17use sp_std::collections::btree_map::BTreeMap;18use codec::{Encode, Decode, MaxEncodedLen};19use scale_info::TypeInfo;2021pub use pallet::*;22#[cfg(feature = "runtime-benchmarks")]23pub mod benchmarking;24pub mod common;25pub mod erc;26pub mod weights;2728pub struct CreateItemData<T: Config> {29	pub const_data: BoundedVec<u8, CustomDataLimit>,30	pub variable_data: BoundedVec<u8, CustomDataLimit>,31	pub owner: T::CrossAccountId,32}33pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;3435#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]36pub struct ItemData<CrossAccountId> {37	pub const_data: BoundedVec<u8, CustomDataLimit>,38	pub variable_data: BoundedVec<u8, CustomDataLimit>,39	pub owner: CrossAccountId,40}4142#[frame_support::pallet]43pub mod pallet {44	use super::*;45	use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};46	use up_data_structs::{CollectionId, TokenId};47	use super::weights::WeightInfo;4849	#[pallet::error]50	pub enum Error<T> {51		/// Not Nonfungible item data used to mint in Nonfungible collection.52		NotNonfungibleDataUsedToMintFungibleCollectionToken,53		/// Used amount > 1 with NFT54		NonfungibleItemsHaveNoAmount,55	}5657	#[pallet::config]58	pub trait Config: frame_system::Config + pallet_common::Config {59		type WeightInfo: WeightInfo;60	}6162	#[pallet::pallet]63	#[pallet::generate_store(pub(super) trait Store)]64	pub struct Pallet<T>(_);6566	#[pallet::storage]67	pub type TokensMinted<T: Config> =68		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;69	#[pallet::storage]70	pub type TokensBurnt<T: Config> =71		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;7273	#[pallet::storage]74	pub type TokenData<T: Config> = StorageNMap<75		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),76		Value = ItemData<T::CrossAccountId>,77		QueryKind = OptionQuery,78	>;7980	/// Used to enumerate tokens owned by account81	#[pallet::storage]82	pub type Owned<T: Config> = StorageNMap<83		Key = (84			Key<Twox64Concat, CollectionId>,85			Key<Blake2_128Concat, T::CrossAccountId>,86			Key<Twox64Concat, TokenId>,87		),88		Value = bool,89		QueryKind = ValueQuery,90	>;9192	#[pallet::storage]93	pub type AccountBalance<T: Config> = StorageNMap<94		Key = (95			Key<Twox64Concat, CollectionId>,96			Key<Blake2_128Concat, T::CrossAccountId>,97		),98		Value = u32,99		QueryKind = ValueQuery,100	>;101102	#[pallet::storage]103	pub type Allowance<T: Config> = StorageNMap<104		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),105		Value = T::CrossAccountId,106		QueryKind = OptionQuery,107	>;108}109110pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);111impl<T: Config> NonfungibleHandle<T> {112	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {113		Self(inner)114	}115	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {116		self.0117	}118}119impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {120	fn recorder(&self) -> &SubstrateRecorder<T> {121		self.0.recorder()122	}123	fn into_recorder(self) -> SubstrateRecorder<T> {124		self.0.into_recorder()125	}126}127impl<T: Config> Deref for NonfungibleHandle<T> {128	type Target = pallet_common::CollectionHandle<T>;129130	fn deref(&self) -> &Self::Target {131		&self.0132	}133}134135impl<T: Config> Pallet<T> {136	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {137		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)138	}139	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {140		<TokenData<T>>::contains_key((collection.id, token))141	}142}143144// unchecked calls skips any permission checks145impl<T: Config> Pallet<T> {146	pub fn init_collection(147		owner: T::AccountId,148		data: CreateCollectionData<T::AccountId>,149	) -> Result<CollectionId, DispatchError> {150		<PalletCommon<T>>::init_collection(owner, data)151	}152	pub fn destroy_collection(153		collection: NonfungibleHandle<T>,154		sender: &T::CrossAccountId,155	) -> DispatchResult {156		let id = collection.id;157158		// =========159160		PalletCommon::destroy_collection(collection.0, sender)?;161162		<TokenData<T>>::remove_prefix((id,), None);163		<Owned<T>>::remove_prefix((id,), None);164		<TokensMinted<T>>::remove(id);165		<TokensBurnt<T>>::remove(id);166		<Allowance<T>>::remove_prefix((id,), None);167		<AccountBalance<T>>::remove_prefix((id,), None);168		Ok(())169	}170171	pub fn burn(172		collection: &NonfungibleHandle<T>,173		sender: &T::CrossAccountId,174		token: TokenId,175	) -> DispatchResult {176		let token_data =177			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;178		ensure!(179			&token_data.owner == sender180				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),181			<CommonError<T>>::NoPermission182		);183184		if collection.access == AccessMode::AllowList {185			collection.check_allowlist(sender)?;186		}187188		let burnt = <TokensBurnt<T>>::get(collection.id)189			.checked_add(1)190			.ok_or(ArithmeticError::Overflow)?;191192		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))193			.checked_sub(1)194			.ok_or(ArithmeticError::Overflow)?;195196		if balance == 0 {197			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));198		} else {199			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);200		}201		// =========202203		<Owned<T>>::remove((collection.id, &token_data.owner, token));204		<TokensBurnt<T>>::insert(collection.id, burnt);205		<TokenData<T>>::remove((collection.id, token));206		let old_spender = <Allowance<T>>::take((collection.id, token));207208		if let Some(old_spender) = old_spender {209			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(210				collection.id,211				token,212				sender.clone(),213				old_spender,214				0,215			));216		}217218		collection.log_mirrored(ERC721Events::Transfer {219			from: *token_data.owner.as_eth(),220			to: H160::default(),221			token_id: token.into(),222		});223		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(224			collection.id,225			token,226			token_data.owner,227			1,228		));229		Ok(())230	}231232	pub fn transfer(233		collection: &NonfungibleHandle<T>,234		from: &T::CrossAccountId,235		to: &T::CrossAccountId,236		token: TokenId,237	) -> DispatchResult {238		ensure!(239			collection.limits.transfers_enabled(),240			<CommonError<T>>::TransferNotAllowed241		);242243		let token_data =244			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;245		ensure!(246			&token_data.owner == from247				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),248			<CommonError<T>>::NoPermission249		);250251		if collection.access == AccessMode::AllowList {252			collection.check_allowlist(from)?;253			collection.check_allowlist(to)?;254		}255		<PalletCommon<T>>::ensure_correct_receiver(to)?;256257		let balance_from = <AccountBalance<T>>::get((collection.id, from))258			.checked_sub(1)259			.ok_or(<CommonError<T>>::TokenValueTooLow)?;260		let balance_to = if from != to {261			let balance_to = <AccountBalance<T>>::get((collection.id, to))262				.checked_add(1)263				.ok_or(ArithmeticError::Overflow)?;264265			ensure!(266				balance_to < collection.limits.account_token_ownership_limit(),267				<CommonError<T>>::AccountTokenLimitExceeded,268			);269270			Some(balance_to)271		} else {272			None273		};274275		// =========276277		<TokenData<T>>::insert(278			(collection.id, token),279			ItemData {280				owner: to.clone(),281				..token_data282			},283		);284285		if let Some(balance_to) = balance_to {286			// from != to287			if balance_from == 0 {288				<AccountBalance<T>>::remove((collection.id, from));289			} else {290				<AccountBalance<T>>::insert((collection.id, from), balance_from);291			}292			<AccountBalance<T>>::insert((collection.id, to), balance_to);293			<Owned<T>>::remove((collection.id, from, token));294			<Owned<T>>::insert((collection.id, to, token), true);295		}296		Self::set_allowance_unchecked(collection, from, token, None, true);297298		collection.log_mirrored(ERC721Events::Transfer {299			from: *from.as_eth(),300			to: *to.as_eth(),301			token_id: token.into(),302		});303		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(304			collection.id,305			token,306			from.clone(),307			to.clone(),308			1,309		));310		Ok(())311	}312313	pub fn create_multiple_items(314		collection: &NonfungibleHandle<T>,315		sender: &T::CrossAccountId,316		data: Vec<CreateItemData<T>>,317	) -> DispatchResult {318		if !collection.is_owner_or_admin(sender) {319			ensure!(320				collection.mint_mode,321				<CommonError<T>>::PublicMintingNotAllowed322			);323			collection.check_allowlist(sender)?;324325			for item in data.iter() {326				collection.check_allowlist(&item.owner)?;327			}328		}329330		for data in data.iter() {331			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;332		}333334		let first_token = <TokensMinted<T>>::get(collection.id);335		let tokens_minted = first_token336			.checked_add(data.len() as u32)337			.ok_or(ArithmeticError::Overflow)?;338		ensure!(339			tokens_minted <= collection.limits.token_limit(),340			<CommonError<T>>::CollectionTokenLimitExceeded341		);342343		let mut balances = BTreeMap::new();344		for data in &data {345			let balance = balances346				.entry(&data.owner)347				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));348			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;349350			ensure!(351				*balance <= collection.limits.account_token_ownership_limit(),352				<CommonError<T>>::AccountTokenLimitExceeded,353			);354		}355356		// =========357358		<TokensMinted<T>>::insert(collection.id, tokens_minted);359		for (account, balance) in balances {360			<AccountBalance<T>>::insert((collection.id, account), balance);361		}362		for (i, data) in data.into_iter().enumerate() {363			let token = first_token + i as u32 + 1;364365			<TokenData<T>>::insert(366				(collection.id, token),367				ItemData {368					const_data: data.const_data,369					variable_data: data.variable_data,370					owner: data.owner.clone(),371				},372			);373			<Owned<T>>::insert((collection.id, &data.owner, token), true);374375			collection.log_mirrored(ERC721Events::Transfer {376				from: H160::default(),377				to: *data.owner.as_eth(),378				token_id: token.into(),379			});380			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(381				collection.id,382				TokenId(token),383				data.owner.clone(),384				1,385			));386		}387		Ok(())388	}389390	pub fn set_allowance_unchecked(391		collection: &NonfungibleHandle<T>,392		sender: &T::CrossAccountId,393		token: TokenId,394		spender: Option<&T::CrossAccountId>,395		assume_implicit_eth: bool,396	) {397		if let Some(spender) = spender {398			let old_spender = <Allowance<T>>::get((collection.id, token));399			<Allowance<T>>::insert((collection.id, token), spender);400			// In ERC721 there is only one possible approved user of token, so we set401			// approved user to spender402			collection.log_mirrored(ERC721Events::Approval {403				owner: *sender.as_eth(),404				approved: *spender.as_eth(),405				token_id: token.into(),406			});407			// In Unique chain, any token can have any amount of approved users, so we need to408			// set allowance of old owner to 0, and allowance of new owner to 1409			if old_spender.as_ref() != Some(spender) {410				if let Some(old_owner) = old_spender {411					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(412						collection.id,413						token,414						sender.clone(),415						old_owner,416						0,417					));418				}419				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(420					collection.id,421					token,422					sender.clone(),423					spender.clone(),424					1,425				));426			}427		} else {428			let old_spender = <Allowance<T>>::take((collection.id, token));429			if !assume_implicit_eth {430				// In ERC721 there is only one possible approved user of token, so we set431				// approved user to zero address432				collection.log_mirrored(ERC721Events::Approval {433					owner: *sender.as_eth(),434					approved: H160::default(),435					token_id: token.into(),436				});437			}438			// In Unique chain, any token can have any amount of approved users, so we need to439			// set allowance of old owner to 0440			if let Some(old_spender) = old_spender {441				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(442					collection.id,443					token,444					sender.clone(),445					old_spender,446					0,447				));448			}449		}450	}451452	pub fn set_allowance(453		collection: &NonfungibleHandle<T>,454		sender: &T::CrossAccountId,455		token: TokenId,456		spender: Option<&T::CrossAccountId>,457	) -> DispatchResult {458		if collection.access == AccessMode::AllowList {459			collection.check_allowlist(sender)?;460			if let Some(spender) = spender {461				collection.check_allowlist(spender)?;462			}463		}464465		if let Some(spender) = spender {466			<PalletCommon<T>>::ensure_correct_receiver(spender)?;467		}468		let token_data =469			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;470		if &token_data.owner != sender {471			ensure!(472				collection.ignores_owned_amount(sender),473				<CommonError<T>>::CantApproveMoreThanOwned474			);475		}476477		// =========478479		Self::set_allowance_unchecked(collection, sender, token, spender, false);480		Ok(())481	}482483	pub fn transfer_from(484		collection: &NonfungibleHandle<T>,485		spender: &T::CrossAccountId,486		from: &T::CrossAccountId,487		to: &T::CrossAccountId,488		token: TokenId,489	) -> DispatchResult {490		if spender.conv_eq(from) {491			return Self::transfer(collection, from, to, token);492		}493		if collection.access == AccessMode::AllowList {494			// `from`, `to` checked in [`transfer`]495			collection.check_allowlist(spender)?;496		}497498		if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {499			ensure!(500				collection.ignores_allowance(spender),501				<CommonError<T>>::TokenValueNotEnough502			);503		}504505		// =========506507		Self::transfer(collection, from, to, token)?;508		// Allowance is reset in [`transfer`]509		Ok(())510	}511512	pub fn burn_from(513		collection: &NonfungibleHandle<T>,514		spender: &T::CrossAccountId,515		from: &T::CrossAccountId,516		token: TokenId,517	) -> DispatchResult {518		if spender.conv_eq(from) {519			return Self::burn(collection, from, token);520		}521		if collection.access == AccessMode::AllowList {522			// `from` checked in [`burn`]523			collection.check_allowlist(spender)?;524		}525526		if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {527			ensure!(528				collection.ignores_allowance(spender),529				<CommonError<T>>::TokenValueNotEnough530			);531		}532533		// =========534535		Self::burn(collection, from, token)536	}537538	pub fn set_variable_metadata(539		collection: &NonfungibleHandle<T>,540		sender: &T::CrossAccountId,541		token: TokenId,542		data: BoundedVec<u8, CustomDataLimit>,543	) -> DispatchResult {544		let token_data =545			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;546		collection.check_can_update_meta(sender, &token_data.owner)?;547548		// =========549550		<TokenData<T>>::insert(551			(collection.id, token),552			ItemData {553				variable_data: data,554				..token_data555			},556		);557		Ok(())558	}559560	/// Delegated to `create_multiple_items`561	pub fn create_item(562		collection: &NonfungibleHandle<T>,563		sender: &T::CrossAccountId,564		data: CreateItemData<T>,565	) -> DispatchResult {566		Self::create_multiple_items(collection, sender, vec![data])567	}568}
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -2,8 +2,8 @@
 
 use frame_support::{ensure, BoundedVec};
 use up_data_structs::{
-	AccessMode, Collection, CollectionId, CustomDataLimit,
-	MAX_REFUNGIBLE_PIECES, TokenId, CreateCollectionData,
+	AccessMode, Collection, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,
+	CreateCollectionData,
 };
 use pallet_common::{
 	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -36,9 +36,8 @@
 use frame_system::{self as system, ensure_signed};
 use sp_runtime::{sp_std::prelude::Vec};
 use up_data_structs::{
-	MAX_DECIMAL_POINTS,
-	VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
-	MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
+	MAX_DECIMAL_POINTS, VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
+	OFFCHAIN_SCHEMA_LIMIT, MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
 	MAX_TOKEN_PREFIX_LENGTH, AccessMode, Collection, CreateItemData, CollectionLimits,
 	CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
 	CreateCollectionData, CustomDataLimit,