difftreelog
Merge pull request #277 from UniqueNetwork/feature/create-collection-ex
in: master
Add createCollectionEx call
18 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -14,7 +14,10 @@
use up_data_structs::{
COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo,
- TokenId, Weight, WithdrawReasons, CollectionStats, CustomDataLimit,
+ TokenId, Weight, WithdrawReasons, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode,
+ NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+ REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,
+ CustomDataLimit, CreateCollectionData, SponsorshipState,
};
pub use pallet::*;
use sp_core::H160;
@@ -285,6 +288,10 @@
TokenVariableDataLimitExceeded,
/// Exceeded max admin count
CollectionAdminCountExceeded,
+ /// Collection limit bounds per collection exceeded
+ CollectionLimitBoundsExceeded,
+ /// Tried to enable permissions which are only permitted to be disabled
+ OwnerPermissionsCantBeReverted,
/// Collection settings not allowing items transferring
TransferNotAllowed,
@@ -395,7 +402,10 @@
}
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+ pub fn init_collection(
+ owner: T::AccountId,
+ data: CreateCollectionData<T::AccountId>,
+ ) -> Result<CollectionId, DispatchError> {
{
ensure!(
data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,
@@ -418,6 +428,29 @@
// =========
+ let collection = Collection {
+ owner: owner.clone(),
+ name: data.name,
+ mode: data.mode.clone(),
+ mint_mode: false,
+ access: data.access.unwrap_or_default(),
+ description: data.description,
+ token_prefix: data.token_prefix,
+ offchain_schema: data.offchain_schema,
+ schema_version: data.schema_version.unwrap_or_default(),
+ sponsorship: data
+ .pending_sponsor
+ .map(SponsorshipState::Unconfirmed)
+ .unwrap_or_default(),
+ variable_on_chain_schema: data.variable_on_chain_schema,
+ const_on_chain_schema: data.const_on_chain_schema,
+ limits: data
+ .limits
+ .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))
+ .unwrap_or_else(|| Ok(CollectionLimits::default()))?,
+ meta_update_permission: data.meta_update_permission.unwrap_or_default(),
+ };
+
// Take a (non-refundable) deposit of collection creation
{
let mut imbalance =
@@ -429,7 +462,7 @@
),
);
<T as Config>::Currency::settle(
- &data.owner,
+ &owner,
imbalance,
WithdrawReasons::TRANSFER,
ExistenceRequirement::KeepAlive,
@@ -438,12 +471,8 @@
}
<CreatedCollectionCount<T>>::put(created_count);
- <Pallet<T>>::deposit_event(Event::CollectionCreated(
- id,
- data.mode.id(),
- data.owner.clone(),
- ));
- <CollectionById<T>>::insert(id, data);
+ <Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));
+ <CollectionById<T>>::insert(id, collection);
Ok(id)
}
@@ -527,6 +556,61 @@
Ok(())
}
+
+ pub fn clamp_limits(
+ mode: CollectionMode,
+ old_limit: &CollectionLimits,
+ mut new_limit: CollectionLimits,
+ ) -> Result<CollectionLimits, DispatchError> {
+ macro_rules! limit_default {
+ ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
+ $(
+ if let Some($new) = $new.$field {
+ let $old = $old.$field($($arg)?);
+ let _ = $new;
+ let _ = $old;
+ $check
+ } else {
+ $new.$field = $old.$field
+ }
+ )*
+ }};
+ }
+
+ limit_default!(old_limit, new_limit,
+ account_token_ownership_limit => ensure!(
+ new_limit <= MAX_TOKEN_OWNERSHIP,
+ <Error<T>>::CollectionLimitBoundsExceeded,
+ ),
+ sponsor_transfer_timeout(match mode {
+ CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,
+ CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+ CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+ }) => ensure!(
+ new_limit <= MAX_SPONSOR_TIMEOUT,
+ <Error<T>>::CollectionLimitBoundsExceeded,
+ ),
+ sponsored_data_size => ensure!(
+ new_limit <= CUSTOM_DATA_LIMIT,
+ <Error<T>>::CollectionLimitBoundsExceeded,
+ ),
+ token_limit => ensure!(
+ old_limit >= new_limit && new_limit > 0,
+ <Error<T>>::CollectionTokenLimitExceeded
+ ),
+ owner_can_transfer => ensure!(
+ old_limit || !new_limit,
+ <Error<T>>::OwnerPermissionsCantBeReverted,
+ ),
+ owner_can_destroy => ensure!(
+ old_limit || !new_limit,
+ <Error<T>>::OwnerPermissionsCantBeReverted,
+ ),
+ sponsored_data_rate_limit => {},
+ transfers_enabled => {},
+ );
+ Ok(new_limit)
+ }
}
#[macro_export]
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -2,7 +2,7 @@
use core::ops::Deref;
use frame_support::{ensure};
-use up_data_structs::{AccessMode, Collection, CollectionId, TokenId};
+use up_data_structs::{AccessMode, Collection, CollectionId, TokenId, CreateCollectionData};
use pallet_common::{
Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
};
@@ -100,8 +100,11 @@
}
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(data)
+ pub fn init_collection(
+ owner: T::AccountId,
+ data: CreateCollectionData<T::AccountId>,
+ ) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(owner, data)
}
pub fn destroy_collection(
collection: FungibleHandle<T>,
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -2,7 +2,9 @@
use erc::ERC721Events;
use frame_support::{BoundedVec, ensure};
-use up_data_structs::{AccessMode, Collection, CollectionId, CustomDataLimit, TokenId};
+use up_data_structs::{
+ AccessMode, Collection, CollectionId, CustomDataLimit, TokenId, CreateCollectionData,
+};
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,
};
@@ -140,8 +142,11 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(data)
+ pub fn init_collection(
+ owner: T::AccountId,
+ data: CreateCollectionData<T::AccountId>,
+ ) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(owner, 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
@@ -3,6 +3,7 @@
use frame_support::{ensure, BoundedVec};
use up_data_structs::{
AccessMode, Collection, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,
+ CreateCollectionData,
};
use pallet_common::{
Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
@@ -155,8 +156,11 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(data)
+ pub fn init_collection(
+ owner: T::AccountId,
+ data: CreateCollectionData<T::AccountId>,
+ ) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(owner, data)
}
pub fn destroy_collection(
collection: RefungibleHandle<T>,
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -36,13 +36,11 @@
use frame_system::{self as system, ensure_signed};
use sp_runtime::{sp_std::prelude::Vec};
use up_data_structs::{
- MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, CUSTOM_DATA_LIMIT,
- VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
- FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
- NFT_SPONSOR_TRANSFER_TIMEOUT, MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
+ MAX_DECIMAL_POINTS, VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
+ OFFCHAIN_SCHEMA_LIMIT, MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
MAX_TOKEN_PREFIX_LENGTH, AccessMode, Collection, CreateItemData, CollectionLimits,
CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
- CustomDataLimit,
+ CreateCollectionData, CustomDataLimit,
};
use pallet_common::{
account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
@@ -84,10 +82,6 @@
ConfirmUnsetSponsorFail,
/// Length of items properties must be greater than 0.
EmptyArgument,
- /// Collection limit bounds per collection exceeded
- CollectionLimitBoundsExceeded,
- /// Tried to enable permissions which are only permitted to be disabled
- OwnerPermissionsCantBeReverted,
}
}
@@ -321,42 +315,39 @@
// returns collection ID
#[weight = <SelfWeightOf<T>>::create_collection()]
#[transactional]
+ #[deprecated]
pub fn create_collection(origin,
collection_name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
collection_description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
- mode: CollectionMode) -> DispatchResult {
-
- // Anyone can create a collection
- let who = ensure_signed(origin)?;
-
- // Create new collection
- let new_collection = Collection {
- owner: who,
+ mode: CollectionMode) -> DispatchResult {
+ let data: CreateCollectionData<T::AccountId> = CreateCollectionData {
name: collection_name,
- mode: mode.clone(),
- mint_mode: false,
- access: AccessMode::Normal,
description: collection_description,
token_prefix,
- offchain_schema: BoundedVec::default(),
- schema_version: SchemaVersion::ImageURL,
- sponsorship: SponsorshipState::Disabled,
- variable_on_chain_schema: BoundedVec::default(),
- const_on_chain_schema: BoundedVec::default(),
- limits: Default::default(),
- meta_update_permission: Default::default(),
+ mode,
+ ..Default::default()
};
+ Self::create_collection_ex(origin, data)
+ }
+
+ /// This method creates a collection
+ ///
+ /// Prefer it to deprecated [`created_collection`] method
+ #[weight = <SelfWeightOf<T>>::create_collection()]
+ #[transactional]
+ pub fn create_collection_ex(origin, data: CreateCollectionData<T::AccountId>) -> DispatchResult {
+ let owner = ensure_signed(origin)?;
- let _id = match mode {
- CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(new_collection)?},
+ let _id = match data.mode {
+ CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(owner, data)?},
CollectionMode::Fungible(decimal_points) => {
// check params
ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
- <PalletFungible<T>>::init_collection(new_collection)?
+ <PalletFungible<T>>::init_collection(owner, data)?
}
CollectionMode::ReFungible => {
- <PalletRefungible<T>>::init_collection(new_collection)?
+ <PalletRefungible<T>>::init_collection(owner, data)?
}
};
@@ -1093,61 +1084,12 @@
collection_id: CollectionId,
new_limit: CollectionLimits,
) -> DispatchResult {
- let mut new_limit = new_limit;
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
target_collection.check_is_owner(&sender)?;
let old_limit = &target_collection.limits;
- macro_rules! limit_default {
- ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
- $(
- if let Some($new) = $new.$field {
- let $old = $old.$field($($arg)?);
- let _ = $new;
- let _ = $old;
- $check
- } else {
- $new.$field = $old.$field
- }
- )*
- }};
- }
-
- limit_default!(old_limit, new_limit,
- account_token_ownership_limit => ensure!(
- new_limit <= MAX_TOKEN_OWNERSHIP,
- <Error<T>>::CollectionLimitBoundsExceeded,
- ),
- sponsor_transfer_timeout(match target_collection.mode {
- CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,
- CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
- CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
- }) => ensure!(
- new_limit <= MAX_SPONSOR_TIMEOUT,
- <Error<T>>::CollectionLimitBoundsExceeded,
- ),
- sponsored_data_size => ensure!(
- new_limit <= CUSTOM_DATA_LIMIT,
- <Error<T>>::CollectionLimitBoundsExceeded,
- ),
- token_limit => ensure!(
- old_limit >= new_limit && new_limit > 0,
- <CommonError<T>>::CollectionTokenLimitExceeded
- ),
- owner_can_transfer => ensure!(
- old_limit || !new_limit,
- <Error<T>>::OwnerPermissionsCantBeReverted,
- ),
- owner_can_destroy => ensure!(
- old_limit || !new_limit,
- <Error<T>>::OwnerPermissionsCantBeReverted,
- ),
- sponsored_data_rate_limit => {},
- transfers_enabled => {},
- );
-
- target_collection.limits = new_limit;
+ target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;
<Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(
collection_id
pallets/unique/src/tests.rsdiffbeforeafterboth--- a/pallets/unique/src/tests.rs
+++ b/pallets/unique/src/tests.rs
@@ -5,7 +5,7 @@
use up_data_structs::{
COLLECTION_NUMBER_LIMIT, CollectionId, CreateItemData, CreateFungibleData, CreateNftData,
CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission,
- TokenId,
+ TokenId, MAX_TOKEN_OWNERSHIP,
};
use frame_support::{assert_noop, assert_ok};
use sp_std::convert::TryInto;
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -263,6 +263,31 @@
pub meta_update_permission: MetaUpdatePermission,
}
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derivative(Default(bound = ""))]
+pub struct CreateCollectionData<AccountId> {
+ #[derivative(Default(value = "CollectionMode::NFT"))]
+ pub mode: CollectionMode,
+ pub access: Option<AccessMode>,
+ #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+ pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
+ #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+ pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
+ #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+ pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
+ #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+ pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
+ pub schema_version: Option<SchemaVersion>,
+ pub pending_sponsor: Option<AccountId>,
+ pub limits: Option<CollectionLimits>,
+ #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+ pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,
+ #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+ pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,
+ pub meta_update_permission: Option<MetaUpdatePermission>,
+}
+
#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct NftItemType<AccountId> {
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -68,9 +68,10 @@
"testPalletPresence": "mocha --timeout 9999999 -r ts-node/register ./**/pallet-presence.test.ts",
"testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
"testEnableDisableTransfers": "mocha --timeout 9999999 -r ts-node/register ./**/enableDisableTransfer.test.ts",
+ "polkadot-types-fetch-metadata": "curl -H 'Content-Type: application/json' -d '{\"id\":\"1\", \"jsonrpc\":\"2.0\", \"method\": \"state_getMetadata\", \"params\":[]}' http://localhost:9933 > src/interfaces/metadata.json",
"polkadot-types-from-defs": "ts-node ./node_modules/.bin/polkadot-types-from-defs --input src/interfaces/ --package .",
- "polkadot-types-from-chain": "ts-node ./node_modules/.bin/polkadot-types-from-chain --endpoint ws://localhost:9944 --output src/interfaces/ --package .",
- "polkadot-types": "yarn polkadot-types-from-defs && yarn polkadot-types-from-chain"
+ "polkadot-types-from-chain": "ts-node ./node_modules/.bin/polkadot-types-from-chain --endpoint src/interfaces/metadata.json --output src/interfaces/ --package .",
+ "polkadot-types": "yarn polkadot-types-fetch-metadata && yarn polkadot-types-from-defs && yarn polkadot-types-from-chain"
},
"author": "",
"license": "SEE LICENSE IN ../LICENSE",
tests/src/check-event/createCollectionEvent.test.tsdiffbeforeafterboth--- a/tests/src/check-event/createCollectionEvent.test.ts
+++ b/tests/src/check-event/createCollectionEvent.test.ts
@@ -27,7 +27,7 @@
});
it('Check event from createCollection(): ', async () => {
await usingApi(async (api: ApiPromise) => {
- const tx = api.tx.unique.createCollection([0x31], [0x32], '0x33', 'NFT');
+ const tx = api.tx.unique.createCollectionEx({name: [0x31], description: [0x32], tokenPrefix: '0x33', mode: 'NFT'});
const events = await submitTransactionAsync(alice, tx);
const msg = JSON.stringify(uniqueEventMessage(events));
expect(msg).to.be.contain(checkSection);
tests/src/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -3,12 +3,11 @@
// file 'LICENSE', which is part of this source code package.
//
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {createCollectionExpectFailure, createCollectionExpectSuccess} from './util/helpers';
+import {expect} from 'chai';
+import privateKey from './substrate/privateKey';
+import usingApi, {executeTransaction, submitTransactionAsync} from './substrate/substrate-api';
+import {createCollectionExpectFailure, createCollectionExpectSuccess, getCreateCollectionResult, getDetailedCollectionInfo} from './util/helpers';
-chai.use(chaiAsPromised);
-
describe('integration test: ext. createCollection():', () => {
it('Create new NFT collection', async () => {
await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
@@ -28,6 +27,45 @@
it('Create new ReFungible collection', async () => {
await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
});
+ it('Create new collection with extra fields', async () => {
+ await usingApi(async api => {
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const tx = api.tx.unique.createCollectionEx({
+ mode: {Fungible: 8},
+ access: 'AllowList',
+ name: [1],
+ description: [2],
+ tokenPrefix: '0x000000',
+ offchainSchema: '0x111111',
+ schemaVersion: 'Unique',
+ pendingSponsor: bob.address,
+ limits: {
+ accountTokenOwnershipLimit: 3,
+ },
+ variableOnChainSchema: '0x222222',
+ constOnChainSchema: '0x333333',
+ metaUpdatePermission: 'Admin',
+ });
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getCreateCollectionResult(events);
+
+ const collection = (await getDetailedCollectionInfo(api, result.collectionId))!;
+ expect(collection.owner.toString()).to.equal(alice.address);
+ expect(collection.mode.asFungible.toNumber()).to.equal(8);
+ expect(collection.access.isAllowList).to.be.true;
+ expect(collection.name.map(v => v.toNumber())).to.deep.equal([1]);
+ expect(collection.description.map(v => v.toNumber())).to.deep.equal([2]);
+ expect(collection.tokenPrefix.toString()).to.equal('0x000000');
+ expect(collection.offchainSchema.toString()).to.equal('0x111111');
+ expect(collection.schemaVersion.isUnique).to.be.true;
+ expect(collection.sponsorship.asUnconfirmed.toString()).to.equal(bob.address);
+ expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.equal(3);
+ expect(collection.variableOnChainSchema.toString()).to.equal('0x222222');
+ expect(collection.constOnChainSchema.toString()).to.equal('0x333333');
+ expect(collection.metaUpdatePermission.isAdmin).to.be.true;
+ });
+ });
});
describe('(!negative test!) integration test: ext. createCollection():', () => {
@@ -40,4 +78,11 @@
it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
await createCollectionExpectFailure({tokenPrefix: 'A'.repeat(17), mode: {type: 'NFT'}});
});
+ it('fails when bad limits are set', async () => {
+ await usingApi(async api => {
+ const alice = privateKey('//Alice');
+ const tx = api.tx.unique.createCollectionEx({mode: 'NFT', limits: {tokenLimit: 0}});
+ await expect(executeTransaction(api, alice, tx)).to.be.rejectedWith(/^common.CollectionTokenLimitExceeded$/);
+ });
+ });
});
tests/src/interfaces/.gitignorediffbeforeafterboth--- /dev/null
+++ b/tests/src/interfaces/.gitignore
@@ -0,0 +1 @@
+metadata.json
tests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth1// Auto-generated via `yarn polkadot-types-from-chain`, do not edit2/* eslint-disable */34import type { ApiTypes } from '@polkadot/api/types';56declare module '@polkadot/api/types/errors' {7 export interface AugmentedErrors<ApiType> {8 balances: {9 /**10 * Beneficiary account must pre-exist11 **/12 DeadAccount: AugmentedError<ApiType>;13 /**14 * Value too low to create account due to existential deposit15 **/16 ExistentialDeposit: AugmentedError<ApiType>;17 /**18 * A vesting schedule already exists for this account19 **/20 ExistingVestingSchedule: AugmentedError<ApiType>;21 /**22 * Balance too low to send value23 **/24 InsufficientBalance: AugmentedError<ApiType>;25 /**26 * Transfer/payment would kill account27 **/28 KeepAlive: AugmentedError<ApiType>;29 /**30 * Account liquidity restrictions prevent withdrawal31 **/32 LiquidityRestrictions: AugmentedError<ApiType>;33 /**34 * Number of named reserves exceed MaxReserves35 **/36 TooManyReserves: AugmentedError<ApiType>;37 /**38 * Vesting balance too high to send value39 **/40 VestingBalance: AugmentedError<ApiType>;41 /**42 * Generic error43 **/44 [key: string]: AugmentedError<ApiType>;45 };46 common: {47 /**48 * Account token limit exceeded per collection49 **/50 AccountTokenLimitExceeded: AugmentedError<ApiType>;51 /**52 * Can't transfer tokens to ethereum zero address53 **/54 AddressIsZero: AugmentedError<ApiType>;55 /**56 * Address is not in allow list.57 **/58 AddressNotInAllowlist: AugmentedError<ApiType>;59 /**60 * Tried to approve more than owned61 **/62 CantApproveMoreThanOwned: AugmentedError<ApiType>;63 /**64 * Exceeded max admin count65 **/66 CollectionAdminCountExceeded: AugmentedError<ApiType>;67 /**68 * Collection description can not be longer than 255 char.69 **/70 CollectionDescriptionLimitExceeded: AugmentedError<ApiType>;71 /**72 * Collection name can not be longer than 63 char.73 **/74 CollectionNameLimitExceeded: AugmentedError<ApiType>;75 /**76 * This collection does not exist.77 **/78 CollectionNotFound: AugmentedError<ApiType>;79 /**80 * Collection token limit exceeded81 **/82 CollectionTokenLimitExceeded: AugmentedError<ApiType>;83 /**84 * Token prefix can not be longer than 15 char.85 **/86 CollectionTokenPrefixLimitExceeded: AugmentedError<ApiType>;87 /**88 * Metadata flag frozen89 **/90 MetadataFlagFrozen: AugmentedError<ApiType>;91 /**92 * Sender parameter and item owner must be equal.93 **/94 MustBeTokenOwner: AugmentedError<ApiType>;95 /**96 * No permission to perform action97 **/98 NoPermission: AugmentedError<ApiType>;99 /**100 * Collection is not in mint mode.101 **/102 PublicMintingNotAllowed: AugmentedError<ApiType>;103 /**104 * Item not exists.105 **/106 TokenNotFound: AugmentedError<ApiType>;107 /**108 * Requested value more than approved.109 **/110 TokenValueNotEnough: AugmentedError<ApiType>;111 /**112 * Item balance not enough.113 **/114 TokenValueTooLow: AugmentedError<ApiType>;115 /**116 * variable_data exceeded data limit.117 **/118 TokenVariableDataLimitExceeded: AugmentedError<ApiType>;119 /**120 * Total collections bound exceeded.121 **/122 TotalCollectionsLimitExceeded: AugmentedError<ApiType>;123 /**124 * Collection settings not allowing items transferring125 **/126 TransferNotAllowed: AugmentedError<ApiType>;127 /**128 * Target collection doesn't supports this operation129 **/130 UnsupportedOperation: AugmentedError<ApiType>;131 /**132 * Generic error133 **/134 [key: string]: AugmentedError<ApiType>;135 };136 cumulusXcm: {137 /**138 * Generic error139 **/140 [key: string]: AugmentedError<ApiType>;141 };142 dmpQueue: {143 /**144 * The amount of weight given is possibly not enough for executing the message.145 **/146 OverLimit: AugmentedError<ApiType>;147 /**148 * The message index given is unknown.149 **/150 Unknown: AugmentedError<ApiType>;151 /**152 * Generic error153 **/154 [key: string]: AugmentedError<ApiType>;155 };156 ethereum: {157 /**158 * Signature is invalid.159 **/160 InvalidSignature: AugmentedError<ApiType>;161 /**162 * Pre-log is present, therefore transact is not allowed.163 **/164 PreLogExists: AugmentedError<ApiType>;165 /**166 * Generic error167 **/168 [key: string]: AugmentedError<ApiType>;169 };170 evm: {171 /**172 * Not enough balance to perform action173 **/174 BalanceLow: AugmentedError<ApiType>;175 /**176 * Calculating total fee overflowed177 **/178 FeeOverflow: AugmentedError<ApiType>;179 /**180 * Gas price is too low.181 **/182 GasPriceTooLow: AugmentedError<ApiType>;183 /**184 * Nonce is invalid185 **/186 InvalidNonce: AugmentedError<ApiType>;187 /**188 * Calculating total payment overflowed189 **/190 PaymentOverflow: AugmentedError<ApiType>;191 /**192 * Withdraw fee failed193 **/194 WithdrawFailed: AugmentedError<ApiType>;195 /**196 * Generic error197 **/198 [key: string]: AugmentedError<ApiType>;199 };200 evmCoderSubstrate: {201 OutOfFund: AugmentedError<ApiType>;202 OutOfGas: AugmentedError<ApiType>;203 /**204 * Generic error205 **/206 [key: string]: AugmentedError<ApiType>;207 };208 evmContractHelpers: {209 /**210 * This method is only executable by owner211 **/212 NoPermission: AugmentedError<ApiType>;213 /**214 * Generic error215 **/216 [key: string]: AugmentedError<ApiType>;217 };218 evmMigration: {219 AccountIsNotMigrating: AugmentedError<ApiType>;220 AccountNotEmpty: AugmentedError<ApiType>;221 /**222 * Generic error223 **/224 [key: string]: AugmentedError<ApiType>;225 };226 fungible: {227 /**228 * Tried to set data for fungible item229 **/230 FungibleItemsDontHaveData: AugmentedError<ApiType>;231 /**232 * Not default id passed as TokenId argument233 **/234 FungibleItemsHaveNoId: AugmentedError<ApiType>;235 /**236 * Not Fungible item data used to mint in Fungible collection.237 **/238 NotFungibleDataUsedToMintFungibleCollectionToken: AugmentedError<ApiType>;239 /**240 * Generic error241 **/242 [key: string]: AugmentedError<ApiType>;243 };244 nonfungible: {245 /**246 * Used amount > 1 with NFT247 **/248 NonfungibleItemsHaveNoAmount: AugmentedError<ApiType>;249 /**250 * Not Nonfungible item data used to mint in Nonfungible collection.251 **/252 NotNonfungibleDataUsedToMintFungibleCollectionToken: AugmentedError<ApiType>;253 /**254 * Generic error255 **/256 [key: string]: AugmentedError<ApiType>;257 };258 parachainSystem: {259 /**260 * The inherent which supplies the host configuration did not run this block261 **/262 HostConfigurationNotAvailable: AugmentedError<ApiType>;263 /**264 * No code upgrade has been authorized.265 **/266 NothingAuthorized: AugmentedError<ApiType>;267 /**268 * No validation function upgrade is currently scheduled.269 **/270 NotScheduled: AugmentedError<ApiType>;271 /**272 * Attempt to upgrade validation function while existing upgrade pending273 **/274 OverlappingUpgrades: AugmentedError<ApiType>;275 /**276 * Polkadot currently prohibits this parachain from upgrading its validation function277 **/278 ProhibitedByPolkadot: AugmentedError<ApiType>;279 /**280 * The supplied validation function has compiled into a blob larger than Polkadot is281 * willing to run282 **/283 TooBig: AugmentedError<ApiType>;284 /**285 * The given code upgrade has not been authorized.286 **/287 Unauthorized: AugmentedError<ApiType>;288 /**289 * The inherent which supplies the validation data did not run this block290 **/291 ValidationDataNotAvailable: AugmentedError<ApiType>;292 /**293 * Generic error294 **/295 [key: string]: AugmentedError<ApiType>;296 };297 polkadotXcm: {298 /**299 * The location is invalid since it already has a subscription from us.300 **/301 AlreadySubscribed: AugmentedError<ApiType>;302 /**303 * The given location could not be used (e.g. because it cannot be expressed in the304 * desired version of XCM).305 **/306 BadLocation: AugmentedError<ApiType>;307 /**308 * The version of the `Versioned` value used is not able to be interpreted.309 **/310 BadVersion: AugmentedError<ApiType>;311 /**312 * Could not re-anchor the assets to declare the fees for the destination chain.313 **/314 CannotReanchor: AugmentedError<ApiType>;315 /**316 * The destination `MultiLocation` provided cannot be inverted.317 **/318 DestinationNotInvertible: AugmentedError<ApiType>;319 /**320 * The assets to be sent are empty.321 **/322 Empty: AugmentedError<ApiType>;323 /**324 * The message execution fails the filter.325 **/326 Filtered: AugmentedError<ApiType>;327 /**328 * Origin is invalid for sending.329 **/330 InvalidOrigin: AugmentedError<ApiType>;331 /**332 * The referenced subscription could not be found.333 **/334 NoSubscription: AugmentedError<ApiType>;335 /**336 * There was some other issue (i.e. not to do with routing) in sending the message. Perhaps337 * a lack of space for buffering the message.338 **/339 SendFailure: AugmentedError<ApiType>;340 /**341 * Too many assets have been attempted for transfer.342 **/343 TooManyAssets: AugmentedError<ApiType>;344 /**345 * The desired destination was unreachable, generally because there is a no way of routing346 * to it.347 **/348 Unreachable: AugmentedError<ApiType>;349 /**350 * The message's weight could not be determined.351 **/352 UnweighableMessage: AugmentedError<ApiType>;353 /**354 * Generic error355 **/356 [key: string]: AugmentedError<ApiType>;357 };358 refungible: {359 /**360 * Not Refungible item data used to mint in Refungible collection.361 **/362 NotRefungibleDataUsedToMintFungibleCollectionToken: AugmentedError<ApiType>;363 /**364 * Maximum refungibility exceeded365 **/366 WrongRefungiblePieces: AugmentedError<ApiType>;367 /**368 * Generic error369 **/370 [key: string]: AugmentedError<ApiType>;371 };372 sudo: {373 /**374 * Sender must be the Sudo account375 **/376 RequireSudo: AugmentedError<ApiType>;377 /**378 * Generic error379 **/380 [key: string]: AugmentedError<ApiType>;381 };382 system: {383 /**384 * The origin filter prevent the call to be dispatched.385 **/386 CallFiltered: AugmentedError<ApiType>;387 /**388 * Failed to extract the runtime version from the new runtime.389 * 390 * Either calling `Core_version` or decoding `RuntimeVersion` failed.391 **/392 FailedToExtractRuntimeVersion: AugmentedError<ApiType>;393 /**394 * The name of specification does not match between the current runtime395 * and the new runtime.396 **/397 InvalidSpecName: AugmentedError<ApiType>;398 /**399 * Suicide called when the account has non-default composite data.400 **/401 NonDefaultComposite: AugmentedError<ApiType>;402 /**403 * There is a non-zero reference count preventing the account from being purged.404 **/405 NonZeroRefCount: AugmentedError<ApiType>;406 /**407 * The specification version is not allowed to decrease between the current runtime408 * and the new runtime.409 **/410 SpecVersionNeedsToIncrease: AugmentedError<ApiType>;411 /**412 * Generic error413 **/414 [key: string]: AugmentedError<ApiType>;415 };416 treasury: {417 /**418 * Proposer's balance is too low.419 **/420 InsufficientProposersBalance: AugmentedError<ApiType>;421 /**422 * No proposal or bounty at that index.423 **/424 InvalidIndex: AugmentedError<ApiType>;425 /**426 * Too many approvals in the queue.427 **/428 TooManyApprovals: AugmentedError<ApiType>;429 /**430 * Generic error431 **/432 [key: string]: AugmentedError<ApiType>;433 };434 unique: {435 /**436 * Decimal_points parameter must be lower than MAX_DECIMAL_POINTS constant, currently it is 30.437 **/438 CollectionDecimalPointLimitExceeded: AugmentedError<ApiType>;439 /**440 * Collection limit bounds per collection exceeded441 **/442 CollectionLimitBoundsExceeded: AugmentedError<ApiType>;443 /**444 * This address is not set as sponsor, use setCollectionSponsor first.445 **/446 ConfirmUnsetSponsorFail: AugmentedError<ApiType>;447 /**448 * Length of items properties must be greater than 0.449 **/450 EmptyArgument: AugmentedError<ApiType>;451 /**452 * Tried to enable permissions which are only permitted to be disabled453 **/454 OwnerPermissionsCantBeReverted: AugmentedError<ApiType>;455 /**456 * Generic error457 **/458 [key: string]: AugmentedError<ApiType>;459 };460 vesting: {461 /**462 * The vested transfer amount is too low463 **/464 AmountLow: AugmentedError<ApiType>;465 /**466 * Insufficient amount of balance to lock467 **/468 InsufficientBalanceToLock: AugmentedError<ApiType>;469 /**470 * Failed because the maximum vesting schedules was exceeded471 **/472 MaxVestingSchedulesExceeded: AugmentedError<ApiType>;473 /**474 * This account have too many vesting schedules475 **/476 TooManyVestingSchedules: AugmentedError<ApiType>;477 /**478 * Vesting period is zero479 **/480 ZeroVestingPeriod: AugmentedError<ApiType>;481 /**482 * Number of vests is zero483 **/484 ZeroVestingPeriodCount: AugmentedError<ApiType>;485 /**486 * Generic error487 **/488 [key: string]: AugmentedError<ApiType>;489 };490 xcmpQueue: {491 /**492 * Bad overweight index.493 **/494 BadOverweightIndex: AugmentedError<ApiType>;495 /**496 * Bad XCM data.497 **/498 BadXcm: AugmentedError<ApiType>;499 /**500 * Bad XCM origin.501 **/502 BadXcmOrigin: AugmentedError<ApiType>;503 /**504 * Failed to send XCM message.505 **/506 FailedToSend: AugmentedError<ApiType>;507 /**508 * Provided weight is possibly not enough to execute the message.509 **/510 WeightOverLimit: AugmentedError<ApiType>;511 /**512 * Generic error513 **/514 [key: string]: AugmentedError<ApiType>;515 };516 }517518 export interface DecoratedErrors<ApiType extends ApiTypes> extends AugmentedErrors<ApiType> {519 [key: string]: ModuleErrors<ApiType>;520 }521}1// Auto-generated via `yarn polkadot-types-from-chain`, do not edit2/* eslint-disable */34import type { ApiTypes } from '@polkadot/api/types';56declare module '@polkadot/api/types/errors' {7 export interface AugmentedErrors<ApiType> {8 balances: {9 /**10 * Beneficiary account must pre-exist11 **/12 DeadAccount: AugmentedError<ApiType>;13 /**14 * Value too low to create account due to existential deposit15 **/16 ExistentialDeposit: AugmentedError<ApiType>;17 /**18 * A vesting schedule already exists for this account19 **/20 ExistingVestingSchedule: AugmentedError<ApiType>;21 /**22 * Balance too low to send value23 **/24 InsufficientBalance: AugmentedError<ApiType>;25 /**26 * Transfer/payment would kill account27 **/28 KeepAlive: AugmentedError<ApiType>;29 /**30 * Account liquidity restrictions prevent withdrawal31 **/32 LiquidityRestrictions: AugmentedError<ApiType>;33 /**34 * Number of named reserves exceed MaxReserves35 **/36 TooManyReserves: AugmentedError<ApiType>;37 /**38 * Vesting balance too high to send value39 **/40 VestingBalance: AugmentedError<ApiType>;41 /**42 * Generic error43 **/44 [key: string]: AugmentedError<ApiType>;45 };46 common: {47 /**48 * Account token limit exceeded per collection49 **/50 AccountTokenLimitExceeded: AugmentedError<ApiType>;51 /**52 * Can't transfer tokens to ethereum zero address53 **/54 AddressIsZero: AugmentedError<ApiType>;55 /**56 * Address is not in allow list.57 **/58 AddressNotInAllowlist: AugmentedError<ApiType>;59 /**60 * Tried to approve more than owned61 **/62 CantApproveMoreThanOwned: AugmentedError<ApiType>;63 /**64 * Exceeded max admin count65 **/66 CollectionAdminCountExceeded: AugmentedError<ApiType>;67 /**68 * Collection description can not be longer than 255 char.69 **/70 CollectionDescriptionLimitExceeded: AugmentedError<ApiType>;71 /**72 * Collection limit bounds per collection exceeded73 **/74 CollectionLimitBoundsExceeded: AugmentedError<ApiType>;75 /**76 * Collection name can not be longer than 63 char.77 **/78 CollectionNameLimitExceeded: AugmentedError<ApiType>;79 /**80 * This collection does not exist.81 **/82 CollectionNotFound: AugmentedError<ApiType>;83 /**84 * Collection token limit exceeded85 **/86 CollectionTokenLimitExceeded: AugmentedError<ApiType>;87 /**88 * Token prefix can not be longer than 15 char.89 **/90 CollectionTokenPrefixLimitExceeded: AugmentedError<ApiType>;91 /**92 * Metadata flag frozen93 **/94 MetadataFlagFrozen: AugmentedError<ApiType>;95 /**96 * Sender parameter and item owner must be equal.97 **/98 MustBeTokenOwner: AugmentedError<ApiType>;99 /**100 * No permission to perform action101 **/102 NoPermission: AugmentedError<ApiType>;103 /**104 * Tried to enable permissions which are only permitted to be disabled105 **/106 OwnerPermissionsCantBeReverted: AugmentedError<ApiType>;107 /**108 * Collection is not in mint mode.109 **/110 PublicMintingNotAllowed: AugmentedError<ApiType>;111 /**112 * Item not exists.113 **/114 TokenNotFound: AugmentedError<ApiType>;115 /**116 * Requested value more than approved.117 **/118 TokenValueNotEnough: AugmentedError<ApiType>;119 /**120 * Item balance not enough.121 **/122 TokenValueTooLow: AugmentedError<ApiType>;123 /**124 * variable_data exceeded data limit.125 **/126 TokenVariableDataLimitExceeded: AugmentedError<ApiType>;127 /**128 * Total collections bound exceeded.129 **/130 TotalCollectionsLimitExceeded: AugmentedError<ApiType>;131 /**132 * Collection settings not allowing items transferring133 **/134 TransferNotAllowed: AugmentedError<ApiType>;135 /**136 * Target collection doesn't supports this operation137 **/138 UnsupportedOperation: AugmentedError<ApiType>;139 /**140 * Generic error141 **/142 [key: string]: AugmentedError<ApiType>;143 };144 cumulusXcm: {145 /**146 * Generic error147 **/148 [key: string]: AugmentedError<ApiType>;149 };150 dmpQueue: {151 /**152 * The amount of weight given is possibly not enough for executing the message.153 **/154 OverLimit: AugmentedError<ApiType>;155 /**156 * The message index given is unknown.157 **/158 Unknown: AugmentedError<ApiType>;159 /**160 * Generic error161 **/162 [key: string]: AugmentedError<ApiType>;163 };164 ethereum: {165 /**166 * Signature is invalid.167 **/168 InvalidSignature: AugmentedError<ApiType>;169 /**170 * Pre-log is present, therefore transact is not allowed.171 **/172 PreLogExists: AugmentedError<ApiType>;173 /**174 * Generic error175 **/176 [key: string]: AugmentedError<ApiType>;177 };178 evm: {179 /**180 * Not enough balance to perform action181 **/182 BalanceLow: AugmentedError<ApiType>;183 /**184 * Calculating total fee overflowed185 **/186 FeeOverflow: AugmentedError<ApiType>;187 /**188 * Gas price is too low.189 **/190 GasPriceTooLow: AugmentedError<ApiType>;191 /**192 * Nonce is invalid193 **/194 InvalidNonce: AugmentedError<ApiType>;195 /**196 * Calculating total payment overflowed197 **/198 PaymentOverflow: AugmentedError<ApiType>;199 /**200 * Withdraw fee failed201 **/202 WithdrawFailed: AugmentedError<ApiType>;203 /**204 * Generic error205 **/206 [key: string]: AugmentedError<ApiType>;207 };208 evmCoderSubstrate: {209 OutOfFund: AugmentedError<ApiType>;210 OutOfGas: AugmentedError<ApiType>;211 /**212 * Generic error213 **/214 [key: string]: AugmentedError<ApiType>;215 };216 evmContractHelpers: {217 /**218 * This method is only executable by owner219 **/220 NoPermission: AugmentedError<ApiType>;221 /**222 * Generic error223 **/224 [key: string]: AugmentedError<ApiType>;225 };226 evmMigration: {227 AccountIsNotMigrating: AugmentedError<ApiType>;228 AccountNotEmpty: AugmentedError<ApiType>;229 /**230 * Generic error231 **/232 [key: string]: AugmentedError<ApiType>;233 };234 fungible: {235 /**236 * Tried to set data for fungible item237 **/238 FungibleItemsDontHaveData: AugmentedError<ApiType>;239 /**240 * Not default id passed as TokenId argument241 **/242 FungibleItemsHaveNoId: AugmentedError<ApiType>;243 /**244 * Not Fungible item data used to mint in Fungible collection.245 **/246 NotFungibleDataUsedToMintFungibleCollectionToken: AugmentedError<ApiType>;247 /**248 * Generic error249 **/250 [key: string]: AugmentedError<ApiType>;251 };252 nonfungible: {253 /**254 * Used amount > 1 with NFT255 **/256 NonfungibleItemsHaveNoAmount: AugmentedError<ApiType>;257 /**258 * Not Nonfungible item data used to mint in Nonfungible collection.259 **/260 NotNonfungibleDataUsedToMintFungibleCollectionToken: AugmentedError<ApiType>;261 /**262 * Generic error263 **/264 [key: string]: AugmentedError<ApiType>;265 };266 parachainSystem: {267 /**268 * The inherent which supplies the host configuration did not run this block269 **/270 HostConfigurationNotAvailable: AugmentedError<ApiType>;271 /**272 * No code upgrade has been authorized.273 **/274 NothingAuthorized: AugmentedError<ApiType>;275 /**276 * No validation function upgrade is currently scheduled.277 **/278 NotScheduled: AugmentedError<ApiType>;279 /**280 * Attempt to upgrade validation function while existing upgrade pending281 **/282 OverlappingUpgrades: AugmentedError<ApiType>;283 /**284 * Polkadot currently prohibits this parachain from upgrading its validation function285 **/286 ProhibitedByPolkadot: AugmentedError<ApiType>;287 /**288 * The supplied validation function has compiled into a blob larger than Polkadot is289 * willing to run290 **/291 TooBig: AugmentedError<ApiType>;292 /**293 * The given code upgrade has not been authorized.294 **/295 Unauthorized: AugmentedError<ApiType>;296 /**297 * The inherent which supplies the validation data did not run this block298 **/299 ValidationDataNotAvailable: AugmentedError<ApiType>;300 /**301 * Generic error302 **/303 [key: string]: AugmentedError<ApiType>;304 };305 polkadotXcm: {306 /**307 * The location is invalid since it already has a subscription from us.308 **/309 AlreadySubscribed: AugmentedError<ApiType>;310 /**311 * The given location could not be used (e.g. because it cannot be expressed in the312 * desired version of XCM).313 **/314 BadLocation: AugmentedError<ApiType>;315 /**316 * The version of the `Versioned` value used is not able to be interpreted.317 **/318 BadVersion: AugmentedError<ApiType>;319 /**320 * Could not re-anchor the assets to declare the fees for the destination chain.321 **/322 CannotReanchor: AugmentedError<ApiType>;323 /**324 * The destination `MultiLocation` provided cannot be inverted.325 **/326 DestinationNotInvertible: AugmentedError<ApiType>;327 /**328 * The assets to be sent are empty.329 **/330 Empty: AugmentedError<ApiType>;331 /**332 * The message execution fails the filter.333 **/334 Filtered: AugmentedError<ApiType>;335 /**336 * Origin is invalid for sending.337 **/338 InvalidOrigin: AugmentedError<ApiType>;339 /**340 * The referenced subscription could not be found.341 **/342 NoSubscription: AugmentedError<ApiType>;343 /**344 * There was some other issue (i.e. not to do with routing) in sending the message. Perhaps345 * a lack of space for buffering the message.346 **/347 SendFailure: AugmentedError<ApiType>;348 /**349 * Too many assets have been attempted for transfer.350 **/351 TooManyAssets: AugmentedError<ApiType>;352 /**353 * The desired destination was unreachable, generally because there is a no way of routing354 * to it.355 **/356 Unreachable: AugmentedError<ApiType>;357 /**358 * The message's weight could not be determined.359 **/360 UnweighableMessage: AugmentedError<ApiType>;361 /**362 * Generic error363 **/364 [key: string]: AugmentedError<ApiType>;365 };366 refungible: {367 /**368 * Not Refungible item data used to mint in Refungible collection.369 **/370 NotRefungibleDataUsedToMintFungibleCollectionToken: AugmentedError<ApiType>;371 /**372 * Maximum refungibility exceeded373 **/374 WrongRefungiblePieces: AugmentedError<ApiType>;375 /**376 * Generic error377 **/378 [key: string]: AugmentedError<ApiType>;379 };380 sudo: {381 /**382 * Sender must be the Sudo account383 **/384 RequireSudo: AugmentedError<ApiType>;385 /**386 * Generic error387 **/388 [key: string]: AugmentedError<ApiType>;389 };390 system: {391 /**392 * The origin filter prevent the call to be dispatched.393 **/394 CallFiltered: AugmentedError<ApiType>;395 /**396 * Failed to extract the runtime version from the new runtime.397 * 398 * Either calling `Core_version` or decoding `RuntimeVersion` failed.399 **/400 FailedToExtractRuntimeVersion: AugmentedError<ApiType>;401 /**402 * The name of specification does not match between the current runtime403 * and the new runtime.404 **/405 InvalidSpecName: AugmentedError<ApiType>;406 /**407 * Suicide called when the account has non-default composite data.408 **/409 NonDefaultComposite: AugmentedError<ApiType>;410 /**411 * There is a non-zero reference count preventing the account from being purged.412 **/413 NonZeroRefCount: AugmentedError<ApiType>;414 /**415 * The specification version is not allowed to decrease between the current runtime416 * and the new runtime.417 **/418 SpecVersionNeedsToIncrease: AugmentedError<ApiType>;419 /**420 * Generic error421 **/422 [key: string]: AugmentedError<ApiType>;423 };424 treasury: {425 /**426 * Proposer's balance is too low.427 **/428 InsufficientProposersBalance: AugmentedError<ApiType>;429 /**430 * No proposal or bounty at that index.431 **/432 InvalidIndex: AugmentedError<ApiType>;433 /**434 * Too many approvals in the queue.435 **/436 TooManyApprovals: AugmentedError<ApiType>;437 /**438 * Generic error439 **/440 [key: string]: AugmentedError<ApiType>;441 };442 unique: {443 /**444 * Decimal_points parameter must be lower than MAX_DECIMAL_POINTS constant, currently it is 30.445 **/446 CollectionDecimalPointLimitExceeded: AugmentedError<ApiType>;447 /**448 * This address is not set as sponsor, use setCollectionSponsor first.449 **/450 ConfirmUnsetSponsorFail: AugmentedError<ApiType>;451 /**452 * Length of items properties must be greater than 0.453 **/454 EmptyArgument: AugmentedError<ApiType>;455 /**456 * Generic error457 **/458 [key: string]: AugmentedError<ApiType>;459 };460 vesting: {461 /**462 * The vested transfer amount is too low463 **/464 AmountLow: AugmentedError<ApiType>;465 /**466 * Insufficient amount of balance to lock467 **/468 InsufficientBalanceToLock: AugmentedError<ApiType>;469 /**470 * Failed because the maximum vesting schedules was exceeded471 **/472 MaxVestingSchedulesExceeded: AugmentedError<ApiType>;473 /**474 * This account have too many vesting schedules475 **/476 TooManyVestingSchedules: AugmentedError<ApiType>;477 /**478 * Vesting period is zero479 **/480 ZeroVestingPeriod: AugmentedError<ApiType>;481 /**482 * Number of vests is zero483 **/484 ZeroVestingPeriodCount: AugmentedError<ApiType>;485 /**486 * Generic error487 **/488 [key: string]: AugmentedError<ApiType>;489 };490 xcmpQueue: {491 /**492 * Bad overweight index.493 **/494 BadOverweightIndex: AugmentedError<ApiType>;495 /**496 * Bad XCM data.497 **/498 BadXcm: AugmentedError<ApiType>;499 /**500 * Bad XCM origin.501 **/502 BadXcmOrigin: AugmentedError<ApiType>;503 /**504 * Failed to send XCM message.505 **/506 FailedToSend: AugmentedError<ApiType>;507 /**508 * Provided weight is possibly not enough to execute the message.509 **/510 WeightOverLimit: AugmentedError<ApiType>;511 /**512 * Generic error513 **/514 [key: string]: AugmentedError<ApiType>;515 };516 }517518 export interface DecoratedErrors<ApiType extends ApiTypes> extends AugmentedErrors<ApiType> {519 [key: string]: ModuleErrors<ApiType>;520 }521}tests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -2,7 +2,7 @@
/* eslint-disable */
import type { CumulusPrimitivesParachainInherentParachainInherentData } from './polkadot';
-import type { PalletCommonAccountBasicCrossAccountIdRepr, UpDataStructsAccessMode, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion } from './unique';
+import type { PalletCommonAccountBasicCrossAccountIdRepr, UpDataStructsAccessMode, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCreateCollectionData, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion } from './unique';
import type { ApiTypes, SubmittableExtrinsic } from '@polkadot/api/types';
import type { Bytes, Compact, Option, U256, Vec, bool, u128, u16, u32, u64 } from '@polkadot/types';
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
@@ -671,6 +671,12 @@
**/
createCollection: AugmentedSubmittable<(collectionName: Vec<u16> | (u16 | AnyNumber | Uint8Array)[], collectionDescription: Vec<u16> | (u16 | AnyNumber | Uint8Array)[], tokenPrefix: Bytes | string | Uint8Array, mode: UpDataStructsCollectionMode | { NFT: any } | { Fungible: any } | { ReFungible: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Vec<u16>, Vec<u16>, Bytes, UpDataStructsCollectionMode]>;
/**
+ * This method creates a collection
+ *
+ * Prefer it to deprecated [`created_collection`] method
+ **/
+ createCollectionEx: AugmentedSubmittable<(data: UpDataStructsCreateCollectionData | { mode?: any; access?: any; name?: any; description?: any; tokenPrefix?: any; offchainSchema?: any; schemaVersion?: any; pendingSponsor?: any; limits?: any; variableOnChainSchema?: any; constOnChainSchema?: any; metaUpdatePermission?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [UpDataStructsCreateCollectionData]>;
+ /**
* This method creates a concrete instance of NFT Collection created with CreateCollection method.
*
* # Permissions
tests/src/interfaces/augment-types.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -3,7 +3,7 @@
import type { EthereumBlock, EthereumLog, EthereumReceipt, EthereumTransactionLegacyTransaction, EvmCoreErrorExitReason, FpRpcTransactionStatus } from './ethereum';
import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundStatus, CumulusPalletXcmpQueueOutboundStatus, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV1AbridgedHostConfiguration, PolkadotPrimitivesV1PersistedValidationData } from './polkadot';
-import type { PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2, UpDataStructsAccessMode, UpDataStructsCollection, UpDataStructsCollectionId, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCollectionStats, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion, UpDataStructsSponsorshipState, UpDataStructsTokenId } from './unique';
+import type { PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2, UpDataStructsAccessMode, UpDataStructsCollection, UpDataStructsCollectionId, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCollectionStats, UpDataStructsCreateCollectionData, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion, UpDataStructsSponsorshipState, UpDataStructsTokenId } from './unique';
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';
import type { BlockAttestations, IncludedBlocks, MoreAttestations } from '@polkadot/types/interfaces/attestations';
@@ -1021,6 +1021,7 @@
UpDataStructsCollectionLimits: UpDataStructsCollectionLimits;
UpDataStructsCollectionMode: UpDataStructsCollectionMode;
UpDataStructsCollectionStats: UpDataStructsCollectionStats;
+ UpDataStructsCreateCollectionData: UpDataStructsCreateCollectionData;
UpDataStructsCreateItemData: UpDataStructsCreateItemData;
UpDataStructsMetaUpdatePermission: UpDataStructsMetaUpdatePermission;
UpDataStructsSchemaVersion: UpDataStructsSchemaVersion;
tests/src/interfaces/unique/definitions.tsdiffbeforeafterboth--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -67,6 +67,20 @@
constOnChainSchema: 'Vec<u8>',
metaUpdatePermission: 'UpDataStructsMetaUpdatePermission',
},
+ UpDataStructsCreateCollectionData: {
+ mode: 'UpDataStructsCollectionMode',
+ access: 'Option<UpDataStructsAccessMode>',
+ name: 'Vec<u16>',
+ description: 'Vec<u16>',
+ tokenPrefix: 'Vec<u8>',
+ offchainSchema: 'Vec<u8>',
+ schemaVersion: 'Option<UpDataStructsSchemaVersion>',
+ pendingSponsor: 'Option<AccountId>',
+ limits: 'Option<UpDataStructsCollectionLimits>',
+ variableOnChainSchema: 'Vec<u8>',
+ constOnChainSchema: 'Vec<u8>',
+ metaUpdatePermission: 'Option<UpDataStructsMetaUpdatePermission>',
+ },
UpDataStructsCollectionStats: {
created: 'u32',
destroyed: 'u32',
@@ -76,7 +90,13 @@
UpDataStructsTokenId: 'u32',
PalletNonfungibleItemData: mkDummy('NftItemData'),
PalletRefungibleItemData: mkDummy('RftItemData'),
- UpDataStructsCollectionMode: mkDummy('CollectionMode'),
+ UpDataStructsCollectionMode: {
+ _enum: {
+ NFT: null,
+ Fungible: 'u32',
+ ReFungible: null,
+ },
+ },
UpDataStructsCreateItemData: mkDummy('CreateItemData'),
UpDataStructsCollectionLimits: {
accountTokenOwnershipLimit: 'Option<u32>',
@@ -101,7 +121,9 @@
UpDataStructsAccessMode: {
_enum: ['Normal', 'AllowList'],
},
- UpDataStructsSchemaVersion: mkDummy('SchemaVersion'),
+ UpDataStructsSchemaVersion: {
+ _enum: ['ImageURL', 'Unique'],
+ },
PalletUnqSchedulerScheduledV2: mkDummy('ScheduledV2'),
PalletUnqSchedulerCallSpec: mkDummy('CallSpec'),
tests/src/interfaces/unique/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/unique/types.ts
+++ b/tests/src/interfaces/unique/types.ts
@@ -77,8 +77,11 @@
}
/** @name UpDataStructsCollectionMode */
-export interface UpDataStructsCollectionMode extends Struct {
- readonly dummyCollectionMode: u32;
+export interface UpDataStructsCollectionMode extends Enum {
+ readonly isNft: boolean;
+ readonly isFungible: boolean;
+ readonly asFungible: u32;
+ readonly isReFungible: boolean;
}
/** @name UpDataStructsCollectionStats */
@@ -88,6 +91,22 @@
readonly alive: u32;
}
+/** @name UpDataStructsCreateCollectionData */
+export interface UpDataStructsCreateCollectionData extends Struct {
+ readonly mode: UpDataStructsCollectionMode;
+ readonly access: Option<UpDataStructsAccessMode>;
+ readonly name: Vec<u16>;
+ readonly description: Vec<u16>;
+ readonly tokenPrefix: Bytes;
+ readonly offchainSchema: Bytes;
+ readonly schemaVersion: Option<UpDataStructsSchemaVersion>;
+ readonly pendingSponsor: Option<AccountId>;
+ readonly limits: Option<UpDataStructsCollectionLimits>;
+ readonly variableOnChainSchema: Bytes;
+ readonly constOnChainSchema: Bytes;
+ readonly metaUpdatePermission: Option<UpDataStructsMetaUpdatePermission>;
+}
+
/** @name UpDataStructsCreateItemData */
export interface UpDataStructsCreateItemData extends Struct {
readonly dummyCreateItemData: u32;
@@ -101,8 +120,9 @@
}
/** @name UpDataStructsSchemaVersion */
-export interface UpDataStructsSchemaVersion extends Struct {
- readonly dummySchemaVersion: u32;
+export interface UpDataStructsSchemaVersion extends Enum {
+ readonly isImageUrl: boolean;
+ readonly isUnique: boolean;
}
/** @name UpDataStructsSponsorshipState */
tests/src/substrate/substrate-api.tsdiffbeforeafterboth--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -95,6 +95,32 @@
return TransactionStatus.Fail;
}
+export function executeTransaction(api: ApiPromise, sender: IKeyringPair, transaction: SubmittableExtrinsic<'promise'>): Promise<EventRecord[]> {
+ return new Promise(async (res, rej) => {
+ try {
+ await transaction.signAndSend(sender, ({events, status}) => {
+ if (!status.isInBlock && !status.isFinalized) return;
+ for (const {event} of events) {
+ if (api.events.system.ExtrinsicSuccess.is(event)) {
+ res(events);
+ } else if (api.events.system.ExtrinsicFailed.is(event)) {
+ const {data: [error]} = event;
+ if (error.isModule) {
+ const decoded = api.registry.findMetaError(error.asModule);
+ const {method, section} = decoded;
+ rej(new Error(`${section}.${method}`));
+ } else {
+ rej(new Error(error.toString()));
+ }
+ }
+ }
+ });
+ } catch (e) {
+ rej(e);
+ }
+ });
+}
+
export function
submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {
/* eslint no-async-promise-executor: "off" */
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -49,7 +49,7 @@
};
} else if ('Substrate' in input) {
return input;
- }else if ('substrate' in input) {
+ } else if ('substrate' in input) {
return {
Substrate: (input as any).substrate,
};
@@ -116,15 +116,15 @@
export interface IChainLimits {
collectionNumbersLimit: number;
- accountTokenOwnershipLimit: number;
- collectionsAdminsLimit: number;
- customDataLimit: number;
- nftSponsorTransferTimeout: number;
- fungibleSponsorTransferTimeout: number;
- refungibleSponsorTransferTimeout: number;
- offchainSchemaLimit: number;
- variableOnChainSchemaLimit: number;
- constOnChainSchemaLimit: number;
+ accountTokenOwnershipLimit: number;
+ collectionsAdminsLimit: number;
+ customDataLimit: number;
+ nftSponsorTransferTimeout: number;
+ fungibleSponsorTransferTimeout: number;
+ refungibleSponsorTransferTimeout: number;
+ offchainSchemaLimit: number;
+ variableOnChainSchemaLimit: number;
+ constOnChainSchemaLimit: number;
}
export interface IReFungibleTokenDataType {
@@ -283,7 +283,7 @@
modeprm = {refungible: null};
}
- const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);
+ const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
const events = await submitTransactionAsync(alicePrivateKey, tx);
const result = getCreateCollectionResult(events);
@@ -329,7 +329,7 @@
// Run the CreateCollection transaction
const alicePrivateKey = privateKey('//Alice');
- const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);
+ const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
const result = getCreateCollectionResult(events);
@@ -557,7 +557,7 @@
await usingApi(async (api) => {
- const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);
+ const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
const events = await submitTransactionAsync(sender, tx);
const result = getGenericResult(events);
@@ -569,7 +569,7 @@
await usingApi(async (api) => {
- const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);
+ const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
const result = getGenericResult(events);
@@ -811,8 +811,7 @@
}
export async function
-getFreeBalance(account: IKeyringPair) : Promise<bigint>
-{
+getFreeBalance(account: IKeyringPair): Promise<bigint> {
let balance = 0n;
await usingApi(async (api) => {
balance = BigInt((await api.query.system.account(account.address)).data.free.toString());