git.delta.rocks / unique-network / refs/commits / 1ac708f72a4b

difftreelog

Merge pull request #411 from UniqueNetwork/feature/total_pieces

bugrazoid2022-07-06parents: #e82bbde #a5763d4.patch.diff
in: master
Add rpc method for total_pieces

11 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -184,12 +184,21 @@
 		token: TokenId,
 		at: Option<BlockHash>,
 	) -> Result<Option<u64>>;
+
 	#[method(name = "unique_effectiveCollectionLimits")]
 	fn effective_collection_limits(
 		&self,
 		collection_id: CollectionId,
 		at: Option<BlockHash>,
 	) -> Result<Option<CollectionLimits>>;
+
+	#[method(name = "unique_totalPieces")]
+	fn total_pieces(
+		&self,
+		collection_id: CollectionId,
+		token_id: TokenId,
+		at: Option<BlockHash>,
+	) -> Result<Option<u128>>;
 }
 
 mod rmrk_unique_rpc {
@@ -463,6 +472,7 @@
 	pass_method!(collection_stats() -> CollectionStats, unique_api);
 	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);
 }
 
 #[allow(deprecated)]
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1384,6 +1384,8 @@
 	fn account_balance(&self, account: T::CrossAccountId) -> u32;
 	/// Amount of specific token account have (Applicable to fungible/refungible)
 	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;
+	/// Amount of token pieces
+	fn total_pieces(&self, token: TokenId) -> Option<u128>;
 	fn allowance(
 		&self,
 		sender: T::CrossAccountId,
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -25,7 +25,8 @@
 use up_data_structs::{Property, PropertyKey, PropertyValue, PropertyKeyPermission};
 
 use crate::{
-	Allowance, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf, weights::WeightInfo,
+	Allowance, TotalSupply, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf,
+	weights::WeightInfo,
 };
 
 pub struct CommonWeights<T: Config>(PhantomData<T>);
@@ -405,4 +406,11 @@
 	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {
 		None
 	}
+
+	fn total_pieces(&self, token: TokenId) -> Option<u128> {
+		if token != TokenId::default() {
+			return None;
+		}
+		<TotalSupply<T>>::try_get(self.id).ok()
+	}
 }
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -487,4 +487,12 @@
 	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {
 		None
 	}
+
+	fn total_pieces(&self, token: TokenId) -> Option<u128> {
+		if <TokenData<T>>::contains_key((self.id, token)) {
+			Some(1)
+		} else {
+			None
+		}
+	}
 }
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -411,6 +411,10 @@
 	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {
 		Some(self)
 	}
+
+	fn total_pieces(&self, token: TokenId) -> Option<u128> {
+		<Pallet<T>>::total_pieces(self.id, token)
+	}
 }
 
 impl<T: Config> RefungibleExtensions<T> for RefungibleHandle<T> {
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -710,4 +710,8 @@
 		<TotalSupply<T>>::insert((collection.id, token), amount);
 		Ok(())
 	}
+
+	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {
+		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()
+	}
 }
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -181,6 +181,7 @@
 pub struct TokenData<CrossAccountId> {
 	pub properties: Vec<Property>,
 	pub owner: Option<CrossAccountId>,
+	pub pieces: u128,
 }
 
 pub struct OverflowError;
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -80,5 +80,6 @@
 		fn collection_stats() -> Result<CollectionStats>;
 		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>>;
 	}
 }
modifiedruntime/common/src/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -89,7 +89,8 @@
                 ) -> Result<TokenData<CrossAccountId>, DispatchError> {
                     let token_data = TokenData {
                         properties: Self::token_properties(collection, token_id, keys)?,
-                        owner: Self::token_owner(collection, token_id)?
+                        owner: Self::token_owner(collection, token_id)?,
+                        pieces: Self::total_pieces(collection, token_id)?.unwrap_or(0),
                     };
 
                     Ok(token_data)
@@ -142,6 +143,10 @@
                 fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {
                     Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))
                 }
+
+                fn total_pieces(collection: CollectionId, token_id: TokenId) -> Result<Option<u128>, DispatchError> {
+                    dispatch_unique_runtime!(collection.total_pieces(token_id))
+                }
             }
 
             impl sp_api::Core<Block> for Runtime {
modifiedtests/src/createItem.test.tsdiffbeforeafterboth
--- a/tests/src/createItem.test.ts
+++ b/tests/src/createItem.test.ts
@@ -24,6 +24,8 @@
   createCollectionWithPropsExpectSuccess,
   createItemWithPropsExpectSuccess,
   createItemWithPropsExpectFailure,
+  createCollection,
+  transferExpectSuccess,
 } from './util/helpers';
 
 const expect = chai.expect;
@@ -95,6 +97,82 @@
     
     await createItemWithPropsExpectSuccess(alice, newCollectionID, createMode, [{key: 'key1', value: 'val1'}]);
   });
+
+  it('Check total pieces of Fungible token', async () => {
+    await usingApi(async api => {
+      const createMode = 'Fungible';
+      const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0}});
+      const amountPieces = 10n;
+      const tokenId = await createItemExpectSuccess(alice, collectionId, createMode, bob.address);
+      {
+        const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
+        expect(totalPieces.isSome).to.be.true;
+        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
+      }
+
+      await transferExpectSuccess(collectionId, tokenId, bob, alice, 1, createMode);
+      {
+        const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
+        expect(totalPieces.isSome).to.be.true;
+        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
+      }
+
+      const totalPieces = (await api.rpc.unique.tokenData(collectionId, tokenId, [])).pieces;
+      expect(totalPieces.isSome).to.be.true;
+      expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
+    });
+  });
+
+  it('Check total pieces of NFT token', async () => {
+    await usingApi(async api => {
+      const createMode = 'NFT';
+      const collectionId = await createCollectionExpectSuccess({mode: {type: createMode}});
+      const amountPieces = 1n;
+      const tokenId = await createItemExpectSuccess(alice, collectionId, createMode, bob.address);
+      {
+        const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
+        expect(totalPieces.isSome).to.be.true;
+        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
+      }
+
+      await transferExpectSuccess(collectionId, tokenId, bob, alice, 1, createMode);
+      {
+        const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
+        expect(totalPieces.isSome).to.be.true;
+        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
+      }
+
+      const totalPieces = (await api.rpc.unique.tokenData(collectionId, tokenId, [])).pieces;
+      expect(totalPieces.isSome).to.be.true;
+      expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
+    });
+  });
+
+  it('Check total pieces of ReFungible token', async () => {
+    await usingApi(async api => {
+      const createMode = 'ReFungible';
+      const createCollectionResult = await createCollection(api, alice, {mode: {type: createMode}});
+      const collectionId  = createCollectionResult.collectionId;
+      const amountPieces = 100n;
+      const tokenId = await createItemExpectSuccess(alice, collectionId, createMode, bob.address);
+      {
+        const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
+        expect(totalPieces.isSome).to.be.true;
+        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
+      }
+
+      await transferExpectSuccess(collectionId, tokenId, bob, alice, 60n, createMode);
+      {
+        const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
+        expect(totalPieces.isSome).to.be.true;
+        expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
+      }
+
+      const totalPieces = (await api.rpc.unique.tokenData(collectionId, tokenId, [])).pieces;
+      expect(totalPieces.isSome).to.be.true;
+      expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
+    });
+  });
 });
 
 describe('Negative integration test: ext. createItem():', () => {
@@ -169,4 +247,37 @@
       await createItemWithPropsExpectFailure(alice, newCollectionID, 'NFT', [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}]);
     });
   });
+
+  it('Check total pieces for invalid Fungible token', async () => {
+    await usingApi(async api => {
+      const createCollectionResult = await createCollection(api, alice, {mode: {type: 'Fungible', decimalPoints: 0}});
+      const collectionId  = createCollectionResult.collectionId;
+      const invalidTokenId = 1000_000;
+      
+      expect((await api.rpc.unique.totalPieces(collectionId, invalidTokenId)).isNone).to.be.true;
+      expect((await api.rpc.unique.tokenData(collectionId, invalidTokenId, [])).pieces.isNone).to.be.true;
+    });
+  });
+
+  it('Check total pieces for invalid NFT token', async () => {
+    await usingApi(async api => {
+      const createCollectionResult = await createCollection(api, alice, {mode: {type: 'NFT'}});
+      const collectionId  = createCollectionResult.collectionId;
+      const invalidTokenId = 1000_000;
+      
+      expect((await api.rpc.unique.totalPieces(collectionId, invalidTokenId)).isNone).to.be.true;
+      expect((await api.rpc.unique.tokenData(collectionId, invalidTokenId, [])).pieces.isNone).to.be.true;
+    });
+  });
+
+  it('Check total pieces for invalid Refungible token', async () => {
+    await usingApi(async api => {
+      const createCollectionResult = await createCollection(api, alice, {mode: {type: 'ReFungible'}});
+      const collectionId  = createCollectionResult.collectionId;
+      const invalidTokenId = 1000_000;
+      
+      expect((await api.rpc.unique.totalPieces(collectionId, invalidTokenId)).isNone).to.be.true;
+      expect((await api.rpc.unique.tokenData(collectionId, invalidTokenId, [])).pieces.isNone).to.be.true;
+    });
+  });
 });
modifiedtests/src/interfaces/unique/definitions.tsdiffbeforeafterboth
before · tests/src/interfaces/unique/definitions.ts
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/>.1617type RpcParam = {18  name: string;19  type: string;20  isOptional?: true;21};2223const CROSS_ACCOUNT_ID_TYPE = 'PalletEvmAccountBasicCrossAccountIdRepr';2425const collectionParam = {name: 'collection', type: 'u32'};26const tokenParam = {name: 'tokenId', type: 'u32'};27const propertyKeysParam = {name: 'propertyKeys', type: 'Vec<String>', isOptional: true};28const crossAccountParam = (name = 'account') => ({name, type: CROSS_ACCOUNT_ID_TYPE});29const atParam = {name: 'at', type: 'Hash', isOptional: true};3031const fun = (description: string, params: RpcParam[], type: string) => ({32  description,33  params: [...params, atParam],34  type,35});3637export default {38  types: {},39  rpc: {40    adminlist: fun('Get admin list', [collectionParam], 'Vec<PalletEvmAccountBasicCrossAccountIdRepr>'),41    allowlist: fun('Get allowlist', [collectionParam], 'Vec<PalletEvmAccountBasicCrossAccountIdRepr>'),4243    accountTokens: fun('Get tokens owned by account', [collectionParam, crossAccountParam()], 'Vec<u32>'),44    collectionTokens: fun('Get tokens contained in collection', [collectionParam], 'Vec<u32>'),4546    lastTokenId: fun('Get last token id', [collectionParam], 'u32'),47    totalSupply: fun('Get amount of unique collection tokens', [collectionParam], 'u32'),48    accountBalance: fun('Get amount of different user tokens', [collectionParam, crossAccountParam()], 'u32'),49    balance: fun('Get amount of specific account token', [collectionParam, crossAccountParam(), tokenParam], 'u128'),50    allowance: fun('Get allowed amount', [collectionParam, crossAccountParam('sender'), crossAccountParam('spender'), tokenParam], 'u128'),51    tokenOwner: fun('Get token owner', [collectionParam, tokenParam], `Option<${CROSS_ACCOUNT_ID_TYPE}>`),52    topmostTokenOwner: fun('Get token owner, in case of nested token - find parent recursive', [collectionParam, tokenParam], `Option<${CROSS_ACCOUNT_ID_TYPE}>`),53    tokenChildren: fun('Get tokens nested directly into the token', [collectionParam, tokenParam], 'Vec<UpDataStructsTokenChild>'),54    constMetadata: fun('Get token constant metadata', [collectionParam, tokenParam], 'Vec<u8>'),55    variableMetadata: fun('Get token variable metadata', [collectionParam, tokenParam], 'Vec<u8>'),56    collectionProperties: fun(57      'Get collection properties',58      [collectionParam, propertyKeysParam],59      'Vec<UpDataStructsProperty>',60    ),61    tokenProperties: fun(62      'Get token properties',63      [collectionParam, tokenParam, propertyKeysParam],64      'Vec<UpDataStructsProperty>',65    ),66    propertyPermissions: fun(67      'Get property permissions',68      [collectionParam, propertyKeysParam],69      'Vec<UpDataStructsPropertyKeyPermission>',70    ),71    tokenData: fun(72      'Get token data',73      [collectionParam, tokenParam, propertyKeysParam],74      'UpDataStructsTokenData',75    ),76    tokenExists: fun('Check if token exists', [collectionParam, tokenParam], 'bool'),77    collectionById: fun('Get collection by specified id', [collectionParam], 'Option<UpDataStructsRpcCollection>'),78    collectionStats: fun('Get collection stats', [], 'UpDataStructsCollectionStats'),79    allowed: fun('Check if user is allowed to use collection', [collectionParam, crossAccountParam()], 'bool'),80    nextSponsored: fun('Get number of blocks when sponsored transaction is available', [collectionParam, crossAccountParam(), tokenParam], 'Option<u64>'),81    effectiveCollectionLimits: fun('Get effective collection limits', [collectionParam], 'Option<UpDataStructsCollectionLimits>'),82  },83};