difftreelog
Merge pull request #463 from UniqueNetwork/feature/remove_const_data_rft
in: master
10 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6311,7 +6311,7 @@
[[package]]
name = "pallet-refungible"
-version = "0.1.2"
+version = "0.2.0"
dependencies = [
"ethereum",
"evm-coder",
@@ -12732,7 +12732,7 @@
[[package]]
name = "up-data-structs"
-version = "0.1.2"
+version = "0.2.0"
dependencies = [
"derivative",
"frame-support",
pallets/refungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/refungible/CHANGELOG.md
+++ b/pallets/refungible/CHANGELOG.md
@@ -2,6 +2,11 @@
All notable changes to this project will be documented in this file.
+## [v0.2.0] - 2022-08-01
+### Deprecated
+- `ItemData`
+- `TokenData`
+
## [v0.1.2] - 2022-07-14
### Other changes
pallets/refungible/Cargo.tomldiffbeforeafterboth--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-refungible"
-version = "0.1.2"
+version = "0.2.0"
license = "GPLv3"
edition = "2021"
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -32,7 +32,7 @@
use crate::{
AccountBalance, Allowance, Balance, Config, Error, Owned, Pallet, RefungibleHandle,
- SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,
+ SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted, TotalSupply,
};
macro_rules! max_weight_of {
@@ -155,7 +155,6 @@
) -> Result<CreateRefungibleExData<T::CrossAccountId>, DispatchError> {
match data {
up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateRefungibleExData {
- const_data: data.const_data,
users: {
let mut out = BTreeMap::new();
out.insert(to.clone(), data.pieces);
@@ -421,7 +420,7 @@
}
fn collection_tokens(&self) -> Vec<TokenId> {
- <TokenData<T>>::iter_prefix((self.id,))
+ <TotalSupply<T>>::iter_prefix((self.id,))
.map(|(id, _)| id)
.collect()
}
pallets/refungible/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//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//! of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//! Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//! transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//! an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//! with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//! collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//! Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;9192use codec::{Encode, Decode, MaxEncodedLen};93use core::ops::Deref;94use evm_coder::ToLog;95use frame_support::{BoundedVec, ensure, fail, storage::with_transaction, transactional};96use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};97use pallet_evm_coder_substrate::WithRecorder;98use pallet_common::{99 CommonCollectionOperations, Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,100};101use pallet_structure::Pallet as PalletStructure;102use scale_info::TypeInfo;103use sp_core::H160;104use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};105use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};106use up_data_structs::{107 AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData,108 CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId, Property,109 PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,110 TrySetProperty,111};112113pub use pallet::*;114#[cfg(feature = "runtime-benchmarks")]115pub mod benchmarking;116pub mod common;117pub mod erc;118pub mod erc_token;119pub mod weights;120pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;121122/// Token data, stored independently from other data used to describe it123/// for the convenience of database access. Notably contains the token metadata.124#[struct_versioning::versioned(version = 2, upper)]125#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]126pub struct ItemData {127 pub const_data: BoundedVec<u8, CustomDataLimit>,128129 #[version(..2)]130 pub variable_data: BoundedVec<u8, CustomDataLimit>,131}132133#[frame_support::pallet]134pub mod pallet {135 use super::*;136 use frame_support::{137 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,138 traits::StorageVersion,139 };140 use frame_system::pallet_prelude::*;141 use up_data_structs::{CollectionId, TokenId};142 use super::weights::WeightInfo;143144 #[pallet::error]145 pub enum Error<T> {146 /// Not Refungible item data used to mint in Refungible collection.147 NotRefungibleDataUsedToMintFungibleCollectionToken,148 /// Maximum refungibility exceeded.149 WrongRefungiblePieces,150 /// Refungible token can't be repartitioned by user who isn't owns all pieces.151 RepartitionWhileNotOwningAllPieces,152 /// Refungible token can't nest other tokens.153 RefungibleDisallowsNesting,154 /// Setting item properties is not allowed.155 SettingPropertiesNotAllowed,156 }157158 #[pallet::config]159 pub trait Config:160 frame_system::Config + pallet_common::Config + pallet_structure::Config161 {162 type WeightInfo: WeightInfo;163 }164165 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);166167 #[pallet::pallet]168 #[pallet::storage_version(STORAGE_VERSION)]169 #[pallet::generate_store(pub(super) trait Store)]170 pub struct Pallet<T>(_);171172 /// Total amount of minted tokens in a collection.173 #[pallet::storage]174 pub type TokensMinted<T: Config> =175 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;176177 /// Amount of tokens burnt in a collection.178 #[pallet::storage]179 pub type TokensBurnt<T: Config> =180 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;181182 /// Token data, used to partially describe a token.183 #[pallet::storage]184 pub type TokenData<T: Config> = StorageNMap<185 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),186 Value = ItemData,187 QueryKind = ValueQuery,188 >;189190 /// Amount of pieces a refungible token is split into.191 #[pallet::storage]192 #[pallet::getter(fn token_properties)]193 pub type TokenProperties<T: Config> = StorageNMap<194 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),195 Value = up_data_structs::Properties,196 QueryKind = ValueQuery,197 OnEmpty = up_data_structs::TokenProperties,198 >;199200 /// Total amount of pieces for token201 #[pallet::storage]202 pub type TotalSupply<T: Config> = StorageNMap<203 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),204 Value = u128,205 QueryKind = ValueQuery,206 >;207208 /// Used to enumerate tokens owned by account.209 #[pallet::storage]210 pub type Owned<T: Config> = StorageNMap<211 Key = (212 Key<Twox64Concat, CollectionId>,213 Key<Blake2_128Concat, T::CrossAccountId>,214 Key<Twox64Concat, TokenId>,215 ),216 Value = bool,217 QueryKind = ValueQuery,218 >;219220 /// Amount of tokens (not pieces) partially owned by an account within a collection.221 #[pallet::storage]222 pub type AccountBalance<T: Config> = StorageNMap<223 Key = (224 Key<Twox64Concat, CollectionId>,225 // Owner226 Key<Blake2_128Concat, T::CrossAccountId>,227 ),228 Value = u32,229 QueryKind = ValueQuery,230 >;231232 /// Amount of token pieces owned by account.233 #[pallet::storage]234 pub type Balance<T: Config> = StorageNMap<235 Key = (236 Key<Twox64Concat, CollectionId>,237 Key<Twox64Concat, TokenId>,238 // Owner239 Key<Blake2_128Concat, T::CrossAccountId>,240 ),241 Value = u128,242 QueryKind = ValueQuery,243 >;244245 /// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.246 #[pallet::storage]247 pub type Allowance<T: Config> = StorageNMap<248 Key = (249 Key<Twox64Concat, CollectionId>,250 Key<Twox64Concat, TokenId>,251 // Owner252 Key<Blake2_128, T::CrossAccountId>,253 // Spender254 Key<Blake2_128Concat, T::CrossAccountId>,255 ),256 Value = u128,257 QueryKind = ValueQuery,258 >;259260 #[pallet::hooks]261 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {262 fn on_runtime_upgrade() -> Weight {263 StorageVersion::new(1).put::<Pallet<T>>();264265 0266 }267 }268}269270pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);271impl<T: Config> RefungibleHandle<T> {272 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {273 Self(inner)274 }275 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {276 self.0277 }278 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {279 &mut self.0280 }281}282283impl<T: Config> Deref for RefungibleHandle<T> {284 type Target = pallet_common::CollectionHandle<T>;285286 fn deref(&self) -> &Self::Target {287 &self.0288 }289}290291impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {292 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {293 self.0.recorder()294 }295 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {296 self.0.into_recorder()297 }298}299300impl<T: Config> Pallet<T> {301 /// Get number of RFT tokens in collection302 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {303 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)304 }305306 /// Check that RFT token exists307 ///308 /// - `token`: Token ID.309 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {310 <TotalSupply<T>>::contains_key((collection.id, token))311 }312313 pub fn set_scoped_token_property(314 collection_id: CollectionId,315 token_id: TokenId,316 scope: PropertyScope,317 property: Property,318 ) -> DispatchResult {319 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {320 properties.try_scoped_set(scope, property.key, property.value)321 })322 .map_err(<CommonError<T>>::from)?;323324 Ok(())325 }326327 pub fn set_scoped_token_properties(328 collection_id: CollectionId,329 token_id: TokenId,330 scope: PropertyScope,331 properties: impl Iterator<Item = Property>,332 ) -> DispatchResult {333 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {334 stored_properties.try_scoped_set_from_iter(scope, properties)335 })336 .map_err(<CommonError<T>>::from)?;337338 Ok(())339 }340}341342// unchecked calls skips any permission checks343impl<T: Config> Pallet<T> {344 /// Create RFT collection345 ///346 /// `init_collection` will take non-refundable deposit for collection creation.347 ///348 /// - `data`: Contains settings for collection limits and permissions.349 pub fn init_collection(350 owner: T::CrossAccountId,351 data: CreateCollectionData<T::AccountId>,352 ) -> Result<CollectionId, DispatchError> {353 <PalletCommon<T>>::init_collection(owner, data, false)354 }355356 /// Destroy RFT collection357 ///358 /// `destroy_collection` will throw error if collection contains any tokens.359 /// Only owner can destroy collection.360 pub fn destroy_collection(361 collection: RefungibleHandle<T>,362 sender: &T::CrossAccountId,363 ) -> DispatchResult {364 let id = collection.id;365366 if Self::collection_has_tokens(id) {367 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());368 }369370 // =========371372 PalletCommon::destroy_collection(collection.0, sender)?;373374 <TokensMinted<T>>::remove(id);375 <TokensBurnt<T>>::remove(id);376 <TokenData<T>>::remove_prefix((id,), None);377 <TotalSupply<T>>::remove_prefix((id,), None);378 <Balance<T>>::remove_prefix((id,), None);379 <Allowance<T>>::remove_prefix((id,), None);380 <Owned<T>>::remove_prefix((id,), None);381 <AccountBalance<T>>::remove_prefix((id,), None);382 Ok(())383 }384385 fn collection_has_tokens(collection_id: CollectionId) -> bool {386 <TokenData<T>>::iter_prefix((collection_id,))387 .next()388 .is_some()389 }390391 pub fn burn_token_unchecked(392 collection: &RefungibleHandle<T>,393 token_id: TokenId,394 ) -> DispatchResult {395 let burnt = <TokensBurnt<T>>::get(collection.id)396 .checked_add(1)397 .ok_or(ArithmeticError::Overflow)?;398399 <TokensBurnt<T>>::insert(collection.id, burnt);400 <TokenData<T>>::remove((collection.id, token_id));401 <TokenProperties<T>>::remove((collection.id, token_id));402 <TotalSupply<T>>::remove((collection.id, token_id));403 <Balance<T>>::remove_prefix((collection.id, token_id), None);404 <Allowance<T>>::remove_prefix((collection.id, token_id), None);405 // TODO: ERC721 transfer event406 Ok(())407 }408409 /// Burn RFT token pieces410 ///411 /// `burn` will decrease total amount of token pieces and amount owned by sender.412 /// `burn` can be called even if there are multiple owners of the RFT token.413 /// If sender wouldn't have any pieces left after `burn` than she will stop being414 /// one of the owners of the token. If there is no account that owns any pieces of415 /// the token than token will be burned too.416 ///417 /// - `amount`: Amount of token pieces to burn.418 /// - `token`: Token who's pieces should be burned419 /// - `collection`: Collection that contains the token420 pub fn burn(421 collection: &RefungibleHandle<T>,422 owner: &T::CrossAccountId,423 token: TokenId,424 amount: u128,425 ) -> DispatchResult {426 let total_supply = <TotalSupply<T>>::get((collection.id, token))427 .checked_sub(amount)428 .ok_or(<CommonError<T>>::TokenValueTooLow)?;429430 // This was probally last owner of this token?431 if total_supply == 0 {432 // Ensure user actually owns this amount433 ensure!(434 <Balance<T>>::get((collection.id, token, owner)) == amount,435 <CommonError<T>>::TokenValueTooLow436 );437 let account_balance = <AccountBalance<T>>::get((collection.id, owner))438 .checked_sub(1)439 // Should not occur440 .ok_or(ArithmeticError::Underflow)?;441442 // =========443444 <Owned<T>>::remove((collection.id, owner, token));445 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);446 <AccountBalance<T>>::insert((collection.id, owner), account_balance);447 Self::burn_token_unchecked(collection, token)?;448 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(449 collection.id,450 token,451 owner.clone(),452 amount,453 ));454 return Ok(());455 }456457 let balance = <Balance<T>>::get((collection.id, token, owner))458 .checked_sub(amount)459 .ok_or(<CommonError<T>>::TokenValueTooLow)?;460 let account_balance = if balance == 0 {461 <AccountBalance<T>>::get((collection.id, owner))462 .checked_sub(1)463 // Should not occur464 .ok_or(ArithmeticError::Underflow)?465 } else {466 0467 };468469 // =========470471 if balance == 0 {472 <Owned<T>>::remove((collection.id, owner, token));473 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);474 <Balance<T>>::remove((collection.id, token, owner));475 <AccountBalance<T>>::insert((collection.id, owner), account_balance);476 } else {477 <Balance<T>>::insert((collection.id, token, owner), balance);478 }479 <TotalSupply<T>>::insert((collection.id, token), total_supply);480481 <PalletEvm<T>>::deposit_log(482 ERC20Events::Transfer {483 from: *owner.as_eth(),484 to: H160::default(),485 value: amount.into(),486 }487 .to_log(T::EvmTokenAddressMapping::token_to_address(488 collection.id,489 token,490 )),491 );492 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(493 collection.id,494 token,495 owner.clone(),496 amount,497 ));498 Ok(())499 }500501 #[transactional]502 fn modify_token_properties(503 collection: &RefungibleHandle<T>,504 sender: &T::CrossAccountId,505 token_id: TokenId,506 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,507 is_token_create: bool,508 nesting_budget: &dyn Budget,509 ) -> DispatchResult {510 let is_collection_admin = || collection.is_owner_or_admin(sender);511 let is_token_owner = || -> Result<bool, DispatchError> {512 let balance = collection.balance(sender.clone(), token_id);513 let total_pieces: u128 =514 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);515 if balance != total_pieces {516 return Ok(false);517 }518519 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(520 sender.clone(),521 collection.id,522 token_id,523 None,524 nesting_budget,525 )?;526527 Ok(is_bundle_owner)528 };529530 for (key, value) in properties {531 let permission = <PalletCommon<T>>::property_permissions(collection.id)532 .get(&key)533 .cloned()534 .unwrap_or_else(PropertyPermission::none);535536 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))537 .get(&key)538 .is_some();539540 match permission {541 PropertyPermission { mutable: false, .. } if is_property_exists => {542 return Err(<CommonError<T>>::NoPermission.into());543 }544545 PropertyPermission {546 collection_admin,547 token_owner,548 ..549 } => {550 //TODO: investigate threats during public minting.551 let is_token_create =552 is_token_create && (collection_admin || token_owner) && value.is_some();553 if !(is_token_create554 || (collection_admin && is_collection_admin())555 || (token_owner && is_token_owner()?))556 {557 fail!(<CommonError<T>>::NoPermission);558 }559 }560 }561562 match value {563 Some(value) => {564 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {565 properties.try_set(key.clone(), value)566 })567 .map_err(<CommonError<T>>::from)?;568569 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(570 collection.id,571 token_id,572 key,573 ));574 }575 None => {576 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {577 properties.remove(&key)578 })579 .map_err(<CommonError<T>>::from)?;580581 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(582 collection.id,583 token_id,584 key,585 ));586 }587 }588 }589590 Ok(())591 }592593 pub fn set_token_properties(594 collection: &RefungibleHandle<T>,595 sender: &T::CrossAccountId,596 token_id: TokenId,597 properties: impl Iterator<Item = Property>,598 is_token_create: bool,599 nesting_budget: &dyn Budget,600 ) -> DispatchResult {601 Self::modify_token_properties(602 collection,603 sender,604 token_id,605 properties.map(|p| (p.key, Some(p.value))),606 is_token_create,607 nesting_budget,608 )609 }610611 pub fn set_token_property(612 collection: &RefungibleHandle<T>,613 sender: &T::CrossAccountId,614 token_id: TokenId,615 property: Property,616 nesting_budget: &dyn Budget,617 ) -> DispatchResult {618 let is_token_create = false;619620 Self::set_token_properties(621 collection,622 sender,623 token_id,624 [property].into_iter(),625 is_token_create,626 nesting_budget,627 )628 }629630 pub fn delete_token_properties(631 collection: &RefungibleHandle<T>,632 sender: &T::CrossAccountId,633 token_id: TokenId,634 property_keys: impl Iterator<Item = PropertyKey>,635 nesting_budget: &dyn Budget,636 ) -> DispatchResult {637 let is_token_create = false;638639 Self::modify_token_properties(640 collection,641 sender,642 token_id,643 property_keys.into_iter().map(|key| (key, None)),644 is_token_create,645 nesting_budget,646 )647 }648649 pub fn delete_token_property(650 collection: &RefungibleHandle<T>,651 sender: &T::CrossAccountId,652 token_id: TokenId,653 property_key: PropertyKey,654 nesting_budget: &dyn Budget,655 ) -> DispatchResult {656 Self::delete_token_properties(657 collection,658 sender,659 token_id,660 [property_key].into_iter(),661 nesting_budget,662 )663 }664665 /// Transfer RFT token pieces from one account to another.666 ///667 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.668 ///669 /// - `from`: Owner of token pieces to transfer.670 /// - `to`: Recepient of transfered token pieces.671 /// - `amount`: Amount of token pieces to transfer.672 /// - `token`: Token whos pieces should be transfered673 /// - `collection`: Collection that contains the token674 pub fn transfer(675 collection: &RefungibleHandle<T>,676 from: &T::CrossAccountId,677 to: &T::CrossAccountId,678 token: TokenId,679 amount: u128,680 nesting_budget: &dyn Budget,681 ) -> DispatchResult {682 ensure!(683 collection.limits.transfers_enabled(),684 <CommonError<T>>::TransferNotAllowed685 );686687 if collection.permissions.access() == AccessMode::AllowList {688 collection.check_allowlist(from)?;689 collection.check_allowlist(to)?;690 }691 <PalletCommon<T>>::ensure_correct_receiver(to)?;692693 let balance_from = <Balance<T>>::get((collection.id, token, from))694 .checked_sub(amount)695 .ok_or(<CommonError<T>>::TokenValueTooLow)?;696 let mut create_target = false;697 let from_to_differ = from != to;698 let balance_to = if from != to {699 let old_balance = <Balance<T>>::get((collection.id, token, to));700 if old_balance == 0 {701 create_target = true;702 }703 Some(704 old_balance705 .checked_add(amount)706 .ok_or(ArithmeticError::Overflow)?,707 )708 } else {709 None710 };711712 let account_balance_from = if balance_from == 0 {713 Some(714 <AccountBalance<T>>::get((collection.id, from))715 .checked_sub(1)716 // Should not occur717 .ok_or(ArithmeticError::Underflow)?,718 )719 } else {720 None721 };722 // Account data is created in token, AccountBalance should be increased723 // But only if from != to as we shouldn't check overflow in this case724 let account_balance_to = if create_target && from_to_differ {725 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))726 .checked_add(1)727 .ok_or(ArithmeticError::Overflow)?;728 ensure!(729 account_balance_to < collection.limits.account_token_ownership_limit(),730 <CommonError<T>>::AccountTokenLimitExceeded,731 );732733 Some(account_balance_to)734 } else {735 None736 };737738 // =========739740 <PalletStructure<T>>::nest_if_sent_to_token(741 from.clone(),742 to,743 collection.id,744 token,745 nesting_budget,746 )?;747748 if let Some(balance_to) = balance_to {749 // from != to750 if balance_from == 0 {751 <Balance<T>>::remove((collection.id, token, from));752 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);753 } else {754 <Balance<T>>::insert((collection.id, token, from), balance_from);755 }756 <Balance<T>>::insert((collection.id, token, to), balance_to);757 if let Some(account_balance_from) = account_balance_from {758 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);759 <Owned<T>>::remove((collection.id, from, token));760 }761 if let Some(account_balance_to) = account_balance_to {762 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);763 <Owned<T>>::insert((collection.id, to, token), true);764 }765 }766767 <PalletEvm<T>>::deposit_log(768 ERC20Events::Transfer {769 from: *from.as_eth(),770 to: *to.as_eth(),771 value: amount.into(),772 }773 .to_log(T::EvmTokenAddressMapping::token_to_address(774 collection.id,775 token,776 )),777 );778 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(779 collection.id,780 token,781 from.clone(),782 to.clone(),783 amount,784 ));785 Ok(())786 }787788 /// Batched operation to create multiple RFT tokens.789 ///790 /// Same as `create_item` but creates multiple tokens.791 ///792 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.793 pub fn create_multiple_items(794 collection: &RefungibleHandle<T>,795 sender: &T::CrossAccountId,796 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,797 nesting_budget: &dyn Budget,798 ) -> DispatchResult {799 if !collection.is_owner_or_admin(sender) {800 ensure!(801 collection.permissions.mint_mode(),802 <CommonError<T>>::PublicMintingNotAllowed803 );804 collection.check_allowlist(sender)?;805806 for item in data.iter() {807 for user in item.users.keys() {808 collection.check_allowlist(user)?;809 }810 }811 }812813 for item in data.iter() {814 for (owner, _) in item.users.iter() {815 <PalletCommon<T>>::ensure_correct_receiver(owner)?;816 }817 }818819 // Total pieces per tokens820 let totals = data821 .iter()822 .map(|data| {823 Ok(data824 .users825 .iter()826 .map(|u| u.1)827 .try_fold(0u128, |acc, v| acc.checked_add(*v))828 .ok_or(ArithmeticError::Overflow)?)829 })830 .collect::<Result<Vec<_>, DispatchError>>()?;831 for total in &totals {832 ensure!(833 *total <= MAX_REFUNGIBLE_PIECES,834 <Error<T>>::WrongRefungiblePieces835 );836 }837838 let first_token_id = <TokensMinted<T>>::get(collection.id);839 let tokens_minted = first_token_id840 .checked_add(data.len() as u32)841 .ok_or(ArithmeticError::Overflow)?;842 ensure!(843 tokens_minted < collection.limits.token_limit(),844 <CommonError<T>>::CollectionTokenLimitExceeded845 );846847 let mut balances = BTreeMap::new();848 for data in &data {849 for owner in data.users.keys() {850 let balance = balances851 .entry(owner)852 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));853 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;854855 ensure!(856 *balance <= collection.limits.account_token_ownership_limit(),857 <CommonError<T>>::AccountTokenLimitExceeded,858 );859 }860 }861862 for (i, token) in data.iter().enumerate() {863 let token_id = TokenId(first_token_id + i as u32 + 1);864 for (to, _) in token.users.iter() {865 <PalletStructure<T>>::check_nesting(866 sender.clone(),867 to,868 collection.id,869 token_id,870 nesting_budget,871 )?;872 }873 }874875 // =========876877 with_transaction(|| {878 for (i, data) in data.iter().enumerate() {879 let token_id = first_token_id + i as u32 + 1;880 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);881882 <TokenData<T>>::insert(883 (collection.id, token_id),884 ItemData {885 const_data: data.const_data.clone(),886 },887 );888889 for (user, amount) in data.users.iter() {890 if *amount == 0 {891 continue;892 }893 <Balance<T>>::insert((collection.id, token_id, &user), amount);894 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);895 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(896 user,897 collection.id,898 TokenId(token_id),899 );900 }901902 if let Err(e) = Self::set_token_properties(903 collection,904 sender,905 TokenId(token_id),906 data.properties.clone().into_iter(),907 true,908 nesting_budget,909 ) {910 return TransactionOutcome::Rollback(Err(e));911 }912 }913 TransactionOutcome::Commit(Ok(()))914 })?;915916 <TokensMinted<T>>::insert(collection.id, tokens_minted);917918 for (account, balance) in balances {919 <AccountBalance<T>>::insert((collection.id, account), balance);920 }921922 for (i, token) in data.into_iter().enumerate() {923 let token_id = first_token_id + i as u32 + 1;924925 for (user, amount) in token.users.into_iter() {926 if amount == 0 {927 continue;928 }929930 <PalletEvm<T>>::deposit_log(931 ERC20Events::Transfer {932 from: H160::default(),933 to: *user.as_eth(),934 value: amount.into(),935 }936 .to_log(T::EvmTokenAddressMapping::token_to_address(937 collection.id,938 TokenId(token_id),939 )),940 );941 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(942 collection.id,943 TokenId(token_id),944 user,945 amount,946 ));947 }948 }949 Ok(())950 }951952 pub fn set_allowance_unchecked(953 collection: &RefungibleHandle<T>,954 sender: &T::CrossAccountId,955 spender: &T::CrossAccountId,956 token: TokenId,957 amount: u128,958 ) {959 if amount == 0 {960 <Allowance<T>>::remove((collection.id, token, sender, spender));961 } else {962 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);963 }964965 <PalletEvm<T>>::deposit_log(966 ERC20Events::Approval {967 owner: *sender.as_eth(),968 spender: *spender.as_eth(),969 value: amount.into(),970 }971 .to_log(T::EvmTokenAddressMapping::token_to_address(972 collection.id,973 token,974 )),975 );976 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(977 collection.id,978 token,979 sender.clone(),980 spender.clone(),981 amount,982 ))983 }984985 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.986 ///987 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.988 pub fn set_allowance(989 collection: &RefungibleHandle<T>,990 sender: &T::CrossAccountId,991 spender: &T::CrossAccountId,992 token: TokenId,993 amount: u128,994 ) -> DispatchResult {995 if collection.permissions.access() == AccessMode::AllowList {996 collection.check_allowlist(sender)?;997 collection.check_allowlist(spender)?;998 }9991000 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10011002 if <Balance<T>>::get((collection.id, token, sender)) < amount {1003 ensure!(1004 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1005 <CommonError<T>>::CantApproveMoreThanOwned1006 );1007 }10081009 // =========10101011 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1012 Ok(())1013 }10141015 /// Returns allowance, which should be set after transaction1016 fn check_allowed(1017 collection: &RefungibleHandle<T>,1018 spender: &T::CrossAccountId,1019 from: &T::CrossAccountId,1020 token: TokenId,1021 amount: u128,1022 nesting_budget: &dyn Budget,1023 ) -> Result<Option<u128>, DispatchError> {1024 if spender.conv_eq(from) {1025 return Ok(None);1026 }1027 if collection.permissions.access() == AccessMode::AllowList {1028 // `from`, `to` checked in [`transfer`]1029 collection.check_allowlist(spender)?;1030 }1031 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1032 // TODO: should collection owner be allowed to perform this transfer?1033 ensure!(1034 <PalletStructure<T>>::check_indirectly_owned(1035 spender.clone(),1036 source.0,1037 source.1,1038 None,1039 nesting_budget1040 )?,1041 <CommonError<T>>::ApprovedValueTooLow,1042 );1043 return Ok(None);1044 }1045 let allowance =1046 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1047 if allowance.is_none() {1048 ensure!(1049 collection.ignores_allowance(spender),1050 <CommonError<T>>::ApprovedValueTooLow1051 );1052 }1053 Ok(allowance)1054 }10551056 /// Transfer RFT token pieces from one account to another.1057 ///1058 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1059 /// The owner should set allowance for the spender to transfer pieces.1060 ///1061 /// [`transfer`]: struct.Pallet.html#method.transfer1062 pub fn transfer_from(1063 collection: &RefungibleHandle<T>,1064 spender: &T::CrossAccountId,1065 from: &T::CrossAccountId,1066 to: &T::CrossAccountId,1067 token: TokenId,1068 amount: u128,1069 nesting_budget: &dyn Budget,1070 ) -> DispatchResult {1071 let allowance =1072 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10731074 // =========10751076 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1077 if let Some(allowance) = allowance {1078 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1079 }1080 Ok(())1081 }10821083 /// Burn RFT token pieces from the account.1084 ///1085 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1086 /// set allowance for the spender to burn pieces1087 ///1088 /// [`burn`]: struct.Pallet.html#method.burn1089 pub fn burn_from(1090 collection: &RefungibleHandle<T>,1091 spender: &T::CrossAccountId,1092 from: &T::CrossAccountId,1093 token: TokenId,1094 amount: u128,1095 nesting_budget: &dyn Budget,1096 ) -> DispatchResult {1097 let allowance =1098 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10991100 // =========11011102 Self::burn(collection, from, token, amount)?;1103 if let Some(allowance) = allowance {1104 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1105 }1106 Ok(())1107 }11081109 /// Create RFT token.1110 ///1111 /// The sender should be the owner/admin of the collection or collection should be configured1112 /// to allow public minting.1113 ///1114 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1115 /// of token pieces they will receive.1116 pub fn create_item(1117 collection: &RefungibleHandle<T>,1118 sender: &T::CrossAccountId,1119 data: CreateRefungibleExData<T::CrossAccountId>,1120 nesting_budget: &dyn Budget,1121 ) -> DispatchResult {1122 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1123 }11241125 /// Repartition RFT token.1126 ///1127 /// `repartition` will set token balance of the sender and total amount of token pieces.1128 /// Sender should own all of the token pieces. `repartition' could be done even if some1129 /// token pieces were burned before.1130 ///1131 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1132 pub fn repartition(1133 collection: &RefungibleHandle<T>,1134 owner: &T::CrossAccountId,1135 token: TokenId,1136 amount: u128,1137 ) -> DispatchResult {1138 ensure!(1139 amount <= MAX_REFUNGIBLE_PIECES,1140 <Error<T>>::WrongRefungiblePieces1141 );1142 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1143 // Ensure user owns all pieces1144 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1145 let balance = <Balance<T>>::get((collection.id, token, owner));1146 ensure!(1147 total_pieces == balance,1148 <Error<T>>::RepartitionWhileNotOwningAllPieces1149 );11501151 <Balance<T>>::insert((collection.id, token, owner), amount);1152 <TotalSupply<T>>::insert((collection.id, token), amount);11531154 if amount > total_pieces {1155 let mint_amount = amount - total_pieces;1156 <PalletEvm<T>>::deposit_log(1157 ERC20Events::Transfer {1158 from: H160::default(),1159 to: *owner.as_eth(),1160 value: mint_amount.into(),1161 }1162 .to_log(T::EvmTokenAddressMapping::token_to_address(1163 collection.id,1164 token,1165 )),1166 );1167 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1168 collection.id,1169 token,1170 owner.clone(),1171 mint_amount,1172 ));1173 } else if total_pieces > amount {1174 let burn_amount = total_pieces - amount;1175 <PalletEvm<T>>::deposit_log(1176 ERC20Events::Transfer {1177 from: *owner.as_eth(),1178 to: H160::default(),1179 value: burn_amount.into(),1180 }1181 .to_log(T::EvmTokenAddressMapping::token_to_address(1182 collection.id,1183 token,1184 )),1185 );1186 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1187 collection.id,1188 token,1189 owner.clone(),1190 burn_amount,1191 ));1192 }11931194 Ok(())1195 }11961197 fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1198 let mut owner = None;1199 let mut count = 0;1200 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1201 count += 1;1202 if count > 1 {1203 return None;1204 }1205 owner = Some(key);1206 }1207 owner1208 }12091210 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1211 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1212 }12131214 pub fn set_collection_properties(1215 collection: &RefungibleHandle<T>,1216 sender: &T::CrossAccountId,1217 properties: Vec<Property>,1218 ) -> DispatchResult {1219 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)1220 }12211222 pub fn delete_collection_properties(1223 collection: &RefungibleHandle<T>,1224 sender: &T::CrossAccountId,1225 property_keys: Vec<PropertyKey>,1226 ) -> DispatchResult {1227 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1228 }12291230 pub fn set_token_property_permissions(1231 collection: &RefungibleHandle<T>,1232 sender: &T::CrossAccountId,1233 property_permissions: Vec<PropertyKeyPermission>,1234 ) -> DispatchResult {1235 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1236 }12371238 /// Returns 10 token in no particular order.1239 ///1240 /// There is no direct way to get token holders in ascending order,1241 /// since `iter_prefix` returns values in no particular order.1242 /// Therefore, getting the 10 largest holders with a large value of holders1243 /// can lead to impact memory allocation + sorting with `n * log (n)`.1244 pub fn token_owners(1245 collection_id: CollectionId,1246 token: TokenId,1247 ) -> Option<Vec<T::CrossAccountId>> {1248 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1249 .map(|(owner, _amount)| owner)1250 .take(10)1251 .collect();12521253 if res.is_empty() {1254 None1255 } else {1256 Some(res)1257 }1258 }1259}primitives/data-structs/CHANGELOG.mddiffbeforeafterboth--- a/primitives/data-structs/CHANGELOG.md
+++ b/primitives/data-structs/CHANGELOG.md
@@ -2,6 +2,9 @@
All notable changes to this project will be documented in this file.
+## [v0.2.0] - 2022-08-01
+### Deprecated
+- `CreateReFungibleData::const_data`
## [v0.1.2] - 2022-07-25
### Added
primitives/data-structs/Cargo.tomldiffbeforeafterboth--- a/primitives/data-structs/Cargo.toml
+++ b/primitives/data-structs/Cargo.toml
@@ -6,7 +6,7 @@
license = 'GPLv3'
homepage = "https://unique.network"
repository = 'https://github.com/UniqueNetwork/unique-chain'
-version = '0.1.2'
+version = '0.2.0'
[dependencies]
scale-info = { version = "2.0.1", default-features = false, features = [
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -780,12 +780,7 @@
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
#[derivative(Debug)]
pub struct CreateReFungibleData {
- /// Immutable metadata of the token
- #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
- #[derivative(Debug(format_with = "bounded::vec_debug"))]
- pub const_data: BoundedVec<u8, CustomDataLimit>,
-
- /// Pieces of created token.
+ /// Number of pieces the RFT is split into
pub pieces: u128,
/// Key-value pairs used to describe the token as metadata
@@ -832,11 +827,6 @@
#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]
pub struct CreateRefungibleExData<CrossAccountId> {
- /// Custom data stored in token.
- #[derivative(Debug(format_with = "bounded::vec_debug"))]
- pub const_data: BoundedVec<u8, CustomDataLimit>,
-
- /// Users who will be assigned the specified number of token parts.
#[derivative(Debug(format_with = "bounded::map_debug"))]
pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,
#[derivative(Debug(format_with = "bounded::vec_debug"))]
@@ -869,16 +859,6 @@
/// Extended data for create ReFungible item in case of
/// single token, which may have many owners
RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),
-}
-
-impl CreateItemData {
- /// Get size of custom data.
- pub fn data_size(&self) -> usize {
- match self {
- CreateItemData::ReFungible(data) => data.const_data.len(),
- _ => 0,
- }
- }
}
impl From<CreateNftData> for CreateItemData {
runtime/common/src/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/src/sponsoring.rs
+++ b/runtime/common/src/sponsoring.rs
@@ -156,17 +156,13 @@
pub fn withdraw_create_item<T: Config>(
collection: &CollectionHandle<T>,
who: &T::CrossAccountId,
- _properties: &CreateItemData,
+ properties: &CreateItemData,
) -> Option<()> {
- if _properties.data_size() as u32 > collection.limits.sponsored_data_size() {
- return None;
- }
-
// sponsor timeout
let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
let limit = collection
.limits
- .sponsor_transfer_timeout(match _properties {
+ .sponsor_transfer_timeout(match properties {
CreateItemData::NFT(_) => NFT_SPONSOR_TRANSFER_TIMEOUT,
CreateItemData::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
CreateItemData::ReFungible(_) => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
runtime/tests/src/tests.rsdiffbeforeafterboth--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -62,7 +62,6 @@
fn default_re_fungible_data() -> CreateReFungibleData {
CreateReFungibleData {
- const_data: vec![1, 2, 3].try_into().unwrap(),
pieces: 1023,
properties: vec![Property {
key: b"test-prop".to_vec().try_into().unwrap(),
@@ -298,7 +297,6 @@
let item = <pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1)));
let balance =
<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1)));
- assert_eq!(item.const_data, data.const_data.into_inner());
assert_eq!(balance, 1023);
});
}
@@ -333,7 +331,6 @@
));
let balance =
<pallet_refungible::Balance<Test>>::get((CollectionId(1), TokenId(1), account(1)));
- assert_eq!(item.const_data.to_vec(), data.const_data.into_inner());
assert_eq!(balance, 1023);
}
});
@@ -446,7 +443,6 @@
let data = default_re_fungible_data();
create_test_item(collection_id, &data.clone().into());
let item = <pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1)));
- assert_eq!(item.const_data, data.const_data.into_inner());
assert_eq!(
<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
1