git.delta.rocks / unique-network / refs/commits / bba462e4a170

difftreelog

Merge pull request #232 from UniqueNetwork/refactor/pallet-common-rpcs

kozyrevdev2021-11-23parents: #55bb4eb #8b6a5ec.patch.diff
in: master
Prefer api.rpc.nft to api.query.common

38 files changed

modified.devcontainer/devcontainer.jsondiffbeforeafterboth
1{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",
modified.devcontainer/docker-compose.ymldiffbeforeafterboth
1version: '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=jaeger
8 - JAEGER_AGENT_PORT=68318 - JAEGER_AGENT_PORT=6831
9 volumes:9 volumes:
10 - ..:/workspaces/nft_private:cached10 - ..:/workspaces/unique-chain:cached
11 - ../../polkadot:/workspaces/polkadot:cached11 - ../../polkadot:/workspaces/polkadot:cached
12 - ../../polkadot-launch:/workspaces/polkadot-launch:cached12 - ../../polkadot-launch:/workspaces/polkadot-launch:cached
13 #- ../../frontier:/workspaces/frontier13 #- ../../frontier:/workspaces/frontier
modified.github/workflows/node_build_test.ymldiffbeforeafterboth
32 key: ${{ secrets.KEY }}32 key: ${{ secrets.KEY }}
33 port: ${{ secrets.SERVER_PORT }}33 port: ${{ secrets.SERVER_PORT }}
34 command_timeout: 300m34 command_timeout: 300m
35 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_hub
38 git clone git@github.com:UniqueNetwork/nft_private.git38 git clone git@github.com:UniqueNetwork/unique-chain.git
39 cd nft_private39 cd unique-chain
40 git checkout develop40 git checkout develop
41 # git pull --all41 # git pull --all
42 chmod +x ci_node.sh42 chmod +x ci_node.sh
43 ./ci_node.sh43 ./ci_node.sh
44 rm -rf /home/polkadot/nft_private44 rm -rf /home/polkadot/unique-chain
4545
modifiedDockerfile-parachaindiffbeforeafterboth
98 npm install --global yarn && \98 npm install --global yarn && \
99 yarn99 yarn
100100
101COPY --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/
103103
104CMD export NVM_DIR="$HOME/.nvm" && \104CMD export NVM_DIR="$HOME/.nvm" && \
modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
3use 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}
92107
93pub struct Nft<C, P> {108pub struct Nft<C, P> {
160175
161 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}
165183
modifiedlaunch-config.jsondiffbeforeafterboth
55 },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": [
modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
19pub 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());
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
12 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>;
8282
83 fn deref(&self) -> &Self::Target {83 fn deref(&self) -> &Self::Target {
84 &self.collection84 &self.collection
311 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 >;
317317
345 QueryKind = ValueQuery,345 QueryKind = ValueQuery,
346 >;346 >;
347
348 /// Not used by code, exists only to provide some types to metadata
349 #[pallet::storage]
350 pub type DummyStorageValue<T> =
351 StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;
347}352}
348353
349impl<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}
359386
360impl<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,
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
91}91}
9292
93impl<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>,
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
42 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)?;
195195
196 // Create new collection196 // Create new collection
197 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 };
213213
214 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 params
218 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 };
225225
954 }954 }
955}955}
956
957// 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}
970956
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
133133
134// unchecked calls skips any permission checks134// unchecked calls skips any permission checks
135impl<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>,
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
156156
157// unchecked calls skips any permission checks157// unchecked calls skips any permission checks
158impl<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>,
modifiedprimitives/nft/src/lib.rsdiffbeforeafterboth
209209
210#[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 char
219 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 restrictions
224 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}
427
428#[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}
427435
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
1#![cfg_attr(not(feature = "std"), no_std)]1#![cfg_attr(not(feature = "std"), no_std)]
22
3use 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;
3232
33 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}
3841
modifiedruntime/src/lib.rsdiffbeforeafterboth
1045 .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 }
10571066
1058 impl sp_api::Core<Block> for Runtime {1067 impl sp_api::Core<Block> for Runtime {
modifiedtests/src/addCollectionAdmin.test.tsdiffbeforeafterboth
8import 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';
1212
13chai.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');
2222
23 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);
2525
26 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');
4040
41 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);
4343
44 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));44 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
modifiedtests/src/addToAllowList.test.tsdiffbeforeafterboth
18 normalizeAccountId,18 normalizeAccountId,
19 addCollectionAdminExpectSuccess,19 addCollectionAdminExpectSuccess,
20 addToAllowListExpectFail,20 addToAllowListExpectFail,
21 getCreatedCollectionCount,
21} from './util/helpers';22} from './util/helpers';
2223
23chai.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-bitwise
58 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');
6061
61 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(bob.address));62 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(bob.address));
modifiedtests/src/approve.test.tsdiffbeforeafterboth
18 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 // nft
414 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 // fungible
417 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 // reFungible
420 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 });
modifiedtests/src/change-collection-owner.test.tsdiffbeforeafterboth
22 setMintPermissionExpectFailure,22 setMintPermissionExpectFailure,
23 destroyCollectionExpectFailure,23 destroyCollectionExpectFailure,
24 setPublicAccessModeExpectSuccess,24 setPublicAccessModeExpectSuccess,
25 queryCollectionExpectSuccess,
25} from './util/helpers';26} from './util/helpers';
2627
27chai.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');
3637
37 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);
3940
40 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);
4243
43 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');
5556
56 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);
5859
59 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;
6465
65 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');
7677
77 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);
7980
80 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);
8283
83 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);
8586
86 // 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 owner
118 const bob = privateKey('//Bob');119 const bob = privateKey('//Bob');
119 const charlie = privateKey('//Charlie');120 const charlie = privateKey('//Charlie');
120121
121 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);
123124
124 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);
126127
127 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);
129130
130 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);
132133
133 // ownership lost134 // ownership lost
134 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;
149150
150 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);
152153
153 // 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;
168169
169 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);
171172
172 // 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');
197198
198 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);
200201
201 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;
206207
207 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);
209210
210 await setCollectionSponsorExpectFailure(collectionId, charlie.address, '//Alice');211 await setCollectionSponsorExpectFailure(collectionId, charlie.address, '//Alice');
modifiedtests/src/confirmSponsorship.test.tsdiffbeforeafterboth
20 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 existed
331 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 });
335336
336 await confirmSponsorshipExpectFailure(collectionId, '//Bob');337 await confirmSponsorshipExpectFailure(collectionId, '//Bob');
modifiedtests/src/contracts.test.tsdiffbeforeafterboth
228 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);
230230
231 expect(await isAllowlisted(collectionId, bob.address)).to.be.false;231 expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
232232
233 {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;
238238
239 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;
246246
247 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 });
modifiedtests/src/createMultipleItems.test.tsdiffbeforeafterboth
20 getLastTokenId,20 getLastTokenId,
21 getVariableMetadata,21 getVariableMetadata,
22 getConstMetadata,22 getConstMetadata,
23 getCreatedCollectionCount,
23} from './util/helpers';24} from './util/helpers';
2425
25chai.use(chaiAsPromised);26chai.use(chaiAsPromised);
273274
274 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.nft
278 .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;
modifiedtests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth
14 createItemExpectSuccess,14 createItemExpectSuccess,
15 getGenericResult,15 getGenericResult,
16 transferExpectSuccess,16 transferExpectSuccess,
17 UNIQUE,
17} from './util/helpers';18} from './util/helpers';
1819
19import {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);
173174
174 // 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 });
180180
modifiedtests/src/destroyCollection.test.tsdiffbeforeafterboth
13 destroyCollectionExpectFailure,13 destroyCollectionExpectFailure,
14 setCollectionLimitsExpectSuccess,14 setCollectionLimitsExpectSuccess,
15 addCollectionAdminExpectSuccess,15 addCollectionAdminExpectSuccess,
16 getCreatedCollectionCount,
16} from './util/helpers';17} from './util/helpers';
1718
18chai.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 existed
49 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 });
modifiedtests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth
1// Auto-generated via `yarn polkadot-types-from-chain`, do not edit1// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
2/* eslint-disable */2/* eslint-disable */
33
4import 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 amount
373 **/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 collection
377 **/
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 allowlist
377 **/381 **/
380 * Get amount of specific account token384 * Get amount of specific account token
381 **/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 id
389 **/
390 collectionById: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<NftDataStructsCollection>>>;
391 /**
392 * Get collection stats
393 **/
394 collectionStats: AugmentedRpc<(at?: Hash | string | Uint8Array) => Observable<NftDataStructsCollectionStats>>;
383 /**395 /**
384 * Get tokens contained in collection396 * Get tokens contained in collection
385 **/397 **/
modifiedtests/src/interfaces/augment-types.tsdiffbeforeafterboth
2/* eslint-disable */2/* eslint-disable */
33
4import 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;
modifiedtests/src/interfaces/nft/definitions.tsdiffbeforeafterboth
40 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'),
modifiedtests/src/interfaces/nft/types.tsdiffbeforeafterboth
48 readonly dummyCollectionMode: u32;48 readonly dummyCollectionMode: u32;
49}49}
50
51/** @name NftDataStructsCollectionStats */
52export interface NftDataStructsCollectionStats extends Struct {
53 readonly created: u32;
54 readonly destroyed: u32;
55 readonly alive: u32;
56}
5057
51/** @name NftDataStructsCreateItemData */58/** @name NftDataStructsCreateItemData */
52export interface NftDataStructsCreateItemData extends Struct {59export interface NftDataStructsCreateItemData extends Struct {
modifiedtests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth
8import 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';
1212
13chai.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 Bob
25 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 Bob
49 const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));49 const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
modifiedtests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth
18 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 existed
99 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 });
103104
104 await removeCollectionSponsorExpectFailure(collectionId);105 await removeCollectionSponsorExpectFailure(collectionId);
modifiedtests/src/removeFromAllowList.test.tsdiffbeforeafterboth
37 });37 });
3838
39 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);
4444
45 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 });
4949
104 });104 });
105105
106 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 });
116116
modifiedtests/src/setCollectionSponsor.test.tsdiffbeforeafterboth
11 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 existed
78 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 });
8283
83 await setCollectionSponsorExpectFailure(collectionId, bob.address);84 await setCollectionSponsorExpectFailure(collectionId, bob.address);
modifiedtests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth
12 createCollectionExpectSuccess,12 createCollectionExpectSuccess,
13 destroyCollectionExpectSuccess,13 destroyCollectionExpectSuccess,
14 addCollectionAdminExpectSuccess,14 addCollectionAdminExpectSuccess,
15 queryCollectionExpectSuccess,
16 getCreatedCollectionCount,
15} from './util/helpers';17} from './util/helpers';
1618
17chai.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: radix
74 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;
modifiedtests/src/setPublicAccessMode.test.tsdiffbeforeafterboth
19 enableAllowListExpectSuccess,19 enableAllowListExpectSuccess,
20 normalizeAccountId,20 normalizeAccountId,
21 addCollectionAdminExpectSuccess,21 addCollectionAdminExpectSuccess,
22 getCreatedCollectionCount,
22} from './util/helpers';23} from './util/helpers';
2324
24chai.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: radix
63 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 });
modifiedtests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth
12 createCollectionExpectSuccess,12 createCollectionExpectSuccess,
13 destroyCollectionExpectSuccess,13 destroyCollectionExpectSuccess,
14 addCollectionAdminExpectSuccess,14 addCollectionAdminExpectSuccess,
15 queryCollectionExpectSuccess,
16 getCreatedCollectionCount,
15} from './util/helpers';17} from './util/helpers';
1618
17chai.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);
5456
55 });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);
8082
81 });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: radix
90 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;
modifiedtests/src/transfer.test.tsdiffbeforeafterboth
19 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 // nft
139 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 // fungible
142 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 // reFungible
145 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 });
modifiedtests/src/transferFrom.test.tsdiffbeforeafterboth
19 transferFromExpectSuccess,19 transferFromExpectSuccess,
20 burnItemExpectSuccess,20 burnItemExpectSuccess,
21 setCollectionLimitsExpectSuccess,21 setCollectionLimitsExpectSuccess,
22 getCreatedCollectionCount,
22} from './util/helpers';23} from './util/helpers';
2324
24chai.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 // nft
112 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);
114115
115 await transferFromExpectFail(nftCollectionCount + 1, 1, bob, alice, charlie, 1);116 await transferFromExpectFail(nftCollectionCount + 1, 1, bob, alice, charlie, 1);
116117
117 // fungible118 // fungible
118 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);
120121
121 await transferFromExpectFail(fungibleCollectionCount + 1, 0, bob, alice, charlie, 1);122 await transferFromExpectFail(fungibleCollectionCount + 1, 0, bob, alice, charlie, 1);
122 // reFungible123 // reFungible
123 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);
125126
126 await transferFromExpectFail(reFungibleCollectionCount + 1, 1, bob, alice, charlie, 1);127 await transferFromExpectFail(reFungibleCollectionCount + 1, 1, bob, alice, charlie, 1);
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
269 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 transaction
272 const collectionCountBefore = (await api.query.common.createdCollectionCount()).toNumber();272 const collectionCountBefore = await getCreatedCollectionCount(api);
273273
274 // Run the CreateCollection transaction274 // Run the CreateCollection transaction
275 const alicePrivateKey = privateKey('//Alice');275 const alicePrivateKey = privateKey('//Alice');
288 const result = getCreateCollectionResult(events);288 const result = getCreateCollectionResult(events);
289289
290 // Get number of collections after the transaction290 // Get number of collections after the transaction
291 const collectionCountAfter = (await api.query.common.createdCollectionCount()).toNumber();291 const collectionCountAfter = await getCreatedCollectionCount(api);
292292
293 // Get the collection293 // Get the collection
294 const collection = (await api.query.common.collectionById(result.collectionId)).unwrap();294 const collection = await queryCollectionExpectSuccess(api, result.collectionId);
295295
296 // What to expect296 // What to expect
297 // tslint:disable-next-line:no-unused-expression297 // tslint:disable-next-line:no-unused-expression
325325
326 await usingApi(async (api) => {326 await usingApi(async (api) => {
327 // Get number of collections before the transaction327 // Get number of collections before the transaction
328 const collectionCountBefore = (await api.query.common.createdCollectionCount()).toNumber();328 const collectionCountBefore = await getCreatedCollectionCount(api);
329329
330 // Run the CreateCollection transaction330 // Run the CreateCollection transaction
331 const alicePrivateKey = privateKey('//Alice');331 const alicePrivateKey = privateKey('//Alice');
334 const result = getCreateCollectionResult(events);334 const result = getCreateCollectionResult(events);
335335
336 // Get number of collections after the transaction336 // Get number of collections after the transaction
337 const collectionCountAfter = (await api.query.common.createdCollectionCount()).toNumber();337 const collectionCountAfter = await getCreatedCollectionCount(api);
338338
339 // What to expect339 // What to expect
340 // tslint:disable-next-line:no-unused-expression340 // tslint:disable-next-line:no-unused-expression
364}364}
365365
366export 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;
399399
400 // What to expect400 // What to expect
401 expect((await api.query.common.collectionById(collectionId)).isNone).to.be.true;401 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;
402 });402 });
403}403}
404404
432 const result = getGenericResult(events);432 const result = getGenericResult(events);
433433
434 // Get the collection434 // Get the collection
435 const collection = (await api.query.common.collectionById(collectionId)).unwrap();435 const collection = await queryCollectionExpectSuccess(api, collectionId);
436436
437 // What to expect437 // What to expect
438 expect(result.success).to.be.true;438 expect(result.success).to.be.true;
452 const result = getGenericResult(events);452 const result = getGenericResult(events);
453453
454 // Get the collection454 // Get the collection
455 const collection = (await api.query.common.collectionById(collectionId)).unwrap();455 const collection = await queryCollectionExpectSuccess(api, collectionId);
456456
457 // What to expect457 // What to expect
458 expect(result.success).to.be.true;458 expect(result.success).to.be.true;
490 const result = getGenericResult(events);490 const result = getGenericResult(events);
491491
492 // Get the collection492 // Get the collection
493 const collection = (await api.query.common.collectionById(collectionId)).unwrap();493 const collection = await queryCollectionExpectSuccess(api, collectionId);
494494
495 // What to expect495 // What to expect
496 expect(result.success).to.be.true;496 expect(result.success).to.be.true;
1058 const result = getGenericResult(events);1058 const result = getGenericResult(events);
10591059
1060 // Get the collection1060 // Get the collection
1061 const collection = (await api.query.common.collectionById(collectionId)).unwrap();1061 const collection = await queryCollectionExpectSuccess(api, collectionId);
10621062
1063 // What to expect1063 // What to expect
1064 // tslint:disable-next-line:no-unused-expression1064 // tslint:disable-next-line:no-unused-expression
1106 expect(result.success).to.be.true;1106 expect(result.success).to.be.true;
11071107
1108 // Get the collection1108 // Get the collection
1109 const collection = (await api.query.common.collectionById(collectionId)).unwrap();1109 const collection = await queryCollectionExpectSuccess(api, collectionId);
11101110
1111 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1111 expect(collection.mintMode.toHuman()).to.be.equal(enabled);
1112 });1112 });
1138 });1138 });
1139}1139}
11401140
1141export 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}
11461144
1147export 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;
11501148
1151 // Run the transaction1149 // Run the transaction
1152 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;
11561154
1157 expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;1155 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
1158 });1156 });
1159}1157}
11601158
1161export 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) => {
11631161
1164 expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;1162 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
11651163
1166 // Run the transaction1164 // Run the transaction
1167 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;
11711169
1172 expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;1170 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
1173 });1171 });
1174}1172}
11751173
12151213
1216export 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};
12201218
1221export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1219export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {
1222 // set global object - collectionsCount1220 // set global object - collectionsCount
1223 return (await api.query.common.createdCollectionCount()).toNumber();1221 return (await api.rpc.nft.collectionStats()).created.toNumber();
1224};1222};
12251223
1226export 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}
12291227
1230export async function waitNewBlocks(blocksCount = 1): Promise<void> {1228export async function waitNewBlocks(blocksCount = 1): Promise<void> {