difftreelog
major: move RFT const data to depricated.
in: master
9 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6320,7 +6320,7 @@
[[package]]
name = "pallet-refungible"
-version = "0.1.2"
+version = "0.2.0"
dependencies = [
"ethereum",
"evm-coder",
@@ -12737,7 +12737,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 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {264 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {265 Some(<ItemDataVersion2>::from(v))266 })267 }268269 0270 }271 }272}273274pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);275impl<T: Config> RefungibleHandle<T> {276 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {277 Self(inner)278 }279 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {280 self.0281 }282 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {283 &mut self.0284 }285}286287impl<T: Config> Deref for RefungibleHandle<T> {288 type Target = pallet_common::CollectionHandle<T>;289290 fn deref(&self) -> &Self::Target {291 &self.0292 }293}294295impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {296 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {297 self.0.recorder()298 }299 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {300 self.0.into_recorder()301 }302}303304impl<T: Config> Pallet<T> {305 /// Get number of RFT tokens in collection306 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {307 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)308 }309310 /// Check that RFT token exists311 ///312 /// - `token`: Token ID.313 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {314 <TotalSupply<T>>::contains_key((collection.id, token))315 }316317 pub fn set_scoped_token_property(318 collection_id: CollectionId,319 token_id: TokenId,320 scope: PropertyScope,321 property: Property,322 ) -> DispatchResult {323 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {324 properties.try_scoped_set(scope, property.key, property.value)325 })326 .map_err(<CommonError<T>>::from)?;327328 Ok(())329 }330331 pub fn set_scoped_token_properties(332 collection_id: CollectionId,333 token_id: TokenId,334 scope: PropertyScope,335 properties: impl Iterator<Item = Property>,336 ) -> DispatchResult {337 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {338 stored_properties.try_scoped_set_from_iter(scope, properties)339 })340 .map_err(<CommonError<T>>::from)?;341342 Ok(())343 }344}345346// unchecked calls skips any permission checks347impl<T: Config> Pallet<T> {348 /// Create RFT collection349 ///350 /// `init_collection` will take non-refundable deposit for collection creation.351 ///352 /// - `data`: Contains settings for collection limits and permissions.353 pub fn init_collection(354 owner: T::CrossAccountId,355 data: CreateCollectionData<T::AccountId>,356 ) -> Result<CollectionId, DispatchError> {357 <PalletCommon<T>>::init_collection(owner, data, false)358 }359360 /// Destroy RFT collection361 ///362 /// `destroy_collection` will throw error if collection contains any tokens.363 /// Only owner can destroy collection.364 pub fn destroy_collection(365 collection: RefungibleHandle<T>,366 sender: &T::CrossAccountId,367 ) -> DispatchResult {368 let id = collection.id;369370 if Self::collection_has_tokens(id) {371 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());372 }373374 // =========375376 PalletCommon::destroy_collection(collection.0, sender)?;377378 <TokensMinted<T>>::remove(id);379 <TokensBurnt<T>>::remove(id);380 <TokenData<T>>::remove_prefix((id,), None);381 <TotalSupply<T>>::remove_prefix((id,), None);382 <Balance<T>>::remove_prefix((id,), None);383 <Allowance<T>>::remove_prefix((id,), None);384 <Owned<T>>::remove_prefix((id,), None);385 <AccountBalance<T>>::remove_prefix((id,), None);386 Ok(())387 }388389 fn collection_has_tokens(collection_id: CollectionId) -> bool {390 <TokenData<T>>::iter_prefix((collection_id,))391 .next()392 .is_some()393 }394395 pub fn burn_token_unchecked(396 collection: &RefungibleHandle<T>,397 token_id: TokenId,398 ) -> DispatchResult {399 let burnt = <TokensBurnt<T>>::get(collection.id)400 .checked_add(1)401 .ok_or(ArithmeticError::Overflow)?;402403 <TokensBurnt<T>>::insert(collection.id, burnt);404 <TokenData<T>>::remove((collection.id, token_id));405 <TokenProperties<T>>::remove((collection.id, token_id));406 <TotalSupply<T>>::remove((collection.id, token_id));407 <Balance<T>>::remove_prefix((collection.id, token_id), None);408 <Allowance<T>>::remove_prefix((collection.id, token_id), None);409 // TODO: ERC721 transfer event410 Ok(())411 }412413 /// Burn RFT token pieces414 ///415 /// `burn` will decrease total amount of token pieces and amount owned by sender.416 /// `burn` can be called even if there are multiple owners of the RFT token.417 /// If sender wouldn't have any pieces left after `burn` than she will stop being418 /// one of the owners of the token. If there is no account that owns any pieces of419 /// the token than token will be burned too.420 ///421 /// - `amount`: Amount of token pieces to burn.422 /// - `token`: Token who's pieces should be burned423 /// - `collection`: Collection that contains the token424 pub fn burn(425 collection: &RefungibleHandle<T>,426 owner: &T::CrossAccountId,427 token: TokenId,428 amount: u128,429 ) -> DispatchResult {430 let total_supply = <TotalSupply<T>>::get((collection.id, token))431 .checked_sub(amount)432 .ok_or(<CommonError<T>>::TokenValueTooLow)?;433434 // This was probally last owner of this token?435 if total_supply == 0 {436 // Ensure user actually owns this amount437 ensure!(438 <Balance<T>>::get((collection.id, token, owner)) == amount,439 <CommonError<T>>::TokenValueTooLow440 );441 let account_balance = <AccountBalance<T>>::get((collection.id, owner))442 .checked_sub(1)443 // Should not occur444 .ok_or(ArithmeticError::Underflow)?;445446 // =========447448 <Owned<T>>::remove((collection.id, owner, token));449 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);450 <AccountBalance<T>>::insert((collection.id, owner), account_balance);451 Self::burn_token_unchecked(collection, token)?;452 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(453 collection.id,454 token,455 owner.clone(),456 amount,457 ));458 return Ok(());459 }460461 let balance = <Balance<T>>::get((collection.id, token, owner))462 .checked_sub(amount)463 .ok_or(<CommonError<T>>::TokenValueTooLow)?;464 let account_balance = if balance == 0 {465 <AccountBalance<T>>::get((collection.id, owner))466 .checked_sub(1)467 // Should not occur468 .ok_or(ArithmeticError::Underflow)?469 } else {470 0471 };472473 // =========474475 if balance == 0 {476 <Owned<T>>::remove((collection.id, owner, token));477 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);478 <Balance<T>>::remove((collection.id, token, owner));479 <AccountBalance<T>>::insert((collection.id, owner), account_balance);480 } else {481 <Balance<T>>::insert((collection.id, token, owner), balance);482 }483 <TotalSupply<T>>::insert((collection.id, token), total_supply);484485 <PalletEvm<T>>::deposit_log(486 ERC20Events::Transfer {487 from: *owner.as_eth(),488 to: H160::default(),489 value: amount.into(),490 }491 .to_log(T::EvmTokenAddressMapping::token_to_address(492 collection.id,493 token,494 )),495 );496 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(497 collection.id,498 token,499 owner.clone(),500 amount,501 ));502 Ok(())503 }504505 #[transactional]506 fn modify_token_properties(507 collection: &RefungibleHandle<T>,508 sender: &T::CrossAccountId,509 token_id: TokenId,510 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,511 is_token_create: bool,512 nesting_budget: &dyn Budget,513 ) -> DispatchResult {514 let is_collection_admin = || collection.is_owner_or_admin(sender);515 let is_token_owner = || -> Result<bool, DispatchError> {516 let balance = collection.balance(sender.clone(), token_id);517 let total_pieces: u128 =518 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);519 if balance != total_pieces {520 return Ok(false);521 }522523 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(524 sender.clone(),525 collection.id,526 token_id,527 None,528 nesting_budget,529 )?;530531 Ok(is_bundle_owner)532 };533534 for (key, value) in properties {535 let permission = <PalletCommon<T>>::property_permissions(collection.id)536 .get(&key)537 .cloned()538 .unwrap_or_else(PropertyPermission::none);539540 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))541 .get(&key)542 .is_some();543544 match permission {545 PropertyPermission { mutable: false, .. } if is_property_exists => {546 return Err(<CommonError<T>>::NoPermission.into());547 }548549 PropertyPermission {550 collection_admin,551 token_owner,552 ..553 } => {554 //TODO: investigate threats during public minting.555 let is_token_create =556 is_token_create && (collection_admin || token_owner) && value.is_some();557 if !(is_token_create558 || (collection_admin && is_collection_admin())559 || (token_owner && is_token_owner()?))560 {561 fail!(<CommonError<T>>::NoPermission);562 }563 }564 }565566 match value {567 Some(value) => {568 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {569 properties.try_set(key.clone(), value)570 })571 .map_err(<CommonError<T>>::from)?;572573 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(574 collection.id,575 token_id,576 key,577 ));578 }579 None => {580 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {581 properties.remove(&key)582 })583 .map_err(<CommonError<T>>::from)?;584585 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(586 collection.id,587 token_id,588 key,589 ));590 }591 }592 }593594 Ok(())595 }596597 pub fn set_token_properties(598 collection: &RefungibleHandle<T>,599 sender: &T::CrossAccountId,600 token_id: TokenId,601 properties: impl Iterator<Item = Property>,602 is_token_create: bool,603 nesting_budget: &dyn Budget,604 ) -> DispatchResult {605 Self::modify_token_properties(606 collection,607 sender,608 token_id,609 properties.map(|p| (p.key, Some(p.value))),610 is_token_create,611 nesting_budget,612 )613 }614615 pub fn set_token_property(616 collection: &RefungibleHandle<T>,617 sender: &T::CrossAccountId,618 token_id: TokenId,619 property: Property,620 nesting_budget: &dyn Budget,621 ) -> DispatchResult {622 let is_token_create = false;623624 Self::set_token_properties(625 collection,626 sender,627 token_id,628 [property].into_iter(),629 is_token_create,630 nesting_budget,631 )632 }633634 pub fn delete_token_properties(635 collection: &RefungibleHandle<T>,636 sender: &T::CrossAccountId,637 token_id: TokenId,638 property_keys: impl Iterator<Item = PropertyKey>,639 nesting_budget: &dyn Budget,640 ) -> DispatchResult {641 let is_token_create = false;642643 Self::modify_token_properties(644 collection,645 sender,646 token_id,647 property_keys.into_iter().map(|key| (key, None)),648 is_token_create,649 nesting_budget,650 )651 }652653 pub fn delete_token_property(654 collection: &RefungibleHandle<T>,655 sender: &T::CrossAccountId,656 token_id: TokenId,657 property_key: PropertyKey,658 nesting_budget: &dyn Budget,659 ) -> DispatchResult {660 Self::delete_token_properties(661 collection,662 sender,663 token_id,664 [property_key].into_iter(),665 nesting_budget,666 )667 }668669 /// Transfer RFT token pieces from one account to another.670 ///671 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.672 ///673 /// - `from`: Owner of token pieces to transfer.674 /// - `to`: Recepient of transfered token pieces.675 /// - `amount`: Amount of token pieces to transfer.676 /// - `token`: Token whos pieces should be transfered677 /// - `collection`: Collection that contains the token678 pub fn transfer(679 collection: &RefungibleHandle<T>,680 from: &T::CrossAccountId,681 to: &T::CrossAccountId,682 token: TokenId,683 amount: u128,684 nesting_budget: &dyn Budget,685 ) -> DispatchResult {686 ensure!(687 collection.limits.transfers_enabled(),688 <CommonError<T>>::TransferNotAllowed689 );690691 if collection.permissions.access() == AccessMode::AllowList {692 collection.check_allowlist(from)?;693 collection.check_allowlist(to)?;694 }695 <PalletCommon<T>>::ensure_correct_receiver(to)?;696697 let balance_from = <Balance<T>>::get((collection.id, token, from))698 .checked_sub(amount)699 .ok_or(<CommonError<T>>::TokenValueTooLow)?;700 let mut create_target = false;701 let from_to_differ = from != to;702 let balance_to = if from != to {703 let old_balance = <Balance<T>>::get((collection.id, token, to));704 if old_balance == 0 {705 create_target = true;706 }707 Some(708 old_balance709 .checked_add(amount)710 .ok_or(ArithmeticError::Overflow)?,711 )712 } else {713 None714 };715716 let account_balance_from = if balance_from == 0 {717 Some(718 <AccountBalance<T>>::get((collection.id, from))719 .checked_sub(1)720 // Should not occur721 .ok_or(ArithmeticError::Underflow)?,722 )723 } else {724 None725 };726 // Account data is created in token, AccountBalance should be increased727 // But only if from != to as we shouldn't check overflow in this case728 let account_balance_to = if create_target && from_to_differ {729 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))730 .checked_add(1)731 .ok_or(ArithmeticError::Overflow)?;732 ensure!(733 account_balance_to < collection.limits.account_token_ownership_limit(),734 <CommonError<T>>::AccountTokenLimitExceeded,735 );736737 Some(account_balance_to)738 } else {739 None740 };741742 // =========743744 <PalletStructure<T>>::nest_if_sent_to_token(745 from.clone(),746 to,747 collection.id,748 token,749 nesting_budget,750 )?;751752 if let Some(balance_to) = balance_to {753 // from != to754 if balance_from == 0 {755 <Balance<T>>::remove((collection.id, token, from));756 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);757 } else {758 <Balance<T>>::insert((collection.id, token, from), balance_from);759 }760 <Balance<T>>::insert((collection.id, token, to), balance_to);761 if let Some(account_balance_from) = account_balance_from {762 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);763 <Owned<T>>::remove((collection.id, from, token));764 }765 if let Some(account_balance_to) = account_balance_to {766 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);767 <Owned<T>>::insert((collection.id, to, token), true);768 }769 }770771 <PalletEvm<T>>::deposit_log(772 ERC20Events::Transfer {773 from: *from.as_eth(),774 to: *to.as_eth(),775 value: amount.into(),776 }777 .to_log(T::EvmTokenAddressMapping::token_to_address(778 collection.id,779 token,780 )),781 );782 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(783 collection.id,784 token,785 from.clone(),786 to.clone(),787 amount,788 ));789 Ok(())790 }791792 /// Batched operation to create multiple RFT tokens.793 ///794 /// Same as `create_item` but creates multiple tokens.795 ///796 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.797 pub fn create_multiple_items(798 collection: &RefungibleHandle<T>,799 sender: &T::CrossAccountId,800 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,801 nesting_budget: &dyn Budget,802 ) -> DispatchResult {803 if !collection.is_owner_or_admin(sender) {804 ensure!(805 collection.permissions.mint_mode(),806 <CommonError<T>>::PublicMintingNotAllowed807 );808 collection.check_allowlist(sender)?;809810 for item in data.iter() {811 for user in item.users.keys() {812 collection.check_allowlist(user)?;813 }814 }815 }816817 for item in data.iter() {818 for (owner, _) in item.users.iter() {819 <PalletCommon<T>>::ensure_correct_receiver(owner)?;820 }821 }822823 // Total pieces per tokens824 let totals = data825 .iter()826 .map(|data| {827 Ok(data828 .users829 .iter()830 .map(|u| u.1)831 .try_fold(0u128, |acc, v| acc.checked_add(*v))832 .ok_or(ArithmeticError::Overflow)?)833 })834 .collect::<Result<Vec<_>, DispatchError>>()?;835 for total in &totals {836 ensure!(837 *total <= MAX_REFUNGIBLE_PIECES,838 <Error<T>>::WrongRefungiblePieces839 );840 }841842 let first_token_id = <TokensMinted<T>>::get(collection.id);843 let tokens_minted = first_token_id844 .checked_add(data.len() as u32)845 .ok_or(ArithmeticError::Overflow)?;846 ensure!(847 tokens_minted < collection.limits.token_limit(),848 <CommonError<T>>::CollectionTokenLimitExceeded849 );850851 let mut balances = BTreeMap::new();852 for data in &data {853 for owner in data.users.keys() {854 let balance = balances855 .entry(owner)856 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));857 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;858859 ensure!(860 *balance <= collection.limits.account_token_ownership_limit(),861 <CommonError<T>>::AccountTokenLimitExceeded,862 );863 }864 }865866 for (i, token) in data.iter().enumerate() {867 let token_id = TokenId(first_token_id + i as u32 + 1);868 for (to, _) in token.users.iter() {869 <PalletStructure<T>>::check_nesting(870 sender.clone(),871 to,872 collection.id,873 token_id,874 nesting_budget,875 )?;876 }877 }878879 // =========880881 with_transaction(|| {882 for (i, data) in data.iter().enumerate() {883 let token_id = first_token_id + i as u32 + 1;884 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);885886 <TokenData<T>>::insert(887 (collection.id, token_id),888 ItemData {889 const_data: data.const_data.clone(),890 },891 );892893 for (user, amount) in data.users.iter() {894 if *amount == 0 {895 continue;896 }897 <Balance<T>>::insert((collection.id, token_id, &user), amount);898 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);899 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(900 user,901 collection.id,902 TokenId(token_id),903 );904 }905906 if let Err(e) = Self::set_token_properties(907 collection,908 sender,909 TokenId(token_id),910 data.properties.clone().into_iter(),911 true,912 nesting_budget,913 ) {914 return TransactionOutcome::Rollback(Err(e));915 }916 }917 TransactionOutcome::Commit(Ok(()))918 })?;919920 <TokensMinted<T>>::insert(collection.id, tokens_minted);921922 for (account, balance) in balances {923 <AccountBalance<T>>::insert((collection.id, account), balance);924 }925926 for (i, token) in data.into_iter().enumerate() {927 let token_id = first_token_id + i as u32 + 1;928929 for (user, amount) in token.users.into_iter() {930 if amount == 0 {931 continue;932 }933934 <PalletEvm<T>>::deposit_log(935 ERC20Events::Transfer {936 from: H160::default(),937 to: *user.as_eth(),938 value: amount.into(),939 }940 .to_log(T::EvmTokenAddressMapping::token_to_address(941 collection.id,942 TokenId(token_id),943 )),944 );945 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(946 collection.id,947 TokenId(token_id),948 user,949 amount,950 ));951 }952 }953 Ok(())954 }955956 pub fn set_allowance_unchecked(957 collection: &RefungibleHandle<T>,958 sender: &T::CrossAccountId,959 spender: &T::CrossAccountId,960 token: TokenId,961 amount: u128,962 ) {963 if amount == 0 {964 <Allowance<T>>::remove((collection.id, token, sender, spender));965 } else {966 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);967 }968969 <PalletEvm<T>>::deposit_log(970 ERC20Events::Approval {971 owner: *sender.as_eth(),972 spender: *spender.as_eth(),973 value: amount.into(),974 }975 .to_log(T::EvmTokenAddressMapping::token_to_address(976 collection.id,977 token,978 )),979 );980 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(981 collection.id,982 token,983 sender.clone(),984 spender.clone(),985 amount,986 ))987 }988989 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.990 ///991 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.992 pub fn set_allowance(993 collection: &RefungibleHandle<T>,994 sender: &T::CrossAccountId,995 spender: &T::CrossAccountId,996 token: TokenId,997 amount: u128,998 ) -> DispatchResult {999 if collection.permissions.access() == AccessMode::AllowList {1000 collection.check_allowlist(sender)?;1001 collection.check_allowlist(spender)?;1002 }10031004 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10051006 if <Balance<T>>::get((collection.id, token, sender)) < amount {1007 ensure!(1008 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1009 <CommonError<T>>::CantApproveMoreThanOwned1010 );1011 }10121013 // =========10141015 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1016 Ok(())1017 }10181019 /// Returns allowance, which should be set after transaction1020 fn check_allowed(1021 collection: &RefungibleHandle<T>,1022 spender: &T::CrossAccountId,1023 from: &T::CrossAccountId,1024 token: TokenId,1025 amount: u128,1026 nesting_budget: &dyn Budget,1027 ) -> Result<Option<u128>, DispatchError> {1028 if spender.conv_eq(from) {1029 return Ok(None);1030 }1031 if collection.permissions.access() == AccessMode::AllowList {1032 // `from`, `to` checked in [`transfer`]1033 collection.check_allowlist(spender)?;1034 }1035 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1036 // TODO: should collection owner be allowed to perform this transfer?1037 ensure!(1038 <PalletStructure<T>>::check_indirectly_owned(1039 spender.clone(),1040 source.0,1041 source.1,1042 None,1043 nesting_budget1044 )?,1045 <CommonError<T>>::ApprovedValueTooLow,1046 );1047 return Ok(None);1048 }1049 let allowance =1050 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1051 if allowance.is_none() {1052 ensure!(1053 collection.ignores_allowance(spender),1054 <CommonError<T>>::ApprovedValueTooLow1055 );1056 }1057 Ok(allowance)1058 }10591060 /// Transfer RFT token pieces from one account to another.1061 ///1062 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1063 /// The owner should set allowance for the spender to transfer pieces.1064 ///1065 /// [`transfer`]: struct.Pallet.html#method.transfer1066 pub fn transfer_from(1067 collection: &RefungibleHandle<T>,1068 spender: &T::CrossAccountId,1069 from: &T::CrossAccountId,1070 to: &T::CrossAccountId,1071 token: TokenId,1072 amount: u128,1073 nesting_budget: &dyn Budget,1074 ) -> DispatchResult {1075 let allowance =1076 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10771078 // =========10791080 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1081 if let Some(allowance) = allowance {1082 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1083 }1084 Ok(())1085 }10861087 /// Burn RFT token pieces from the account.1088 ///1089 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1090 /// set allowance for the spender to burn pieces1091 ///1092 /// [`burn`]: struct.Pallet.html#method.burn1093 pub fn burn_from(1094 collection: &RefungibleHandle<T>,1095 spender: &T::CrossAccountId,1096 from: &T::CrossAccountId,1097 token: TokenId,1098 amount: u128,1099 nesting_budget: &dyn Budget,1100 ) -> DispatchResult {1101 let allowance =1102 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11031104 // =========11051106 Self::burn(collection, from, token, amount)?;1107 if let Some(allowance) = allowance {1108 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1109 }1110 Ok(())1111 }11121113 /// Create RFT token.1114 ///1115 /// The sender should be the owner/admin of the collection or collection should be configured1116 /// to allow public minting.1117 ///1118 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1119 /// of token pieces they will receive.1120 pub fn create_item(1121 collection: &RefungibleHandle<T>,1122 sender: &T::CrossAccountId,1123 data: CreateRefungibleExData<T::CrossAccountId>,1124 nesting_budget: &dyn Budget,1125 ) -> DispatchResult {1126 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1127 }11281129 /// Repartition RFT token.1130 ///1131 /// `repartition` will set token balance of the sender and total amount of token pieces.1132 /// Sender should own all of the token pieces. `repartition' could be done even if some1133 /// token pieces were burned before.1134 ///1135 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1136 pub fn repartition(1137 collection: &RefungibleHandle<T>,1138 owner: &T::CrossAccountId,1139 token: TokenId,1140 amount: u128,1141 ) -> DispatchResult {1142 ensure!(1143 amount <= MAX_REFUNGIBLE_PIECES,1144 <Error<T>>::WrongRefungiblePieces1145 );1146 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1147 // Ensure user owns all pieces1148 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1149 let balance = <Balance<T>>::get((collection.id, token, owner));1150 ensure!(1151 total_pieces == balance,1152 <Error<T>>::RepartitionWhileNotOwningAllPieces1153 );11541155 <Balance<T>>::insert((collection.id, token, owner), amount);1156 <TotalSupply<T>>::insert((collection.id, token), amount);11571158 if amount > total_pieces {1159 let mint_amount = amount - total_pieces;1160 <PalletEvm<T>>::deposit_log(1161 ERC20Events::Transfer {1162 from: H160::default(),1163 to: *owner.as_eth(),1164 value: mint_amount.into(),1165 }1166 .to_log(T::EvmTokenAddressMapping::token_to_address(1167 collection.id,1168 token,1169 )),1170 );1171 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1172 collection.id,1173 token,1174 owner.clone(),1175 mint_amount,1176 ));1177 } else if total_pieces > amount {1178 let burn_amount = total_pieces - amount;1179 <PalletEvm<T>>::deposit_log(1180 ERC20Events::Transfer {1181 from: *owner.as_eth(),1182 to: H160::default(),1183 value: burn_amount.into(),1184 }1185 .to_log(T::EvmTokenAddressMapping::token_to_address(1186 collection.id,1187 token,1188 )),1189 );1190 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1191 collection.id,1192 token,1193 owner.clone(),1194 burn_amount,1195 ));1196 }11971198 Ok(())1199 }12001201 fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1202 let mut owner = None;1203 let mut count = 0;1204 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1205 count += 1;1206 if count > 1 {1207 return None;1208 }1209 owner = Some(key);1210 }1211 owner1212 }12131214 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1215 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1216 }12171218 pub fn set_collection_properties(1219 collection: &RefungibleHandle<T>,1220 sender: &T::CrossAccountId,1221 properties: Vec<Property>,1222 ) -> DispatchResult {1223 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)1224 }12251226 pub fn delete_collection_properties(1227 collection: &RefungibleHandle<T>,1228 sender: &T::CrossAccountId,1229 property_keys: Vec<PropertyKey>,1230 ) -> DispatchResult {1231 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1232 }12331234 pub fn set_token_property_permissions(1235 collection: &RefungibleHandle<T>,1236 sender: &T::CrossAccountId,1237 property_permissions: Vec<PropertyKeyPermission>,1238 ) -> DispatchResult {1239 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1240 }12411242 /// Returns 10 token in no particular order.1243 ///1244 /// There is no direct way to get token holders in ascending order,1245 /// since `iter_prefix` returns values in no particular order.1246 /// Therefore, getting the 10 largest holders with a large value of holders1247 /// can lead to impact memory allocation + sorting with `n * log (n)`.1248 pub fn token_owners(1249 collection_id: CollectionId,1250 token: TokenId,1251 ) -> Option<Vec<T::CrossAccountId>> {1252 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1253 .map(|(owner, _amount)| owner)1254 .take(10)1255 .collect();12561257 if res.is_empty() {1258 None1259 } else {1260 Some(res)1261 }1262 }1263}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//! # 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)]126#[deprecated(since = "0.2.0", note = "ItemData is no more contains usefull data")]127pub struct ItemData {128 pub const_data: BoundedVec<u8, CustomDataLimit>,129130 #[version(..2)]131 pub variable_data: BoundedVec<u8, CustomDataLimit>,132}133134#[frame_support::pallet]135pub mod pallet {136 use super::*;137 use frame_support::{138 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,139 traits::StorageVersion,140 };141 use frame_system::pallet_prelude::*;142 use up_data_structs::{CollectionId, TokenId};143 use super::weights::WeightInfo;144145 #[pallet::error]146 pub enum Error<T> {147 /// Not Refungible item data used to mint in Refungible collection.148 NotRefungibleDataUsedToMintFungibleCollectionToken,149 /// Maximum refungibility exceeded.150 WrongRefungiblePieces,151 /// Refungible token can't be repartitioned by user who isn't owns all pieces.152 RepartitionWhileNotOwningAllPieces,153 /// Refungible token can't nest other tokens.154 RefungibleDisallowsNesting,155 /// Setting item properties is not allowed.156 SettingPropertiesNotAllowed,157 }158159 #[pallet::config]160 pub trait Config:161 frame_system::Config + pallet_common::Config + pallet_structure::Config162 {163 type WeightInfo: WeightInfo;164 }165166 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);167168 #[pallet::pallet]169 #[pallet::storage_version(STORAGE_VERSION)]170 #[pallet::generate_store(pub(super) trait Store)]171 pub struct Pallet<T>(_);172173 /// Total amount of minted tokens in a collection.174 #[pallet::storage]175 pub type TokensMinted<T: Config> =176 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;177178 /// Amount of tokens burnt in a collection.179 #[pallet::storage]180 pub type TokensBurnt<T: Config> =181 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;182183 /// Token data, used to partially describe a token.184 // TODO: remove185 #[pallet::storage]186 #[deprecated(since = "0.2.0", note = "ItemData is no more contains usefull data")]187 pub type TokenData<T: Config> = StorageNMap<188 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),189 Value = ItemData,190 QueryKind = ValueQuery,191 >;192193 /// Amount of pieces a refungible token is split into.194 #[pallet::storage]195 #[pallet::getter(fn token_properties)]196 pub type TokenProperties<T: Config> = StorageNMap<197 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),198 Value = up_data_structs::Properties,199 QueryKind = ValueQuery,200 OnEmpty = up_data_structs::TokenProperties,201 >;202203 /// Total amount of pieces for token204 #[pallet::storage]205 pub type TotalSupply<T: Config> = StorageNMap<206 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),207 Value = u128,208 QueryKind = ValueQuery,209 >;210211 /// Used to enumerate tokens owned by account.212 #[pallet::storage]213 pub type Owned<T: Config> = StorageNMap<214 Key = (215 Key<Twox64Concat, CollectionId>,216 Key<Blake2_128Concat, T::CrossAccountId>,217 Key<Twox64Concat, TokenId>,218 ),219 Value = bool,220 QueryKind = ValueQuery,221 >;222223 /// Amount of tokens (not pieces) partially owned by an account within a collection.224 #[pallet::storage]225 pub type AccountBalance<T: Config> = StorageNMap<226 Key = (227 Key<Twox64Concat, CollectionId>,228 // Owner229 Key<Blake2_128Concat, T::CrossAccountId>,230 ),231 Value = u32,232 QueryKind = ValueQuery,233 >;234235 /// Amount of token pieces owned by account.236 #[pallet::storage]237 pub type Balance<T: Config> = StorageNMap<238 Key = (239 Key<Twox64Concat, CollectionId>,240 Key<Twox64Concat, TokenId>,241 // Owner242 Key<Blake2_128Concat, T::CrossAccountId>,243 ),244 Value = u128,245 QueryKind = ValueQuery,246 >;247248 /// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.249 #[pallet::storage]250 pub type Allowance<T: Config> = StorageNMap<251 Key = (252 Key<Twox64Concat, CollectionId>,253 Key<Twox64Concat, TokenId>,254 // Owner255 Key<Blake2_128, T::CrossAccountId>,256 // Spender257 Key<Blake2_128Concat, T::CrossAccountId>,258 ),259 Value = u128,260 QueryKind = ValueQuery,261 >;262263 #[pallet::hooks]264 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {265 fn on_runtime_upgrade() -> Weight {266 let storage_version = StorageVersion::get::<Pallet<T>>();267 if storage_version < StorageVersion::new(1) {268 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {269 Some(<ItemDataVersion2>::from(v))270 })271 } else if storage_version < StorageVersion::new(2) {272 <TokenData<T>>::remove_all(None);273 }274275 0276 }277 }278}279280pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);281impl<T: Config> RefungibleHandle<T> {282 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {283 Self(inner)284 }285 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {286 self.0287 }288 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {289 &mut self.0290 }291}292293impl<T: Config> Deref for RefungibleHandle<T> {294 type Target = pallet_common::CollectionHandle<T>;295296 fn deref(&self) -> &Self::Target {297 &self.0298 }299}300301impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {302 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {303 self.0.recorder()304 }305 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {306 self.0.into_recorder()307 }308}309310impl<T: Config> Pallet<T> {311 /// Get number of RFT tokens in collection312 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {313 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)314 }315316 /// Check that RFT token exists317 ///318 /// - `token`: Token ID.319 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {320 <TotalSupply<T>>::contains_key((collection.id, token))321 }322323 pub fn set_scoped_token_property(324 collection_id: CollectionId,325 token_id: TokenId,326 scope: PropertyScope,327 property: Property,328 ) -> DispatchResult {329 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {330 properties.try_scoped_set(scope, property.key, property.value)331 })332 .map_err(<CommonError<T>>::from)?;333334 Ok(())335 }336337 pub fn set_scoped_token_properties(338 collection_id: CollectionId,339 token_id: TokenId,340 scope: PropertyScope,341 properties: impl Iterator<Item = Property>,342 ) -> DispatchResult {343 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {344 stored_properties.try_scoped_set_from_iter(scope, properties)345 })346 .map_err(<CommonError<T>>::from)?;347348 Ok(())349 }350}351352// unchecked calls skips any permission checks353impl<T: Config> Pallet<T> {354 /// Create RFT collection355 ///356 /// `init_collection` will take non-refundable deposit for collection creation.357 ///358 /// - `data`: Contains settings for collection limits and permissions.359 pub fn init_collection(360 owner: T::CrossAccountId,361 data: CreateCollectionData<T::AccountId>,362 ) -> Result<CollectionId, DispatchError> {363 <PalletCommon<T>>::init_collection(owner, data, false)364 }365366 /// Destroy RFT collection367 ///368 /// `destroy_collection` will throw error if collection contains any tokens.369 /// Only owner can destroy collection.370 pub fn destroy_collection(371 collection: RefungibleHandle<T>,372 sender: &T::CrossAccountId,373 ) -> DispatchResult {374 let id = collection.id;375376 if Self::collection_has_tokens(id) {377 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());378 }379380 // =========381382 PalletCommon::destroy_collection(collection.0, sender)?;383384 <TokensMinted<T>>::remove(id);385 <TokensBurnt<T>>::remove(id);386 <TotalSupply<T>>::remove_prefix((id,), None);387 <Balance<T>>::remove_prefix((id,), None);388 <Allowance<T>>::remove_prefix((id,), None);389 <Owned<T>>::remove_prefix((id,), None);390 <AccountBalance<T>>::remove_prefix((id,), None);391 Ok(())392 }393394 fn collection_has_tokens(collection_id: CollectionId) -> bool {395 <TotalSupply<T>>::iter_prefix((collection_id,))396 .next()397 .is_some()398 }399400 pub fn burn_token_unchecked(401 collection: &RefungibleHandle<T>,402 token_id: TokenId,403 ) -> DispatchResult {404 let burnt = <TokensBurnt<T>>::get(collection.id)405 .checked_add(1)406 .ok_or(ArithmeticError::Overflow)?;407408 <TokensBurnt<T>>::insert(collection.id, burnt);409 <TokenProperties<T>>::remove((collection.id, token_id));410 <TotalSupply<T>>::remove((collection.id, token_id));411 <Balance<T>>::remove_prefix((collection.id, token_id), None);412 <Allowance<T>>::remove_prefix((collection.id, token_id), None);413 // TODO: ERC721 transfer event414 Ok(())415 }416417 /// Burn RFT token pieces418 ///419 /// `burn` will decrease total amount of token pieces and amount owned by sender.420 /// `burn` can be called even if there are multiple owners of the RFT token.421 /// If sender wouldn't have any pieces left after `burn` than she will stop being422 /// one of the owners of the token. If there is no account that owns any pieces of423 /// the token than token will be burned too.424 ///425 /// - `amount`: Amount of token pieces to burn.426 /// - `token`: Token who's pieces should be burned427 /// - `collection`: Collection that contains the token428 pub fn burn(429 collection: &RefungibleHandle<T>,430 owner: &T::CrossAccountId,431 token: TokenId,432 amount: u128,433 ) -> DispatchResult {434 let total_supply = <TotalSupply<T>>::get((collection.id, token))435 .checked_sub(amount)436 .ok_or(<CommonError<T>>::TokenValueTooLow)?;437438 // This was probally last owner of this token?439 if total_supply == 0 {440 // Ensure user actually owns this amount441 ensure!(442 <Balance<T>>::get((collection.id, token, owner)) == amount,443 <CommonError<T>>::TokenValueTooLow444 );445 let account_balance = <AccountBalance<T>>::get((collection.id, owner))446 .checked_sub(1)447 // Should not occur448 .ok_or(ArithmeticError::Underflow)?;449450 // =========451452 <Owned<T>>::remove((collection.id, owner, token));453 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);454 <AccountBalance<T>>::insert((collection.id, owner), account_balance);455 Self::burn_token_unchecked(collection, token)?;456 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(457 collection.id,458 token,459 owner.clone(),460 amount,461 ));462 return Ok(());463 }464465 let balance = <Balance<T>>::get((collection.id, token, owner))466 .checked_sub(amount)467 .ok_or(<CommonError<T>>::TokenValueTooLow)?;468 let account_balance = if balance == 0 {469 <AccountBalance<T>>::get((collection.id, owner))470 .checked_sub(1)471 // Should not occur472 .ok_or(ArithmeticError::Underflow)?473 } else {474 0475 };476477 // =========478479 if balance == 0 {480 <Owned<T>>::remove((collection.id, owner, token));481 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);482 <Balance<T>>::remove((collection.id, token, owner));483 <AccountBalance<T>>::insert((collection.id, owner), account_balance);484 } else {485 <Balance<T>>::insert((collection.id, token, owner), balance);486 }487 <TotalSupply<T>>::insert((collection.id, token), total_supply);488489 <PalletEvm<T>>::deposit_log(490 ERC20Events::Transfer {491 from: *owner.as_eth(),492 to: H160::default(),493 value: amount.into(),494 }495 .to_log(T::EvmTokenAddressMapping::token_to_address(496 collection.id,497 token,498 )),499 );500 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(501 collection.id,502 token,503 owner.clone(),504 amount,505 ));506 Ok(())507 }508509 #[transactional]510 fn modify_token_properties(511 collection: &RefungibleHandle<T>,512 sender: &T::CrossAccountId,513 token_id: TokenId,514 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,515 is_token_create: bool,516 nesting_budget: &dyn Budget,517 ) -> DispatchResult {518 let is_collection_admin = || collection.is_owner_or_admin(sender);519 let is_token_owner = || -> Result<bool, DispatchError> {520 let balance = collection.balance(sender.clone(), token_id);521 let total_pieces: u128 =522 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);523 if balance != total_pieces {524 return Ok(false);525 }526527 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(528 sender.clone(),529 collection.id,530 token_id,531 None,532 nesting_budget,533 )?;534535 Ok(is_bundle_owner)536 };537538 for (key, value) in properties {539 let permission = <PalletCommon<T>>::property_permissions(collection.id)540 .get(&key)541 .cloned()542 .unwrap_or_else(PropertyPermission::none);543544 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))545 .get(&key)546 .is_some();547548 match permission {549 PropertyPermission { mutable: false, .. } if is_property_exists => {550 return Err(<CommonError<T>>::NoPermission.into());551 }552553 PropertyPermission {554 collection_admin,555 token_owner,556 ..557 } => {558 //TODO: investigate threats during public minting.559 let is_token_create =560 is_token_create && (collection_admin || token_owner) && value.is_some();561 if !(is_token_create562 || (collection_admin && is_collection_admin())563 || (token_owner && is_token_owner()?))564 {565 fail!(<CommonError<T>>::NoPermission);566 }567 }568 }569570 match value {571 Some(value) => {572 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {573 properties.try_set(key.clone(), value)574 })575 .map_err(<CommonError<T>>::from)?;576577 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(578 collection.id,579 token_id,580 key,581 ));582 }583 None => {584 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {585 properties.remove(&key)586 })587 .map_err(<CommonError<T>>::from)?;588589 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(590 collection.id,591 token_id,592 key,593 ));594 }595 }596 }597598 Ok(())599 }600601 pub fn set_token_properties(602 collection: &RefungibleHandle<T>,603 sender: &T::CrossAccountId,604 token_id: TokenId,605 properties: impl Iterator<Item = Property>,606 is_token_create: bool,607 nesting_budget: &dyn Budget,608 ) -> DispatchResult {609 Self::modify_token_properties(610 collection,611 sender,612 token_id,613 properties.map(|p| (p.key, Some(p.value))),614 is_token_create,615 nesting_budget,616 )617 }618619 pub fn set_token_property(620 collection: &RefungibleHandle<T>,621 sender: &T::CrossAccountId,622 token_id: TokenId,623 property: Property,624 nesting_budget: &dyn Budget,625 ) -> DispatchResult {626 let is_token_create = false;627628 Self::set_token_properties(629 collection,630 sender,631 token_id,632 [property].into_iter(),633 is_token_create,634 nesting_budget,635 )636 }637638 pub fn delete_token_properties(639 collection: &RefungibleHandle<T>,640 sender: &T::CrossAccountId,641 token_id: TokenId,642 property_keys: impl Iterator<Item = PropertyKey>,643 nesting_budget: &dyn Budget,644 ) -> DispatchResult {645 let is_token_create = false;646647 Self::modify_token_properties(648 collection,649 sender,650 token_id,651 property_keys.into_iter().map(|key| (key, None)),652 is_token_create,653 nesting_budget,654 )655 }656657 pub fn delete_token_property(658 collection: &RefungibleHandle<T>,659 sender: &T::CrossAccountId,660 token_id: TokenId,661 property_key: PropertyKey,662 nesting_budget: &dyn Budget,663 ) -> DispatchResult {664 Self::delete_token_properties(665 collection,666 sender,667 token_id,668 [property_key].into_iter(),669 nesting_budget,670 )671 }672673 /// Transfer RFT token pieces from one account to another.674 ///675 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.676 ///677 /// - `from`: Owner of token pieces to transfer.678 /// - `to`: Recepient of transfered token pieces.679 /// - `amount`: Amount of token pieces to transfer.680 /// - `token`: Token whos pieces should be transfered681 /// - `collection`: Collection that contains the token682 pub fn transfer(683 collection: &RefungibleHandle<T>,684 from: &T::CrossAccountId,685 to: &T::CrossAccountId,686 token: TokenId,687 amount: u128,688 nesting_budget: &dyn Budget,689 ) -> DispatchResult {690 ensure!(691 collection.limits.transfers_enabled(),692 <CommonError<T>>::TransferNotAllowed693 );694695 if collection.permissions.access() == AccessMode::AllowList {696 collection.check_allowlist(from)?;697 collection.check_allowlist(to)?;698 }699 <PalletCommon<T>>::ensure_correct_receiver(to)?;700701 let balance_from = <Balance<T>>::get((collection.id, token, from))702 .checked_sub(amount)703 .ok_or(<CommonError<T>>::TokenValueTooLow)?;704 let mut create_target = false;705 let from_to_differ = from != to;706 let balance_to = if from != to {707 let old_balance = <Balance<T>>::get((collection.id, token, to));708 if old_balance == 0 {709 create_target = true;710 }711 Some(712 old_balance713 .checked_add(amount)714 .ok_or(ArithmeticError::Overflow)?,715 )716 } else {717 None718 };719720 let account_balance_from = if balance_from == 0 {721 Some(722 <AccountBalance<T>>::get((collection.id, from))723 .checked_sub(1)724 // Should not occur725 .ok_or(ArithmeticError::Underflow)?,726 )727 } else {728 None729 };730 // Account data is created in token, AccountBalance should be increased731 // But only if from != to as we shouldn't check overflow in this case732 let account_balance_to = if create_target && from_to_differ {733 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))734 .checked_add(1)735 .ok_or(ArithmeticError::Overflow)?;736 ensure!(737 account_balance_to < collection.limits.account_token_ownership_limit(),738 <CommonError<T>>::AccountTokenLimitExceeded,739 );740741 Some(account_balance_to)742 } else {743 None744 };745746 // =========747748 <PalletStructure<T>>::nest_if_sent_to_token(749 from.clone(),750 to,751 collection.id,752 token,753 nesting_budget,754 )?;755756 if let Some(balance_to) = balance_to {757 // from != to758 if balance_from == 0 {759 <Balance<T>>::remove((collection.id, token, from));760 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);761 } else {762 <Balance<T>>::insert((collection.id, token, from), balance_from);763 }764 <Balance<T>>::insert((collection.id, token, to), balance_to);765 if let Some(account_balance_from) = account_balance_from {766 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);767 <Owned<T>>::remove((collection.id, from, token));768 }769 if let Some(account_balance_to) = account_balance_to {770 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);771 <Owned<T>>::insert((collection.id, to, token), true);772 }773 }774775 <PalletEvm<T>>::deposit_log(776 ERC20Events::Transfer {777 from: *from.as_eth(),778 to: *to.as_eth(),779 value: amount.into(),780 }781 .to_log(T::EvmTokenAddressMapping::token_to_address(782 collection.id,783 token,784 )),785 );786 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(787 collection.id,788 token,789 from.clone(),790 to.clone(),791 amount,792 ));793 Ok(())794 }795796 /// Batched operation to create multiple RFT tokens.797 ///798 /// Same as `create_item` but creates multiple tokens.799 ///800 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.801 pub fn create_multiple_items(802 collection: &RefungibleHandle<T>,803 sender: &T::CrossAccountId,804 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,805 nesting_budget: &dyn Budget,806 ) -> DispatchResult {807 if !collection.is_owner_or_admin(sender) {808 ensure!(809 collection.permissions.mint_mode(),810 <CommonError<T>>::PublicMintingNotAllowed811 );812 collection.check_allowlist(sender)?;813814 for item in data.iter() {815 for user in item.users.keys() {816 collection.check_allowlist(user)?;817 }818 }819 }820821 for item in data.iter() {822 for (owner, _) in item.users.iter() {823 <PalletCommon<T>>::ensure_correct_receiver(owner)?;824 }825 }826827 // Total pieces per tokens828 let totals = data829 .iter()830 .map(|data| {831 Ok(data832 .users833 .iter()834 .map(|u| u.1)835 .try_fold(0u128, |acc, v| acc.checked_add(*v))836 .ok_or(ArithmeticError::Overflow)?)837 })838 .collect::<Result<Vec<_>, DispatchError>>()?;839 for total in &totals {840 ensure!(841 *total <= MAX_REFUNGIBLE_PIECES,842 <Error<T>>::WrongRefungiblePieces843 );844 }845846 let first_token_id = <TokensMinted<T>>::get(collection.id);847 let tokens_minted = first_token_id848 .checked_add(data.len() as u32)849 .ok_or(ArithmeticError::Overflow)?;850 ensure!(851 tokens_minted < collection.limits.token_limit(),852 <CommonError<T>>::CollectionTokenLimitExceeded853 );854855 let mut balances = BTreeMap::new();856 for data in &data {857 for owner in data.users.keys() {858 let balance = balances859 .entry(owner)860 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));861 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;862863 ensure!(864 *balance <= collection.limits.account_token_ownership_limit(),865 <CommonError<T>>::AccountTokenLimitExceeded,866 );867 }868 }869870 for (i, token) in data.iter().enumerate() {871 let token_id = TokenId(first_token_id + i as u32 + 1);872 for (to, _) in token.users.iter() {873 <PalletStructure<T>>::check_nesting(874 sender.clone(),875 to,876 collection.id,877 token_id,878 nesting_budget,879 )?;880 }881 }882883 // =========884885 with_transaction(|| {886 for (i, data) in data.iter().enumerate() {887 let token_id = first_token_id + i as u32 + 1;888 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);889890 for (user, amount) in data.users.iter() {891 if *amount == 0 {892 continue;893 }894 <Balance<T>>::insert((collection.id, token_id, &user), amount);895 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);896 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(897 user,898 collection.id,899 TokenId(token_id),900 );901 }902903 if let Err(e) = Self::set_token_properties(904 collection,905 sender,906 TokenId(token_id),907 data.properties.clone().into_iter(),908 true,909 nesting_budget,910 ) {911 return TransactionOutcome::Rollback(Err(e));912 }913 }914 TransactionOutcome::Commit(Ok(()))915 })?;916917 <TokensMinted<T>>::insert(collection.id, tokens_minted);918919 for (account, balance) in balances {920 <AccountBalance<T>>::insert((collection.id, account), balance);921 }922923 for (i, token) in data.into_iter().enumerate() {924 let token_id = first_token_id + i as u32 + 1;925926 for (user, amount) in token.users.into_iter() {927 if amount == 0 {928 continue;929 }930931 <PalletEvm<T>>::deposit_log(932 ERC20Events::Transfer {933 from: H160::default(),934 to: *user.as_eth(),935 value: amount.into(),936 }937 .to_log(T::EvmTokenAddressMapping::token_to_address(938 collection.id,939 TokenId(token_id),940 )),941 );942 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(943 collection.id,944 TokenId(token_id),945 user,946 amount,947 ));948 }949 }950 Ok(())951 }952953 pub fn set_allowance_unchecked(954 collection: &RefungibleHandle<T>,955 sender: &T::CrossAccountId,956 spender: &T::CrossAccountId,957 token: TokenId,958 amount: u128,959 ) {960 if amount == 0 {961 <Allowance<T>>::remove((collection.id, token, sender, spender));962 } else {963 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);964 }965966 <PalletEvm<T>>::deposit_log(967 ERC20Events::Approval {968 owner: *sender.as_eth(),969 spender: *spender.as_eth(),970 value: amount.into(),971 }972 .to_log(T::EvmTokenAddressMapping::token_to_address(973 collection.id,974 token,975 )),976 );977 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(978 collection.id,979 token,980 sender.clone(),981 spender.clone(),982 amount,983 ))984 }985986 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.987 ///988 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.989 pub fn set_allowance(990 collection: &RefungibleHandle<T>,991 sender: &T::CrossAccountId,992 spender: &T::CrossAccountId,993 token: TokenId,994 amount: u128,995 ) -> DispatchResult {996 if collection.permissions.access() == AccessMode::AllowList {997 collection.check_allowlist(sender)?;998 collection.check_allowlist(spender)?;999 }10001001 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10021003 if <Balance<T>>::get((collection.id, token, sender)) < amount {1004 ensure!(1005 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1006 <CommonError<T>>::CantApproveMoreThanOwned1007 );1008 }10091010 // =========10111012 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1013 Ok(())1014 }10151016 /// Returns allowance, which should be set after transaction1017 fn check_allowed(1018 collection: &RefungibleHandle<T>,1019 spender: &T::CrossAccountId,1020 from: &T::CrossAccountId,1021 token: TokenId,1022 amount: u128,1023 nesting_budget: &dyn Budget,1024 ) -> Result<Option<u128>, DispatchError> {1025 if spender.conv_eq(from) {1026 return Ok(None);1027 }1028 if collection.permissions.access() == AccessMode::AllowList {1029 // `from`, `to` checked in [`transfer`]1030 collection.check_allowlist(spender)?;1031 }1032 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1033 // TODO: should collection owner be allowed to perform this transfer?1034 ensure!(1035 <PalletStructure<T>>::check_indirectly_owned(1036 spender.clone(),1037 source.0,1038 source.1,1039 None,1040 nesting_budget1041 )?,1042 <CommonError<T>>::ApprovedValueTooLow,1043 );1044 return Ok(None);1045 }1046 let allowance =1047 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1048 if allowance.is_none() {1049 ensure!(1050 collection.ignores_allowance(spender),1051 <CommonError<T>>::ApprovedValueTooLow1052 );1053 }1054 Ok(allowance)1055 }10561057 /// Transfer RFT token pieces from one account to another.1058 ///1059 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1060 /// The owner should set allowance for the spender to transfer pieces.1061 ///1062 /// [`transfer`]: struct.Pallet.html#method.transfer1063 pub fn transfer_from(1064 collection: &RefungibleHandle<T>,1065 spender: &T::CrossAccountId,1066 from: &T::CrossAccountId,1067 to: &T::CrossAccountId,1068 token: TokenId,1069 amount: u128,1070 nesting_budget: &dyn Budget,1071 ) -> DispatchResult {1072 let allowance =1073 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10741075 // =========10761077 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1078 if let Some(allowance) = allowance {1079 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1080 }1081 Ok(())1082 }10831084 /// Burn RFT token pieces from the account.1085 ///1086 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1087 /// set allowance for the spender to burn pieces1088 ///1089 /// [`burn`]: struct.Pallet.html#method.burn1090 pub fn burn_from(1091 collection: &RefungibleHandle<T>,1092 spender: &T::CrossAccountId,1093 from: &T::CrossAccountId,1094 token: TokenId,1095 amount: u128,1096 nesting_budget: &dyn Budget,1097 ) -> DispatchResult {1098 let allowance =1099 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11001101 // =========11021103 Self::burn(collection, from, token, amount)?;1104 if let Some(allowance) = allowance {1105 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1106 }1107 Ok(())1108 }11091110 /// Create RFT token.1111 ///1112 /// The sender should be the owner/admin of the collection or collection should be configured1113 /// to allow public minting.1114 ///1115 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1116 /// of token pieces they will receive.1117 pub fn create_item(1118 collection: &RefungibleHandle<T>,1119 sender: &T::CrossAccountId,1120 data: CreateRefungibleExData<T::CrossAccountId>,1121 nesting_budget: &dyn Budget,1122 ) -> DispatchResult {1123 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1124 }11251126 /// Repartition RFT token.1127 ///1128 /// `repartition` will set token balance of the sender and total amount of token pieces.1129 /// Sender should own all of the token pieces. `repartition' could be done even if some1130 /// token pieces were burned before.1131 ///1132 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1133 pub fn repartition(1134 collection: &RefungibleHandle<T>,1135 owner: &T::CrossAccountId,1136 token: TokenId,1137 amount: u128,1138 ) -> DispatchResult {1139 ensure!(1140 amount <= MAX_REFUNGIBLE_PIECES,1141 <Error<T>>::WrongRefungiblePieces1142 );1143 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1144 // Ensure user owns all pieces1145 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1146 let balance = <Balance<T>>::get((collection.id, token, owner));1147 ensure!(1148 total_pieces == balance,1149 <Error<T>>::RepartitionWhileNotOwningAllPieces1150 );11511152 <Balance<T>>::insert((collection.id, token, owner), amount);1153 <TotalSupply<T>>::insert((collection.id, token), amount);11541155 if amount > total_pieces {1156 let mint_amount = amount - total_pieces;1157 <PalletEvm<T>>::deposit_log(1158 ERC20Events::Transfer {1159 from: H160::default(),1160 to: *owner.as_eth(),1161 value: mint_amount.into(),1162 }1163 .to_log(T::EvmTokenAddressMapping::token_to_address(1164 collection.id,1165 token,1166 )),1167 );1168 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1169 collection.id,1170 token,1171 owner.clone(),1172 mint_amount,1173 ));1174 } else if total_pieces > amount {1175 let burn_amount = total_pieces - amount;1176 <PalletEvm<T>>::deposit_log(1177 ERC20Events::Transfer {1178 from: *owner.as_eth(),1179 to: H160::default(),1180 value: burn_amount.into(),1181 }1182 .to_log(T::EvmTokenAddressMapping::token_to_address(1183 collection.id,1184 token,1185 )),1186 );1187 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1188 collection.id,1189 token,1190 owner.clone(),1191 burn_amount,1192 ));1193 }11941195 Ok(())1196 }11971198 fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1199 let mut owner = None;1200 let mut count = 0;1201 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1202 count += 1;1203 if count > 1 {1204 return None;1205 }1206 owner = Some(key);1207 }1208 owner1209 }12101211 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1212 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1213 }12141215 pub fn set_collection_properties(1216 collection: &RefungibleHandle<T>,1217 sender: &T::CrossAccountId,1218 properties: Vec<Property>,1219 ) -> DispatchResult {1220 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)1221 }12221223 pub fn delete_collection_properties(1224 collection: &RefungibleHandle<T>,1225 sender: &T::CrossAccountId,1226 property_keys: Vec<PropertyKey>,1227 ) -> DispatchResult {1228 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1229 }12301231 pub fn set_token_property_permissions(1232 collection: &RefungibleHandle<T>,1233 sender: &T::CrossAccountId,1234 property_permissions: Vec<PropertyKeyPermission>,1235 ) -> DispatchResult {1236 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1237 }12381239 /// Returns 10 token in no particular order.1240 ///1241 /// There is no direct way to get token holders in ascending order,1242 /// since `iter_prefix` returns values in no particular order.1243 /// Therefore, getting the 10 largest holders with a large value of holders1244 /// can lead to impact memory allocation + sorting with `n * log (n)`.1245 pub fn token_owners(1246 collection_id: CollectionId,1247 token: TokenId,1248 ) -> Option<Vec<T::CrossAccountId>> {1249 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1250 .map(|(owner, _amount)| owner)1251 .take(10)1252 .collect();12531254 if res.is_empty() {1255 None1256 } else {1257 Some(res)1258 }1259 }1260}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"))]
@@ -874,10 +864,7 @@
impl CreateItemData {
/// Get size of custom data.
pub fn data_size(&self) -> usize {
- match self {
- CreateItemData::ReFungible(data) => data.const_data.len(),
- _ => 0,
- }
+ 0
}
}
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