difftreelog
Merge pull request #426 from UniqueNetwork/feature/token_owners
in: master
31 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5953,7 +5953,7 @@
[[package]]
name = "pallet-fungible"
-version = "0.1.0"
+version = "0.1.1"
dependencies = [
"ethereum",
"evm-coder",
@@ -6198,7 +6198,7 @@
[[package]]
name = "pallet-nonfungible"
-version = "0.1.0"
+version = "0.1.1"
dependencies = [
"ethereum",
"evm-coder",
@@ -12377,7 +12377,7 @@
[[package]]
name = "uc-rpc"
-version = "0.1.0"
+version = "0.1.1"
dependencies = [
"anyhow",
"jsonrpsee",
@@ -12682,7 +12682,7 @@
[[package]]
name = "unique-runtime-common"
-version = "0.9.24"
+version = "0.9.25"
dependencies = [
"evm-coder",
"fp-rpc",
@@ -12754,7 +12754,7 @@
[[package]]
name = "up-rpc"
-version = "0.1.0"
+version = "0.1.1"
dependencies = [
"pallet-common",
"pallet-evm",
client/rpc/CHANGELOG.mddiffbeforeafterboth--- /dev/null
+++ b/client/rpc/CHANGELOG.md
@@ -0,0 +1,11 @@
+# Change Log
+
+All notable changes to this project will be documented in this file.
+
+## [0.1.1] - 2022-07-14
+
+### Added
+
+ - Implementation of RPC method `token_owners` returning 10 owners in no particular order.
+ This was an internal request to improve the web interface and support fractionalization event.
+
\ No newline at end of file
client/rpc/Cargo.tomldiffbeforeafterboth--- a/client/rpc/Cargo.toml
+++ b/client/rpc/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "uc-rpc"
-version = "0.1.0"
+version = "0.1.1"
license = "GPLv3"
edition = "2021"
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -70,6 +70,16 @@
token: TokenId,
at: Option<BlockHash>,
) -> Result<Option<CrossAccountId>>;
+
+ /// Returns 10 tokens owners in no particular order.
+ #[method(name = "unique_tokenOwners")]
+ fn token_owners(
+ &self,
+ collection: CollectionId,
+ token: TokenId,
+ at: Option<BlockHash>,
+ ) -> Result<Vec<CrossAccountId>>;
+
#[method(name = "unique_topmostTokenOwner")]
fn topmost_token_owner(
&self,
@@ -473,6 +483,7 @@
pass_method!(next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Option<u64>, unique_api);
pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>, unique_api);
pass_method!(total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128>, unique_api);
+ pass_method!(token_owners(collection: CollectionId, token: TokenId) -> Vec<CrossAccountId>, unique_api);
}
#[allow(deprecated)]
pallets/common/CHANGELOG.mddiffbeforeafterboth--- /dev/null
+++ b/pallets/common/CHANGELOG.md
@@ -0,0 +1,12 @@
+# Change Log
+
+All notable changes to this project will be documented in this file.
+
+## [0.1.1] - 2022-07-14
+
+### Added
+
+ - Implementation of RPC method `token_owners` returning 10 owners in no particular order.
+ This was an internal request to improve the web interface and support fractionalization event.
+
+
\ No newline at end of file
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1748,6 +1748,11 @@
/// * `token` - The token for which you need to find out the owner.
fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;
+ /// Returns 10 tokens owners in no particular order.
+ ///
+ /// * `token` - The token for which you need to find out the owners.
+ fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;
+
/// Get the value of the token property by key.
///
/// * `token` - Token with the property to get.
pallets/fungible/CHANGELOG.mddiffbeforeafterboth--- /dev/null
+++ b/pallets/fungible/CHANGELOG.md
@@ -0,0 +1,13 @@
+# Change Log
+
+All notable changes to this project will be documented in this file.
+
+## [0.1.1] - 2022-07-14
+
+### Added
+
+ - Implementation of RPC method `token_owners` returning 10 owners in no particular order.
+ This was an internal request to improve the web interface and support fractionalization event.
+
+
+
\ No newline at end of file
pallets/fungible/Cargo.tomldiffbeforeafterboth--- a/pallets/fungible/Cargo.toml
+++ b/pallets/fungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-fungible"
-version = "0.1.0"
+version = "0.1.1"
license = "GPLv3"
edition = "2021"
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -362,6 +362,11 @@
None
}
+ /// Returns 10 tokens owners in no particular order.
+ fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {
+ <Pallet<T>>::token_owners(self.id, token).unwrap_or_default()
+ }
+
fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {
None
}
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -95,7 +95,7 @@
use pallet_evm_coder_substrate::WithRecorder;
use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
-use sp_std::{collections::btree_map::BTreeMap};
+use sp_std::{collections::btree_map::BTreeMap, vec::Vec};
pub use pallet::*;
@@ -613,4 +613,26 @@
nesting_budget,
)
}
+
+ /// Returns 10 tokens owners in no particular order
+ ///
+ /// There is no direct way to get token holders in ascending order,
+ /// since `iter_prefix` returns values in no particular order.
+ /// Therefore, getting the 10 largest holders with a large value of holders
+ /// can lead to impact memory allocation + sorting with `n * log (n)`.
+ pub fn token_owners(
+ collection: CollectionId,
+ _token: TokenId,
+ ) -> Option<Vec<T::CrossAccountId>> {
+ let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))
+ .map(|(owner, _amount)| owner)
+ .take(10)
+ .collect();
+
+ if res.is_empty() {
+ None
+ } else {
+ Some(res)
+ }
+ }
}
pallets/nonfungible/CHANGELOG.mddiffbeforeafterboth--- /dev/null
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -0,0 +1,11 @@
+# Change Log
+
+All notable changes to this project will be documented in this file.
+
+## [0.1.1] - 2022-07-14
+
+### Added
+
+- Implementation of RPC method `token_owners`.
+ For reasons of compatibility with this pallet, returns only one owner if token exists.
+ This was an internal request to improve the web interface and support fractionalization event.
\ No newline at end of file
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-nonfungible"
-version = "0.1.0"
+version = "0.1.1"
license = "GPLv3"
edition = "2021"
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -26,7 +26,7 @@
weights::WeightInfo as _,
};
use sp_runtime::DispatchError;
-use sp_std::vec::Vec;
+use sp_std::{vec::Vec, vec};
use crate::{
AccountBalance, Allowance, Config, CreateItemData, Error, NonfungibleHandle, Owned, Pallet,
@@ -422,6 +422,11 @@
<TokenData<T>>::get((self.id, token)).map(|t| t.owner)
}
+ /// Returns token owners.
+ fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {
+ self.token_owner(token).map_or_else(|| vec![], |t| vec![t])
+ }
+
fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
<Pallet<T>>::token_properties((self.id, token_id))
.get(key)
pallets/refungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/refungible/CHANGELOG.md
+++ b/pallets/refungible/CHANGELOG.md
@@ -1,6 +1,18 @@
-## v0.1.2 - 2022-07
+# Change Log
-### Refungible Pallet
+All notable changes to this project will be documented in this file.
+## [v0.1.2] - 2022-07-14
+
+### Other changes
+
feat(refungible-pallet): add ERC-20 EVM API for RFT token pieces ([#413](https://github.com/UniqueNetwork/unique-chain/pull/413))
-test(refungible-pallet): add tests for ERC-20 EVM API for RFT token pieces ([#413](https://github.com/UniqueNetwork/unique-chain/pull/413))
\ No newline at end of file
+test(refungible-pallet): add tests for ERC-20 EVM API for RFT token pieces ([#413](https://github.com/UniqueNetwork/unique-chain/pull/413))
+
+## [v0.1.1] - 2022-07-14
+
+### Other changes
+
+- feat: RPC method `token_owners` returning 10 owners in no particular order.
+
+This was an internal request to improve the web interface and support fractionalization event.
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -438,6 +438,11 @@
<Pallet<T>>::token_owner(self.id, token)
}
+ /// Returns 10 token in no particular order.
+ fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {
+ <Pallet<T>>::token_owners(self.id, token).unwrap_or_default()
+ }
+
fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {
None
}
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`]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#[struct_versioning::versioned(version = 2, upper)]123#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]124pub struct ItemData {125 pub const_data: BoundedVec<u8, CustomDataLimit>,126127 #[version(..2)]128 pub variable_data: BoundedVec<u8, CustomDataLimit>,129}130131#[frame_support::pallet]132pub mod pallet {133 use super::*;134 use frame_support::{135 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,136 traits::StorageVersion,137 };138 use frame_system::pallet_prelude::*;139 use up_data_structs::{CollectionId, TokenId};140 use super::weights::WeightInfo;141142 #[pallet::error]143 pub enum Error<T> {144 /// Not Refungible item data used to mint in Refungible collection.145 NotRefungibleDataUsedToMintFungibleCollectionToken,146 /// Maximum refungibility exceeded147 WrongRefungiblePieces,148 /// Refungible token can't be repartitioned by user who isn't owns all pieces149 RepartitionWhileNotOwningAllPieces,150 /// Refungible token can't nest other tokens151 RefungibleDisallowsNesting,152 /// Setting item properties is not allowed153 SettingPropertiesNotAllowed,154 }155156 #[pallet::config]157 pub trait Config:158 frame_system::Config + pallet_common::Config + pallet_structure::Config159 {160 type WeightInfo: WeightInfo;161 }162163 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);164165 #[pallet::pallet]166 #[pallet::storage_version(STORAGE_VERSION)]167 #[pallet::generate_store(pub(super) trait Store)]168 pub struct Pallet<T>(_);169170 /// Amount of tokens minted for collection171 #[pallet::storage]172 pub type TokensMinted<T: Config> =173 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;174175 /// Amount of burnt tokens for collection176 #[pallet::storage]177 pub type TokensBurnt<T: Config> =178 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;179180 /// Custom data serialized to bytes for token181 #[pallet::storage]182 pub type TokenData<T: Config> = StorageNMap<183 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),184 Value = ItemData,185 QueryKind = ValueQuery,186 >;187188 #[pallet::storage]189 #[pallet::getter(fn token_properties)]190 pub type TokenProperties<T: Config> = StorageNMap<191 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),192 Value = up_data_structs::Properties,193 QueryKind = ValueQuery,194 OnEmpty = up_data_structs::TokenProperties,195 >;196197 /// Total amount of pieces for token198 #[pallet::storage]199 pub type TotalSupply<T: Config> = StorageNMap<200 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),201 Value = u128,202 QueryKind = ValueQuery,203 >;204205 /// Used to enumerate tokens owned by account206 #[pallet::storage]207 pub type Owned<T: Config> = StorageNMap<208 Key = (209 Key<Twox64Concat, CollectionId>,210 Key<Blake2_128Concat, T::CrossAccountId>,211 Key<Twox64Concat, TokenId>,212 ),213 Value = bool,214 QueryKind = ValueQuery,215 >;216217 /// Amount of tokens owned by account218 #[pallet::storage]219 pub type AccountBalance<T: Config> = StorageNMap<220 Key = (221 Key<Twox64Concat, CollectionId>,222 // Owner223 Key<Blake2_128Concat, T::CrossAccountId>,224 ),225 Value = u32,226 QueryKind = ValueQuery,227 >;228229 /// Amount of token pieces owned by account230 #[pallet::storage]231 pub type Balance<T: Config> = StorageNMap<232 Key = (233 Key<Twox64Concat, CollectionId>,234 Key<Twox64Concat, TokenId>,235 // Owner236 Key<Blake2_128Concat, T::CrossAccountId>,237 ),238 Value = u128,239 QueryKind = ValueQuery,240 >;241242 /// Allowance set by an owner for a spender for a token243 #[pallet::storage]244 pub type Allowance<T: Config> = StorageNMap<245 Key = (246 Key<Twox64Concat, CollectionId>,247 Key<Twox64Concat, TokenId>,248 // Owner249 Key<Blake2_128, T::CrossAccountId>,250 // Spender251 Key<Blake2_128Concat, T::CrossAccountId>,252 ),253 Value = u128,254 QueryKind = ValueQuery,255 >;256257 #[pallet::hooks]258 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {259 fn on_runtime_upgrade() -> Weight {260 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {261 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {262 Some(<ItemDataVersion2>::from(v))263 })264 }265266 0267 }268 }269}270271pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);272impl<T: Config> RefungibleHandle<T> {273 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {274 Self(inner)275 }276 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {277 self.0278 }279 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {280 &mut self.0281 }282}283284impl<T: Config> Deref for RefungibleHandle<T> {285 type Target = pallet_common::CollectionHandle<T>;286287 fn deref(&self) -> &Self::Target {288 &self.0289 }290}291292impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {293 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {294 self.0.recorder()295 }296 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {297 self.0.into_recorder()298 }299}300301impl<T: Config> Pallet<T> {302 /// Get number of RFT tokens in collection303 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {304 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)305 }306307 /// Check that RFT token exists308 ///309 /// - `token`: Token ID.310 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {311 <TotalSupply<T>>::contains_key((collection.id, token))312 }313314 pub fn set_scoped_token_property(315 collection_id: CollectionId,316 token_id: TokenId,317 scope: PropertyScope,318 property: Property,319 ) -> DispatchResult {320 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {321 properties.try_scoped_set(scope, property.key, property.value)322 })323 .map_err(<CommonError<T>>::from)?;324325 Ok(())326 }327328 pub fn set_scoped_token_properties(329 collection_id: CollectionId,330 token_id: TokenId,331 scope: PropertyScope,332 properties: impl Iterator<Item = Property>,333 ) -> DispatchResult {334 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {335 stored_properties.try_scoped_set_from_iter(scope, properties)336 })337 .map_err(<CommonError<T>>::from)?;338339 Ok(())340 }341}342343// unchecked calls skips any permission checks344impl<T: Config> Pallet<T> {345 /// Create RFT collection346 ///347 /// `init_collection` will take non-refundable deposit for collection creation.348 ///349 /// - `data`: Contains settings for collection limits and permissions.350 pub fn init_collection(351 owner: T::CrossAccountId,352 data: CreateCollectionData<T::AccountId>,353 ) -> Result<CollectionId, DispatchError> {354 <PalletCommon<T>>::init_collection(owner, data, false)355 }356357 /// Destroy RFT collection358 ///359 /// `destroy_collection` will throw error if collection contains any tokens.360 /// Only owner can destroy collection.361 pub fn destroy_collection(362 collection: RefungibleHandle<T>,363 sender: &T::CrossAccountId,364 ) -> DispatchResult {365 let id = collection.id;366367 if Self::collection_has_tokens(id) {368 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());369 }370371 // =========372373 PalletCommon::destroy_collection(collection.0, sender)?;374375 <TokensMinted<T>>::remove(id);376 <TokensBurnt<T>>::remove(id);377 <TokenData<T>>::remove_prefix((id,), None);378 <TotalSupply<T>>::remove_prefix((id,), None);379 <Balance<T>>::remove_prefix((id,), None);380 <Allowance<T>>::remove_prefix((id,), None);381 <Owned<T>>::remove_prefix((id,), None);382 <AccountBalance<T>>::remove_prefix((id,), None);383 Ok(())384 }385386 fn collection_has_tokens(collection_id: CollectionId) -> bool {387 <TokenData<T>>::iter_prefix((collection_id,))388 .next()389 .is_some()390 }391392 pub fn burn_token_unchecked(393 collection: &RefungibleHandle<T>,394 token_id: TokenId,395 ) -> DispatchResult {396 let burnt = <TokensBurnt<T>>::get(collection.id)397 .checked_add(1)398 .ok_or(ArithmeticError::Overflow)?;399400 <TokensBurnt<T>>::insert(collection.id, burnt);401 <TokenData<T>>::remove((collection.id, token_id));402 <TokenProperties<T>>::remove((collection.id, token_id));403 <TotalSupply<T>>::remove((collection.id, token_id));404 <Balance<T>>::remove_prefix((collection.id, token_id), None);405 <Allowance<T>>::remove_prefix((collection.id, token_id), None);406 // TODO: ERC721 transfer event407 Ok(())408 }409410 /// Burn RFT token pieces411 ///412 /// `burn` will decrease total amount of token pieces and amount owned by sender.413 /// `burn` can be called even if there are multiple owners of the RFT token.414 /// If sender wouldn't have any pieces left after `burn` than she will stop being415 /// one of the owners of the token. If there is no account that owns any pieces of416 /// the token than token will be burned too.417 ///418 /// - `amount`: Amount of token pieces to burn.419 /// - `token`: Token who's pieces should be burned420 /// - `collection`: Collection that contains the token421 pub fn burn(422 collection: &RefungibleHandle<T>,423 owner: &T::CrossAccountId,424 token: TokenId,425 amount: u128,426 ) -> DispatchResult {427 let total_supply = <TotalSupply<T>>::get((collection.id, token))428 .checked_sub(amount)429 .ok_or(<CommonError<T>>::TokenValueTooLow)?;430431 // This was probally last owner of this token?432 if total_supply == 0 {433 // Ensure user actually owns this amount434 ensure!(435 <Balance<T>>::get((collection.id, token, owner)) == amount,436 <CommonError<T>>::TokenValueTooLow437 );438 let account_balance = <AccountBalance<T>>::get((collection.id, owner))439 .checked_sub(1)440 // Should not occur441 .ok_or(ArithmeticError::Underflow)?;442443 // =========444445 <Owned<T>>::remove((collection.id, owner, token));446 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);447 <AccountBalance<T>>::insert((collection.id, owner), account_balance);448 Self::burn_token_unchecked(collection, token)?;449 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(450 collection.id,451 token,452 owner.clone(),453 amount,454 ));455 return Ok(());456 }457458 let balance = <Balance<T>>::get((collection.id, token, owner))459 .checked_sub(amount)460 .ok_or(<CommonError<T>>::TokenValueTooLow)?;461 let account_balance = if balance == 0 {462 <AccountBalance<T>>::get((collection.id, owner))463 .checked_sub(1)464 // Should not occur465 .ok_or(ArithmeticError::Underflow)?466 } else {467 0468 };469470 // =========471472 if balance == 0 {473 <Owned<T>>::remove((collection.id, owner, token));474 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);475 <Balance<T>>::remove((collection.id, token, owner));476 <AccountBalance<T>>::insert((collection.id, owner), account_balance);477 } else {478 <Balance<T>>::insert((collection.id, token, owner), balance);479 }480 <TotalSupply<T>>::insert((collection.id, token), total_supply);481482 <PalletEvm<T>>::deposit_log(483 ERC20Events::Transfer {484 from: *owner.as_eth(),485 to: H160::default(),486 value: amount.into(),487 }488 .to_log(T::EvmTokenAddressMapping::token_to_address(489 collection.id,490 token,491 )),492 );493 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(494 collection.id,495 token,496 owner.clone(),497 amount,498 ));499 Ok(())500 }501502 #[transactional]503 fn modify_token_properties(504 collection: &RefungibleHandle<T>,505 sender: &T::CrossAccountId,506 token_id: TokenId,507 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,508 is_token_create: bool,509 nesting_budget: &dyn Budget,510 ) -> DispatchResult {511 let is_collection_admin = || collection.is_owner_or_admin(sender);512 let is_token_owner = || -> Result<bool, DispatchError> {513 let balance = collection.balance(sender.clone(), token_id);514 let total_pieces: u128 =515 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);516 if balance != total_pieces {517 return Ok(false);518 }519520 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(521 sender.clone(),522 collection.id,523 token_id,524 None,525 nesting_budget,526 )?;527528 Ok(is_bundle_owner)529 };530531 for (key, value) in properties {532 let permission = <PalletCommon<T>>::property_permissions(collection.id)533 .get(&key)534 .cloned()535 .unwrap_or_else(PropertyPermission::none);536537 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))538 .get(&key)539 .is_some();540541 match permission {542 PropertyPermission { mutable: false, .. } if is_property_exists => {543 return Err(<CommonError<T>>::NoPermission.into());544 }545546 PropertyPermission {547 collection_admin,548 token_owner,549 ..550 } => {551 //TODO: investigate threats during public minting.552 let is_token_create =553 is_token_create && (collection_admin || token_owner) && value.is_some();554 if !(is_token_create555 || (collection_admin && is_collection_admin())556 || (token_owner && is_token_owner()?))557 {558 fail!(<CommonError<T>>::NoPermission);559 }560 }561 }562563 match value {564 Some(value) => {565 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {566 properties.try_set(key.clone(), value)567 })568 .map_err(<CommonError<T>>::from)?;569570 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(571 collection.id,572 token_id,573 key,574 ));575 }576 None => {577 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {578 properties.remove(&key)579 })580 .map_err(<CommonError<T>>::from)?;581582 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(583 collection.id,584 token_id,585 key,586 ));587 }588 }589 }590591 Ok(())592 }593594 pub fn set_token_properties(595 collection: &RefungibleHandle<T>,596 sender: &T::CrossAccountId,597 token_id: TokenId,598 properties: impl Iterator<Item = Property>,599 is_token_create: bool,600 nesting_budget: &dyn Budget,601 ) -> DispatchResult {602 Self::modify_token_properties(603 collection,604 sender,605 token_id,606 properties.map(|p| (p.key, Some(p.value))),607 is_token_create,608 nesting_budget,609 )610 }611612 pub fn set_token_property(613 collection: &RefungibleHandle<T>,614 sender: &T::CrossAccountId,615 token_id: TokenId,616 property: Property,617 nesting_budget: &dyn Budget,618 ) -> DispatchResult {619 let is_token_create = false;620621 Self::set_token_properties(622 collection,623 sender,624 token_id,625 [property].into_iter(),626 is_token_create,627 nesting_budget,628 )629 }630631 pub fn delete_token_properties(632 collection: &RefungibleHandle<T>,633 sender: &T::CrossAccountId,634 token_id: TokenId,635 property_keys: impl Iterator<Item = PropertyKey>,636 nesting_budget: &dyn Budget,637 ) -> DispatchResult {638 let is_token_create = false;639640 Self::modify_token_properties(641 collection,642 sender,643 token_id,644 property_keys.into_iter().map(|key| (key, None)),645 is_token_create,646 nesting_budget,647 )648 }649650 pub fn delete_token_property(651 collection: &RefungibleHandle<T>,652 sender: &T::CrossAccountId,653 token_id: TokenId,654 property_key: PropertyKey,655 nesting_budget: &dyn Budget,656 ) -> DispatchResult {657 Self::delete_token_properties(658 collection,659 sender,660 token_id,661 [property_key].into_iter(),662 nesting_budget,663 )664 }665666 /// Transfer RFT token pieces from one account to another.667 ///668 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.669 ///670 /// - `from`: Owner of token pieces to transfer.671 /// - `to`: Recepient of transfered token pieces.672 /// - `amount`: Amount of token pieces to transfer.673 /// - `token`: Token whos pieces should be transfered674 /// - `collection`: Collection that contains the token675 pub fn transfer(676 collection: &RefungibleHandle<T>,677 from: &T::CrossAccountId,678 to: &T::CrossAccountId,679 token: TokenId,680 amount: u128,681 nesting_budget: &dyn Budget,682 ) -> DispatchResult {683 ensure!(684 collection.limits.transfers_enabled(),685 <CommonError<T>>::TransferNotAllowed686 );687688 if collection.permissions.access() == AccessMode::AllowList {689 collection.check_allowlist(from)?;690 collection.check_allowlist(to)?;691 }692 <PalletCommon<T>>::ensure_correct_receiver(to)?;693694 let balance_from = <Balance<T>>::get((collection.id, token, from))695 .checked_sub(amount)696 .ok_or(<CommonError<T>>::TokenValueTooLow)?;697 let mut create_target = false;698 let from_to_differ = from != to;699 let balance_to = if from != to {700 let old_balance = <Balance<T>>::get((collection.id, token, to));701 if old_balance == 0 {702 create_target = true;703 }704 Some(705 old_balance706 .checked_add(amount)707 .ok_or(ArithmeticError::Overflow)?,708 )709 } else {710 None711 };712713 let account_balance_from = if balance_from == 0 {714 Some(715 <AccountBalance<T>>::get((collection.id, from))716 .checked_sub(1)717 // Should not occur718 .ok_or(ArithmeticError::Underflow)?,719 )720 } else {721 None722 };723 // Account data is created in token, AccountBalance should be increased724 // But only if from != to as we shouldn't check overflow in this case725 let account_balance_to = if create_target && from_to_differ {726 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))727 .checked_add(1)728 .ok_or(ArithmeticError::Overflow)?;729 ensure!(730 account_balance_to < collection.limits.account_token_ownership_limit(),731 <CommonError<T>>::AccountTokenLimitExceeded,732 );733734 Some(account_balance_to)735 } else {736 None737 };738739 // =========740741 <PalletStructure<T>>::nest_if_sent_to_token(742 from.clone(),743 to,744 collection.id,745 token,746 nesting_budget,747 )?;748749 if let Some(balance_to) = balance_to {750 // from != to751 if balance_from == 0 {752 <Balance<T>>::remove((collection.id, token, from));753 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);754 } else {755 <Balance<T>>::insert((collection.id, token, from), balance_from);756 }757 <Balance<T>>::insert((collection.id, token, to), balance_to);758 if let Some(account_balance_from) = account_balance_from {759 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);760 <Owned<T>>::remove((collection.id, from, token));761 }762 if let Some(account_balance_to) = account_balance_to {763 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);764 <Owned<T>>::insert((collection.id, to, token), true);765 }766 }767768 <PalletEvm<T>>::deposit_log(769 ERC20Events::Transfer {770 from: *from.as_eth(),771 to: *to.as_eth(),772 value: amount.into(),773 }774 .to_log(T::EvmTokenAddressMapping::token_to_address(775 collection.id,776 token,777 )),778 );779 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(780 collection.id,781 token,782 from.clone(),783 to.clone(),784 amount,785 ));786 Ok(())787 }788789 /// Batched operation to create multiple RFT tokens.790 ///791 /// Same as `create_item` but creates multiple tokens.792 ///793 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.794 pub fn create_multiple_items(795 collection: &RefungibleHandle<T>,796 sender: &T::CrossAccountId,797 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,798 nesting_budget: &dyn Budget,799 ) -> DispatchResult {800 if !collection.is_owner_or_admin(sender) {801 ensure!(802 collection.permissions.mint_mode(),803 <CommonError<T>>::PublicMintingNotAllowed804 );805 collection.check_allowlist(sender)?;806807 for item in data.iter() {808 for user in item.users.keys() {809 collection.check_allowlist(user)?;810 }811 }812 }813814 for item in data.iter() {815 for (owner, _) in item.users.iter() {816 <PalletCommon<T>>::ensure_correct_receiver(owner)?;817 }818 }819820 // Total pieces per tokens821 let totals = data822 .iter()823 .map(|data| {824 Ok(data825 .users826 .iter()827 .map(|u| u.1)828 .try_fold(0u128, |acc, v| acc.checked_add(*v))829 .ok_or(ArithmeticError::Overflow)?)830 })831 .collect::<Result<Vec<_>, DispatchError>>()?;832 for total in &totals {833 ensure!(834 *total <= MAX_REFUNGIBLE_PIECES,835 <Error<T>>::WrongRefungiblePieces836 );837 }838839 let first_token_id = <TokensMinted<T>>::get(collection.id);840 let tokens_minted = first_token_id841 .checked_add(data.len() as u32)842 .ok_or(ArithmeticError::Overflow)?;843 ensure!(844 tokens_minted < collection.limits.token_limit(),845 <CommonError<T>>::CollectionTokenLimitExceeded846 );847848 let mut balances = BTreeMap::new();849 for data in &data {850 for owner in data.users.keys() {851 let balance = balances852 .entry(owner)853 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));854 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;855856 ensure!(857 *balance <= collection.limits.account_token_ownership_limit(),858 <CommonError<T>>::AccountTokenLimitExceeded,859 );860 }861 }862863 for (i, token) in data.iter().enumerate() {864 let token_id = TokenId(first_token_id + i as u32 + 1);865 for (to, _) in token.users.iter() {866 <PalletStructure<T>>::check_nesting(867 sender.clone(),868 to,869 collection.id,870 token_id,871 nesting_budget,872 )?;873 }874 }875876 // =========877878 with_transaction(|| {879 for (i, data) in data.iter().enumerate() {880 let token_id = first_token_id + i as u32 + 1;881 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);882883 <TokenData<T>>::insert(884 (collection.id, token_id),885 ItemData {886 const_data: data.const_data.clone(),887 },888 );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 }1238}primitives/rpc/CHANGELOG.mddiffbeforeafterboth--- /dev/null
+++ b/primitives/rpc/CHANGELOG.md
@@ -0,0 +1,10 @@
+# Change Log
+
+All notable changes to this project will be documented in this file.
+
+## [0.1.1] - 2022-07-14
+
+### Added
+
+ - Implementation of RPC method `token_owners` returning 10 owners in no particular order.
+ This was an internal request to improve the web interface and support fractionalization event.
\ No newline at end of file
primitives/rpc/Cargo.tomldiffbeforeafterboth--- a/primitives/rpc/Cargo.toml
+++ b/primitives/rpc/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "up-rpc"
-version = "0.1.0"
+version = "0.1.1"
license = "GPLv3"
edition = "2021"
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -81,5 +81,6 @@
fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>>;
fn effective_collection_limits(collection_id: CollectionId) -> Result<Option<CollectionLimits>>;
fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Result<Option<u128>>;
+ fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec<CrossAccountId>>;
}
}
runtime/common/CHANGELOG.mddiffbeforeafterboth--- /dev/null
+++ b/runtime/common/CHANGELOG.md
@@ -0,0 +1,13 @@
+# Change Log
+
+All notable changes to this project will be documented in this file.
+
+## [0.9.25] - 2022-07-14
+
+### Added
+
+ - Implementation of RPC method `token_owners` returning 10 owners in no particular order.
+ This was an internal request to improve the web interface and support fractionalization event.
+
+
+
\ No newline at end of file
runtime/common/src/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -40,6 +40,11 @@
fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
dispatch_unique_runtime!(collection.token_owner(token))
}
+
+ fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec::<CrossAccountId>, DispatchError> {
+ dispatch_unique_runtime!(collection.token_owners(token))
+ }
+
fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
let budget = up_data_structs::budget::Value::new(10);
tests/CHANGELOG.mddiffbeforeafterboth--- /dev/null
+++ b/tests/CHANGELOG.md
@@ -0,0 +1,11 @@
+# Change Log
+
+All notable changes to this project will be documented in this file.
+
+## 2022-07-14
+
+### Added
+ - Integrintegration tests of RPC method `token_owners`.
+ - Integrintegration tests of Fungible Pallet.
+
+
\ No newline at end of file
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -80,6 +80,8 @@
"testLimits": "mocha --timeout 9999999 -r ts-node/register ./**/limits.test.ts",
"testEthCreateCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createCollection.test.ts",
"testRFT": "mocha --timeout 9999999 -r ts-node/register ./**/refungible.test.ts",
+ "testFT": "mocha --timeout 9999999 -r ts-node/register ./**/fungible.test.ts",
+ "testRPC": "mocha --timeout 9999999 -r ts-node/register ./**/rpc.test.ts",
"polkadot-types-fetch-metadata": "curl -H 'Content-Type: application/json' -d '{\"id\":\"1\", \"jsonrpc\":\"2.0\", \"method\": \"state_getMetadata\", \"params\":[]}' http://localhost:9933 > src/interfaces/metadata.json",
"polkadot-types-from-defs": "ts-node ./node_modules/.bin/polkadot-types-from-defs --endpoint src/interfaces/metadata.json --input src/interfaces/ --package .",
"polkadot-types-from-chain": "ts-node ./node_modules/.bin/polkadot-types-from-chain --endpoint src/interfaces/metadata.json --output src/interfaces/ --package .",
tests/src/fungible.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/fungible.test.ts
@@ -0,0 +1,184 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {default as usingApi} from './substrate/substrate-api';
+import {IKeyringPair} from '@polkadot/types/types';
+import {
+ getBalance,
+ createMultipleItemsExpectSuccess,
+ isTokenExists,
+ getLastTokenId,
+ getAllowance,
+ approve,
+ transferFrom,
+ createCollection,
+ transfer,
+ burnItem,
+ normalizeAccountId,
+ CrossAccountId,
+ createFungibleItemExpectSuccess,
+ U128_MAX,
+ burnFromExpectSuccess,
+} from './util/helpers';
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+let alice: IKeyringPair;
+let bob: IKeyringPair;
+
+describe('integration test: Fungible functionality:', () => {
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ alice = privateKeyWrapper('//Alice');
+ bob = privateKeyWrapper('//Bob');
+ });
+ });
+
+ it('Create fungible collection and token', async () => {
+ await usingApi(async api => {
+ const createCollectionResult = await createCollection(api, alice, {mode: {type: 'Fungible', decimalPoints: 0}});
+ expect(createCollectionResult.success).to.be.true;
+ const collectionId = createCollectionResult.collectionId;
+ const defaultTokenId = await getLastTokenId(api, collectionId);
+ const aliceTokenId = await createFungibleItemExpectSuccess(alice, collectionId, {Value: U128_MAX}, alice.address);
+ const aliceBalance = await getBalance(api, collectionId, alice, aliceTokenId);
+ const itemCountAfter = await getLastTokenId(api, collectionId);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(itemCountAfter).to.be.equal(defaultTokenId);
+ expect(aliceBalance).to.be.equal(U128_MAX);
+ });
+ });
+
+ it('RPC method tokenOnewrs for fungible collection and token', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
+ const facelessCrowd = Array.from(Array(7).keys()).map(i => normalizeAccountId(privateKeyWrapper(i.toString())));
+
+ const createCollectionResult = await createCollection(api, alice, {mode: {type: 'Fungible', decimalPoints: 0}});
+ const collectionId = createCollectionResult.collectionId;
+ const aliceTokenId = await createFungibleItemExpectSuccess(alice, collectionId, {Value: U128_MAX}, alice.address);
+
+ await transfer(api, collectionId, aliceTokenId, alice, bob, 1000n);
+ await transfer(api, collectionId, aliceTokenId, alice, ethAcc, 900n);
+
+ for (let i = 0; i < 7; i++) {
+ await transfer(api, collectionId, aliceTokenId, alice, facelessCrowd[i], 1);
+ }
+
+ const owners = await api.rpc.unique.tokenOwners(collectionId, aliceTokenId);
+ const ids = (owners.toJSON() as CrossAccountId[]).map(s => normalizeAccountId(s));
+ const aliceID = normalizeAccountId(alice);
+ const bobId = normalizeAccountId(bob);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(ids).to.deep.include.members([aliceID, ethAcc, bobId, ...facelessCrowd]);
+ expect(owners.length == 10).to.be.true;
+
+ const eleven = privateKeyWrapper('11');
+ expect(await transfer(api, collectionId, aliceTokenId, alice, eleven, 10n)).to.be.true;
+ expect((await api.rpc.unique.tokenOwners(collectionId, aliceTokenId)).length).to.be.equal(10);
+ });
+ });
+
+ it('Transfer token', async () => {
+ await usingApi(async api => {
+ const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
+ const collectionId = (await createCollection(api, alice, {mode: {type: 'Fungible', decimalPoints: 0}})).collectionId;
+ const tokenId = await createFungibleItemExpectSuccess(alice, collectionId, {Value: 500n}, alice.address);
+
+ expect(await getBalance(api, collectionId, alice, tokenId)).to.be.equal(500n);
+ expect(await transfer(api, collectionId, tokenId, alice, bob, 60n)).to.be.true;
+ expect(await transfer(api, collectionId, tokenId, alice, ethAcc, 140n)).to.be.true;
+
+ expect(await getBalance(api, collectionId, alice, tokenId)).to.be.equal(300n);
+ expect(await getBalance(api, collectionId, bob, tokenId)).to.be.equal(60n);
+ expect(await getBalance(api, collectionId, ethAcc, tokenId)).to.be.equal(140n);
+ await expect(transfer(api, collectionId, tokenId, alice, bob, 350n)).to.eventually.be.rejected;
+ });
+ });
+
+ it('Tokens multiple creation', async () => {
+ await usingApi(async api => {
+ const collectionId = (await createCollection(api, alice, {mode: {type: 'Fungible', decimalPoints: 0}})).collectionId;
+
+ const args = [
+ {Fungible: {Value: 500n}},
+ {Fungible: {Value: 400n}},
+ {Fungible: {Value: 300n}},
+ ];
+
+ await createMultipleItemsExpectSuccess(alice, collectionId, args);
+ expect(await getBalance(api, collectionId, alice, 0)).to.be.equal(1200n);
+ });
+ });
+
+ it('Burn some tokens ', async () => {
+ await usingApi(async api => {
+ const collectionId = (await createCollection(api, alice, {mode: {type: 'Fungible', decimalPoints: 0}})).collectionId;
+ const tokenId = (await createFungibleItemExpectSuccess(alice, collectionId, {Value: 500n}, alice.address));
+ expect(await isTokenExists(api, collectionId, tokenId)).to.be.true;
+ expect(await getBalance(api, collectionId, alice, tokenId)).to.be.equal(500n);
+ expect(await burnItem(api, alice, collectionId, tokenId, 499n)).to.be.true;
+ expect(await isTokenExists(api, collectionId, tokenId)).to.be.true;
+ expect(await getBalance(api, collectionId, alice, tokenId)).to.be.equal(1n);
+ });
+ });
+
+ it('Burn all tokens ', async () => {
+ await usingApi(async api => {
+ const collectionId = (await createCollection(api, alice, {mode: {type: 'Fungible', decimalPoints: 0}})).collectionId;
+ const tokenId = (await createFungibleItemExpectSuccess(alice, collectionId, {Value: 500n}, alice.address));
+ expect(await isTokenExists(api, collectionId, tokenId)).to.be.true;
+ expect(await burnItem(api, alice, collectionId, tokenId, 500n)).to.be.true;
+ expect(await isTokenExists(api, collectionId, tokenId)).to.be.true;
+
+ expect(await getBalance(api, collectionId, alice, tokenId)).to.be.equal(0n);
+ expect((await api.rpc.unique.totalPieces(collectionId, tokenId)).value.toBigInt()).to.be.equal(0n);
+ });
+ });
+
+ it('Set allowance for token', async () => {
+ await usingApi(async api => {
+ const collectionId = (await createCollection(api, alice, {mode: {type: 'Fungible', decimalPoints: 0}})).collectionId;
+ const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
+
+ const tokenId = (await createFungibleItemExpectSuccess(alice, collectionId, {Value: 100n}, alice.address));
+ expect(await getBalance(api, collectionId, alice, tokenId)).to.be.equal(100n);
+
+ expect(await approve(api, collectionId, tokenId, alice, bob, 60n)).to.be.true;
+ expect(await getAllowance(api, collectionId, alice, bob, tokenId)).to.be.equal(60n);
+ expect(await getBalance(api, collectionId, bob, tokenId)).to.be.equal(0n);
+
+ expect(await transferFrom(api, collectionId, tokenId, bob, alice, bob, 20n)).to.be.true;
+ expect(await getBalance(api, collectionId, alice, tokenId)).to.be.equal(80n);
+ expect(await getBalance(api, collectionId, bob, tokenId)).to.be.equal(20n);
+ expect(await getAllowance(api, collectionId, alice, bob, tokenId)).to.be.equal(40n);
+
+ await burnFromExpectSuccess(bob, alice, collectionId, tokenId, 10n);
+
+ expect(await getBalance(api, collectionId, alice, tokenId)).to.be.equal(70n);
+ expect(await getAllowance(api, collectionId, alice, bob, tokenId)).to.be.equal(30n);
+ expect(await transferFrom(api, collectionId, tokenId, bob, alice, ethAcc, 10n)).to.be.true;
+ expect(await getBalance(api, collectionId, ethAcc, tokenId)).to.be.equal(10n);
+ });
+ });
+});
tests/src/interfaces/augment-api-consts.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-consts.ts
+++ b/tests/src/interfaces/augment-api-consts.ts
@@ -29,7 +29,13 @@
[key: string]: Codec;
};
common: {
+ /**
+ * Maximum admins per collection.
+ **/
collectionAdminsLimit: u32 & AugmentedConst<ApiType>;
+ /**
+ * Set price to create a collection.
+ **/
collectionCreationPrice: u128 & AugmentedConst<ApiType>;
/**
* Generic const
tests/src/interfaces/augment-api-events.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-events.ts
+++ b/tests/src/interfaces/augment-api-events.ts
@@ -59,82 +59,47 @@
};
common: {
/**
- * * collection_id
- *
- * * item_id
- *
- * * sender
- *
- * * spender
- *
- * * amount
+ * Amount pieces of token owned by `sender` was approved for `spender`.
**/
Approved: AugmentedEvent<ApiType, [u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
/**
* New collection was created
- *
- * # Arguments
- *
- * * collection_id: Globally unique identifier of newly created collection.
- *
- * * mode: [CollectionMode] converted into u8.
- *
- * * account_id: Collection owner.
**/
CollectionCreated: AugmentedEvent<ApiType, [u32, u8, AccountId32]>;
/**
* New collection was destroyed
- *
- * # Arguments
- *
- * * collection_id: Globally unique identifier of collection.
**/
CollectionDestroyed: AugmentedEvent<ApiType, [u32]>;
+ /**
+ * The property has been deleted.
+ **/
CollectionPropertyDeleted: AugmentedEvent<ApiType, [u32, Bytes]>;
+ /**
+ * The colletion property has been set.
+ **/
CollectionPropertySet: AugmentedEvent<ApiType, [u32, Bytes]>;
/**
* New item was created.
- *
- * # Arguments
- *
- * * collection_id: Id of the collection where item was created.
- *
- * * item_id: Id of an item. Unique within the collection.
- *
- * * recipient: Owner of newly created item
- *
- * * amount: Always 1 for NFT
**/
ItemCreated: AugmentedEvent<ApiType, [u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
/**
* Collection item was burned.
- *
- * # Arguments
- *
- * * collection_id.
- *
- * * item_id: Identifier of burned NFT.
- *
- * * owner: which user has destroyed its tokens
- *
- * * amount: Always 1 for NFT
**/
ItemDestroyed: AugmentedEvent<ApiType, [u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
+ /**
+ * The colletion property permission has been set.
+ **/
PropertyPermissionSet: AugmentedEvent<ApiType, [u32, Bytes]>;
+ /**
+ * The token property has been deleted.
+ **/
TokenPropertyDeleted: AugmentedEvent<ApiType, [u32, u32, Bytes]>;
+ /**
+ * The token property has been set.
+ **/
TokenPropertySet: AugmentedEvent<ApiType, [u32, u32, Bytes]>;
/**
* Item was transferred
- *
- * * collection_id: Id of collection to which item is belong
- *
- * * item_id: Id of an item
- *
- * * sender: Original owner of item
- *
- * * recipient: New owner of item
- *
- * * amount: Always 1 for NFT
**/
Transfer: AugmentedEvent<ApiType, [u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
/**
tests/src/interfaces/augment-api-query.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -69,24 +69,36 @@
[key: string]: QueryableStorageEntry<ApiType>;
};
common: {
+ /**
+ * Storage of collection admins count.
+ **/
adminAmount: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<u32>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
/**
* Allowlisted collection users
**/
allowlist: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array) => Observable<bool>, [u32, PalletEvmAccountBasicCrossAccountIdRepr]> & QueryableStorageEntry<ApiType, [u32, PalletEvmAccountBasicCrossAccountIdRepr]>;
/**
- * Collection info
+ * Storage of collection info.
**/
collectionById: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Option<UpDataStructsCollection>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
/**
- * Collection properties
+ * Storage of collection properties.
**/
collectionProperties: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<UpDataStructsProperties>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
+ /**
+ * Storage of collection properties permissions.
+ **/
collectionPropertyPermissions: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<BTreeMap<Bytes, UpDataStructsPropertyPermission>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
+ /**
+ * Storage of the count of created collections.
+ **/
createdCollectionCount: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
+ /**
+ * Storage of the count of deleted collections.
+ **/
destroyedCollectionCount: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
/**
- * Not used by code, exists only to provide some types to metadata
+ * Not used by code, exists only to provide some types to metadata.
**/
dummyStorageValue: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[UpDataStructsCollectionStats, u32, u32, UpDataStructsTokenChild, PhantomTypeUpDataStructs]>>>, []> & QueryableStorageEntry<ApiType, []>;
/**
@@ -231,20 +243,42 @@
[key: string]: QueryableStorageEntry<ApiType>;
};
nonfungible: {
+ /**
+ * Amount of tokens owned by account.
+ **/
accountBalance: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array) => Observable<u32>, [u32, PalletEvmAccountBasicCrossAccountIdRepr]> & QueryableStorageEntry<ApiType, [u32, PalletEvmAccountBasicCrossAccountIdRepr]>;
+ /**
+ * Allowance set by an owner for a spender for a token.
+ **/
allowance: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<Option<PalletEvmAccountBasicCrossAccountIdRepr>>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>;
/**
- * Used to enumerate tokens owned by account
+ * Used to enumerate tokens owned by account.
**/
owned: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, arg3: u32 | AnyNumber | Uint8Array) => Observable<bool>, [u32, PalletEvmAccountBasicCrossAccountIdRepr, u32]> & QueryableStorageEntry<ApiType, [u32, PalletEvmAccountBasicCrossAccountIdRepr, u32]>;
+ /**
+ * Custom data that is serialized to bytes and attached to a token property.
+ * Currently used to store RMRK data.
+ **/
tokenAuxProperties: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array, arg3: UpDataStructsPropertyScope | 'None' | 'Rmrk' | number | Uint8Array, arg4: Bytes | string | Uint8Array) => Observable<Option<Bytes>>, [u32, u32, UpDataStructsPropertyScope, Bytes]> & QueryableStorageEntry<ApiType, [u32, u32, UpDataStructsPropertyScope, Bytes]>;
/**
- * Used to enumerate token's children
+ * Used to enumerate token's children.
**/
tokenChildren: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array, arg3: ITuple<[u32, u32]> | [u32 | AnyNumber | Uint8Array, u32 | AnyNumber | Uint8Array]) => Observable<bool>, [u32, u32, ITuple<[u32, u32]>]> & QueryableStorageEntry<ApiType, [u32, u32, ITuple<[u32, u32]>]>;
+ /**
+ * Custom data serialized to bytes for token.
+ **/
tokenData: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<Option<PalletNonfungibleItemData>>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>;
+ /**
+ * Key-Value map stored for token.
+ **/
tokenProperties: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<UpDataStructsProperties>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>;
+ /**
+ * Amount of burnt tokens for collection.
+ **/
tokensBurnt: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<u32>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
+ /**
+ * Amount of tokens minted for collection.
+ **/
tokensMinted: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<u32>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
/**
* Generic query
@@ -430,6 +464,9 @@
**/
tokenData: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<PalletRefungibleItemData>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>;
tokenProperties: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<UpDataStructsProperties>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>;
+ /**
+ * Amount of burnt tokens for collection
+ **/
tokensBurnt: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<u32>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
/**
* Amount of tokens minted for collection
tests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-rpc.ts
+++ b/tests/src/interfaces/augment-api-rpc.ts
@@ -709,6 +709,10 @@
**/
tokenOwner: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, tokenId: u32 | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<PalletEvmAccountBasicCrossAccountIdRepr>>>;
/**
+ * Returns 10 tokens owners in no particular order
+ **/
+ tokenOwners: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, tokenId: u32 | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<PalletEvmAccountBasicCrossAccountIdRepr>>>;
+ /**
* Get token properties
**/
tokenProperties: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, tokenId: u32 | AnyNumber | Uint8Array, propertyKeys?: Vec<Text> | (Text | string)[], at?: Hash | string | Uint8Array) => Observable<Vec<UpDataStructsProperty>>>;
tests/src/interfaces/unique/definitions.tsdiffbeforeafterboth--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -49,6 +49,7 @@
balance: fun('Get amount of specific account token', [collectionParam, crossAccountParam(), tokenParam], 'u128'),
allowance: fun('Get allowed amount', [collectionParam, crossAccountParam('sender'), crossAccountParam('spender'), tokenParam], 'u128'),
tokenOwner: fun('Get token owner', [collectionParam, tokenParam], `Option<${CROSS_ACCOUNT_ID_TYPE}>`),
+ tokenOwners: fun('Returns 10 tokens owners in no particular order', [collectionParam, tokenParam], `Vec<${CROSS_ACCOUNT_ID_TYPE}>`),
topmostTokenOwner: fun('Get token owner, in case of nested token - find parent recursive', [collectionParam, tokenParam], `Option<${CROSS_ACCOUNT_ID_TYPE}>`),
tokenChildren: fun('Get tokens nested directly into the token', [collectionParam, tokenParam], 'Vec<UpDataStructsTokenChild>'),
constMetadata: fun('Get token constant metadata', [collectionParam, tokenParam], 'Vec<u8>'),
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -32,6 +32,8 @@
repartitionRFT,
createCollectionWithPropsExpectSuccess,
getDetailedCollectionInfo,
+ normalizeAccountId,
+ CrossAccountId,
getCreateItemsResult,
getDestroyItemsResult,
} from './util/helpers';
@@ -55,14 +57,14 @@
it('Create refungible collection and token', async () => {
await usingApi(async api => {
const createCollectionResult = await createCollection(api, alice, {mode: {type: 'ReFungible'}});
- expect(createCollectionResult.success).to.be.true;
+ expect(createCollectionResult.success).to.be.true;
const collectionId = createCollectionResult.collectionId;
-
+
const itemCountBefore = await getLastTokenId(api, collectionId);
const result = await createRefungibleToken(api, alice, collectionId, 100n);
-
+
const itemCountAfter = await getLastTokenId(api, collectionId);
-
+
// What to expect
// tslint:disable-next-line:no-unused-expression
expect(result.success).to.be.true;
@@ -71,7 +73,43 @@
expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());
});
});
-
+
+ it('RPC method tokenOnewrs for refungible collection and token', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
+ const facelessCrowd = Array.from(Array(7).keys()).map(i => normalizeAccountId(privateKeyWrapper(i.toString())));
+
+ const createCollectionResult = await createCollection(api, alice, {mode: {type: 'ReFungible'}});
+ const collectionId = createCollectionResult.collectionId;
+
+ const result = await createRefungibleToken(api, alice, collectionId, 10_000n);
+ const aliceTokenId = result.itemId;
+
+
+ await transfer(api, collectionId, aliceTokenId, alice, bob, 1000n);
+ await transfer(api, collectionId, aliceTokenId, alice, ethAcc, 900n);
+
+ for (let i = 0; i < 7; i++) {
+ await transfer(api, collectionId, aliceTokenId, alice, facelessCrowd[i], 50*(i+1));
+ }
+
+ const owners = await api.rpc.unique.tokenOwners(collectionId, aliceTokenId);
+ const ids = (owners.toJSON() as CrossAccountId[]).map(s => normalizeAccountId(s));
+
+ const aliceID = normalizeAccountId(alice);
+ const bobId = normalizeAccountId(bob);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(ids).to.deep.include.members([aliceID, ethAcc, bobId, ...facelessCrowd]);
+ expect(owners.length).to.be.equal(10);
+
+ const eleven = privateKeyWrapper('11');
+ expect(await transfer(api, collectionId, aliceTokenId, alice, eleven, 10n)).to.be.true;
+ expect((await api.rpc.unique.tokenOwners(collectionId, aliceTokenId)).length).to.be.equal(10);
+ });
+ });
+
it('Transfer token pieces', async () => {
await usingApi(async api => {
const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;
tests/src/rpc.test.tsdiffbeforeafterboth--- a/tests/src/rpc.test.ts
+++ b/tests/src/rpc.test.ts
@@ -1,12 +1,57 @@
+import {IKeyringPair} from '@polkadot/types/types';
import {expect} from 'chai';
import usingApi from './substrate/substrate-api';
-import {createCollectionExpectSuccess, getTokenOwner} from './util/helpers';
+import {createCollection, createCollectionExpectSuccess, createFungibleItemExpectSuccess, CrossAccountId, getTokenOwner, normalizeAccountId, transfer, U128_MAX} from './util/helpers';
+
+let alice: IKeyringPair;
+let bob: IKeyringPair;
-describe('getTokenOwner', () => {
+
+describe('integration test: RPC methods', () => {
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ alice = privateKeyWrapper('//Alice');
+ bob = privateKeyWrapper('//Bob');
+ });
+ });
+
+
it('returns None for fungible collection', async () => {
await usingApi(async api => {
const collection = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
await expect(getTokenOwner(api, collection, 0)).to.be.rejectedWith(/^owner == null$/);
});
});
+
+ it('RPC method tokenOwners for fungible collection and token', async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
+ const facelessCrowd = Array.from(Array(7).keys()).map(i => normalizeAccountId(privateKeyWrapper(i.toString())));
+
+ const createCollectionResult = await createCollection(api, alice, {mode: {type: 'Fungible', decimalPoints: 0}});
+ const collectionId = createCollectionResult.collectionId;
+ const aliceTokenId = await createFungibleItemExpectSuccess(alice, collectionId, {Value: U128_MAX}, alice.address);
+
+ await transfer(api, collectionId, aliceTokenId, alice, bob, 1000n);
+ await transfer(api, collectionId, aliceTokenId, alice, ethAcc, 900n);
+
+ for (let i = 0; i < 7; i++) {
+ await transfer(api, collectionId, aliceTokenId, alice, facelessCrowd[i], 1);
+ }
+
+ const owners = await api.rpc.unique.tokenOwners(collectionId, aliceTokenId);
+ const ids = (owners.toJSON() as CrossAccountId[]).map(s => normalizeAccountId(s));
+ const aliceID = normalizeAccountId(alice);
+ const bobId = normalizeAccountId(bob);
+
+ // What to expect
+ // tslint:disable-next-line:no-unused-expression
+ expect(ids).to.deep.include.members([aliceID, ethAcc, bobId, ...facelessCrowd]);
+ expect(owners.length == 10).to.be.true;
+
+ const eleven = privateKeyWrapper('11');
+ expect(await transfer(api, collectionId, aliceTokenId, alice, eleven, 10n)).to.be.true;
+ expect((await api.rpc.unique.tokenOwners(collectionId, aliceTokenId)).length).to.be.equal(10);
+ });
+ });
});
\ No newline at end of file