difftreelog
feat(rpc) token children
in: master
9 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -21,7 +21,7 @@
use jsonrpc_derive::rpc;
use up_data_structs::{
RpcCollection, CollectionId, CollectionStats, CollectionLimits, TokenId, Property,
- PropertyKeyPermission, TokenData,
+ PropertyKeyPermission, TokenData, TokenChild,
};
use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};
use sp_blockchain::HeaderBackend;
@@ -72,6 +72,13 @@
token: TokenId,
at: Option<BlockHash>,
) -> Result<Option<CrossAccountId>>;
+ #[rpc(name = "unique_tokenChildren")]
+ fn token_children(
+ &self,
+ collection: CollectionId,
+ token: TokenId,
+ at: Option<BlockHash>,
+ ) -> Result<Vec<TokenChild>>;
#[rpc(name = "unique_collectionProperties")]
fn collection_properties(
@@ -411,6 +418,7 @@
pass_method!(
topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api
);
+ pass_method!(token_children(collection: CollectionId, token: TokenId) -> Vec<TokenChild>, unique_api);
pass_method!(total_supply(collection: CollectionId) -> u32, unique_api);
pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32, unique_api);
pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string(), unique_api);
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -40,6 +40,7 @@
MAX_TOKEN_PREFIX_LENGTH,
COLLECTION_ADMINS_LIMIT,
TokenId,
+ TokenChild,
CollectionStats,
MAX_TOKEN_OWNERSHIP,
CollectionMode,
@@ -502,6 +503,7 @@
CollectionStats,
CollectionId,
TokenId,
+ TokenChild,
PhantomType<(
TokenData<T::CrossAccountId>,
RpcCollection<T::AccountId>,
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -22,7 +22,7 @@
use up_data_structs::{
AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,
- PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,
+ PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty, TokenChild,
};
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_common::{
@@ -988,6 +988,15 @@
.is_some()
}
+ pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {
+ <TokenChildren<T>>::iter_prefix((collection_id, token_id))
+ .map(|((child_collection_id, child_id), _)| TokenChild {
+ collection: child_collection_id,
+ token: child_id,
+ })
+ .collect()
+ }
+
/// Delegated to `create_multiple_items`
pub fn create_item(
collection: &NonfungibleHandle<T>,
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -585,6 +585,14 @@
#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+// todo possibly rename to be used generally as an address pair
+pub struct TokenChild {
+ pub token: TokenId,
+ pub collection: CollectionId,
+}
+
+#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct CollectionStats {
pub created: u32,
pub destroyed: u32,
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -18,7 +18,7 @@
use up_data_structs::{
CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits, Property,
- PropertyKeyPermission, TokenData,
+ PropertyKeyPermission, TokenData, TokenChild,
};
use sp_std::vec::Vec;
use codec::Decode;
@@ -41,6 +41,7 @@
fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
+ fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>>;
fn collection_properties(collection: CollectionId, properties: Option<Vec<Vec<u8>>>) -> Result<Vec<Property>>;
runtime/common/src/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -29,7 +29,9 @@
Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))
}
-
+ fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {
+ Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))
+ }
fn collection_properties(
collection: CollectionId,
keys: Option<Vec<Vec<u8>>>
tests/src/interfaces/unique/definitions.tsdiffbeforeafterboth--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -50,6 +50,7 @@
allowance: fun('Get allowed amount', [collectionParam, crossAccountParam('sender'), crossAccountParam('spender'), tokenParam], 'u128'),
tokenOwner: fun('Get token owner', [collectionParam, tokenParam], `Option<${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>'),
variableMetadata: fun('Get token variable metadata', [collectionParam, tokenParam], 'Vec<u8>'),
collectionProperties: fun(
tests/src/nesting/nest.test.tsdiffbeforeafterboth8 createItemExpectSuccess,8 createItemExpectSuccess,9 enableAllowListExpectSuccess,9 enableAllowListExpectSuccess,10 enablePublicMintingExpectSuccess,10 enablePublicMintingExpectSuccess,11 getTokenChildren,11 getTokenOwner,12 getTokenOwner,12 getTopmostTokenOwner,13 getTopmostTokenOwner,13 normalizeAccountId,14 normalizeAccountId,89 });90 });90 });91 });9293 it('Checks token children', async () => {94 await usingApi(async api => {95 const collectionA = await createCollectionExpectSuccess({mode: {type: 'NFT'}});96 await setCollectionPermissionsExpectSuccess(alice, collectionA, {nesting: 'Owner'});97 const collectionB = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});9899 const targetToken = await createItemExpectSuccess(alice, collectionA, 'NFT');100 const targetAddress = {Ethereum: tokenIdToAddress(collectionA, targetToken)};101 let children = await getTokenChildren(api, collectionA, targetToken);102 expect(children.length).to.be.equal(0, 'Children length check at creation');103104 // Create a nested NFT token105 const tokenA = await createItemExpectSuccess(alice, collectionA, 'NFT', targetAddress);106 children = await getTokenChildren(api, collectionA, targetToken);107 expect(children.length).to.be.equal(1, 'Children length check at nesting #1');108 expect(children).to.have.deep.members([109 {token: tokenA, collection: collectionA},110 ], 'Children contents check at nesting #1');111112 // Create then nest113 const tokenB = await createItemExpectSuccess(alice, collectionA, 'NFT');114 await transferExpectSuccess(collectionA, tokenB, alice, targetAddress);115 children = await getTokenChildren(api, collectionA, targetToken);116 expect(children.length).to.be.equal(2, 'Children length check at nesting #2');117 expect(children).to.have.deep.members([118 {token: tokenA, collection: collectionA},119 {token: tokenB, collection: collectionA},120 ], 'Children contents check at nesting #2');121122 // Move token B to a different user outside the nesting tree123 await transferFromExpectSuccess(collectionA, tokenB, alice, targetAddress, bob);124 children = await getTokenChildren(api, collectionA, targetToken);125 expect(children.length).to.be.equal(1, 'Children length check at unnesting');126 expect(children).to.be.have.deep.members([127 {token: tokenA, collection: collectionA},128 ], 'Children contents check at unnesting');129 130 // Create a fungible token in another collection and then nest131 const tokenC = await createItemExpectSuccess(alice, collectionB, 'Fungible');132 await transferExpectSuccess(collectionB, tokenC, alice, targetAddress, 1, 'Fungible');133 children = await getTokenChildren(api, collectionA, targetToken);134 expect(children.length).to.be.equal(2, 'Children length check at nesting #3 (from another collection)');135 expect(children).to.be.have.deep.members([136 {token: tokenA, collection: collectionA},137 {token: tokenC, collection: collectionB},138 ], 'Children contents check at nesting #3 (from another collection)');139140 // Move the fungible token inside token A deeper in the nesting tree141 await transferFromExpectSuccess(collectionB, tokenC, alice, targetAddress, {Ethereum: tokenIdToAddress(collectionA, tokenA)}, 1, 'Fungible');142 children = await getTokenChildren(api, collectionA, targetToken);143 expect(children.length).to.be.equal(1, 'Children length check at deeper nesting');144 expect(children).to.be.have.deep.members([145 {token: tokenA, collection: collectionA},146 ], 'Children contents check at deeper nesting');147 });148 });9114992 // ---------- Non-Fungible ----------150 // ---------- Non-Fungible ----------93151232 });290 });233 });291 });292293 // TODO delete if this is actually wrong294 // TODO remake all other nesting tests if this is right295 it('Affirms that transfer is disallowed to transfer nested tokens', async () => {296 await usingApi(async () => {297 const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});298 await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: 'Owner'});299300 const tokenA = await createItemExpectSuccess(alice, collection, 'NFT');301 const tokenB = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, tokenA)});302 303 await transferExpectFailure(collection, tokenB, alice, bob);304 });305 });234306235 it('Disallows excessive token nesting', async () => {307 it('Disallows excessive token nesting', async () => {236 await usingApi(async api => {308 await usingApi(async api => {tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -28,6 +28,7 @@
import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
import {hexToStr, strToUTF16, utf16ToStr} from './util';
import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';
+import {UpDataStructsTokenChild} from '../interfaces';
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -1072,6 +1073,13 @@
if (owner == null) throw new Error('owner == null');
return normalizeAccountId(owner);
}
+export async function getTokenChildren(
+ api: ApiPromise,
+ collectionId: number,
+ tokenId: number,
+): Promise<UpDataStructsTokenChild[]> {
+ return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;
+}
export async function isTokenExists(
api: ApiPromise,
collectionId: number,