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.jsondiffbeforeafterboth--- a/.devcontainer/devcontainer.json
+++ b/.devcontainer/devcontainer.json
@@ -1,8 +1,8 @@
{
"name": "Rust",
"dockerComposeFile": "./docker-compose.yml",
- "service": "nft_private",
- "workspaceFolder": "/workspaces/nft_private",
+ "service": "unique-chain",
+ "workspaceFolder": "/workspaces/unique-chain",
"settings": {
"terminal.integrated.shell.linux": "/bin/bash",
"lldb.executable": "/usr/bin/lldb",
.devcontainer/docker-compose.ymldiffbeforeafterboth--- a/.devcontainer/docker-compose.yml
+++ b/.devcontainer/docker-compose.yml
@@ -1,13 +1,13 @@
version: '3'
services:
- nft_private:
+ unique-chain:
build:
context: .
environment:
- JAEGER_AGENT_HOST=jaeger
- JAEGER_AGENT_PORT=6831
volumes:
- - ..:/workspaces/nft_private:cached
+ - ..:/workspaces/unique-chain:cached
- ../../polkadot:/workspaces/polkadot:cached
- ../../polkadot-launch:/workspaces/polkadot-launch:cached
#- ../../frontier:/workspaces/frontier
.github/workflows/node_build_test.ymldiffbeforeafterboth--- a/.github/workflows/node_build_test.yml
+++ b/.github/workflows/node_build_test.yml
@@ -35,10 +35,10 @@
script: |
eval $(ssh-agent -s)
ssh-add /home/devops/.ssh/git_hub
- git clone git@github.com:UniqueNetwork/nft_private.git
- cd nft_private
+ git clone git@github.com:UniqueNetwork/unique-chain.git
+ cd unique-chain
git checkout develop
# git pull --all
chmod +x ci_node.sh
./ci_node.sh
- rm -rf /home/polkadot/nft_private
+ rm -rf /home/polkadot/unique-chain
Dockerfile-parachaindiffbeforeafterboth--- a/Dockerfile-parachain
+++ b/Dockerfile-parachain
@@ -98,7 +98,7 @@
npm install --global yarn && \
yarn
-COPY --from=builder /nft_parachain/target/$PROFILE/nft /nft_private/target/$PROFILE/
+COPY --from=builder /nft_parachain/target/$PROFILE/nft /unique-chain/target/$PROFILE/
COPY --from=builder-polkadot /nft_parachain/polkadot/target/$PROFILE/polkadot /polkadot/target/$PROFILE/
CMD export NVM_DIR="$HOME/.nvm" && \
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -3,7 +3,7 @@
use codec::Decode;
use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
use jsonrpc_derive::rpc;
-use nft_data_structs::{CollectionId, TokenId};
+use nft_data_structs::{Collection, CollectionId, CollectionStats, TokenId};
use sp_api::{BlockId, BlockT, ProvideRuntimeApi};
use sp_blockchain::HeaderBackend;
use up_rpc::NftApi as NftRuntimeApi;
@@ -86,8 +86,23 @@
collection: CollectionId,
at: Option<BlockHash>,
) -> Result<Vec<CrossAccountId>>;
+ #[rpc(name = "nft_allowed")]
+ fn allowed(
+ &self,
+ collection: CollectionId,
+ user: CrossAccountId,
+ at: Option<BlockHash>,
+ ) -> Result<bool>;
#[rpc(name = "nft_lastTokenId")]
fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;
+ #[rpc(name = "nft_collectionById")]
+ fn collection_by_id(
+ &self,
+ collection: CollectionId,
+ at: Option<BlockHash>,
+ ) -> Result<Option<Collection<AccountId>>>;
+ #[rpc(name = "nft_collectionStats")]
+ fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;
}
pub struct Nft<C, P> {
@@ -160,5 +175,8 @@
pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>);
pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>);
+ pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool);
pass_method!(last_token_id(collection: CollectionId) -> TokenId);
+ pass_method!(collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>>);
+ pass_method!(collection_stats() -> CollectionStats);
}
launch-config.jsondiffbeforeafterboth--- a/launch-config.json
+++ b/launch-config.json
@@ -55,7 +55,7 @@
},
"parachains": [
{
- "bin": "../nft_private/target/release/nft",
+ "bin": "../unique-chain/target/release/nft",
"id": "2000",
"balance": "1000000000000000000000",
"nodes": [
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -19,7 +19,7 @@
pub fn create_collection_raw<T: Config, R>(
owner: T::AccountId,
mode: CollectionMode,
- handler: impl FnOnce(Collection<T>) -> Result<CollectionId, DispatchError>,
+ handler: impl FnOnce(Collection<T::AccountId>) -> Result<CollectionId, DispatchError>,
cast: impl FnOnce(CollectionHandle<T>) -> R,
) -> Result<R, DispatchError> {
T::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -12,7 +12,7 @@
COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,
- WithdrawReasons,
+ WithdrawReasons, CollectionStats,
};
pub use pallet::*;
use sp_core::H160;
@@ -26,7 +26,7 @@
#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]
pub struct CollectionHandle<T: Config> {
pub id: CollectionId,
- collection: Collection<T>,
+ collection: Collection<T::AccountId>,
pub recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,
}
impl<T: Config> CollectionHandle<T> {
@@ -78,7 +78,7 @@
}
}
impl<T: Config> Deref for CollectionHandle<T> {
- type Target = Collection<T>;
+ type Target = Collection<T::AccountId>;
fn deref(&self) -> &Self::Target {
&self.collection
@@ -311,7 +311,7 @@
pub type CollectionById<T> = StorageMap<
Hasher = Blake2_128Concat,
Key = CollectionId,
- Value = Collection<T>,
+ Value = Collection<<T as frame_system::Config>::AccountId>,
QueryKind = OptionQuery,
>;
@@ -344,6 +344,11 @@
Value = bool,
QueryKind = ValueQuery,
>;
+
+ /// Not used by code, exists only to provide some types to metadata
+ #[pallet::storage]
+ pub type DummyStorageValue<T> =
+ StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;
}
impl<T: Config> Pallet<T> {
@@ -355,10 +360,32 @@
);
Ok(())
}
+ pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
+ <IsAdmin<T>>::iter_prefix((collection,))
+ .map(|(a, _)| a)
+ .collect()
+ }
+ pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
+ <Allowlist<T>>::iter_prefix((collection,))
+ .map(|(a, _)| a)
+ .collect()
+ }
+ pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {
+ <Allowlist<T>>::get((collection, user))
+ }
+ pub fn collection_stats() -> CollectionStats {
+ let created = <CreatedCollectionCount<T>>::get();
+ let destroyed = <DestroyedCollectionCount<T>>::get();
+ CollectionStats {
+ created: created.0,
+ destroyed: destroyed.0,
+ alive: created.0 - destroyed.0,
+ }
+ }
}
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
+ pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
{
ensure!(
data.name.len() <= MAX_COLLECTION_NAME_LENGTH,
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -91,8 +91,8 @@
}
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
- PalletCommon::init_collection(data)
+ pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(data)
}
pub fn destroy_collection(
collection: FungibleHandle<T>,
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -42,8 +42,8 @@
CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
};
use pallet_common::{
- account::CrossAccountId, CollectionHandle, IsAdmin, Pallet as PalletCommon,
- Error as CommonError, CommonWeightInfo, Allowlist,
+ account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
+ CommonWeightInfo,
};
use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};
use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
@@ -194,7 +194,7 @@
let who = ensure_signed(origin)?;
// Create new collection
- let new_collection = Collection::<T> {
+ let new_collection = Collection {
owner: who.clone(),
name: collection_name,
mode: mode.clone(),
@@ -212,14 +212,14 @@
};
let _id = match mode {
- CollectionMode::NFT => {PalletNonfungible::init_collection(new_collection)?},
+ CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(new_collection)?},
CollectionMode::Fungible(decimal_points) => {
// check params
ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
- PalletFungible::init_collection(new_collection)?
+ <PalletFungible<T>>::init_collection(new_collection)?
}
CollectionMode::ReFungible => {
- PalletRefungible::init_collection(new_collection)?
+ <PalletRefungible<T>>::init_collection(new_collection)?
}
};
@@ -951,19 +951,5 @@
target_collection.save()
}
- }
-}
-
-// TODO: limit returned entries?
-impl<T: Config> Pallet<T> {
- pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
- <IsAdmin<T>>::iter_prefix((collection,))
- .map(|(a, _)| a)
- .collect()
- }
- pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
- <Allowlist<T>>::iter_prefix((collection,))
- .map(|(a, _)| a)
- .collect()
}
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -133,8 +133,8 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
- PalletCommon::init_collection(data)
+ pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(data)
}
pub fn destroy_collection(
collection: NonfungibleHandle<T>,
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -156,8 +156,8 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
- PalletCommon::init_collection(data)
+ pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(data)
}
pub fn destroy_collection(
collection: RefungibleHandle<T>,
primitives/nft/src/lib.rsdiffbeforeafterboth--- a/primitives/nft/src/lib.rs
+++ b/primitives/nft/src/lib.rs
@@ -209,8 +209,8 @@
#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub struct Collection<T: frame_system::Config> {
- pub owner: T::AccountId,
+pub struct Collection<AccountId> {
+ pub owner: AccountId,
pub mode: CollectionMode,
pub access: AccessMode,
pub name: Vec<u16>, // 64 include null escape char
@@ -219,7 +219,7 @@
pub mint_mode: bool,
pub offchain_schema: Vec<u8>,
pub schema_version: SchemaVersion,
- pub sponsorship: SponsorshipState<T::AccountId>,
+ pub sponsorship: SponsorshipState<AccountId>,
pub limits: CollectionLimits, // Collection private restrictions
pub variable_on_chain_schema: Vec<u8>, //
pub const_on_chain_schema: Vec<u8>, //
@@ -424,3 +424,11 @@
CreateItemData::Fungible(item)
}
}
+
+#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct CollectionStats {
+ pub created: u32,
+ pub destroyed: u32,
+ pub alive: u32,
+}
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -1,6 +1,6 @@
#![cfg_attr(not(feature = "std"), no_std)]
-use nft_data_structs::{CollectionId, TokenId};
+use nft_data_structs::{CollectionId, TokenId, Collection, CollectionStats};
use sp_std::vec::Vec;
use sp_core::H160;
use codec::Decode;
@@ -32,6 +32,9 @@
fn adminlist(collection: CollectionId) -> Vec<CrossAccountId>;
fn allowlist(collection: CollectionId) -> Vec<CrossAccountId>;
+ fn allowed(collection: CollectionId, user: CrossAccountId) -> bool;
fn last_token_id(collection: CollectionId) -> TokenId;
+ fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>>;
+ fn collection_stats() -> CollectionStats;
}
}
runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -1045,14 +1045,23 @@
.or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))
}
fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {
- <pallet_nft::Pallet<Runtime>>::adminlist(collection)
+ <pallet_common::Pallet<Runtime>>::adminlist(collection)
}
fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {
- <pallet_nft::Pallet<Runtime>>::allowlist(collection)
+ <pallet_common::Pallet<Runtime>>::allowlist(collection)
+ }
+ fn allowed(collection: CollectionId, user: CrossAccountId) -> bool {
+ <pallet_common::Pallet<Runtime>>::allowed(collection, user)
}
fn last_token_id(collection: CollectionId) -> TokenId {
dispatch_nft_runtime!(collection.last_token_id())
}
+ fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>> {
+ <pallet_common::CollectionById<Runtime>>::get(collection)
+ }
+ fn collection_stats() -> CollectionStats {
+ <pallet_common::Pallet<Runtime>>::collection_stats()
+ }
}
impl sp_api::Core<Block> for Runtime {
tests/src/addCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/addCollectionAdmin.test.ts
+++ b/tests/src/addCollectionAdmin.test.ts
@@ -8,7 +8,7 @@
import chaiAsPromised from 'chai-as-promised';
import privateKey from './substrate/privateKey';
import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId} from './util/helpers';
+import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId, queryCollectionExpectSuccess} from './util/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -20,7 +20,7 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.equal(alice.address);
const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
@@ -38,7 +38,7 @@
const bob = privateKey('//Bob');
const charlie = privateKey('//CHARLIE');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.equal(alice.address);
const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
tests/src/addToAllowList.test.tsdiffbeforeafterboth--- a/tests/src/addToAllowList.test.ts
+++ b/tests/src/addToAllowList.test.ts
@@ -18,6 +18,7 @@
normalizeAccountId,
addCollectionAdminExpectSuccess,
addToAllowListExpectFail,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -55,7 +56,7 @@
it('Allow list an address in the collection that does not exist', async () => {
await usingApi(async (api) => {
// tslint:disable-next-line: no-bitwise
- const collectionId = ((await api.query.common.createdCollectionCount()).toNumber()) + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const bob = privateKey('//Bob');
const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(bob.address));
tests/src/approve.test.tsdiffbeforeafterboth--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -18,6 +18,7 @@
transferExpectSuccess,
addCollectionAdminExpectSuccess,
adminApproveFromExpectSuccess,
+ getCreatedCollectionCount,
transferFromExpectSuccess,
transferFromExpectFail,
} from './util/helpers';
@@ -411,13 +412,13 @@
it('Approve for a collection that does not exist', async () => {
await usingApi(async (api: ApiPromise) => {
// nft
- const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const nftCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(nftCollectionCount + 1, 1, alice, bob);
// fungible
- const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const fungibleCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(fungibleCollectionCount + 1, 0, alice, bob);
// reFungible
- const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const reFungibleCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(reFungibleCollectionCount + 1, 1, alice, bob);
});
});
tests/src/change-collection-owner.test.tsdiffbeforeafterboth--- a/tests/src/change-collection-owner.test.ts
+++ b/tests/src/change-collection-owner.test.ts
@@ -22,6 +22,7 @@
setMintPermissionExpectFailure,
destroyCollectionExpectFailure,
setPublicAccessModeExpectSuccess,
+ queryCollectionExpectSuccess,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -34,13 +35,13 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection =await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await submitTransactionAsync(alice, changeOwnerTx);
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
});
});
@@ -53,7 +54,7 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
@@ -62,7 +63,7 @@
const badChangeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, alice.address);
await expect(submitTransactionExpectFailAsync(alice, badChangeOwnerTx)).to.be.rejected;
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
});
});
@@ -74,13 +75,13 @@
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await submitTransactionAsync(alice, changeOwnerTx);
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
// After changing the owner of the collection, all privileged methods are available to the new owner
@@ -118,20 +119,20 @@
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await submitTransactionAsync(alice, changeOwnerTx);
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
const changeOwnerTx2 = api.tx.nft.changeCollectionOwner(collectionId, charlie.address);
await submitTransactionAsync(bob, changeOwnerTx2);
// ownership lost
- const collectionAfterOwnerChange2 = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange2 = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange2.owner.toString()).to.be.deep.eq(charlie.address);
});
});
@@ -147,7 +148,7 @@
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(alice.address);
// Verifying that nothing bad happened (network is live, new collections can be created, etc.)
@@ -166,7 +167,7 @@
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(alice.address);
// Verifying that nothing bad happened (network is live, new collections can be created, etc.)
@@ -195,7 +196,7 @@
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
@@ -204,7 +205,7 @@
const badChangeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, alice.address);
await expect(submitTransactionExpectFailAsync(alice, badChangeOwnerTx)).to.be.rejected;
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
await setCollectionSponsorExpectFailure(collectionId, charlie.address, '//Alice');
tests/src/confirmSponsorship.test.tsdiffbeforeafterboth--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -20,6 +20,7 @@
addToAllowListExpectSuccess,
normalizeAccountId,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
import {Keyring} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
@@ -330,7 +331,7 @@
// Find the collection that never existed
let collectionId = 0;
await usingApi(async (api) => {
- collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ collectionId = await getCreatedCollectionCount(api) + 1;
});
await confirmSponsorshipExpectFailure(collectionId, '//Bob');
tests/src/contracts.test.tsdiffbeforeafterboth--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -228,7 +228,7 @@
const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);
await submitTransactionAsync(alice, changeAdminTx);
- expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
{
const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, true);
@@ -236,7 +236,7 @@
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isAllowlisted(collectionId, bob.address)).to.be.true;
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.true;
}
{
const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, false);
@@ -244,7 +244,7 @@
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
}
});
});
tests/src/createMultipleItems.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -20,6 +20,7 @@
getLastTokenId,
getVariableMetadata,
getConstMetadata,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -273,7 +274,7 @@
it('Create token in not existing collection', async () => {
await usingApi(async (api: ApiPromise) => {
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const createMultipleItemsTx = api.tx.nft
.createMultipleItems(collectionId, normalizeAccountId(alice.address), ['NFT', 'NFT', 'NFT']);
await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTx)).to.be.rejected;
tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -14,6 +14,7 @@
createItemExpectSuccess,
getGenericResult,
transferExpectSuccess,
+ UNIQUE,
} from './util/helpers';
import {default as waitNewBlocks} from './substrate/wait-new-blocks';
@@ -169,12 +170,11 @@
const aliceBalanceBefore: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
await transferExpectSuccess(collectionId, tokenId, alice, bob, 1, 'NFT');
const aliceBalanceAfter: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
- const fee = aliceBalanceBefore - aliceBalanceAfter;
+ const fee = Number(aliceBalanceBefore - aliceBalanceAfter) / Number(UNIQUE);
- // console.log(fee.toString());
const expectedTransferFee = 0.1;
const tolerance = 0.001;
- expect(Number(fee) / 1e15 - expectedTransferFee).to.be.lessThan(tolerance);
+ expect(Number(fee) / Number(UNIQUE) - expectedTransferFee).to.be.lessThan(tolerance);
});
});
tests/src/destroyCollection.test.tsdiffbeforeafterboth--- a/tests/src/destroyCollection.test.ts
+++ b/tests/src/destroyCollection.test.ts
@@ -13,6 +13,7 @@
destroyCollectionExpectFailure,
setCollectionLimitsExpectSuccess,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -46,7 +47,7 @@
it('(!negative test!) Destroy a collection that never existed', async () => {
await usingApi(async (api) => {
// Find the collection that never existed
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
await destroyCollectionExpectFailure(collectionId);
});
});
tests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-rpc.ts
+++ b/tests/src/interfaces/augment-api-rpc.ts
@@ -1,7 +1,7 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
-import type { NftDataStructsCollectionId, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr } from './nft';
+import type { NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionStats, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr } from './nft';
import type { Bytes, HashMap, Json, Metadata, Null, Option, StorageKey, Text, U256, U64, Vec, bool, u128, u32, u64 } from '@polkadot/types';
import type { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';
import type { EpochAuthorship } from '@polkadot/types/interfaces/babe';
@@ -373,6 +373,10 @@
**/
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>>;
/**
+ * Check if user is allowed to use collection
+ **/
+ allowed: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, account: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<bool>>;
+ /**
* Get allowlist
**/
allowlist: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<PalletCommonAccountBasicCrossAccountIdRepr>>>;
@@ -381,6 +385,14 @@
**/
balance: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, account: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: NftDataStructsTokenId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
/**
+ * Get collection by specified id
+ **/
+ collectionById: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<NftDataStructsCollection>>>;
+ /**
+ * Get collection stats
+ **/
+ collectionStats: AugmentedRpc<(at?: Hash | string | Uint8Array) => Observable<NftDataStructsCollectionStats>>;
+ /**
* Get tokens contained in collection
**/
collectionTokens: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<NftDataStructsTokenId>>>;
tests/src/interfaces/augment-types.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -2,7 +2,7 @@
/* eslint-disable */
import type { EthereumBlock, EthereumLog, EthereumReceipt, EthereumTransactionLegacyTransaction, EvmCoreErrorExitReason, FpRpcTransactionStatus } from './ethereum';
-import type { NftDataStructsAccessMode, NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionLimits, NftDataStructsCollectionMode, NftDataStructsCreateItemData, NftDataStructsMetaUpdatePermission, NftDataStructsSchemaVersion, NftDataStructsSponsorshipState, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2 } from './nft';
+import type { NftDataStructsAccessMode, NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionLimits, NftDataStructsCollectionMode, NftDataStructsCollectionStats, NftDataStructsCreateItemData, NftDataStructsMetaUpdatePermission, NftDataStructsSchemaVersion, NftDataStructsSponsorshipState, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2 } from './nft';
import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundStatus, CumulusPalletXcmpQueueOutboundStatus, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV1AbridgedHostConfiguration, PolkadotPrimitivesV1PersistedValidationData } from './polkadot';
import 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';
import type { AssetApproval, AssetApprovalKey, AssetBalance, AssetDestroyWitness, AssetDetails, AssetMetadata, TAssetBalance, TAssetDepositBalance } from '@polkadot/types/interfaces/assets';
@@ -627,6 +627,7 @@
NftDataStructsCollectionId: NftDataStructsCollectionId;
NftDataStructsCollectionLimits: NftDataStructsCollectionLimits;
NftDataStructsCollectionMode: NftDataStructsCollectionMode;
+ NftDataStructsCollectionStats: NftDataStructsCollectionStats;
NftDataStructsCreateItemData: NftDataStructsCreateItemData;
NftDataStructsMetaUpdatePermission: NftDataStructsMetaUpdatePermission;
NftDataStructsSchemaVersion: NftDataStructsSchemaVersion;
tests/src/interfaces/nft/definitions.tsdiffbeforeafterboth--- a/tests/src/interfaces/nft/definitions.ts
+++ b/tests/src/interfaces/nft/definitions.ts
@@ -40,6 +40,9 @@
constMetadata: fun('Get token constant metadata', [collectionParam, tokenParam], 'Vec<u8>'),
variableMetadata: fun('Get token variable metadata', [collectionParam, tokenParam], 'Vec<u8>'),
tokenExists: fun('Check if token exists', [collectionParam, tokenParam], 'bool'),
+ collectionById: fun('Get collection by specified id', [collectionParam], 'Option<NftDataStructsCollection>'),
+ collectionStats: fun('Get collection stats', [], 'NftDataStructsCollectionStats'),
+ allowed: fun('Check if user is allowed to use collection', [collectionParam, crossAccountParam()], 'bool'),
},
types: {
PalletCommonAccountBasicCrossAccountIdRepr: {
@@ -64,6 +67,11 @@
constOnChainSchema: 'Vec<u8>',
metaUpdatePermission: 'NftDataStructsMetaUpdatePermission',
},
+ NftDataStructsCollectionStats: {
+ created: 'u32',
+ destroyed: 'u32',
+ alive: 'u32',
+ },
NftDataStructsCollectionId: 'u32',
NftDataStructsTokenId: 'u32',
PalletNonfungibleItemData: mkDummy('NftItemData'),
tests/src/interfaces/nft/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/nft/types.ts
+++ b/tests/src/interfaces/nft/types.ts
@@ -48,6 +48,13 @@
readonly dummyCollectionMode: u32;
}
+/** @name NftDataStructsCollectionStats */
+export interface NftDataStructsCollectionStats extends Struct {
+ readonly created: u32;
+ readonly destroyed: u32;
+ readonly alive: u32;
+}
+
/** @name NftDataStructsCreateItemData */
export interface NftDataStructsCreateItemData extends Struct {
readonly dummyCreateItemData: u32;
tests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionAdmin.test.ts
+++ b/tests/src/removeCollectionAdmin.test.ts
@@ -8,7 +8,7 @@
import chaiAsPromised from 'chai-as-promised';
import privateKey from './substrate/privateKey';
import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId} from './util/helpers';
+import {createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId, queryCollectionExpectSuccess} from './util/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -19,7 +19,7 @@
const collectionId = await createCollectionExpectSuccess();
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
// first - add collection admin Bob
const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
@@ -43,7 +43,7 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
// first - add collection admin Bob
const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
tests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionSponsor.test.ts
+++ b/tests/src/removeCollectionSponsor.test.ts
@@ -18,6 +18,7 @@
removeCollectionSponsorExpectFailure,
normalizeAccountId,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
import {Keyring} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
@@ -98,7 +99,7 @@
// Find the collection that never existed
let collectionId = 0;
await usingApi(async (api) => {
- collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ collectionId = await getCreatedCollectionCount(api) + 1;
});
await removeCollectionSponsorExpectFailure(collectionId);
tests/src/removeFromAllowList.test.tsdiffbeforeafterboth--- a/tests/src/removeFromAllowList.test.ts
+++ b/tests/src/removeFromAllowList.test.ts
@@ -37,13 +37,13 @@
});
it('ensure bob is not in allowlist after removal', async () => {
- await usingApi(async () => {
+ await usingApi(async api => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
await enableAllowListExpectSuccess(alice, collectionId);
await addToAllowListExpectSuccess(alice, collectionId, bob.address);
await removeFromAllowListExpectSuccess(alice, collectionId, normalizeAccountId(bob.address));
- expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
});
});
@@ -104,13 +104,13 @@
});
it('ensure address is not in allowlist after removal', async () => {
- await usingApi(async () => {
+ await usingApi(async api => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
await enableAllowListExpectSuccess(alice, collectionId);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
await removeFromAllowListExpectSuccess(bob, collectionId, normalizeAccountId(charlie.address));
- expect(await isAllowlisted(collectionId, charlie.address)).to.be.false;
+ expect(await isAllowlisted(api, collectionId, charlie.address)).to.be.false;
});
});
tests/src/setCollectionSponsor.test.tsdiffbeforeafterboth--- a/tests/src/setCollectionSponsor.test.ts
+++ b/tests/src/setCollectionSponsor.test.ts
@@ -11,6 +11,7 @@
destroyCollectionExpectSuccess,
setCollectionSponsorExpectFailure,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
import {Keyring} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
@@ -77,7 +78,7 @@
// Find the collection that never existed
let collectionId = 0;
await usingApi(async (api) => {
- collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ collectionId = await getCreatedCollectionCount(api) + 1;
});
await setCollectionSponsorExpectFailure(collectionId, bob.address);
tests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth--- a/tests/src/setConstOnChainSchema.test.ts
+++ b/tests/src/setConstOnChainSchema.test.ts
@@ -12,6 +12,8 @@
createCollectionExpectSuccess,
destroyCollectionExpectSuccess,
addCollectionAdminExpectSuccess,
+ queryCollectionExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -37,7 +39,7 @@
it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
await submitTransactionAsync(alice, setShema);
@@ -47,7 +49,7 @@
it('Collection admin can set the scheme', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
@@ -60,7 +62,7 @@
const collectionId = await createCollectionExpectSuccess();
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
await submitTransactionAsync(alice, setShema);
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.constOnChainSchema.toString()).to.be.eq(shema);
});
});
@@ -71,7 +73,7 @@
it('Set a non-existent collection', async () => {
await usingApi(async (api) => {
// tslint:disable-next-line: radix
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;
});
@@ -97,7 +99,7 @@
it('Execute method not on behalf of the collection owner', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
await expect(submitTransactionExpectFailAsync(bob, setShema)).to.be.rejected;
tests/src/setPublicAccessMode.test.tsdiffbeforeafterboth--- a/tests/src/setPublicAccessMode.test.ts
+++ b/tests/src/setPublicAccessMode.test.ts
@@ -19,6 +19,7 @@
enableAllowListExpectSuccess,
normalizeAccountId,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -60,7 +61,7 @@
it('Set a non-existent collection', async () => {
await usingApi(async (api: ApiPromise) => {
// tslint:disable-next-line: radix
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const tx = api.tx.nft.setPublicAccessMode(collectionId, 'AllowList');
await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
});
tests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth--- a/tests/src/setVariableOnChainSchema.test.ts
+++ b/tests/src/setVariableOnChainSchema.test.ts
@@ -12,6 +12,8 @@
createCollectionExpectSuccess,
destroyCollectionExpectSuccess,
addCollectionAdminExpectSuccess,
+ queryCollectionExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -37,7 +39,7 @@
it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await submitTransactionAsync(alice, setSchema);
@@ -49,7 +51,7 @@
const collectionId = await createCollectionExpectSuccess();
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await submitTransactionAsync(alice, setSchema);
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);
});
@@ -61,7 +63,7 @@
it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
@@ -75,7 +77,7 @@
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await submitTransactionAsync(bob, setSchema);
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);
});
@@ -87,7 +89,7 @@
it('Set a non-existent collection', async () => {
await usingApi(async (api) => {
// tslint:disable-next-line: radix
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
});
@@ -113,7 +115,7 @@
it('Execute method not on behalf of the collection owner', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await expect(submitTransactionExpectFailAsync(bob, setSchema)).to.be.rejected;
tests/src/transfer.test.tsdiffbeforeafterboth--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -19,6 +19,7 @@
transferExpectFailure,
transferExpectSuccess,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
toSubstrateAddress,
getTokenOwner,
normalizeAccountId,
@@ -136,13 +137,13 @@
it('Transfer with not existed collection_id', async () => {
await usingApi(async (api) => {
// nft
- const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const nftCollectionCount = await getCreatedCollectionCount(api);
await transferExpectFailure(nftCollectionCount + 1, 1, alice, bob, 1);
// fungible
- const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const fungibleCollectionCount = await getCreatedCollectionCount(api);
await transferExpectFailure(fungibleCollectionCount + 1, 0, alice, bob, 1);
// reFungible
- const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const reFungibleCollectionCount = await getCreatedCollectionCount(api);
await transferExpectFailure(reFungibleCollectionCount + 1, 1, alice, bob, 1);
});
});
tests/src/transferFrom.test.tsdiffbeforeafterboth--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -19,6 +19,7 @@
transferFromExpectSuccess,
burnItemExpectSuccess,
setCollectionLimitsExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -109,18 +110,18 @@
it('transferFrom for a collection that does not exist', async () => {
await usingApi(async (api: ApiPromise) => {
// nft
- const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const nftCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(nftCollectionCount + 1, 1, alice, bob);
await transferFromExpectFail(nftCollectionCount + 1, 1, bob, alice, charlie, 1);
// fungible
- const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const fungibleCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(fungibleCollectionCount + 1, 0, alice, bob);
await transferFromExpectFail(fungibleCollectionCount + 1, 0, bob, alice, charlie, 1);
// reFungible
- const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const reFungibleCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(reFungibleCollectionCount + 1, 1, alice, bob);
await transferFromExpectFail(reFungibleCollectionCount + 1, 1, bob, alice, charlie, 1);
tests/src/util/helpers.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import {ApiPromise, Keyring} from '@polkadot/api';7import type {AccountId, EventRecord} from '@polkadot/types/interfaces';8import {IKeyringPair} from '@polkadot/types/types';9import {evmToAddress} from '@polkadot/util-crypto';10import BN from 'bn.js';11import chai from 'chai';12import chaiAsPromised from 'chai-as-promised';13import {alicesPublicKey} from '../accounts';14import {NftDataStructsCollection} from '../interfaces';15import privateKey from '../substrate/privateKey';16import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';17import {hexToStr, strToUTF16, utf16ToStr} from './util';1819chai.use(chaiAsPromised);20const expect = chai.expect;2122export type CrossAccountId = {23 Substrate: string,24} | {25 Ethereum: string,26};27export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {28 if (typeof input === 'string') {29 if (input.length === 48 || input.length === 47) {30 return {Substrate: input};31 } else if (input.length === 42 && input.startsWith('0x')) {32 return {Ethereum: input.toLowerCase()};33 } else if (input.length === 40 && !input.startsWith('0x')) {34 return {Ethereum: '0x' + input.toLowerCase()};35 } else {36 throw new Error(`Unknown address format: "${input}"`);37 }38 }39 if ('address' in input) {40 return {Substrate: input.address};41 }42 if ('Ethereum' in input) {43 return {44 Ethereum: input.Ethereum.toLowerCase(),45 };46 } else if ('ethereum' in input) {47 return {48 Ethereum: (input as any).ethereum.toLowerCase(),49 };50 } else if ('Substrate' in input) {51 return input;52 }else if ('substrate' in input) {53 return {54 Substrate: (input as any).substrate,55 };56 }5758 // AccountId59 return {Substrate: input.toString()};60}61export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {62 input = normalizeAccountId(input);63 if ('Substrate' in input) {64 return input.Substrate;65 } else {66 return evmToAddress(input.Ethereum);67 }68}6970export const U128_MAX = (1n << 128n) - 1n;7172const MICROUNIQUE = 1_000_000_000n;73const MILLIUNIQUE = 1_000n * MICROUNIQUE;74const CENTIUNIQUE = 10n * MILLIUNIQUE;75export const UNIQUE = 100n * CENTIUNIQUE;7677type GenericResult = {78 success: boolean,79};8081interface CreateCollectionResult {82 success: boolean;83 collectionId: number;84}8586interface CreateItemResult {87 success: boolean;88 collectionId: number;89 itemId: number;90 recipient?: CrossAccountId;91}9293interface TransferResult {94 success: boolean;95 collectionId: number;96 itemId: number;97 sender?: CrossAccountId;98 recipient?: CrossAccountId;99 value: bigint;100}101102interface IReFungibleOwner {103 fraction: BN;104 owner: number[];105}106107interface IGetMessage {108 checkMsgNftMethod: string;109 checkMsgTrsMethod: string;110 checkMsgSysMethod: string;111}112113export interface IFungibleTokenDataType {114 value: number;115}116117export interface IChainLimits {118 collectionNumbersLimit: number;119 accountTokenOwnershipLimit: number;120 collectionsAdminsLimit: number;121 customDataLimit: number;122 nftSponsorTransferTimeout: number;123 fungibleSponsorTransferTimeout: number;124 refungibleSponsorTransferTimeout: number;125 offchainSchemaLimit: number;126 variableOnChainSchemaLimit: number;127 constOnChainSchemaLimit: number;128}129130export interface IReFungibleTokenDataType {131 owner: IReFungibleOwner[];132 constData: number[];133 variableData: number[];134}135136export function nftEventMessage(events: EventRecord[]): IGetMessage {137 let checkMsgNftMethod = '';138 let checkMsgTrsMethod = '';139 let checkMsgSysMethod = '';140 events.forEach(({event: {method, section}}) => {141 if (section === 'common') {142 checkMsgNftMethod = method;143 } else if (section === 'treasury') {144 checkMsgTrsMethod = method;145 } else if (section === 'system') {146 checkMsgSysMethod = method;147 } else { return null; }148 });149 const result: IGetMessage = {150 checkMsgNftMethod,151 checkMsgTrsMethod,152 checkMsgSysMethod,153 };154 return result;155}156157export function getGenericResult(events: EventRecord[]): GenericResult {158 const result: GenericResult = {159 success: false,160 };161 events.forEach(({event: {method}}) => {162 // console.log(` ${phase}: ${section}.${method}:: ${data}`);163 if (method === 'ExtrinsicSuccess') {164 result.success = true;165 }166 });167 return result;168}169170171172export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {173 let success = false;174 let collectionId = 0;175 events.forEach(({event: {data, method, section}}) => {176 // console.log(` ${phase}: ${section}.${method}:: ${data}`);177 if (method == 'ExtrinsicSuccess') {178 success = true;179 } else if ((section == 'common') && (method == 'CollectionCreated')) {180 collectionId = parseInt(data[0].toString(), 10);181 }182 });183 const result: CreateCollectionResult = {184 success,185 collectionId,186 };187 return result;188}189190export function getCreateItemResult(events: EventRecord[]): CreateItemResult {191 let success = false;192 let collectionId = 0;193 let itemId = 0;194 let recipient;195 events.forEach(({event: {data, method, section}}) => {196 // console.log(` ${phase}: ${section}.${method}:: ${data}`);197 if (method == 'ExtrinsicSuccess') {198 success = true;199 } else if ((section == 'common') && (method == 'ItemCreated')) {200 collectionId = parseInt(data[0].toString(), 10);201 itemId = parseInt(data[1].toString(), 10);202 recipient = normalizeAccountId(data[2].toJSON() as any);203 }204 });205 const result: CreateItemResult = {206 success,207 collectionId,208 itemId,209 recipient,210 };211 return result;212}213214export function getTransferResult(events: EventRecord[]): TransferResult {215 const result: TransferResult = {216 success: false,217 collectionId: 0,218 itemId: 0,219 value: 0n,220 };221222 events.forEach(({event: {data, method, section}}) => {223 if (method === 'ExtrinsicSuccess') {224 result.success = true;225 } else if (section === 'common' && method === 'Transfer') {226 result.collectionId = +data[0].toString();227 result.itemId = +data[1].toString();228 result.sender = normalizeAccountId(data[2].toJSON() as any);229 result.recipient = normalizeAccountId(data[3].toJSON() as any);230 result.value = BigInt(data[4].toString());231 }232 });233234 return result;235}236237interface Nft {238 type: 'NFT';239}240241interface Fungible {242 type: 'Fungible';243 decimalPoints: number;244}245246interface ReFungible {247 type: 'ReFungible';248}249250type CollectionMode = Nft | Fungible | ReFungible;251252export type CreateCollectionParams = {253 mode: CollectionMode,254 name: string,255 description: string,256 tokenPrefix: string,257};258259const defaultCreateCollectionParams: CreateCollectionParams = {260 description: 'description',261 mode: {type: 'NFT'},262 name: 'name',263 tokenPrefix: 'prefix',264};265266export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {267 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};268269 let collectionId = 0;270 await usingApi(async (api) => {271 // Get number of collections before the transaction272 const collectionCountBefore = (await api.query.common.createdCollectionCount()).toNumber();273274 // Run the CreateCollection transaction275 const alicePrivateKey = privateKey('//Alice');276277 let modeprm = {};278 if (mode.type === 'NFT') {279 modeprm = {nft: null};280 } else if (mode.type === 'Fungible') {281 modeprm = {fungible: mode.decimalPoints};282 } else if (mode.type === 'ReFungible') {283 modeprm = {refungible: null};284 }285286 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);287 const events = await submitTransactionAsync(alicePrivateKey, tx);288 const result = getCreateCollectionResult(events);289290 // Get number of collections after the transaction291 const collectionCountAfter = (await api.query.common.createdCollectionCount()).toNumber();292293 // Get the collection294 const collection = (await api.query.common.collectionById(result.collectionId)).unwrap();295296 // What to expect297 // tslint:disable-next-line:no-unused-expression298 expect(result.success).to.be.true;299 expect(result.collectionId).to.be.equal(collectionCountAfter);300 // tslint:disable-next-line:no-unused-expression301 expect(collection).to.be.not.null;302 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');303 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));304 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);305 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);306 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);307308 collectionId = result.collectionId;309 });310311 return collectionId;312}313314export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {315 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};316317 let modeprm = {};318 if (mode.type === 'NFT') {319 modeprm = {nft: null};320 } else if (mode.type === 'Fungible') {321 modeprm = {fungible: mode.decimalPoints};322 } else if (mode.type === 'ReFungible') {323 modeprm = {refungible: null};324 }325326 await usingApi(async (api) => {327 // Get number of collections before the transaction328 const collectionCountBefore = (await api.query.common.createdCollectionCount()).toNumber();329330 // Run the CreateCollection transaction331 const alicePrivateKey = privateKey('//Alice');332 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);333 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;334 const result = getCreateCollectionResult(events);335336 // Get number of collections after the transaction337 const collectionCountAfter = (await api.query.common.createdCollectionCount()).toNumber();338339 // What to expect340 // tslint:disable-next-line:no-unused-expression341 expect(result.success).to.be.false;342 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');343 });344}345346export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {347 let bal = 0n;348 let unused;349 do {350 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;351 const keyring = new Keyring({type: 'sr25519'});352 unused = keyring.addFromUri(`//${randomSeed}`);353 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();354 } while (bal !== 0n);355 return unused;356}357358export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {359 return (await api.rpc.nft.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();360}361362export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {363 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));364}365366export async function findNotExistingCollection(api: ApiPromise): Promise<number> {367 const totalNumber = (await api.query.common.createdCollectionCount()).toNumber();368 const newCollection: number = totalNumber + 1;369 return newCollection;370}371372function getDestroyResult(events: EventRecord[]): boolean {373 let success = false;374 events.forEach(({event: {method}}) => {375 if (method == 'ExtrinsicSuccess') {376 success = true;377 }378 });379 return success;380}381382export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {383 await usingApi(async (api) => {384 // Run the DestroyCollection transaction385 const alicePrivateKey = privateKey(senderSeed);386 const tx = api.tx.nft.destroyCollection(collectionId);387 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;388 });389}390391export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {392 await usingApi(async (api) => {393 // Run the DestroyCollection transaction394 const alicePrivateKey = privateKey(senderSeed);395 const tx = api.tx.nft.destroyCollection(collectionId);396 const events = await submitTransactionAsync(alicePrivateKey, tx);397 const result = getDestroyResult(events);398 expect(result).to.be.true;399400 // What to expect401 expect((await api.query.common.collectionById(collectionId)).isNone).to.be.true;402 });403}404405export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {406 await usingApi(async (api) => {407 const tx = api.tx.nft.setCollectionLimits(collectionId, limits);408 const events = await submitTransactionAsync(sender, tx);409 const result = getGenericResult(events);410411 expect(result.success).to.be.true;412 });413}414415export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {416 await usingApi(async (api) => {417 const tx = api.tx.nft.setCollectionLimits(collectionId, limits);418 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;419 const result = getGenericResult(events);420421 expect(result.success).to.be.false;422 });423}424425export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {426 await usingApi(async (api) => {427428 // Run the transaction429 const senderPrivateKey = privateKey(sender);430 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);431 const events = await submitTransactionAsync(senderPrivateKey, tx);432 const result = getGenericResult(events);433434 // Get the collection435 const collection = (await api.query.common.collectionById(collectionId)).unwrap();436437 // What to expect438 expect(result.success).to.be.true;439 expect(collection.sponsorship.toJSON()).to.deep.equal({440 unconfirmed: sponsor,441 });442 });443}444445export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {446 await usingApi(async (api) => {447448 // Run the transaction449 const alicePrivateKey = privateKey(sender);450 const tx = api.tx.nft.removeCollectionSponsor(collectionId);451 const events = await submitTransactionAsync(alicePrivateKey, tx);452 const result = getGenericResult(events);453454 // Get the collection455 const collection = (await api.query.common.collectionById(collectionId)).unwrap();456457 // What to expect458 expect(result.success).to.be.true;459 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});460 });461}462463export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {464 await usingApi(async (api) => {465466 // Run the transaction467 const alicePrivateKey = privateKey(senderSeed);468 const tx = api.tx.nft.removeCollectionSponsor(collectionId);469 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;470 });471}472473export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {474 await usingApi(async (api) => {475476 // Run the transaction477 const alicePrivateKey = privateKey(senderSeed);478 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);479 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;480 });481}482483export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {484 await usingApi(async (api) => {485486 // Run the transaction487 const sender = privateKey(senderSeed);488 const tx = api.tx.nft.confirmSponsorship(collectionId);489 const events = await submitTransactionAsync(sender, tx);490 const result = getGenericResult(events);491492 // Get the collection493 const collection = (await api.query.common.collectionById(collectionId)).unwrap();494495 // What to expect496 expect(result.success).to.be.true;497 expect(collection.sponsorship.toJSON()).to.be.deep.equal({498 confirmed: sender.address,499 });500 });501}502503504export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {505 await usingApi(async (api) => {506507 // Run the transaction508 const sender = privateKey(senderSeed);509 const tx = api.tx.nft.confirmSponsorship(collectionId);510 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;511 });512}513514export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {515516 await usingApi(async (api) => {517 const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag as any);518 const events = await submitTransactionAsync(sender, tx);519 const result = getGenericResult(events);520521 expect(result.success).to.be.true;522 });523}524525export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {526527 await usingApi(async (api) => {528 const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag as any);529 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;530 const result = getGenericResult(events);531532 expect(result.success).to.be.false;533 });534}535536export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {537 await usingApi(async (api) => {538 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);539 const events = await submitTransactionAsync(sender, tx);540 const result = getGenericResult(events);541542 expect(result.success).to.be.true;543 });544}545546export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {547 await usingApi(async (api) => {548 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);549 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;550 const result = getGenericResult(events);551552 expect(result.success).to.be.false;553 });554}555556export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {557558 await usingApi(async (api) => {559560 const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);561 const events = await submitTransactionAsync(sender, tx);562 const result = getGenericResult(events);563564 expect(result.success).to.be.true;565 });566}567568export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {569570 await usingApi(async (api) => {571572 const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);573 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;574 const result = getGenericResult(events);575576 expect(result.success).to.be.false;577 });578}579580export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {581 await usingApi(async (api) => {582 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);583 const events = await submitTransactionAsync(sender, tx);584 const result = getGenericResult(events);585586 expect(result.success).to.be.true;587 });588}589590export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {591 await usingApi(async (api) => {592 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);593 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;594 const result = getGenericResult(events);595596 expect(result.success).to.be.false;597 });598}599600export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {601 await usingApi(async (api) => {602 const tx = api.tx.nft.toggleContractAllowList(contractAddress, value);603 const events = await submitTransactionAsync(sender, tx);604 const result = getGenericResult(events);605606 expect(result.success).to.be.true;607 });608}609610export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {611 let allowlisted = false;612 await usingApi(async (api) => {613 allowlisted = (await api.query.nft.contractAllowList(contractAddress, user)).toJSON() as boolean;614 });615 return allowlisted;616}617618export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {619 await usingApi(async (api) => {620 const tx = api.tx.nft.addToContractAllowList(contractAddress.toString(), user.toString());621 const events = await submitTransactionAsync(sender, tx);622 const result = getGenericResult(events);623624 expect(result.success).to.be.true;625 });626}627628export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {629 await usingApi(async (api) => {630 const tx = api.tx.nft.removeFromContractAllowList(contractAddress.toString(), user.toString());631 const events = await submitTransactionAsync(sender, tx);632 const result = getGenericResult(events);633634 expect(result.success).to.be.true;635 });636}637638export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {639 await usingApi(async (api) => {640 const tx = api.tx.nft.removeFromContractAllowList(contractAddress.toString(), user.toString());641 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;642 const result = getGenericResult(events);643644 expect(result.success).to.be.false;645 });646}647648export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {649 await usingApi(async (api) => {650 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));651 const events = await submitTransactionAsync(sender, tx);652 const result = getGenericResult(events);653654 expect(result.success).to.be.true;655 });656}657658export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {659 await usingApi(async (api) => {660 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));661 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;662 });663}664665export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {666 await usingApi(async (api) => {667 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));668 const events = await submitTransactionAsync(sender, tx);669 const result = getGenericResult(events);670671 expect(result.success).to.be.true;672 });673}674675export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {676 await usingApi(async (api) => {677 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));678 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;679 });680}681682export interface CreateFungibleData {683 readonly Value: bigint;684}685686export interface CreateReFungibleData { }687export interface CreateNftData { }688689export type CreateItemData = {690 NFT: CreateNftData;691} | {692 Fungible: CreateFungibleData;693} | {694 ReFungible: CreateReFungibleData;695};696697export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {698 await usingApi(async (api) => {699 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);700 // if burning token by admin - use adminButnItemExpectSuccess701 expect(balanceBefore >= BigInt(value)).to.be.true;702703 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);704 const events = await submitTransactionAsync(sender, tx);705 const result = getGenericResult(events);706 expect(result.success).to.be.true;707708 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);709 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);710 });711}712713export async function714approveExpectSuccess(715 collectionId: number,716 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,717) {718 await usingApi(async (api: ApiPromise) => {719 const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved), collectionId, tokenId, amount);720 const events = await submitTransactionAsync(owner, approveNftTx);721 const result = getGenericResult(events);722 expect(result.success).to.be.true;723724 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));725 });726}727728export async function adminApproveFromExpectSuccess(729 collectionId: number,730 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,731) {732 await usingApi(async (api: ApiPromise) => {733 const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved), collectionId, tokenId, amount);734 const events = await submitTransactionAsync(admin, approveNftTx);735 const result = getGenericResult(events);736 expect(result.success).to.be.true;737738 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));739 });740}741742export async function743transferFromExpectSuccess(744 collectionId: number,745 tokenId: number,746 accountApproved: IKeyringPair,747 accountFrom: IKeyringPair | CrossAccountId,748 accountTo: IKeyringPair | CrossAccountId,749 value: number | bigint = 1,750 type = 'NFT',751) {752 await usingApi(async (api: ApiPromise) => {753 const to = normalizeAccountId(accountTo);754 let balanceBefore = 0n;755 if (type === 'Fungible') {756 balanceBefore = await getBalance(api, collectionId, to, tokenId);757 }758 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);759 const events = await submitTransactionAsync(accountApproved, transferFromTx);760 const result = getCreateItemResult(events);761 // tslint:disable-next-line:no-unused-expression762 expect(result.success).to.be.true;763 if (type === 'NFT') {764 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);765 }766 if (type === 'Fungible') {767 const balanceAfter = await getBalance(api, collectionId, to, tokenId);768 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));769 }770 if (type === 'ReFungible') {771 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));772 }773 });774}775776export async function777transferFromExpectFail(778 collectionId: number,779 tokenId: number,780 accountApproved: IKeyringPair,781 accountFrom: IKeyringPair,782 accountTo: IKeyringPair,783 value: number | bigint = 1,784) {785 await usingApi(async (api: ApiPromise) => {786 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);787 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;788 const result = getCreateCollectionResult(events);789 // tslint:disable-next-line:no-unused-expression790 expect(result.success).to.be.false;791 });792}793794/* eslint no-async-promise-executor: "off" */795async function getBlockNumber(api: ApiPromise): Promise<number> {796 return new Promise<number>(async (resolve) => {797 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {798 unsubscribe();799 resolve(head.number.toNumber());800 });801 });802}803804export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {805 await usingApi(async (api) => {806 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(address));807 const events = await submitTransactionAsync(sender, changeAdminTx);808 const result = getCreateCollectionResult(events);809 expect(result.success).to.be.true;810 });811}812813export async function814getFreeBalance(account: IKeyringPair) : Promise<bigint>815{816 let balance = 0n;817 await usingApi(async (api) => {818 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());819 });820821 return balance;822}823824export async function825scheduleTransferExpectSuccess(826 collectionId: number,827 tokenId: number,828 sender: IKeyringPair,829 recipient: IKeyringPair,830 value: number | bigint = 1,831 blockSchedule: number,832) {833 await usingApi(async (api: ApiPromise) => {834 const blockNumber: number | undefined = await getBlockNumber(api);835 const expectedBlockNumber = blockNumber + blockSchedule;836837 expect(blockNumber).to.be.greaterThan(0);838 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);839 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);840841 await submitTransactionAsync(sender, scheduleTx);842843 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();844845 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));846847 // sleep for 4 blocks848 await waitNewBlocks(blockSchedule + 1);849850 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();851852 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));853 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);854 });855}856857858export async function859transferExpectSuccess(860 collectionId: number,861 tokenId: number,862 sender: IKeyringPair,863 recipient: IKeyringPair | CrossAccountId,864 value: number | bigint = 1,865 type = 'NFT',866) {867 await usingApi(async (api: ApiPromise) => {868 const to = normalizeAccountId(recipient);869870 let balanceBefore = 0n;871 if (type === 'Fungible') {872 balanceBefore = await getBalance(api, collectionId, to, tokenId);873 }874 const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);875 const events = await submitTransactionAsync(sender, transferTx);876 const result = getTransferResult(events);877 // tslint:disable-next-line:no-unused-expression878 expect(result.success).to.be.true;879 expect(result.collectionId).to.be.equal(collectionId);880 expect(result.itemId).to.be.equal(tokenId);881 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));882 expect(result.recipient).to.be.deep.equal(to);883 expect(result.value).to.be.equal(BigInt(value));884 if (type === 'NFT') {885 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);886 }887 if (type === 'Fungible') {888 const balanceAfter = await getBalance(api, collectionId, to, tokenId);889 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));890 }891 if (type === 'ReFungible') {892 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;893 }894 });895}896897export async function898transferExpectFailure(899 collectionId: number,900 tokenId: number,901 sender: IKeyringPair,902 recipient: IKeyringPair,903 value: number | bigint = 1,904) {905 await usingApi(async (api: ApiPromise) => {906 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);907 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;908 const result = getGenericResult(events);909 // if (events && Array.isArray(events)) {910 // const result = getCreateCollectionResult(events);911 // tslint:disable-next-line:no-unused-expression912 expect(result.success).to.be.false;913 //}914 });915}916917export async function918approveExpectFail(919 collectionId: number,920 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,921) {922 await usingApi(async (api: ApiPromise) => {923 const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);924 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;925 const result = getCreateCollectionResult(events);926 // tslint:disable-next-line:no-unused-expression927 expect(result.success).to.be.false;928 });929}930931export async function getBalance(932 api: ApiPromise,933 collectionId: number,934 owner: string | CrossAccountId,935 token: number,936): Promise<bigint> {937 return (await api.rpc.nft.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();938}939export async function getTokenOwner(940 api: ApiPromise,941 collectionId: number,942 token: number,943): Promise<CrossAccountId> {944 return normalizeAccountId((await api.rpc.nft.tokenOwner(collectionId, token)).toJSON() as any);945}946export async function isTokenExists(947 api: ApiPromise,948 collectionId: number,949 token: number,950): Promise<boolean> {951 return (await api.rpc.nft.tokenExists(collectionId, token)).toJSON();952}953export async function getLastTokenId(954 api: ApiPromise,955 collectionId: number,956): Promise<number> {957 return (await api.rpc.nft.lastTokenId(collectionId)).toJSON();958}959export async function getAdminList(960 api: ApiPromise,961 collectionId: number,962): Promise<string[]> {963 return (await api.rpc.nft.adminlist(collectionId)).toHuman() as any;964}965export async function getVariableMetadata(966 api: ApiPromise,967 collectionId: number,968 tokenId: number,969): Promise<number[]> {970 return [...(await api.rpc.nft.variableMetadata(collectionId, tokenId))];971}972export async function getConstMetadata(973 api: ApiPromise,974 collectionId: number,975 tokenId: number,976): Promise<number[]> {977 return [...(await api.rpc.nft.constMetadata(collectionId, tokenId))];978}979980export async function createFungibleItemExpectSuccess(981 sender: IKeyringPair,982 collectionId: number,983 data: CreateFungibleData,984 owner: CrossAccountId | string = sender.address,985) {986 return await usingApi(async (api) => {987 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});988989 const events = await submitTransactionAsync(sender, tx);990 const result = getCreateItemResult(events);991992 expect(result.success).to.be.true;993 return result.itemId;994 });995}996997export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {998 let newItemId = 0;999 await usingApi(async (api) => {1000 const to = normalizeAccountId(owner);1001 const itemCountBefore = await getLastTokenId(api, collectionId);1002 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10031004 let tx;1005 if (createMode === 'Fungible') {1006 const createData = {fungible: {value: 10}};1007 tx = api.tx.nft.createItem(collectionId, to, createData as any);1008 } else if (createMode === 'ReFungible') {1009 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1010 tx = api.tx.nft.createItem(collectionId, to, createData as any);1011 } else {1012 const createData = {nft: {const_data: [], variable_data: []}};1013 tx = api.tx.nft.createItem(collectionId, to, createData as any);1014 }10151016 const events = await submitTransactionAsync(sender, tx);1017 const result = getCreateItemResult(events);10181019 const itemCountAfter = await getLastTokenId(api, collectionId);1020 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10211022 // What to expect1023 // tslint:disable-next-line:no-unused-expression1024 expect(result.success).to.be.true;1025 if (createMode === 'Fungible') {1026 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1027 } else {1028 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1029 }1030 expect(collectionId).to.be.equal(result.collectionId);1031 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1032 expect(to).to.be.deep.equal(result.recipient);1033 newItemId = result.itemId;1034 });1035 return newItemId;1036}10371038export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1039 await usingApi(async (api) => {1040 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);10411042 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1043 const result = getCreateItemResult(events);10441045 expect(result.success).to.be.false;1046 });1047}10481049export async function setPublicAccessModeExpectSuccess(1050 sender: IKeyringPair, collectionId: number,1051 accessMode: 'Normal' | 'AllowList',1052) {1053 await usingApi(async (api) => {10541055 // Run the transaction1056 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1057 const events = await submitTransactionAsync(sender, tx);1058 const result = getGenericResult(events);10591060 // Get the collection1061 const collection = (await api.query.common.collectionById(collectionId)).unwrap();10621063 // What to expect1064 // tslint:disable-next-line:no-unused-expression1065 expect(result.success).to.be.true;1066 expect(collection.access.toHuman()).to.be.equal(accessMode);1067 });1068}10691070export async function setPublicAccessModeExpectFail(1071 sender: IKeyringPair, collectionId: number,1072 accessMode: 'Normal' | 'AllowList',1073) {1074 await usingApi(async (api) => {10751076 // Run the transaction1077 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1078 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1079 const result = getGenericResult(events);10801081 // What to expect1082 // tslint:disable-next-line:no-unused-expression1083 expect(result.success).to.be.false;1084 });1085}10861087export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1088 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1089}10901091export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1092 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1093}10941095export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1096 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1097}10981099export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1100 await usingApi(async (api) => {11011102 // Run the transaction1103 const tx = api.tx.nft.setMintPermission(collectionId, enabled);1104 const events = await submitTransactionAsync(sender, tx);1105 const result = getGenericResult(events);1106 expect(result.success).to.be.true;11071108 // Get the collection1109 const collection = (await api.query.common.collectionById(collectionId)).unwrap();11101111 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1112 });1113}11141115export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1116 await setMintPermissionExpectSuccess(sender, collectionId, true);1117}11181119export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1120 await usingApi(async (api) => {1121 // Run the transaction1122 const tx = api.tx.nft.setMintPermission(collectionId, enabled);1123 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1124 const result = getCreateCollectionResult(events);1125 // tslint:disable-next-line:no-unused-expression1126 expect(result.success).to.be.false;1127 });1128}11291130export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1131 await usingApi(async (api) => {1132 // Run the transaction1133 const tx = api.tx.nft.setChainLimits(limits);1134 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1135 const result = getCreateCollectionResult(events);1136 // tslint:disable-next-line:no-unused-expression1137 expect(result.success).to.be.false;1138 });1139}11401141export async function isAllowlisted(collectionId: number, address: string | CrossAccountId) {1142 return await usingApi(async (api) => {1143 return (await api.query.common.allowlist(collectionId, normalizeAccountId(address))).toJSON();1144 });1145}11461147export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1148 await usingApi(async (api) => {1149 expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.false;11501151 // Run the transaction1152 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));1153 const events = await submitTransactionAsync(sender, tx);1154 const result = getGenericResult(events);1155 expect(result.success).to.be.true;11561157 expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;1158 });1159}11601161export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1162 await usingApi(async (api) => {11631164 expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;11651166 // Run the transaction1167 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));1168 const events = await submitTransactionAsync(sender, tx);1169 const result = getGenericResult(events);1170 expect(result.success).to.be.true;11711172 expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;1173 });1174}11751176export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1177 await usingApi(async (api) => {11781179 // Run the transaction1180 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));1181 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1182 const result = getGenericResult(events);11831184 // What to expect1185 // tslint:disable-next-line:no-unused-expression1186 expect(result.success).to.be.false;1187 });1188}11891190export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1191 await usingApi(async (api) => {1192 // Run the transaction1193 const tx = api.tx.nft.removeFromAllowList(collectionId, normalizeAccountId(address));1194 const events = await submitTransactionAsync(sender, tx);1195 const result = getGenericResult(events);11961197 // What to expect1198 // tslint:disable-next-line:no-unused-expression1199 expect(result.success).to.be.true;1200 });1201}12021203export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1204 await usingApi(async (api) => {1205 // Run the transaction1206 const tx = api.tx.nft.removeFromAllowList(collectionId, normalizeAccountId(address));1207 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1208 const result = getGenericResult(events);12091210 // What to expect1211 // tslint:disable-next-line:no-unused-expression1212 expect(result.success).to.be.false;1213 });1214}12151216export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1217 : Promise<NftDataStructsCollection | null> => {1218 return (await api.query.common.collectionById(collectionId)).unwrapOr(null);1219};12201221export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1222 // set global object - collectionsCount1223 return (await api.query.common.createdCollectionCount()).toNumber();1224};12251226export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<NftDataStructsCollection> {1227 return (await api.query.common.collectionById(collectionId)).unwrap();1228}12291230export async function waitNewBlocks(blocksCount = 1): Promise<void> {1231 await usingApi(async (api) => {1232 const promise = new Promise<void>(async (resolve) => {1233 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1234 if (blocksCount > 0) {1235 blocksCount--;1236 } else {1237 unsubscribe();1238 resolve();1239 }1240 });1241 });1242 return promise;1243 });1244}1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import {ApiPromise, Keyring} from '@polkadot/api';7import type {AccountId, EventRecord} from '@polkadot/types/interfaces';8import {IKeyringPair} from '@polkadot/types/types';9import {evmToAddress} from '@polkadot/util-crypto';10import BN from 'bn.js';11import chai from 'chai';12import chaiAsPromised from 'chai-as-promised';13import {alicesPublicKey} from '../accounts';14import {NftDataStructsCollection} from '../interfaces';15import privateKey from '../substrate/privateKey';16import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';17import {hexToStr, strToUTF16, utf16ToStr} from './util';1819chai.use(chaiAsPromised);20const expect = chai.expect;2122export type CrossAccountId = {23 Substrate: string,24} | {25 Ethereum: string,26};27export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {28 if (typeof input === 'string') {29 if (input.length === 48 || input.length === 47) {30 return {Substrate: input};31 } else if (input.length === 42 && input.startsWith('0x')) {32 return {Ethereum: input.toLowerCase()};33 } else if (input.length === 40 && !input.startsWith('0x')) {34 return {Ethereum: '0x' + input.toLowerCase()};35 } else {36 throw new Error(`Unknown address format: "${input}"`);37 }38 }39 if ('address' in input) {40 return {Substrate: input.address};41 }42 if ('Ethereum' in input) {43 return {44 Ethereum: input.Ethereum.toLowerCase(),45 };46 } else if ('ethereum' in input) {47 return {48 Ethereum: (input as any).ethereum.toLowerCase(),49 };50 } else if ('Substrate' in input) {51 return input;52 }else if ('substrate' in input) {53 return {54 Substrate: (input as any).substrate,55 };56 }5758 // AccountId59 return {Substrate: input.toString()};60}61export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {62 input = normalizeAccountId(input);63 if ('Substrate' in input) {64 return input.Substrate;65 } else {66 return evmToAddress(input.Ethereum);67 }68}6970export const U128_MAX = (1n << 128n) - 1n;7172const MICROUNIQUE = 1_000_000_000n;73const MILLIUNIQUE = 1_000n * MICROUNIQUE;74const CENTIUNIQUE = 10n * MILLIUNIQUE;75export const UNIQUE = 100n * CENTIUNIQUE;7677type GenericResult = {78 success: boolean,79};8081interface CreateCollectionResult {82 success: boolean;83 collectionId: number;84}8586interface CreateItemResult {87 success: boolean;88 collectionId: number;89 itemId: number;90 recipient?: CrossAccountId;91}9293interface TransferResult {94 success: boolean;95 collectionId: number;96 itemId: number;97 sender?: CrossAccountId;98 recipient?: CrossAccountId;99 value: bigint;100}101102interface IReFungibleOwner {103 fraction: BN;104 owner: number[];105}106107interface IGetMessage {108 checkMsgNftMethod: string;109 checkMsgTrsMethod: string;110 checkMsgSysMethod: string;111}112113export interface IFungibleTokenDataType {114 value: number;115}116117export interface IChainLimits {118 collectionNumbersLimit: number;119 accountTokenOwnershipLimit: number;120 collectionsAdminsLimit: number;121 customDataLimit: number;122 nftSponsorTransferTimeout: number;123 fungibleSponsorTransferTimeout: number;124 refungibleSponsorTransferTimeout: number;125 offchainSchemaLimit: number;126 variableOnChainSchemaLimit: number;127 constOnChainSchemaLimit: number;128}129130export interface IReFungibleTokenDataType {131 owner: IReFungibleOwner[];132 constData: number[];133 variableData: number[];134}135136export function nftEventMessage(events: EventRecord[]): IGetMessage {137 let checkMsgNftMethod = '';138 let checkMsgTrsMethod = '';139 let checkMsgSysMethod = '';140 events.forEach(({event: {method, section}}) => {141 if (section === 'common') {142 checkMsgNftMethod = method;143 } else if (section === 'treasury') {144 checkMsgTrsMethod = method;145 } else if (section === 'system') {146 checkMsgSysMethod = method;147 } else { return null; }148 });149 const result: IGetMessage = {150 checkMsgNftMethod,151 checkMsgTrsMethod,152 checkMsgSysMethod,153 };154 return result;155}156157export function getGenericResult(events: EventRecord[]): GenericResult {158 const result: GenericResult = {159 success: false,160 };161 events.forEach(({event: {method}}) => {162 // console.log(` ${phase}: ${section}.${method}:: ${data}`);163 if (method === 'ExtrinsicSuccess') {164 result.success = true;165 }166 });167 return result;168}169170171172export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {173 let success = false;174 let collectionId = 0;175 events.forEach(({event: {data, method, section}}) => {176 // console.log(` ${phase}: ${section}.${method}:: ${data}`);177 if (method == 'ExtrinsicSuccess') {178 success = true;179 } else if ((section == 'common') && (method == 'CollectionCreated')) {180 collectionId = parseInt(data[0].toString(), 10);181 }182 });183 const result: CreateCollectionResult = {184 success,185 collectionId,186 };187 return result;188}189190export function getCreateItemResult(events: EventRecord[]): CreateItemResult {191 let success = false;192 let collectionId = 0;193 let itemId = 0;194 let recipient;195 events.forEach(({event: {data, method, section}}) => {196 // console.log(` ${phase}: ${section}.${method}:: ${data}`);197 if (method == 'ExtrinsicSuccess') {198 success = true;199 } else if ((section == 'common') && (method == 'ItemCreated')) {200 collectionId = parseInt(data[0].toString(), 10);201 itemId = parseInt(data[1].toString(), 10);202 recipient = normalizeAccountId(data[2].toJSON() as any);203 }204 });205 const result: CreateItemResult = {206 success,207 collectionId,208 itemId,209 recipient,210 };211 return result;212}213214export function getTransferResult(events: EventRecord[]): TransferResult {215 const result: TransferResult = {216 success: false,217 collectionId: 0,218 itemId: 0,219 value: 0n,220 };221222 events.forEach(({event: {data, method, section}}) => {223 if (method === 'ExtrinsicSuccess') {224 result.success = true;225 } else if (section === 'common' && method === 'Transfer') {226 result.collectionId = +data[0].toString();227 result.itemId = +data[1].toString();228 result.sender = normalizeAccountId(data[2].toJSON() as any);229 result.recipient = normalizeAccountId(data[3].toJSON() as any);230 result.value = BigInt(data[4].toString());231 }232 });233234 return result;235}236237interface Nft {238 type: 'NFT';239}240241interface Fungible {242 type: 'Fungible';243 decimalPoints: number;244}245246interface ReFungible {247 type: 'ReFungible';248}249250type CollectionMode = Nft | Fungible | ReFungible;251252export type CreateCollectionParams = {253 mode: CollectionMode,254 name: string,255 description: string,256 tokenPrefix: string,257};258259const defaultCreateCollectionParams: CreateCollectionParams = {260 description: 'description',261 mode: {type: 'NFT'},262 name: 'name',263 tokenPrefix: 'prefix',264};265266export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {267 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};268269 let collectionId = 0;270 await usingApi(async (api) => {271 // Get number of collections before the transaction272 const collectionCountBefore = await getCreatedCollectionCount(api);273274 // Run the CreateCollection transaction275 const alicePrivateKey = privateKey('//Alice');276277 let modeprm = {};278 if (mode.type === 'NFT') {279 modeprm = {nft: null};280 } else if (mode.type === 'Fungible') {281 modeprm = {fungible: mode.decimalPoints};282 } else if (mode.type === 'ReFungible') {283 modeprm = {refungible: null};284 }285286 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);287 const events = await submitTransactionAsync(alicePrivateKey, tx);288 const result = getCreateCollectionResult(events);289290 // Get number of collections after the transaction291 const collectionCountAfter = await getCreatedCollectionCount(api);292293 // Get the collection294 const collection = await queryCollectionExpectSuccess(api, result.collectionId);295296 // What to expect297 // tslint:disable-next-line:no-unused-expression298 expect(result.success).to.be.true;299 expect(result.collectionId).to.be.equal(collectionCountAfter);300 // tslint:disable-next-line:no-unused-expression301 expect(collection).to.be.not.null;302 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');303 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));304 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);305 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);306 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);307308 collectionId = result.collectionId;309 });310311 return collectionId;312}313314export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {315 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};316317 let modeprm = {};318 if (mode.type === 'NFT') {319 modeprm = {nft: null};320 } else if (mode.type === 'Fungible') {321 modeprm = {fungible: mode.decimalPoints};322 } else if (mode.type === 'ReFungible') {323 modeprm = {refungible: null};324 }325326 await usingApi(async (api) => {327 // Get number of collections before the transaction328 const collectionCountBefore = await getCreatedCollectionCount(api);329330 // Run the CreateCollection transaction331 const alicePrivateKey = privateKey('//Alice');332 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);333 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;334 const result = getCreateCollectionResult(events);335336 // Get number of collections after the transaction337 const collectionCountAfter = await getCreatedCollectionCount(api);338339 // What to expect340 // tslint:disable-next-line:no-unused-expression341 expect(result.success).to.be.false;342 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');343 });344}345346export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {347 let bal = 0n;348 let unused;349 do {350 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;351 const keyring = new Keyring({type: 'sr25519'});352 unused = keyring.addFromUri(`//${randomSeed}`);353 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();354 } while (bal !== 0n);355 return unused;356}357358export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {359 return (await api.rpc.nft.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();360}361362export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {363 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));364}365366export async function findNotExistingCollection(api: ApiPromise): Promise<number> {367 const totalNumber = await getCreatedCollectionCount(api);368 const newCollection: number = totalNumber + 1;369 return newCollection;370}371372function getDestroyResult(events: EventRecord[]): boolean {373 let success = false;374 events.forEach(({event: {method}}) => {375 if (method == 'ExtrinsicSuccess') {376 success = true;377 }378 });379 return success;380}381382export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {383 await usingApi(async (api) => {384 // Run the DestroyCollection transaction385 const alicePrivateKey = privateKey(senderSeed);386 const tx = api.tx.nft.destroyCollection(collectionId);387 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;388 });389}390391export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {392 await usingApi(async (api) => {393 // Run the DestroyCollection transaction394 const alicePrivateKey = privateKey(senderSeed);395 const tx = api.tx.nft.destroyCollection(collectionId);396 const events = await submitTransactionAsync(alicePrivateKey, tx);397 const result = getDestroyResult(events);398 expect(result).to.be.true;399400 // What to expect401 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;402 });403}404405export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {406 await usingApi(async (api) => {407 const tx = api.tx.nft.setCollectionLimits(collectionId, limits);408 const events = await submitTransactionAsync(sender, tx);409 const result = getGenericResult(events);410411 expect(result.success).to.be.true;412 });413}414415export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {416 await usingApi(async (api) => {417 const tx = api.tx.nft.setCollectionLimits(collectionId, limits);418 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;419 const result = getGenericResult(events);420421 expect(result.success).to.be.false;422 });423}424425export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {426 await usingApi(async (api) => {427428 // Run the transaction429 const senderPrivateKey = privateKey(sender);430 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);431 const events = await submitTransactionAsync(senderPrivateKey, tx);432 const result = getGenericResult(events);433434 // Get the collection435 const collection = await queryCollectionExpectSuccess(api, collectionId);436437 // What to expect438 expect(result.success).to.be.true;439 expect(collection.sponsorship.toJSON()).to.deep.equal({440 unconfirmed: sponsor,441 });442 });443}444445export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {446 await usingApi(async (api) => {447448 // Run the transaction449 const alicePrivateKey = privateKey(sender);450 const tx = api.tx.nft.removeCollectionSponsor(collectionId);451 const events = await submitTransactionAsync(alicePrivateKey, tx);452 const result = getGenericResult(events);453454 // Get the collection455 const collection = await queryCollectionExpectSuccess(api, collectionId);456457 // What to expect458 expect(result.success).to.be.true;459 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});460 });461}462463export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {464 await usingApi(async (api) => {465466 // Run the transaction467 const alicePrivateKey = privateKey(senderSeed);468 const tx = api.tx.nft.removeCollectionSponsor(collectionId);469 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;470 });471}472473export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {474 await usingApi(async (api) => {475476 // Run the transaction477 const alicePrivateKey = privateKey(senderSeed);478 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);479 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;480 });481}482483export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {484 await usingApi(async (api) => {485486 // Run the transaction487 const sender = privateKey(senderSeed);488 const tx = api.tx.nft.confirmSponsorship(collectionId);489 const events = await submitTransactionAsync(sender, tx);490 const result = getGenericResult(events);491492 // Get the collection493 const collection = await queryCollectionExpectSuccess(api, collectionId);494495 // What to expect496 expect(result.success).to.be.true;497 expect(collection.sponsorship.toJSON()).to.be.deep.equal({498 confirmed: sender.address,499 });500 });501}502503504export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {505 await usingApi(async (api) => {506507 // Run the transaction508 const sender = privateKey(senderSeed);509 const tx = api.tx.nft.confirmSponsorship(collectionId);510 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;511 });512}513514export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {515516 await usingApi(async (api) => {517 const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag as any);518 const events = await submitTransactionAsync(sender, tx);519 const result = getGenericResult(events);520521 expect(result.success).to.be.true;522 });523}524525export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {526527 await usingApi(async (api) => {528 const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag as any);529 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;530 const result = getGenericResult(events);531532 expect(result.success).to.be.false;533 });534}535536export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {537 await usingApi(async (api) => {538 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);539 const events = await submitTransactionAsync(sender, tx);540 const result = getGenericResult(events);541542 expect(result.success).to.be.true;543 });544}545546export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {547 await usingApi(async (api) => {548 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);549 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;550 const result = getGenericResult(events);551552 expect(result.success).to.be.false;553 });554}555556export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {557558 await usingApi(async (api) => {559560 const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);561 const events = await submitTransactionAsync(sender, tx);562 const result = getGenericResult(events);563564 expect(result.success).to.be.true;565 });566}567568export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {569570 await usingApi(async (api) => {571572 const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);573 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;574 const result = getGenericResult(events);575576 expect(result.success).to.be.false;577 });578}579580export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {581 await usingApi(async (api) => {582 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);583 const events = await submitTransactionAsync(sender, tx);584 const result = getGenericResult(events);585586 expect(result.success).to.be.true;587 });588}589590export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {591 await usingApi(async (api) => {592 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);593 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;594 const result = getGenericResult(events);595596 expect(result.success).to.be.false;597 });598}599600export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {601 await usingApi(async (api) => {602 const tx = api.tx.nft.toggleContractAllowList(contractAddress, value);603 const events = await submitTransactionAsync(sender, tx);604 const result = getGenericResult(events);605606 expect(result.success).to.be.true;607 });608}609610export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {611 let allowlisted = false;612 await usingApi(async (api) => {613 allowlisted = (await api.query.nft.contractAllowList(contractAddress, user)).toJSON() as boolean;614 });615 return allowlisted;616}617618export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {619 await usingApi(async (api) => {620 const tx = api.tx.nft.addToContractAllowList(contractAddress.toString(), user.toString());621 const events = await submitTransactionAsync(sender, tx);622 const result = getGenericResult(events);623624 expect(result.success).to.be.true;625 });626}627628export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {629 await usingApi(async (api) => {630 const tx = api.tx.nft.removeFromContractAllowList(contractAddress.toString(), user.toString());631 const events = await submitTransactionAsync(sender, tx);632 const result = getGenericResult(events);633634 expect(result.success).to.be.true;635 });636}637638export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {639 await usingApi(async (api) => {640 const tx = api.tx.nft.removeFromContractAllowList(contractAddress.toString(), user.toString());641 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;642 const result = getGenericResult(events);643644 expect(result.success).to.be.false;645 });646}647648export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {649 await usingApi(async (api) => {650 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));651 const events = await submitTransactionAsync(sender, tx);652 const result = getGenericResult(events);653654 expect(result.success).to.be.true;655 });656}657658export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {659 await usingApi(async (api) => {660 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));661 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;662 });663}664665export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {666 await usingApi(async (api) => {667 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));668 const events = await submitTransactionAsync(sender, tx);669 const result = getGenericResult(events);670671 expect(result.success).to.be.true;672 });673}674675export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {676 await usingApi(async (api) => {677 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));678 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;679 });680}681682export interface CreateFungibleData {683 readonly Value: bigint;684}685686export interface CreateReFungibleData { }687export interface CreateNftData { }688689export type CreateItemData = {690 NFT: CreateNftData;691} | {692 Fungible: CreateFungibleData;693} | {694 ReFungible: CreateReFungibleData;695};696697export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {698 await usingApi(async (api) => {699 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);700 // if burning token by admin - use adminButnItemExpectSuccess701 expect(balanceBefore >= BigInt(value)).to.be.true;702703 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);704 const events = await submitTransactionAsync(sender, tx);705 const result = getGenericResult(events);706 expect(result.success).to.be.true;707708 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);709 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);710 });711}712713export async function714approveExpectSuccess(715 collectionId: number,716 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,717) {718 await usingApi(async (api: ApiPromise) => {719 const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved), collectionId, tokenId, amount);720 const events = await submitTransactionAsync(owner, approveNftTx);721 const result = getGenericResult(events);722 expect(result.success).to.be.true;723724 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));725 });726}727728export async function adminApproveFromExpectSuccess(729 collectionId: number,730 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,731) {732 await usingApi(async (api: ApiPromise) => {733 const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved), collectionId, tokenId, amount);734 const events = await submitTransactionAsync(admin, approveNftTx);735 const result = getGenericResult(events);736 expect(result.success).to.be.true;737738 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));739 });740}741742export async function743transferFromExpectSuccess(744 collectionId: number,745 tokenId: number,746 accountApproved: IKeyringPair,747 accountFrom: IKeyringPair | CrossAccountId,748 accountTo: IKeyringPair | CrossAccountId,749 value: number | bigint = 1,750 type = 'NFT',751) {752 await usingApi(async (api: ApiPromise) => {753 const to = normalizeAccountId(accountTo);754 let balanceBefore = 0n;755 if (type === 'Fungible') {756 balanceBefore = await getBalance(api, collectionId, to, tokenId);757 }758 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);759 const events = await submitTransactionAsync(accountApproved, transferFromTx);760 const result = getCreateItemResult(events);761 // tslint:disable-next-line:no-unused-expression762 expect(result.success).to.be.true;763 if (type === 'NFT') {764 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);765 }766 if (type === 'Fungible') {767 const balanceAfter = await getBalance(api, collectionId, to, tokenId);768 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));769 }770 if (type === 'ReFungible') {771 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));772 }773 });774}775776export async function777transferFromExpectFail(778 collectionId: number,779 tokenId: number,780 accountApproved: IKeyringPair,781 accountFrom: IKeyringPair,782 accountTo: IKeyringPair,783 value: number | bigint = 1,784) {785 await usingApi(async (api: ApiPromise) => {786 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);787 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;788 const result = getCreateCollectionResult(events);789 // tslint:disable-next-line:no-unused-expression790 expect(result.success).to.be.false;791 });792}793794/* eslint no-async-promise-executor: "off" */795async function getBlockNumber(api: ApiPromise): Promise<number> {796 return new Promise<number>(async (resolve) => {797 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {798 unsubscribe();799 resolve(head.number.toNumber());800 });801 });802}803804export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {805 await usingApi(async (api) => {806 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(address));807 const events = await submitTransactionAsync(sender, changeAdminTx);808 const result = getCreateCollectionResult(events);809 expect(result.success).to.be.true;810 });811}812813export async function814getFreeBalance(account: IKeyringPair) : Promise<bigint>815{816 let balance = 0n;817 await usingApi(async (api) => {818 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());819 });820821 return balance;822}823824export async function825scheduleTransferExpectSuccess(826 collectionId: number,827 tokenId: number,828 sender: IKeyringPair,829 recipient: IKeyringPair,830 value: number | bigint = 1,831 blockSchedule: number,832) {833 await usingApi(async (api: ApiPromise) => {834 const blockNumber: number | undefined = await getBlockNumber(api);835 const expectedBlockNumber = blockNumber + blockSchedule;836837 expect(blockNumber).to.be.greaterThan(0);838 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);839 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);840841 await submitTransactionAsync(sender, scheduleTx);842843 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();844845 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));846847 // sleep for 4 blocks848 await waitNewBlocks(blockSchedule + 1);849850 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();851852 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));853 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);854 });855}856857858export async function859transferExpectSuccess(860 collectionId: number,861 tokenId: number,862 sender: IKeyringPair,863 recipient: IKeyringPair | CrossAccountId,864 value: number | bigint = 1,865 type = 'NFT',866) {867 await usingApi(async (api: ApiPromise) => {868 const to = normalizeAccountId(recipient);869870 let balanceBefore = 0n;871 if (type === 'Fungible') {872 balanceBefore = await getBalance(api, collectionId, to, tokenId);873 }874 const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);875 const events = await submitTransactionAsync(sender, transferTx);876 const result = getTransferResult(events);877 // tslint:disable-next-line:no-unused-expression878 expect(result.success).to.be.true;879 expect(result.collectionId).to.be.equal(collectionId);880 expect(result.itemId).to.be.equal(tokenId);881 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));882 expect(result.recipient).to.be.deep.equal(to);883 expect(result.value).to.be.equal(BigInt(value));884 if (type === 'NFT') {885 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);886 }887 if (type === 'Fungible') {888 const balanceAfter = await getBalance(api, collectionId, to, tokenId);889 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));890 }891 if (type === 'ReFungible') {892 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;893 }894 });895}896897export async function898transferExpectFailure(899 collectionId: number,900 tokenId: number,901 sender: IKeyringPair,902 recipient: IKeyringPair,903 value: number | bigint = 1,904) {905 await usingApi(async (api: ApiPromise) => {906 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);907 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;908 const result = getGenericResult(events);909 // if (events && Array.isArray(events)) {910 // const result = getCreateCollectionResult(events);911 // tslint:disable-next-line:no-unused-expression912 expect(result.success).to.be.false;913 //}914 });915}916917export async function918approveExpectFail(919 collectionId: number,920 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,921) {922 await usingApi(async (api: ApiPromise) => {923 const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);924 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;925 const result = getCreateCollectionResult(events);926 // tslint:disable-next-line:no-unused-expression927 expect(result.success).to.be.false;928 });929}930931export async function getBalance(932 api: ApiPromise,933 collectionId: number,934 owner: string | CrossAccountId,935 token: number,936): Promise<bigint> {937 return (await api.rpc.nft.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();938}939export async function getTokenOwner(940 api: ApiPromise,941 collectionId: number,942 token: number,943): Promise<CrossAccountId> {944 return normalizeAccountId((await api.rpc.nft.tokenOwner(collectionId, token)).toJSON() as any);945}946export async function isTokenExists(947 api: ApiPromise,948 collectionId: number,949 token: number,950): Promise<boolean> {951 return (await api.rpc.nft.tokenExists(collectionId, token)).toJSON();952}953export async function getLastTokenId(954 api: ApiPromise,955 collectionId: number,956): Promise<number> {957 return (await api.rpc.nft.lastTokenId(collectionId)).toJSON();958}959export async function getAdminList(960 api: ApiPromise,961 collectionId: number,962): Promise<string[]> {963 return (await api.rpc.nft.adminlist(collectionId)).toHuman() as any;964}965export async function getVariableMetadata(966 api: ApiPromise,967 collectionId: number,968 tokenId: number,969): Promise<number[]> {970 return [...(await api.rpc.nft.variableMetadata(collectionId, tokenId))];971}972export async function getConstMetadata(973 api: ApiPromise,974 collectionId: number,975 tokenId: number,976): Promise<number[]> {977 return [...(await api.rpc.nft.constMetadata(collectionId, tokenId))];978}979980export async function createFungibleItemExpectSuccess(981 sender: IKeyringPair,982 collectionId: number,983 data: CreateFungibleData,984 owner: CrossAccountId | string = sender.address,985) {986 return await usingApi(async (api) => {987 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});988989 const events = await submitTransactionAsync(sender, tx);990 const result = getCreateItemResult(events);991992 expect(result.success).to.be.true;993 return result.itemId;994 });995}996997export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {998 let newItemId = 0;999 await usingApi(async (api) => {1000 const to = normalizeAccountId(owner);1001 const itemCountBefore = await getLastTokenId(api, collectionId);1002 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10031004 let tx;1005 if (createMode === 'Fungible') {1006 const createData = {fungible: {value: 10}};1007 tx = api.tx.nft.createItem(collectionId, to, createData as any);1008 } else if (createMode === 'ReFungible') {1009 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1010 tx = api.tx.nft.createItem(collectionId, to, createData as any);1011 } else {1012 const createData = {nft: {const_data: [], variable_data: []}};1013 tx = api.tx.nft.createItem(collectionId, to, createData as any);1014 }10151016 const events = await submitTransactionAsync(sender, tx);1017 const result = getCreateItemResult(events);10181019 const itemCountAfter = await getLastTokenId(api, collectionId);1020 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10211022 // What to expect1023 // tslint:disable-next-line:no-unused-expression1024 expect(result.success).to.be.true;1025 if (createMode === 'Fungible') {1026 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1027 } else {1028 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1029 }1030 expect(collectionId).to.be.equal(result.collectionId);1031 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1032 expect(to).to.be.deep.equal(result.recipient);1033 newItemId = result.itemId;1034 });1035 return newItemId;1036}10371038export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1039 await usingApi(async (api) => {1040 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);10411042 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1043 const result = getCreateItemResult(events);10441045 expect(result.success).to.be.false;1046 });1047}10481049export async function setPublicAccessModeExpectSuccess(1050 sender: IKeyringPair, collectionId: number,1051 accessMode: 'Normal' | 'AllowList',1052) {1053 await usingApi(async (api) => {10541055 // Run the transaction1056 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1057 const events = await submitTransactionAsync(sender, tx);1058 const result = getGenericResult(events);10591060 // Get the collection1061 const collection = await queryCollectionExpectSuccess(api, collectionId);10621063 // What to expect1064 // tslint:disable-next-line:no-unused-expression1065 expect(result.success).to.be.true;1066 expect(collection.access.toHuman()).to.be.equal(accessMode);1067 });1068}10691070export async function setPublicAccessModeExpectFail(1071 sender: IKeyringPair, collectionId: number,1072 accessMode: 'Normal' | 'AllowList',1073) {1074 await usingApi(async (api) => {10751076 // Run the transaction1077 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1078 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1079 const result = getGenericResult(events);10801081 // What to expect1082 // tslint:disable-next-line:no-unused-expression1083 expect(result.success).to.be.false;1084 });1085}10861087export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1088 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1089}10901091export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1092 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1093}10941095export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1096 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1097}10981099export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1100 await usingApi(async (api) => {11011102 // Run the transaction1103 const tx = api.tx.nft.setMintPermission(collectionId, enabled);1104 const events = await submitTransactionAsync(sender, tx);1105 const result = getGenericResult(events);1106 expect(result.success).to.be.true;11071108 // Get the collection1109 const collection = await queryCollectionExpectSuccess(api, collectionId);11101111 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1112 });1113}11141115export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1116 await setMintPermissionExpectSuccess(sender, collectionId, true);1117}11181119export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1120 await usingApi(async (api) => {1121 // Run the transaction1122 const tx = api.tx.nft.setMintPermission(collectionId, enabled);1123 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1124 const result = getCreateCollectionResult(events);1125 // tslint:disable-next-line:no-unused-expression1126 expect(result.success).to.be.false;1127 });1128}11291130export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1131 await usingApi(async (api) => {1132 // Run the transaction1133 const tx = api.tx.nft.setChainLimits(limits);1134 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1135 const result = getCreateCollectionResult(events);1136 // tslint:disable-next-line:no-unused-expression1137 expect(result.success).to.be.false;1138 });1139}11401141export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1142 return (await api.rpc.nft.allowed(collectionId, normalizeAccountId(address))).toJSON();1143}11441145export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1146 await usingApi(async (api) => {1147 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11481149 // Run the transaction1150 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));1151 const events = await submitTransactionAsync(sender, tx);1152 const result = getGenericResult(events);1153 expect(result.success).to.be.true;11541155 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1156 });1157}11581159export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1160 await usingApi(async (api) => {11611162 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11631164 // Run the transaction1165 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));1166 const events = await submitTransactionAsync(sender, tx);1167 const result = getGenericResult(events);1168 expect(result.success).to.be.true;11691170 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1171 });1172}11731174export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1175 await usingApi(async (api) => {11761177 // Run the transaction1178 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));1179 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1180 const result = getGenericResult(events);11811182 // What to expect1183 // tslint:disable-next-line:no-unused-expression1184 expect(result.success).to.be.false;1185 });1186}11871188export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1189 await usingApi(async (api) => {1190 // Run the transaction1191 const tx = api.tx.nft.removeFromAllowList(collectionId, normalizeAccountId(address));1192 const events = await submitTransactionAsync(sender, tx);1193 const result = getGenericResult(events);11941195 // What to expect1196 // tslint:disable-next-line:no-unused-expression1197 expect(result.success).to.be.true;1198 });1199}12001201export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1202 await usingApi(async (api) => {1203 // Run the transaction1204 const tx = api.tx.nft.removeFromAllowList(collectionId, normalizeAccountId(address));1205 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1206 const result = getGenericResult(events);12071208 // What to expect1209 // tslint:disable-next-line:no-unused-expression1210 expect(result.success).to.be.false;1211 });1212}12131214export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1215 : Promise<NftDataStructsCollection | null> => {1216 return (await api.rpc.nft.collectionById(collectionId)).unwrapOr(null);1217};12181219export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1220 // set global object - collectionsCount1221 return (await api.rpc.nft.collectionStats()).created.toNumber();1222};12231224export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<NftDataStructsCollection> {1225 return (await api.rpc.nft.collectionById(collectionId)).unwrap();1226}12271228export async function waitNewBlocks(blocksCount = 1): Promise<void> {1229 await usingApi(async (api) => {1230 const promise = new Promise<void>(async (resolve) => {1231 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1232 if (blocksCount > 0) {1233 blocksCount--;1234 } else {1235 unsubscribe();1236 resolve();1237 }1238 });1239 });1240 return promise;1241 });1242}