difftreelog
Merge pull request #232 from UniqueNetwork/refactor/pallet-common-rpcs
in: master
Prefer api.rpc.nft to api.query.common
38 files changed
.devcontainer/devcontainer.jsondiffbeforeafterboth1{1{2 "name": "Rust",2 "name": "Rust",3 "dockerComposeFile": "./docker-compose.yml",3 "dockerComposeFile": "./docker-compose.yml",4 "service": "nft_private",4 "service": "unique-chain",5 "workspaceFolder": "/workspaces/nft_private",5 "workspaceFolder": "/workspaces/unique-chain",6 "settings": { 6 "settings": { 7 "terminal.integrated.shell.linux": "/bin/bash",7 "terminal.integrated.shell.linux": "/bin/bash",8 "lldb.executable": "/usr/bin/lldb",8 "lldb.executable": "/usr/bin/lldb",.devcontainer/docker-compose.ymldiffbeforeafterboth1version: '3'1version: '3'2services:2services:3 nft_private:3 unique-chain:4 build: 4 build: 5 context: .5 context: .6 environment:6 environment:7 - JAEGER_AGENT_HOST=jaeger7 - JAEGER_AGENT_HOST=jaeger8 - JAEGER_AGENT_PORT=68318 - JAEGER_AGENT_PORT=68319 volumes:9 volumes:10 - ..:/workspaces/nft_private:cached10 - ..:/workspaces/unique-chain:cached11 - ../../polkadot:/workspaces/polkadot:cached11 - ../../polkadot:/workspaces/polkadot:cached12 - ../../polkadot-launch:/workspaces/polkadot-launch:cached12 - ../../polkadot-launch:/workspaces/polkadot-launch:cached13 #- ../../frontier:/workspaces/frontier13 #- ../../frontier:/workspaces/frontier.github/workflows/node_build_test.ymldiffbeforeafterboth32 key: ${{ secrets.KEY }}32 key: ${{ secrets.KEY }}33 port: ${{ secrets.SERVER_PORT }}33 port: ${{ secrets.SERVER_PORT }}34 command_timeout: 300m34 command_timeout: 300m35 script: |35 script: |36 eval $(ssh-agent -s)36 eval $(ssh-agent -s)37 ssh-add /home/devops/.ssh/git_hub37 ssh-add /home/devops/.ssh/git_hub38 git clone git@github.com:UniqueNetwork/nft_private.git38 git clone git@github.com:UniqueNetwork/unique-chain.git39 cd nft_private39 cd unique-chain40 git checkout develop40 git checkout develop41 # git pull --all41 # git pull --all42 chmod +x ci_node.sh42 chmod +x ci_node.sh43 ./ci_node.sh43 ./ci_node.sh44 rm -rf /home/polkadot/nft_private44 rm -rf /home/polkadot/unique-chain4545Dockerfile-parachaindiffbeforeafterboth98 npm install --global yarn && \98 npm install --global yarn && \99 yarn99 yarn100100101COPY --from=builder /nft_parachain/target/$PROFILE/nft /nft_private/target/$PROFILE/101COPY --from=builder /nft_parachain/target/$PROFILE/nft /unique-chain/target/$PROFILE/102COPY --from=builder-polkadot /nft_parachain/polkadot/target/$PROFILE/polkadot /polkadot/target/$PROFILE/102COPY --from=builder-polkadot /nft_parachain/polkadot/target/$PROFILE/polkadot /polkadot/target/$PROFILE/103103104CMD export NVM_DIR="$HOME/.nvm" && \104CMD export NVM_DIR="$HOME/.nvm" && \client/rpc/src/lib.rsdiffbeforeafterboth3use codec::Decode;3use codec::Decode;4use jsonrpc_core::{Error as RpcError, ErrorCode, Result};4use jsonrpc_core::{Error as RpcError, ErrorCode, Result};5use jsonrpc_derive::rpc;5use jsonrpc_derive::rpc;6use nft_data_structs::{CollectionId, TokenId};6use nft_data_structs::{Collection, CollectionId, CollectionStats, TokenId};7use sp_api::{BlockId, BlockT, ProvideRuntimeApi};7use sp_api::{BlockId, BlockT, ProvideRuntimeApi};8use sp_blockchain::HeaderBackend;8use sp_blockchain::HeaderBackend;9use up_rpc::NftApi as NftRuntimeApi;9use up_rpc::NftApi as NftRuntimeApi;86 collection: CollectionId,86 collection: CollectionId,87 at: Option<BlockHash>,87 at: Option<BlockHash>,88 ) -> Result<Vec<CrossAccountId>>;88 ) -> Result<Vec<CrossAccountId>>;89 #[rpc(name = "nft_allowed")]90 fn allowed(91 &self,92 collection: CollectionId,93 user: CrossAccountId,94 at: Option<BlockHash>,95 ) -> Result<bool>;89 #[rpc(name = "nft_lastTokenId")]96 #[rpc(name = "nft_lastTokenId")]90 fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;97 fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;98 #[rpc(name = "nft_collectionById")]99 fn collection_by_id(100 &self,101 collection: CollectionId,102 at: Option<BlockHash>,103 ) -> Result<Option<Collection<AccountId>>>;104 #[rpc(name = "nft_collectionStats")]105 fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;91}106}9210793pub struct Nft<C, P> {108pub struct Nft<C, P> {160175161 pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>);176 pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>);162 pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>);177 pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>);178 pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool);163 pass_method!(last_token_id(collection: CollectionId) -> TokenId);179 pass_method!(last_token_id(collection: CollectionId) -> TokenId);180 pass_method!(collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>>);181 pass_method!(collection_stats() -> CollectionStats);164}182}165183launch-config.jsondiffbeforeafterboth55 },55 },56 "parachains": [56 "parachains": [57 {57 {58 "bin": "../nft_private/target/release/nft",58 "bin": "../unique-chain/target/release/nft",59 "id": "2000",59 "id": "2000",60 "balance": "1000000000000000000000",60 "balance": "1000000000000000000000",61 "nodes": [61 "nodes": [pallets/common/src/benchmarking.rsdiffbeforeafterboth19pub fn create_collection_raw<T: Config, R>(19pub fn create_collection_raw<T: Config, R>(20 owner: T::AccountId,20 owner: T::AccountId,21 mode: CollectionMode,21 mode: CollectionMode,22 handler: impl FnOnce(Collection<T>) -> Result<CollectionId, DispatchError>,22 handler: impl FnOnce(Collection<T::AccountId>) -> Result<CollectionId, DispatchError>,23 cast: impl FnOnce(CollectionHandle<T>) -> R,23 cast: impl FnOnce(CollectionHandle<T>) -> R,24) -> Result<R, DispatchError> {24) -> Result<R, DispatchError> {25 T::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());25 T::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());pallets/common/src/lib.rsdiffbeforeafterboth12 COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,12 COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,13 MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,13 MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,14 COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,14 COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,15 WithdrawReasons,15 WithdrawReasons, CollectionStats,16};16};17pub use pallet::*;17pub use pallet::*;18use sp_core::H160;18use sp_core::H160;26#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]26#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]27pub struct CollectionHandle<T: Config> {27pub struct CollectionHandle<T: Config> {28 pub id: CollectionId,28 pub id: CollectionId,29 collection: Collection<T>,29 collection: Collection<T::AccountId>,30 pub recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,30 pub recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,31}31}32impl<T: Config> CollectionHandle<T> {32impl<T: Config> CollectionHandle<T> {78 }78 }79}79}80impl<T: Config> Deref for CollectionHandle<T> {80impl<T: Config> Deref for CollectionHandle<T> {81 type Target = Collection<T>;81 type Target = Collection<T::AccountId>;828283 fn deref(&self) -> &Self::Target {83 fn deref(&self) -> &Self::Target {84 &self.collection84 &self.collection311 pub type CollectionById<T> = StorageMap<311 pub type CollectionById<T> = StorageMap<312 Hasher = Blake2_128Concat,312 Hasher = Blake2_128Concat,313 Key = CollectionId,313 Key = CollectionId,314 Value = Collection<T>,314 Value = Collection<<T as frame_system::Config>::AccountId>,315 QueryKind = OptionQuery,315 QueryKind = OptionQuery,316 >;316 >;317317345 QueryKind = ValueQuery,345 QueryKind = ValueQuery,346 >;346 >;347348 /// Not used by code, exists only to provide some types to metadata349 #[pallet::storage]350 pub type DummyStorageValue<T> =351 StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;347}352}348353349impl<T: Config> Pallet<T> {354impl<T: Config> Pallet<T> {355 );360 );356 Ok(())361 Ok(())357 }362 }363 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {364 <IsAdmin<T>>::iter_prefix((collection,))365 .map(|(a, _)| a)366 .collect()367 }368 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {369 <Allowlist<T>>::iter_prefix((collection,))370 .map(|(a, _)| a)371 .collect()372 }373 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {374 <Allowlist<T>>::get((collection, user))375 }376 pub fn collection_stats() -> CollectionStats {377 let created = <CreatedCollectionCount<T>>::get();378 let destroyed = <DestroyedCollectionCount<T>>::get();379 CollectionStats {380 created: created.0,381 destroyed: destroyed.0,382 alive: created.0 - destroyed.0,383 }384 }358}385}359386360impl<T: Config> Pallet<T> {387impl<T: Config> Pallet<T> {361 pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {388 pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {362 {389 {363 ensure!(390 ensure!(364 data.name.len() <= MAX_COLLECTION_NAME_LENGTH,391 data.name.len() <= MAX_COLLECTION_NAME_LENGTH,pallets/fungible/src/lib.rsdiffbeforeafterboth91}91}929293impl<T: Config> Pallet<T> {93impl<T: Config> Pallet<T> {94 pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {94 pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {95 PalletCommon::init_collection(data)95 <PalletCommon<T>>::init_collection(data)96 }96 }97 pub fn destroy_collection(97 pub fn destroy_collection(98 collection: FungibleHandle<T>,98 collection: FungibleHandle<T>,pallets/nft/src/lib.rsdiffbeforeafterboth42 CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,42 CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,43};43};44use pallet_common::{44use pallet_common::{45 account::CrossAccountId, CollectionHandle, IsAdmin, Pallet as PalletCommon,45 account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,46 Error as CommonError, CommonWeightInfo, Allowlist,46 CommonWeightInfo,47};47};48use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};48use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};49use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};49use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};194 let who = ensure_signed(origin)?;194 let who = ensure_signed(origin)?;195195196 // Create new collection196 // Create new collection197 let new_collection = Collection::<T> {197 let new_collection = Collection {198 owner: who.clone(),198 owner: who.clone(),199 name: collection_name,199 name: collection_name,200 mode: mode.clone(),200 mode: mode.clone(),212 };212 };213213214 let _id = match mode {214 let _id = match mode {215 CollectionMode::NFT => {PalletNonfungible::init_collection(new_collection)?},215 CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(new_collection)?},216 CollectionMode::Fungible(decimal_points) => {216 CollectionMode::Fungible(decimal_points) => {217 // check params217 // check params218 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);218 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);219 PalletFungible::init_collection(new_collection)?219 <PalletFungible<T>>::init_collection(new_collection)?220 }220 }221 CollectionMode::ReFungible => {221 CollectionMode::ReFungible => {222 PalletRefungible::init_collection(new_collection)?222 <PalletRefungible<T>>::init_collection(new_collection)?223 }223 }224 };224 };225225954 }954 }955}955}956957// TODO: limit returned entries?958impl<T: Config> Pallet<T> {959 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {960 <IsAdmin<T>>::iter_prefix((collection,))961 .map(|(a, _)| a)962 .collect()963 }964 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {965 <Allowlist<T>>::iter_prefix((collection,))966 .map(|(a, _)| a)967 .collect()968 }969}970956pallets/nonfungible/src/lib.rsdiffbeforeafterboth133133134// unchecked calls skips any permission checks134// unchecked calls skips any permission checks135impl<T: Config> Pallet<T> {135impl<T: Config> Pallet<T> {136 pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {136 pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {137 PalletCommon::init_collection(data)137 <PalletCommon<T>>::init_collection(data)138 }138 }139 pub fn destroy_collection(139 pub fn destroy_collection(140 collection: NonfungibleHandle<T>,140 collection: NonfungibleHandle<T>,pallets/refungible/src/lib.rsdiffbeforeafterboth156156157// unchecked calls skips any permission checks157// unchecked calls skips any permission checks158impl<T: Config> Pallet<T> {158impl<T: Config> Pallet<T> {159 pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {159 pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {160 PalletCommon::init_collection(data)160 <PalletCommon<T>>::init_collection(data)161 }161 }162 pub fn destroy_collection(162 pub fn destroy_collection(163 collection: RefungibleHandle<T>,163 collection: RefungibleHandle<T>,primitives/nft/src/lib.rsdiffbeforeafterboth209209210#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]210#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]211#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]211#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]212pub struct Collection<T: frame_system::Config> {212pub struct Collection<AccountId> {213 pub owner: T::AccountId,213 pub owner: AccountId,214 pub mode: CollectionMode,214 pub mode: CollectionMode,215 pub access: AccessMode,215 pub access: AccessMode,216 pub name: Vec<u16>, // 64 include null escape char216 pub name: Vec<u16>, // 64 include null escape char219 pub mint_mode: bool,219 pub mint_mode: bool,220 pub offchain_schema: Vec<u8>,220 pub offchain_schema: Vec<u8>,221 pub schema_version: SchemaVersion,221 pub schema_version: SchemaVersion,222 pub sponsorship: SponsorshipState<T::AccountId>,222 pub sponsorship: SponsorshipState<AccountId>,223 pub limits: CollectionLimits, // Collection private restrictions223 pub limits: CollectionLimits, // Collection private restrictions224 pub variable_on_chain_schema: Vec<u8>, //224 pub variable_on_chain_schema: Vec<u8>, //225 pub const_on_chain_schema: Vec<u8>, //225 pub const_on_chain_schema: Vec<u8>, //425 }425 }426}426}427428#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]429#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]430pub struct CollectionStats {431 pub created: u32,432 pub destroyed: u32,433 pub alive: u32,434}427435primitives/rpc/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]1#![cfg_attr(not(feature = "std"), no_std)]223use nft_data_structs::{CollectionId, TokenId};3use nft_data_structs::{CollectionId, TokenId, Collection, CollectionStats};4use sp_std::vec::Vec;4use sp_std::vec::Vec;5use sp_core::H160;5use sp_core::H160;6use codec::Decode;6use codec::Decode;323233 fn adminlist(collection: CollectionId) -> Vec<CrossAccountId>;33 fn adminlist(collection: CollectionId) -> Vec<CrossAccountId>;34 fn allowlist(collection: CollectionId) -> Vec<CrossAccountId>;34 fn allowlist(collection: CollectionId) -> Vec<CrossAccountId>;35 fn allowed(collection: CollectionId, user: CrossAccountId) -> bool;35 fn last_token_id(collection: CollectionId) -> TokenId;36 fn last_token_id(collection: CollectionId) -> TokenId;37 fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>>;38 fn collection_stats() -> CollectionStats;36 }39 }37}40}3841runtime/src/lib.rsdiffbeforeafterboth1045 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1045 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1046 }1046 }1047 fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {1047 fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {1048 <pallet_nft::Pallet<Runtime>>::adminlist(collection)1048 <pallet_common::Pallet<Runtime>>::adminlist(collection)1049 }1049 }1050 fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {1050 fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {1051 <pallet_nft::Pallet<Runtime>>::allowlist(collection)1051 <pallet_common::Pallet<Runtime>>::allowlist(collection)1052 }1052 }1053 fn allowed(collection: CollectionId, user: CrossAccountId) -> bool {1054 <pallet_common::Pallet<Runtime>>::allowed(collection, user)1055 }1053 fn last_token_id(collection: CollectionId) -> TokenId {1056 fn last_token_id(collection: CollectionId) -> TokenId {1054 dispatch_nft_runtime!(collection.last_token_id())1057 dispatch_nft_runtime!(collection.last_token_id())1055 }1058 }1059 fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>> {1060 <pallet_common::CollectionById<Runtime>>::get(collection)1061 }1062 fn collection_stats() -> CollectionStats {1063 <pallet_common::Pallet<Runtime>>::collection_stats()1064 }1056 }1065 }105710661058 impl sp_api::Core<Block> for Runtime {1067 impl sp_api::Core<Block> for Runtime {tests/src/addCollectionAdmin.test.tsdiffbeforeafterboth8import chaiAsPromised from 'chai-as-promised';8import chaiAsPromised from 'chai-as-promised';9import privateKey from './substrate/privateKey';9import privateKey from './substrate/privateKey';10import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';10import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';11import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId} from './util/helpers';11import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId, queryCollectionExpectSuccess} from './util/helpers';121213chai.use(chaiAsPromised);13chai.use(chaiAsPromised);14const expect = chai.expect;14const expect = chai.expect;20 const alice = privateKey('//Alice');20 const alice = privateKey('//Alice');21 const bob = privateKey('//Bob');21 const bob = privateKey('//Bob');222223 const collection = (await api.query.common.collectionById(collectionId)).unwrap();23 const collection = await queryCollectionExpectSuccess(api, collectionId);24 expect(collection.owner.toString()).to.be.equal(alice.address);24 expect(collection.owner.toString()).to.be.equal(alice.address);252526 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));26 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));38 const bob = privateKey('//Bob');38 const bob = privateKey('//Bob');39 const charlie = privateKey('//CHARLIE');39 const charlie = privateKey('//CHARLIE');404041 const collection = (await api.query.common.collectionById(collectionId)).unwrap();41 const collection = await queryCollectionExpectSuccess(api, collectionId);42 expect(collection.owner.toString()).to.be.equal(alice.address);42 expect(collection.owner.toString()).to.be.equal(alice.address);434344 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));44 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));tests/src/addToAllowList.test.tsdiffbeforeafterboth18 normalizeAccountId,18 normalizeAccountId,19 addCollectionAdminExpectSuccess,19 addCollectionAdminExpectSuccess,20 addToAllowListExpectFail,20 addToAllowListExpectFail,21 getCreatedCollectionCount,21} from './util/helpers';22} from './util/helpers';222323chai.use(chaiAsPromised);24chai.use(chaiAsPromised);55 it('Allow list an address in the collection that does not exist', async () => {56 it('Allow list an address in the collection that does not exist', async () => {56 await usingApi(async (api) => {57 await usingApi(async (api) => {57 // tslint:disable-next-line: no-bitwise58 // tslint:disable-next-line: no-bitwise58 const collectionId = ((await api.query.common.createdCollectionCount()).toNumber()) + 1;59 const collectionId = await getCreatedCollectionCount(api) + 1;59 const bob = privateKey('//Bob');60 const bob = privateKey('//Bob');606161 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(bob.address));62 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(bob.address));tests/src/approve.test.tsdiffbeforeafterboth18 transferExpectSuccess,18 transferExpectSuccess,19 addCollectionAdminExpectSuccess,19 addCollectionAdminExpectSuccess,20 adminApproveFromExpectSuccess,20 adminApproveFromExpectSuccess,21 getCreatedCollectionCount,21 transferFromExpectSuccess,22 transferFromExpectSuccess,22 transferFromExpectFail,23 transferFromExpectFail,23} from './util/helpers';24} from './util/helpers';411 it('Approve for a collection that does not exist', async () => {412 it('Approve for a collection that does not exist', async () => {412 await usingApi(async (api: ApiPromise) => {413 await usingApi(async (api: ApiPromise) => {413 // nft414 // nft414 const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();415 const nftCollectionCount = await getCreatedCollectionCount(api);415 await approveExpectFail(nftCollectionCount + 1, 1, alice, bob);416 await approveExpectFail(nftCollectionCount + 1, 1, alice, bob);416 // fungible417 // fungible417 const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();418 const fungibleCollectionCount = await getCreatedCollectionCount(api);418 await approveExpectFail(fungibleCollectionCount + 1, 0, alice, bob);419 await approveExpectFail(fungibleCollectionCount + 1, 0, alice, bob);419 // reFungible420 // reFungible420 const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();421 const reFungibleCollectionCount = await getCreatedCollectionCount(api);421 await approveExpectFail(reFungibleCollectionCount + 1, 1, alice, bob);422 await approveExpectFail(reFungibleCollectionCount + 1, 1, alice, bob);422 });423 });423 });424 });tests/src/change-collection-owner.test.tsdiffbeforeafterboth22 setMintPermissionExpectFailure,22 setMintPermissionExpectFailure,23 destroyCollectionExpectFailure,23 destroyCollectionExpectFailure,24 setPublicAccessModeExpectSuccess,24 setPublicAccessModeExpectSuccess,25 queryCollectionExpectSuccess,25} from './util/helpers';26} from './util/helpers';262727chai.use(chaiAsPromised);28chai.use(chaiAsPromised);34 const alice = privateKey('//Alice');35 const alice = privateKey('//Alice');35 const bob = privateKey('//Bob');36 const bob = privateKey('//Bob');363737 const collection = (await api.query.common.collectionById(collectionId)).unwrap();38 const collection =await queryCollectionExpectSuccess(api, collectionId);38 expect(collection.owner.toString()).to.be.deep.eq(alice.address);39 expect(collection.owner.toString()).to.be.deep.eq(alice.address);394040 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);41 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);41 await submitTransactionAsync(alice, changeOwnerTx);42 await submitTransactionAsync(alice, changeOwnerTx);424343 const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();44 const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);44 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);45 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);45 });46 });46 });47 });53 const alice = privateKey('//Alice');54 const alice = privateKey('//Alice');54 const bob = privateKey('//Bob');55 const bob = privateKey('//Bob');555656 const collection = (await api.query.common.collectionById(collectionId)).unwrap();57 const collection = await queryCollectionExpectSuccess(api, collectionId);57 expect(collection.owner.toString()).to.be.deep.eq(alice.address);58 expect(collection.owner.toString()).to.be.deep.eq(alice.address);585959 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);60 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);62 const badChangeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, alice.address);63 const badChangeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, alice.address);63 await expect(submitTransactionExpectFailAsync(alice, badChangeOwnerTx)).to.be.rejected;64 await expect(submitTransactionExpectFailAsync(alice, badChangeOwnerTx)).to.be.rejected;646565 const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();66 const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);66 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);67 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);67 });68 });68 });69 });74 const bob = privateKey('//Bob');75 const bob = privateKey('//Bob');75 const charlie = privateKey('//Charlie');76 const charlie = privateKey('//Charlie');767777 const collection = (await api.query.common.collectionById(collectionId)).unwrap();78 const collection = await queryCollectionExpectSuccess(api, collectionId);78 expect(collection.owner.toString()).to.be.deep.eq(alice.address);79 expect(collection.owner.toString()).to.be.deep.eq(alice.address);798080 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);81 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);81 await submitTransactionAsync(alice, changeOwnerTx);82 await submitTransactionAsync(alice, changeOwnerTx);828383 const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();84 const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);84 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);85 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);858686 // After changing the owner of the collection, all privileged methods are available to the new owner87 // After changing the owner of the collection, all privileged methods are available to the new owner118 const bob = privateKey('//Bob');119 const bob = privateKey('//Bob');119 const charlie = privateKey('//Charlie');120 const charlie = privateKey('//Charlie');120121121 const collection = (await api.query.common.collectionById(collectionId)).unwrap();122 const collection = await queryCollectionExpectSuccess(api, collectionId);122 expect(collection.owner.toString()).to.be.deep.eq(alice.address);123 expect(collection.owner.toString()).to.be.deep.eq(alice.address);123124124 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);125 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);125 await submitTransactionAsync(alice, changeOwnerTx);126 await submitTransactionAsync(alice, changeOwnerTx);126127127 const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();128 const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);128 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);129 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);129130130 const changeOwnerTx2 = api.tx.nft.changeCollectionOwner(collectionId, charlie.address);131 const changeOwnerTx2 = api.tx.nft.changeCollectionOwner(collectionId, charlie.address);131 await submitTransactionAsync(bob, changeOwnerTx2);132 await submitTransactionAsync(bob, changeOwnerTx2);132133133 // ownership lost134 // ownership lost134 const collectionAfterOwnerChange2 = (await api.query.common.collectionById(collectionId)).unwrap();135 const collectionAfterOwnerChange2 = await queryCollectionExpectSuccess(api, collectionId);135 expect(collectionAfterOwnerChange2.owner.toString()).to.be.deep.eq(charlie.address);136 expect(collectionAfterOwnerChange2.owner.toString()).to.be.deep.eq(charlie.address);136 });137 });137 });138 });147 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);148 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);148 await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;149 await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;149150150 const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();151 const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);151 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(alice.address);152 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(alice.address);152153153 // Verifying that nothing bad happened (network is live, new collections can be created, etc.)154 // Verifying that nothing bad happened (network is live, new collections can be created, etc.)166 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);167 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);167 await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;168 await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;168169169 const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();170 const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);170 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(alice.address);171 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(alice.address);171172172 // Verifying that nothing bad happened (network is live, new collections can be created, etc.)173 // Verifying that nothing bad happened (network is live, new collections can be created, etc.)195 const bob = privateKey('//Bob');196 const bob = privateKey('//Bob');196 const charlie = privateKey('//Charlie');197 const charlie = privateKey('//Charlie');197198198 const collection = (await api.query.common.collectionById(collectionId)).unwrap();199 const collection = await queryCollectionExpectSuccess(api, collectionId);199 expect(collection.owner.toString()).to.be.deep.eq(alice.address);200 expect(collection.owner.toString()).to.be.deep.eq(alice.address);200201201 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);202 const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);204 const badChangeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, alice.address);205 const badChangeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, alice.address);205 await expect(submitTransactionExpectFailAsync(alice, badChangeOwnerTx)).to.be.rejected;206 await expect(submitTransactionExpectFailAsync(alice, badChangeOwnerTx)).to.be.rejected;206207207 const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();208 const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);208 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);209 expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);209210210 await setCollectionSponsorExpectFailure(collectionId, charlie.address, '//Alice');211 await setCollectionSponsorExpectFailure(collectionId, charlie.address, '//Alice');tests/src/confirmSponsorship.test.tsdiffbeforeafterboth20 addToAllowListExpectSuccess,20 addToAllowListExpectSuccess,21 normalizeAccountId,21 normalizeAccountId,22 addCollectionAdminExpectSuccess,22 addCollectionAdminExpectSuccess,23 getCreatedCollectionCount,23} from './util/helpers';24} from './util/helpers';24import {Keyring} from '@polkadot/api';25import {Keyring} from '@polkadot/api';25import {IKeyringPair} from '@polkadot/types/types';26import {IKeyringPair} from '@polkadot/types/types';330 // Find the collection that never existed331 // Find the collection that never existed331 let collectionId = 0;332 let collectionId = 0;332 await usingApi(async (api) => {333 await usingApi(async (api) => {333 collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;334 collectionId = await getCreatedCollectionCount(api) + 1;334 });335 });335336336 await confirmSponsorshipExpectFailure(collectionId, '//Bob');337 await confirmSponsorshipExpectFailure(collectionId, '//Bob');tests/src/contracts.test.tsdiffbeforeafterboth228 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);228 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);229 await submitTransactionAsync(alice, changeAdminTx);229 await submitTransactionAsync(alice, changeAdminTx);230230231 expect(await isAllowlisted(collectionId, bob.address)).to.be.false;231 expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;232232233 {233 {234 const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, true);234 const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, true);235 const events = await submitTransactionAsync(alice, transferTx);235 const events = await submitTransactionAsync(alice, transferTx);236 const result = getGenericResult(events);236 const result = getGenericResult(events);237 expect(result.success).to.be.true;237 expect(result.success).to.be.true;238238239 expect(await isAllowlisted(collectionId, bob.address)).to.be.true;239 expect(await isAllowlisted(api, collectionId, bob.address)).to.be.true;240 }240 }241 {241 {242 const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, false);242 const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, false);243 const events = await submitTransactionAsync(alice, transferTx);243 const events = await submitTransactionAsync(alice, transferTx);244 const result = getGenericResult(events);244 const result = getGenericResult(events);245 expect(result.success).to.be.true;245 expect(result.success).to.be.true;246246247 expect(await isAllowlisted(collectionId, bob.address)).to.be.false;247 expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;248 }248 }249 });249 });250 });250 });tests/src/createMultipleItems.test.tsdiffbeforeafterboth20 getLastTokenId,20 getLastTokenId,21 getVariableMetadata,21 getVariableMetadata,22 getConstMetadata,22 getConstMetadata,23 getCreatedCollectionCount,23} from './util/helpers';24} from './util/helpers';242525chai.use(chaiAsPromised);26chai.use(chaiAsPromised);273274274 it('Create token in not existing collection', async () => {275 it('Create token in not existing collection', async () => {275 await usingApi(async (api: ApiPromise) => {276 await usingApi(async (api: ApiPromise) => {276 const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;277 const collectionId = await getCreatedCollectionCount(api) + 1;277 const createMultipleItemsTx = api.tx.nft278 const createMultipleItemsTx = api.tx.nft278 .createMultipleItems(collectionId, normalizeAccountId(alice.address), ['NFT', 'NFT', 'NFT']);279 .createMultipleItems(collectionId, normalizeAccountId(alice.address), ['NFT', 'NFT', 'NFT']);279 await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTx)).to.be.rejected;280 await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTx)).to.be.rejected;tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth14 createItemExpectSuccess,14 createItemExpectSuccess,15 getGenericResult,15 getGenericResult,16 transferExpectSuccess,16 transferExpectSuccess,17 UNIQUE,17} from './util/helpers';18} from './util/helpers';181919import {default as waitNewBlocks} from './substrate/wait-new-blocks';20import {default as waitNewBlocks} from './substrate/wait-new-blocks';169 const aliceBalanceBefore: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();170 const aliceBalanceBefore: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();170 await transferExpectSuccess(collectionId, tokenId, alice, bob, 1, 'NFT');171 await transferExpectSuccess(collectionId, tokenId, alice, bob, 1, 'NFT');171 const aliceBalanceAfter: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();172 const aliceBalanceAfter: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();172 const fee = aliceBalanceBefore - aliceBalanceAfter;173 const fee = Number(aliceBalanceBefore - aliceBalanceAfter) / Number(UNIQUE);173174174 // console.log(fee.toString());175 const expectedTransferFee = 0.1;175 const expectedTransferFee = 0.1;176 const tolerance = 0.001;176 const tolerance = 0.001;177 expect(Number(fee) / 1e15 - expectedTransferFee).to.be.lessThan(tolerance);177 expect(Number(fee) / Number(UNIQUE) - expectedTransferFee).to.be.lessThan(tolerance);178 });178 });179 });179 });180180tests/src/destroyCollection.test.tsdiffbeforeafterboth13 destroyCollectionExpectFailure,13 destroyCollectionExpectFailure,14 setCollectionLimitsExpectSuccess,14 setCollectionLimitsExpectSuccess,15 addCollectionAdminExpectSuccess,15 addCollectionAdminExpectSuccess,16 getCreatedCollectionCount,16} from './util/helpers';17} from './util/helpers';171818chai.use(chaiAsPromised);19chai.use(chaiAsPromised);46 it('(!negative test!) Destroy a collection that never existed', async () => {47 it('(!negative test!) Destroy a collection that never existed', async () => {47 await usingApi(async (api) => {48 await usingApi(async (api) => {48 // Find the collection that never existed49 // Find the collection that never existed49 const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;50 const collectionId = await getCreatedCollectionCount(api) + 1;50 await destroyCollectionExpectFailure(collectionId);51 await destroyCollectionExpectFailure(collectionId);51 });52 });52 });53 });tests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth1// Auto-generated via `yarn polkadot-types-from-chain`, do not edit1// Auto-generated via `yarn polkadot-types-from-chain`, do not edit2/* eslint-disable */2/* eslint-disable */334import type { NftDataStructsCollectionId, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr } from './nft';4import type { NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionStats, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr } from './nft';5import type { Bytes, HashMap, Json, Metadata, Null, Option, StorageKey, Text, U256, U64, Vec, bool, u128, u32, u64 } from '@polkadot/types';5import type { Bytes, HashMap, Json, Metadata, Null, Option, StorageKey, Text, U256, U64, Vec, bool, u128, u32, u64 } from '@polkadot/types';6import type { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';6import type { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';7import type { EpochAuthorship } from '@polkadot/types/interfaces/babe';7import type { EpochAuthorship } from '@polkadot/types/interfaces/babe';372 * Get allowed amount372 * Get allowed amount373 **/373 **/374 allowance: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, sender: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, spender: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: NftDataStructsTokenId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;374 allowance: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, sender: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, spender: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: NftDataStructsTokenId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;375 /**376 * Check if user is allowed to use collection377 **/378 allowed: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, account: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<bool>>;375 /**379 /**376 * Get allowlist380 * Get allowlist377 **/381 **/380 * Get amount of specific account token384 * Get amount of specific account token381 **/385 **/382 balance: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, account: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: NftDataStructsTokenId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;386 balance: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, account: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: NftDataStructsTokenId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;387 /**388 * Get collection by specified id389 **/390 collectionById: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<NftDataStructsCollection>>>;391 /**392 * Get collection stats393 **/394 collectionStats: AugmentedRpc<(at?: Hash | string | Uint8Array) => Observable<NftDataStructsCollectionStats>>;383 /**395 /**384 * Get tokens contained in collection396 * Get tokens contained in collection385 **/397 **/tests/src/interfaces/augment-types.tsdiffbeforeafterboth2/* eslint-disable */2/* eslint-disable */334import type { EthereumBlock, EthereumLog, EthereumReceipt, EthereumTransactionLegacyTransaction, EvmCoreErrorExitReason, FpRpcTransactionStatus } from './ethereum';4import type { EthereumBlock, EthereumLog, EthereumReceipt, EthereumTransactionLegacyTransaction, EvmCoreErrorExitReason, FpRpcTransactionStatus } from './ethereum';5import type { NftDataStructsAccessMode, NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionLimits, NftDataStructsCollectionMode, NftDataStructsCreateItemData, NftDataStructsMetaUpdatePermission, NftDataStructsSchemaVersion, NftDataStructsSponsorshipState, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2 } from './nft';5import type { NftDataStructsAccessMode, NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionLimits, NftDataStructsCollectionMode, NftDataStructsCollectionStats, NftDataStructsCreateItemData, NftDataStructsMetaUpdatePermission, NftDataStructsSchemaVersion, NftDataStructsSponsorshipState, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2 } from './nft';6import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundStatus, CumulusPalletXcmpQueueOutboundStatus, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV1AbridgedHostConfiguration, PolkadotPrimitivesV1PersistedValidationData } from './polkadot';6import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundStatus, CumulusPalletXcmpQueueOutboundStatus, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV1AbridgedHostConfiguration, PolkadotPrimitivesV1PersistedValidationData } from './polkadot';7import type { BitVec, Bool, Bytes, Data, I128, I16, I256, I32, I64, I8, Json, Null, Raw, StorageKey, Text, Type, U128, U16, U256, U32, U64, U8, USize, bool, i128, i16, i256, i32, i64, i8, u128, u16, u256, u32, u64, u8, usize } from '@polkadot/types';7import type { BitVec, Bool, Bytes, Data, I128, I16, I256, I32, I64, I8, Json, Null, Raw, StorageKey, Text, Type, U128, U16, U256, U32, U64, U8, USize, bool, i128, i16, i256, i32, i64, i8, u128, u16, u256, u32, u64, u8, usize } from '@polkadot/types';8import type { AssetApproval, AssetApprovalKey, AssetBalance, AssetDestroyWitness, AssetDetails, AssetMetadata, TAssetBalance, TAssetDepositBalance } from '@polkadot/types/interfaces/assets';8import type { AssetApproval, AssetApprovalKey, AssetBalance, AssetDestroyWitness, AssetDetails, AssetMetadata, TAssetBalance, TAssetDepositBalance } from '@polkadot/types/interfaces/assets';627 NftDataStructsCollectionId: NftDataStructsCollectionId;627 NftDataStructsCollectionId: NftDataStructsCollectionId;628 NftDataStructsCollectionLimits: NftDataStructsCollectionLimits;628 NftDataStructsCollectionLimits: NftDataStructsCollectionLimits;629 NftDataStructsCollectionMode: NftDataStructsCollectionMode;629 NftDataStructsCollectionMode: NftDataStructsCollectionMode;630 NftDataStructsCollectionStats: NftDataStructsCollectionStats;630 NftDataStructsCreateItemData: NftDataStructsCreateItemData;631 NftDataStructsCreateItemData: NftDataStructsCreateItemData;631 NftDataStructsMetaUpdatePermission: NftDataStructsMetaUpdatePermission;632 NftDataStructsMetaUpdatePermission: NftDataStructsMetaUpdatePermission;632 NftDataStructsSchemaVersion: NftDataStructsSchemaVersion;633 NftDataStructsSchemaVersion: NftDataStructsSchemaVersion;tests/src/interfaces/nft/definitions.tsdiffbeforeafterboth40 constMetadata: fun('Get token constant metadata', [collectionParam, tokenParam], 'Vec<u8>'),40 constMetadata: fun('Get token constant metadata', [collectionParam, tokenParam], 'Vec<u8>'),41 variableMetadata: fun('Get token variable metadata', [collectionParam, tokenParam], 'Vec<u8>'),41 variableMetadata: fun('Get token variable metadata', [collectionParam, tokenParam], 'Vec<u8>'),42 tokenExists: fun('Check if token exists', [collectionParam, tokenParam], 'bool'),42 tokenExists: fun('Check if token exists', [collectionParam, tokenParam], 'bool'),43 collectionById: fun('Get collection by specified id', [collectionParam], 'Option<NftDataStructsCollection>'),44 collectionStats: fun('Get collection stats', [], 'NftDataStructsCollectionStats'),45 allowed: fun('Check if user is allowed to use collection', [collectionParam, crossAccountParam()], 'bool'),43 },46 },44 types: {47 types: {45 PalletCommonAccountBasicCrossAccountIdRepr: {48 PalletCommonAccountBasicCrossAccountIdRepr: {64 constOnChainSchema: 'Vec<u8>',67 constOnChainSchema: 'Vec<u8>',65 metaUpdatePermission: 'NftDataStructsMetaUpdatePermission',68 metaUpdatePermission: 'NftDataStructsMetaUpdatePermission',66 },69 },70 NftDataStructsCollectionStats: {71 created: 'u32',72 destroyed: 'u32',73 alive: 'u32',74 },67 NftDataStructsCollectionId: 'u32',75 NftDataStructsCollectionId: 'u32',68 NftDataStructsTokenId: 'u32',76 NftDataStructsTokenId: 'u32',69 PalletNonfungibleItemData: mkDummy('NftItemData'),77 PalletNonfungibleItemData: mkDummy('NftItemData'),tests/src/interfaces/nft/types.tsdiffbeforeafterboth48 readonly dummyCollectionMode: u32;48 readonly dummyCollectionMode: u32;49}49}5051/** @name NftDataStructsCollectionStats */52export interface NftDataStructsCollectionStats extends Struct {53 readonly created: u32;54 readonly destroyed: u32;55 readonly alive: u32;56}505751/** @name NftDataStructsCreateItemData */58/** @name NftDataStructsCreateItemData */52export interface NftDataStructsCreateItemData extends Struct {59export interface NftDataStructsCreateItemData extends Struct {tests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth8import chaiAsPromised from 'chai-as-promised';8import chaiAsPromised from 'chai-as-promised';9import privateKey from './substrate/privateKey';9import privateKey from './substrate/privateKey';10import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';10import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';11import {createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId} from './util/helpers';11import {createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId, queryCollectionExpectSuccess} from './util/helpers';121213chai.use(chaiAsPromised);13chai.use(chaiAsPromised);14const expect = chai.expect;14const expect = chai.expect;19 const collectionId = await createCollectionExpectSuccess();19 const collectionId = await createCollectionExpectSuccess();20 const alice = privateKey('//Alice');20 const alice = privateKey('//Alice');21 const bob = privateKey('//Bob');21 const bob = privateKey('//Bob');22 const collection = (await api.query.common.collectionById(collectionId)).unwrap();22 const collection = await queryCollectionExpectSuccess(api, collectionId);23 expect(collection.owner.toString()).to.be.deep.eq(alice.address);23 expect(collection.owner.toString()).to.be.deep.eq(alice.address);24 // first - add collection admin Bob24 // first - add collection admin Bob25 const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));25 const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));43 const alice = privateKey('//Alice');43 const alice = privateKey('//Alice');44 const bob = privateKey('//Bob');44 const bob = privateKey('//Bob');45 const charlie = privateKey('//Charlie');45 const charlie = privateKey('//Charlie');46 const collection = (await api.query.common.collectionById(collectionId)).unwrap();46 const collection = await queryCollectionExpectSuccess(api, collectionId);47 expect(collection.owner.toString()).to.be.eq(alice.address);47 expect(collection.owner.toString()).to.be.eq(alice.address);48 // first - add collection admin Bob48 // first - add collection admin Bob49 const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));49 const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));tests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth18 removeCollectionSponsorExpectFailure,18 removeCollectionSponsorExpectFailure,19 normalizeAccountId,19 normalizeAccountId,20 addCollectionAdminExpectSuccess,20 addCollectionAdminExpectSuccess,21 getCreatedCollectionCount,21} from './util/helpers';22} from './util/helpers';22import {Keyring} from '@polkadot/api';23import {Keyring} from '@polkadot/api';23import {IKeyringPair} from '@polkadot/types/types';24import {IKeyringPair} from '@polkadot/types/types';98 // Find the collection that never existed99 // Find the collection that never existed99 let collectionId = 0;100 let collectionId = 0;100 await usingApi(async (api) => {101 await usingApi(async (api) => {101 collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;102 collectionId = await getCreatedCollectionCount(api) + 1;102 });103 });103104104 await removeCollectionSponsorExpectFailure(collectionId);105 await removeCollectionSponsorExpectFailure(collectionId);tests/src/removeFromAllowList.test.tsdiffbeforeafterboth37 });37 });383839 it('ensure bob is not in allowlist after removal', async () => {39 it('ensure bob is not in allowlist after removal', async () => {40 await usingApi(async () => {40 await usingApi(async api => {41 const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});41 const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});42 await enableAllowListExpectSuccess(alice, collectionId);42 await enableAllowListExpectSuccess(alice, collectionId);43 await addToAllowListExpectSuccess(alice, collectionId, bob.address);43 await addToAllowListExpectSuccess(alice, collectionId, bob.address);444445 await removeFromAllowListExpectSuccess(alice, collectionId, normalizeAccountId(bob.address));45 await removeFromAllowListExpectSuccess(alice, collectionId, normalizeAccountId(bob.address));46 expect(await isAllowlisted(collectionId, bob.address)).to.be.false;46 expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;47 });47 });48 });48 });4949104 });104 });105105106 it('ensure address is not in allowlist after removal', async () => {106 it('ensure address is not in allowlist after removal', async () => {107 await usingApi(async () => {107 await usingApi(async api => {108 const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});108 const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});109 await enableAllowListExpectSuccess(alice, collectionId);109 await enableAllowListExpectSuccess(alice, collectionId);110 await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);110 await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);111 await addToAllowListExpectSuccess(alice, collectionId, charlie.address);111 await addToAllowListExpectSuccess(alice, collectionId, charlie.address);112 await removeFromAllowListExpectSuccess(bob, collectionId, normalizeAccountId(charlie.address));112 await removeFromAllowListExpectSuccess(bob, collectionId, normalizeAccountId(charlie.address));113 expect(await isAllowlisted(collectionId, charlie.address)).to.be.false;113 expect(await isAllowlisted(api, collectionId, charlie.address)).to.be.false;114 });114 });115 });115 });116116tests/src/setCollectionSponsor.test.tsdiffbeforeafterboth11 destroyCollectionExpectSuccess,11 destroyCollectionExpectSuccess,12 setCollectionSponsorExpectFailure,12 setCollectionSponsorExpectFailure,13 addCollectionAdminExpectSuccess,13 addCollectionAdminExpectSuccess,14 getCreatedCollectionCount,14} from './util/helpers';15} from './util/helpers';15import {Keyring} from '@polkadot/api';16import {Keyring} from '@polkadot/api';16import {IKeyringPair} from '@polkadot/types/types';17import {IKeyringPair} from '@polkadot/types/types';77 // Find the collection that never existed78 // Find the collection that never existed78 let collectionId = 0;79 let collectionId = 0;79 await usingApi(async (api) => {80 await usingApi(async (api) => {80 collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;81 collectionId = await getCreatedCollectionCount(api) + 1;81 });82 });828383 await setCollectionSponsorExpectFailure(collectionId, bob.address);84 await setCollectionSponsorExpectFailure(collectionId, bob.address);tests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth12 createCollectionExpectSuccess,12 createCollectionExpectSuccess,13 destroyCollectionExpectSuccess,13 destroyCollectionExpectSuccess,14 addCollectionAdminExpectSuccess,14 addCollectionAdminExpectSuccess,15 queryCollectionExpectSuccess,16 getCreatedCollectionCount,15} from './util/helpers';17} from './util/helpers';161817chai.use(chaiAsPromised);19chai.use(chaiAsPromised);37 it('Run extrinsic with parameters of the collection id, set the scheme', async () => {39 it('Run extrinsic with parameters of the collection id, set the scheme', async () => {38 await usingApi(async (api) => {40 await usingApi(async (api) => {39 const collectionId = await createCollectionExpectSuccess();41 const collectionId = await createCollectionExpectSuccess();40 const collection = (await api.query.common.collectionById(collectionId)).unwrap();42 const collection = await queryCollectionExpectSuccess(api, collectionId);41 expect(collection.owner.toString()).to.be.eq(alice.address);43 expect(collection.owner.toString()).to.be.eq(alice.address);42 const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);44 const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);43 await submitTransactionAsync(alice, setShema);45 await submitTransactionAsync(alice, setShema);47 it('Collection admin can set the scheme', async () => {49 it('Collection admin can set the scheme', async () => {48 await usingApi(async (api) => {50 await usingApi(async (api) => {49 const collectionId = await createCollectionExpectSuccess();51 const collectionId = await createCollectionExpectSuccess();50 const collection = (await api.query.common.collectionById(collectionId)).unwrap();52 const collection = await queryCollectionExpectSuccess(api, collectionId);51 expect(collection.owner.toString()).to.be.eq(alice.address);53 expect(collection.owner.toString()).to.be.eq(alice.address);52 await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);54 await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);53 const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);55 const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);60 const collectionId = await createCollectionExpectSuccess();62 const collectionId = await createCollectionExpectSuccess();61 const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);63 const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);62 await submitTransactionAsync(alice, setShema);64 await submitTransactionAsync(alice, setShema);63 const collection = (await api.query.common.collectionById(collectionId)).unwrap();65 const collection = await queryCollectionExpectSuccess(api, collectionId);64 expect(collection.constOnChainSchema.toString()).to.be.eq(shema);66 expect(collection.constOnChainSchema.toString()).to.be.eq(shema);65 });67 });66 });68 });71 it('Set a non-existent collection', async () => {73 it('Set a non-existent collection', async () => {72 await usingApi(async (api) => {74 await usingApi(async (api) => {73 // tslint:disable-next-line: radix75 // tslint:disable-next-line: radix74 const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;76 const collectionId = await getCreatedCollectionCount(api) + 1;75 const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);77 const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);76 await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;78 await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;77 });79 });97 it('Execute method not on behalf of the collection owner', async () => {99 it('Execute method not on behalf of the collection owner', async () => {98 await usingApi(async (api) => {100 await usingApi(async (api) => {99 const collectionId = await createCollectionExpectSuccess();101 const collectionId = await createCollectionExpectSuccess();100 const collection = (await api.query.common.collectionById(collectionId)).unwrap();102 const collection = await queryCollectionExpectSuccess(api, collectionId);101 expect(collection.owner.toString()).to.be.eq(alice.address);103 expect(collection.owner.toString()).to.be.eq(alice.address);102 const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);104 const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);103 await expect(submitTransactionExpectFailAsync(bob, setShema)).to.be.rejected;105 await expect(submitTransactionExpectFailAsync(bob, setShema)).to.be.rejected;tests/src/setPublicAccessMode.test.tsdiffbeforeafterboth19 enableAllowListExpectSuccess,19 enableAllowListExpectSuccess,20 normalizeAccountId,20 normalizeAccountId,21 addCollectionAdminExpectSuccess,21 addCollectionAdminExpectSuccess,22 getCreatedCollectionCount,22} from './util/helpers';23} from './util/helpers';232424chai.use(chaiAsPromised);25chai.use(chaiAsPromised);60 it('Set a non-existent collection', async () => {61 it('Set a non-existent collection', async () => {61 await usingApi(async (api: ApiPromise) => {62 await usingApi(async (api: ApiPromise) => {62 // tslint:disable-next-line: radix63 // tslint:disable-next-line: radix63 const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;64 const collectionId = await getCreatedCollectionCount(api) + 1;64 const tx = api.tx.nft.setPublicAccessMode(collectionId, 'AllowList');65 const tx = api.tx.nft.setPublicAccessMode(collectionId, 'AllowList');65 await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;66 await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;66 });67 });tests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth12 createCollectionExpectSuccess,12 createCollectionExpectSuccess,13 destroyCollectionExpectSuccess,13 destroyCollectionExpectSuccess,14 addCollectionAdminExpectSuccess,14 addCollectionAdminExpectSuccess,15 queryCollectionExpectSuccess,16 getCreatedCollectionCount,15} from './util/helpers';17} from './util/helpers';161817chai.use(chaiAsPromised);19chai.use(chaiAsPromised);37 it('Run extrinsic with parameters of the collection id, set the scheme', async () => {39 it('Run extrinsic with parameters of the collection id, set the scheme', async () => {38 await usingApi(async (api) => {40 await usingApi(async (api) => {39 const collectionId = await createCollectionExpectSuccess();41 const collectionId = await createCollectionExpectSuccess();40 const collection = (await api.query.common.collectionById(collectionId)).unwrap();42 const collection = await queryCollectionExpectSuccess(api, collectionId);41 expect(collection.owner.toString()).to.be.eq(alice.address);43 expect(collection.owner.toString()).to.be.eq(alice.address);42 const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);44 const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);43 await submitTransactionAsync(alice, setSchema);45 await submitTransactionAsync(alice, setSchema);49 const collectionId = await createCollectionExpectSuccess();51 const collectionId = await createCollectionExpectSuccess();50 const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);52 const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);51 await submitTransactionAsync(alice, setSchema);53 await submitTransactionAsync(alice, setSchema);52 const collection = (await api.query.common.collectionById(collectionId)).unwrap();54 const collection = await queryCollectionExpectSuccess(api, collectionId);53 expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);55 expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);545655 });57 });61 it('Run extrinsic with parameters of the collection id, set the scheme', async () => {63 it('Run extrinsic with parameters of the collection id, set the scheme', async () => {62 await usingApi(async (api) => {64 await usingApi(async (api) => {63 const collectionId = await createCollectionExpectSuccess();65 const collectionId = await createCollectionExpectSuccess();64 const collection = (await api.query.common.collectionById(collectionId)).unwrap();66 const collection = await queryCollectionExpectSuccess(api, collectionId);65 expect(collection.owner.toString()).to.be.eq(alice.address);67 expect(collection.owner.toString()).to.be.eq(alice.address);66 await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);68 await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);67 const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);69 const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);75 await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);77 await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);76 const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);78 const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);77 await submitTransactionAsync(bob, setSchema);79 await submitTransactionAsync(bob, setSchema);78 const collection = (await api.query.common.collectionById(collectionId)).unwrap();80 const collection = await queryCollectionExpectSuccess(api, collectionId);79 expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);81 expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);808281 });83 });87 it('Set a non-existent collection', async () => {89 it('Set a non-existent collection', async () => {88 await usingApi(async (api) => {90 await usingApi(async (api) => {89 // tslint:disable-next-line: radix91 // tslint:disable-next-line: radix90 const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;92 const collectionId = await getCreatedCollectionCount(api) + 1;91 const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);93 const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);92 await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;94 await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;93 });95 });113 it('Execute method not on behalf of the collection owner', async () => {115 it('Execute method not on behalf of the collection owner', async () => {114 await usingApi(async (api) => {116 await usingApi(async (api) => {115 const collectionId = await createCollectionExpectSuccess();117 const collectionId = await createCollectionExpectSuccess();116 const collection = (await api.query.common.collectionById(collectionId)).unwrap();118 const collection = await queryCollectionExpectSuccess(api, collectionId);117 expect(collection.owner.toString()).to.be.eq(alice.address);119 expect(collection.owner.toString()).to.be.eq(alice.address);118 const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);120 const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);119 await expect(submitTransactionExpectFailAsync(bob, setSchema)).to.be.rejected;121 await expect(submitTransactionExpectFailAsync(bob, setSchema)).to.be.rejected;tests/src/transfer.test.tsdiffbeforeafterboth19 transferExpectFailure,19 transferExpectFailure,20 transferExpectSuccess,20 transferExpectSuccess,21 addCollectionAdminExpectSuccess,21 addCollectionAdminExpectSuccess,22 getCreatedCollectionCount,22 toSubstrateAddress,23 toSubstrateAddress,23 getTokenOwner,24 getTokenOwner,24 normalizeAccountId,25 normalizeAccountId,136 it('Transfer with not existed collection_id', async () => {137 it('Transfer with not existed collection_id', async () => {137 await usingApi(async (api) => {138 await usingApi(async (api) => {138 // nft139 // nft139 const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();140 const nftCollectionCount = await getCreatedCollectionCount(api);140 await transferExpectFailure(nftCollectionCount + 1, 1, alice, bob, 1);141 await transferExpectFailure(nftCollectionCount + 1, 1, alice, bob, 1);141 // fungible142 // fungible142 const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();143 const fungibleCollectionCount = await getCreatedCollectionCount(api);143 await transferExpectFailure(fungibleCollectionCount + 1, 0, alice, bob, 1);144 await transferExpectFailure(fungibleCollectionCount + 1, 0, alice, bob, 1);144 // reFungible145 // reFungible145 const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();146 const reFungibleCollectionCount = await getCreatedCollectionCount(api);146 await transferExpectFailure(reFungibleCollectionCount + 1, 1, alice, bob, 1);147 await transferExpectFailure(reFungibleCollectionCount + 1, 1, alice, bob, 1);147 });148 });148 });149 });tests/src/transferFrom.test.tsdiffbeforeafterboth19 transferFromExpectSuccess,19 transferFromExpectSuccess,20 burnItemExpectSuccess,20 burnItemExpectSuccess,21 setCollectionLimitsExpectSuccess,21 setCollectionLimitsExpectSuccess,22 getCreatedCollectionCount,22} from './util/helpers';23} from './util/helpers';232424chai.use(chaiAsPromised);25chai.use(chaiAsPromised);109 it('transferFrom for a collection that does not exist', async () => {110 it('transferFrom for a collection that does not exist', async () => {110 await usingApi(async (api: ApiPromise) => {111 await usingApi(async (api: ApiPromise) => {111 // nft112 // nft112 const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();113 const nftCollectionCount = await getCreatedCollectionCount(api);113 await approveExpectFail(nftCollectionCount + 1, 1, alice, bob);114 await approveExpectFail(nftCollectionCount + 1, 1, alice, bob);114115115 await transferFromExpectFail(nftCollectionCount + 1, 1, bob, alice, charlie, 1);116 await transferFromExpectFail(nftCollectionCount + 1, 1, bob, alice, charlie, 1);116117117 // fungible118 // fungible118 const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();119 const fungibleCollectionCount = await getCreatedCollectionCount(api);119 await approveExpectFail(fungibleCollectionCount + 1, 0, alice, bob);120 await approveExpectFail(fungibleCollectionCount + 1, 0, alice, bob);120121121 await transferFromExpectFail(fungibleCollectionCount + 1, 0, bob, alice, charlie, 1);122 await transferFromExpectFail(fungibleCollectionCount + 1, 0, bob, alice, charlie, 1);122 // reFungible123 // reFungible123 const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();124 const reFungibleCollectionCount = await getCreatedCollectionCount(api);124 await approveExpectFail(reFungibleCollectionCount + 1, 1, alice, bob);125 await approveExpectFail(reFungibleCollectionCount + 1, 1, alice, bob);125126126 await transferFromExpectFail(reFungibleCollectionCount + 1, 1, bob, alice, charlie, 1);127 await transferFromExpectFail(reFungibleCollectionCount + 1, 1, bob, alice, charlie, 1);tests/src/util/helpers.tsdiffbeforeafterboth269 let collectionId = 0;269 let collectionId = 0;270 await usingApi(async (api) => {270 await usingApi(async (api) => {271 // Get number of collections before the transaction271 // Get number of collections before the transaction272 const collectionCountBefore = (await api.query.common.createdCollectionCount()).toNumber();272 const collectionCountBefore = await getCreatedCollectionCount(api);273273274 // Run the CreateCollection transaction274 // Run the CreateCollection transaction275 const alicePrivateKey = privateKey('//Alice');275 const alicePrivateKey = privateKey('//Alice');288 const result = getCreateCollectionResult(events);288 const result = getCreateCollectionResult(events);289289290 // Get number of collections after the transaction290 // Get number of collections after the transaction291 const collectionCountAfter = (await api.query.common.createdCollectionCount()).toNumber();291 const collectionCountAfter = await getCreatedCollectionCount(api);292292293 // Get the collection293 // Get the collection294 const collection = (await api.query.common.collectionById(result.collectionId)).unwrap();294 const collection = await queryCollectionExpectSuccess(api, result.collectionId);295295296 // What to expect296 // What to expect297 // tslint:disable-next-line:no-unused-expression297 // tslint:disable-next-line:no-unused-expression325325326 await usingApi(async (api) => {326 await usingApi(async (api) => {327 // Get number of collections before the transaction327 // Get number of collections before the transaction328 const collectionCountBefore = (await api.query.common.createdCollectionCount()).toNumber();328 const collectionCountBefore = await getCreatedCollectionCount(api);329329330 // Run the CreateCollection transaction330 // Run the CreateCollection transaction331 const alicePrivateKey = privateKey('//Alice');331 const alicePrivateKey = privateKey('//Alice');334 const result = getCreateCollectionResult(events);334 const result = getCreateCollectionResult(events);335335336 // Get number of collections after the transaction336 // Get number of collections after the transaction337 const collectionCountAfter = (await api.query.common.createdCollectionCount()).toNumber();337 const collectionCountAfter = await getCreatedCollectionCount(api);338338339 // What to expect339 // What to expect340 // tslint:disable-next-line:no-unused-expression340 // tslint:disable-next-line:no-unused-expression364}364}365365366export async function findNotExistingCollection(api: ApiPromise): Promise<number> {366export async function findNotExistingCollection(api: ApiPromise): Promise<number> {367 const totalNumber = (await api.query.common.createdCollectionCount()).toNumber();367 const totalNumber = await getCreatedCollectionCount(api);368 const newCollection: number = totalNumber + 1;368 const newCollection: number = totalNumber + 1;369 return newCollection;369 return newCollection;370}370}398 expect(result).to.be.true;398 expect(result).to.be.true;399399400 // What to expect400 // What to expect401 expect((await api.query.common.collectionById(collectionId)).isNone).to.be.true;401 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;402 });402 });403}403}404404432 const result = getGenericResult(events);432 const result = getGenericResult(events);433433434 // Get the collection434 // Get the collection435 const collection = (await api.query.common.collectionById(collectionId)).unwrap();435 const collection = await queryCollectionExpectSuccess(api, collectionId);436436437 // What to expect437 // What to expect438 expect(result.success).to.be.true;438 expect(result.success).to.be.true;452 const result = getGenericResult(events);452 const result = getGenericResult(events);453453454 // Get the collection454 // Get the collection455 const collection = (await api.query.common.collectionById(collectionId)).unwrap();455 const collection = await queryCollectionExpectSuccess(api, collectionId);456456457 // What to expect457 // What to expect458 expect(result.success).to.be.true;458 expect(result.success).to.be.true;490 const result = getGenericResult(events);490 const result = getGenericResult(events);491491492 // Get the collection492 // Get the collection493 const collection = (await api.query.common.collectionById(collectionId)).unwrap();493 const collection = await queryCollectionExpectSuccess(api, collectionId);494494495 // What to expect495 // What to expect496 expect(result.success).to.be.true;496 expect(result.success).to.be.true;1058 const result = getGenericResult(events);1058 const result = getGenericResult(events);105910591060 // Get the collection1060 // Get the collection1061 const collection = (await api.query.common.collectionById(collectionId)).unwrap();1061 const collection = await queryCollectionExpectSuccess(api, collectionId);106210621063 // What to expect1063 // What to expect1064 // tslint:disable-next-line:no-unused-expression1064 // tslint:disable-next-line:no-unused-expression1106 expect(result.success).to.be.true;1106 expect(result.success).to.be.true;110711071108 // Get the collection1108 // Get the collection1109 const collection = (await api.query.common.collectionById(collectionId)).unwrap();1109 const collection = await queryCollectionExpectSuccess(api, collectionId);111011101111 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1111 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1112 });1112 });1138 });1138 });1139}1139}114011401141export async function isAllowlisted(collectionId: number, address: string | CrossAccountId) {1141export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1142 return await usingApi(async (api) => {1142 return (await api.rpc.nft.allowed(collectionId, normalizeAccountId(address))).toJSON();1143 return (await api.query.common.allowlist(collectionId, normalizeAccountId(address))).toJSON();1144 });1145}1143}114611441147export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1145export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1148 await usingApi(async (api) => {1146 await usingApi(async (api) => {1149 expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.false;1147 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;115011481151 // Run the transaction1149 // Run the transaction1152 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));1150 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));1153 const events = await submitTransactionAsync(sender, tx);1151 const events = await submitTransactionAsync(sender, tx);1154 const result = getGenericResult(events);1152 const result = getGenericResult(events);1155 expect(result.success).to.be.true;1153 expect(result.success).to.be.true;115611541157 expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;1155 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1158 });1156 });1159}1157}116011581161export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1159export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1162 await usingApi(async (api) => {1160 await usingApi(async (api) => {116311611164 expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;1162 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;116511631166 // Run the transaction1164 // Run the transaction1167 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));1165 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));1168 const events = await submitTransactionAsync(sender, tx);1166 const events = await submitTransactionAsync(sender, tx);1169 const result = getGenericResult(events);1167 const result = getGenericResult(events);1170 expect(result.success).to.be.true;1168 expect(result.success).to.be.true;117111691172 expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;1170 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1173 });1171 });1174}1172}11751173121512131216export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1214export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1217 : Promise<NftDataStructsCollection | null> => {1215 : Promise<NftDataStructsCollection | null> => {1218 return (await api.query.common.collectionById(collectionId)).unwrapOr(null);1216 return (await api.rpc.nft.collectionById(collectionId)).unwrapOr(null);1219};1217};122012181221export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1219export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1222 // set global object - collectionsCount1220 // set global object - collectionsCount1223 return (await api.query.common.createdCollectionCount()).toNumber();1221 return (await api.rpc.nft.collectionStats()).created.toNumber();1224};1222};122512231226export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<NftDataStructsCollection> {1224export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<NftDataStructsCollection> {1227 return (await api.query.common.collectionById(collectionId)).unwrap();1225 return (await api.rpc.nft.collectionById(collectionId)).unwrap();1228}1226}122912271230export async function waitNewBlocks(blocksCount = 1): Promise<void> {1228export async function waitNewBlocks(blocksCount = 1): Promise<void> {