git.delta.rocks / unique-network / refs/commits / 96967bb10fde

difftreelog

Integration tests for setCollectionSponsor

Greg Zaitsev2020-12-23parent: #8686594.patch.diff
in: master

6 files changed

modifiednode/src/chain_spec.rsdiffbeforeafterboth
--- a/node/src/chain_spec.rs
+++ b/node/src/chain_spec.rs
@@ -193,7 +193,7 @@
 					offchain_schema: vec![],
 					schema_version: SchemaVersion::default(),
                     sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),
-                    unconfirmed_sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),
+                    sponsor_confirmed: true,
                     const_on_chain_schema: vec![],
 					variable_on_chain_schema: vec![],
 					limits: CollectionLimits::default()
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -136,7 +136,7 @@
     pub offchain_schema: Vec<u8>,
     pub schema_version: SchemaVersion,
     pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender
-    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship
+    pub sponsor_confirmed: bool, // False if sponsor address has not yet confirmed sponsorship. True otherwise.
     pub limits: CollectionLimits, // Collection private restrictions 
     pub variable_on_chain_schema: Vec<u8>, //
     pub const_on_chain_schema: Vec<u8>, //
@@ -591,7 +591,7 @@
                 offchain_schema: Vec::new(),
                 schema_version: SchemaVersion::ImageURL,
                 sponsor: T::AccountId::default(),
-                unconfirmed_sponsor: T::AccountId::default(),
+                sponsor_confirmed: false,
                 variable_on_chain_schema: Vec::new(),
                 const_on_chain_schema: Vec::new(),
                 limits: CollectionLimits::default(),
@@ -869,7 +869,8 @@
             let mut target_collection = <Collection<T>>::get(collection_id);
             ensure!(sender == target_collection.owner, Error::<T>::NoPermission);
 
-            target_collection.unconfirmed_sponsor = new_sponsor;
+            target_collection.sponsor = new_sponsor;
+            target_collection.sponsor_confirmed = false;
             <Collection<T>>::insert(collection_id, target_collection);
 
             Ok(())
@@ -889,10 +890,9 @@
             ensure!(<Collection<T>>::contains_key(collection_id), Error::<T>::CollectionNotFound);
 
             let mut target_collection = <Collection<T>>::get(collection_id);
-            ensure!(sender == target_collection.unconfirmed_sponsor, Error::<T>::ConfirmUnsetSponsorFail);
+            ensure!(sender == target_collection.sponsor, Error::<T>::ConfirmUnsetSponsorFail);
 
-            target_collection.sponsor = target_collection.unconfirmed_sponsor;
-            target_collection.unconfirmed_sponsor = T::AccountId::default();
+            target_collection.sponsor_confirmed = true;
             <Collection<T>>::insert(collection_id, target_collection);
 
             Ok(())
@@ -917,6 +917,7 @@
             ensure!(sender == target_collection.owner, Error::<T>::NoPermission);
 
             target_collection.sponsor = T::AccountId::default();
+            target_collection.sponsor_confirmed = false;
             <Collection<T>>::insert(collection_id, target_collection);
 
             Ok(())
@@ -2338,7 +2339,8 @@
             Some(Call::create_item(collection_id, _owner, _properties)) => {
 
                 // check free create limit
-                if <Collection<T>>::get(collection_id).limits.sponsored_data_size >= (_properties.len() as u32)
+                if (<Collection<T>>::get(collection_id).limits.sponsored_data_size >= (_properties.len() as u32)) &&
+                   (<Collection<T>>::get(collection_id).sponsor_confirmed)
                 {
                     <Collection<T>>::get(collection_id).sponsor
                 } else {
@@ -2347,84 +2349,87 @@
             }
             Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {
                 
-                let _collection_limits = <Collection<T>>::get(collection_id).limits;
-                let _collection_mode = <Collection<T>>::get(collection_id).mode;
-
-                // sponsor timeout
-                let sponsor_transfer = match _collection_mode {
-                    CollectionMode::NFT => {
-
-                        // get correct limit
-                        let limit: u32 = if _collection_limits.sponsor_transfer_timeout > 0 {
-                            _collection_limits.sponsor_transfer_timeout
-                        } else {
-                            ChainLimit::get().nft_sponsor_transfer_timeout
-                        };
-
-                        let basket = <NftTransferBasket<T>>::get(collection_id, _item_id);
-                        let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
-                        let limit_time = basket + limit.into();
-                        if block_number >= limit_time {
-                            <NftTransferBasket<T>>::insert(collection_id, _item_id, block_number);
-                            true
-                        }
-                        else {
-                            false
-                        }
-                    }
-                    CollectionMode::Fungible(_) => {
-
-                        // get correct limit
-                        let limit: u32 = if _collection_limits.sponsor_transfer_timeout > 0 {
-                            _collection_limits.sponsor_transfer_timeout
-                        } else {
-                            ChainLimit::get().fungible_sponsor_transfer_timeout
-                        };
-
-                        let mut basket = <FungibleTransferBasket<T>>::get(collection_id, _item_id);
-                        let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
-                        if basket.iter().any(|i| i.address == _new_owner.clone())
-                        {
-                            let item = basket.iter_mut().find(|i| i.address == _new_owner.clone()).unwrap().clone();
-                            let limit_time = item.start_block + limit.into();
+                let mut sponsor_transfer = false;
+                if <Collection<T>>::get(collection_id).sponsor_confirmed {
+                    let _collection_limits = <Collection<T>>::get(collection_id).limits;
+                    let _collection_mode = <Collection<T>>::get(collection_id).mode;
+    
+                    // sponsor timeout
+                    sponsor_transfer = match _collection_mode {
+                        CollectionMode::NFT => {
+    
+                            // get correct limit
+                            let limit: u32 = if _collection_limits.sponsor_transfer_timeout > 0 {
+                                _collection_limits.sponsor_transfer_timeout
+                            } else {
+                                ChainLimit::get().nft_sponsor_transfer_timeout
+                            };
+    
+                            let basket = <NftTransferBasket<T>>::get(collection_id, _item_id);
+                            let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
+                            let limit_time = basket + limit.into();
                             if block_number >= limit_time {
-                                basket.retain(|x| x.address == item.address);
-                                basket.push(BasketItem { start_block: block_number, address: _new_owner.clone() });
-                                <FungibleTransferBasket<T>>::insert(collection_id, _item_id, basket);
+                                <NftTransferBasket<T>>::insert(collection_id, _item_id, block_number);
                                 true
                             }
                             else {
                                 false
                             }
                         }
-                        else {
-                            basket.push(BasketItem { start_block: block_number, address: _new_owner.clone()});
-                            true
+                        CollectionMode::Fungible(_) => {
+    
+                            // get correct limit
+                            let limit: u32 = if _collection_limits.sponsor_transfer_timeout > 0 {
+                                _collection_limits.sponsor_transfer_timeout
+                            } else {
+                                ChainLimit::get().fungible_sponsor_transfer_timeout
+                            };
+    
+                            let mut basket = <FungibleTransferBasket<T>>::get(collection_id, _item_id);
+                            let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
+                            if basket.iter().any(|i| i.address == _new_owner.clone())
+                            {
+                                let item = basket.iter_mut().find(|i| i.address == _new_owner.clone()).unwrap().clone();
+                                let limit_time = item.start_block + limit.into();
+                                if block_number >= limit_time {
+                                    basket.retain(|x| x.address == item.address);
+                                    basket.push(BasketItem { start_block: block_number, address: _new_owner.clone() });
+                                    <FungibleTransferBasket<T>>::insert(collection_id, _item_id, basket);
+                                    true
+                                }
+                                else {
+                                    false
+                                }
+                            }
+                            else {
+                                basket.push(BasketItem { start_block: block_number, address: _new_owner.clone()});
+                                true
+                            }
+                        }
+                        CollectionMode::ReFungible(_) => {
+    
+                            // get correct limit
+                            let limit: u32 = if _collection_limits.sponsor_transfer_timeout > 0 {
+                                _collection_limits.sponsor_transfer_timeout
+                            } else {
+                                ChainLimit::get().refungible_sponsor_transfer_timeout
+                            };
+    
+                            let basket = <ReFungibleTransferBasket<T>>::get(collection_id, _item_id);
+                            let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
+                            let limit_time = basket + limit.into();
+                            if block_number >= limit_time {
+                                <ReFungibleTransferBasket<T>>::insert(collection_id, _item_id, block_number);
+                                true
+                            } else {
+                                false
+                            }
                         }
-                    }
-                    CollectionMode::ReFungible(_) => {
-
-                        // get correct limit
-                        let limit: u32 = if _collection_limits.sponsor_transfer_timeout > 0 {
-                            _collection_limits.sponsor_transfer_timeout
-                        } else {
-                            ChainLimit::get().refungible_sponsor_transfer_timeout
-                        };
-
-                        let basket = <ReFungibleTransferBasket<T>>::get(collection_id, _item_id);
-                        let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
-                        let limit_time = basket + limit.into();
-                        if block_number >= limit_time {
-                            <ReFungibleTransferBasket<T>>::insert(collection_id, _item_id, block_number);
-                            true
-                        } else {
+                        _ => {
                             false
-                        }
-                    }
-                    _ => {
-                        false
-                    },
-                };
+                        },
+                    };
+                }
 
                 if !sponsor_transfer {
                     T::AccountId::default()
modifiedruntime_types.jsondiffbeforeafterboth
--- a/runtime_types.json
+++ b/runtime_types.json
@@ -70,7 +70,7 @@
       "OffchainSchema": "Vec<u8>",
       "SchemaVersion": "SchemaVersion",
       "Sponsor": "AccountId",
-      "UnconfirmedSponsor": "AccountId",
+      "SponsorConfirmed": "bool",
       "Limits": "CollectionLimits",
       "VariableOnChainSchema": "Vec<u8>",
       "ConstOnChainSchema": "Vec<u8>"
modifiedtests/src/destroyCollection.test.tsdiffbeforeafterboth
--- a/tests/src/destroyCollection.test.ts
+++ b/tests/src/destroyCollection.test.ts
@@ -1,55 +1,12 @@
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
 import { default as usingApi, submitTransactionAsync } from "./substrate/substrate-api";
-import { createCollectionExpectSuccess, createCollectionExpectFailure } from "./util/helpers";
+import { createCollectionExpectSuccess, createCollectionExpectFailure, destroyCollectionExpectSuccess, destroyCollectionExpectFailure } from "./util/helpers";
 import type { AccountId, EventRecord } from '@polkadot/types/interfaces';
 import privateKey from './substrate/privateKey';
-import { nullPublicKey } from './accounts'; 
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
-
-function getDestroyResult(events: EventRecord[]): boolean {
-  let success: boolean = false;
-  events.forEach(({ phase, event: { data, method, section } }) => {
-    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);
-    if (method == 'ExtrinsicSuccess') {
-      success = true;
-    }
-  });
-  return success;
-}
-
-async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {
-  await usingApi(async (api) => {
-    // Run the DestroyCollection transaction
-    const alicePrivateKey = privateKey(senderSeed);
-    const tx = api.tx.nft.destroyCollection(collectionId);
-    const events = await submitTransactionAsync(alicePrivateKey, tx);
-    const result = getDestroyResult(events);
-
-    // Get the collection 
-    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();
-
-    // What to expect
-    expect(result).to.be.true;
-    expect(collection).to.be.not.null;
-    expect(collection.Owner).to.be.equal(nullPublicKey);
-  });
-}
-
-async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {
-  await usingApi(async (api) => {
-    // Run the DestroyCollection transaction
-    const alicePrivateKey = privateKey(senderSeed);
-    const tx = api.tx.nft.destroyCollection(collectionId);
-    const events = await submitTransactionAsync(alicePrivateKey, tx);
-    const result = getDestroyResult(events);
-
-    // What to expect
-    expect(result).to.be.false;
-  });
-}
 
 describe('integration test: ext. destroyCollection():', () => {
   it('NFT collection can be destroyed', async () => {
addedtests/src/setCollectionSponsor.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/setCollectionSponsor.test.ts
@@ -0,0 +1,78 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import { default as usingApi } from "./substrate/substrate-api";
+import { createCollectionExpectSuccess, setCollectionSponsorExpectSuccess, destroyCollectionExpectSuccess, setCollectionSponsorExpectFailure } from "./util/helpers";
+import { Keyring } from "@polkadot/api";
+import { IKeyringPair } from "@polkadot/types/types";
+import type { AccountId } from '@polkadot/types/interfaces';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+let bob: IKeyringPair;
+
+describe('integration test: ext. setCollectionSponsor():', () => {
+
+  before(async () => {
+    await usingApi(async (api) => {
+      const keyring = new Keyring({ type: 'sr25519' });
+      bob = keyring.addFromUri(`//Bob`);
+    });
+  });
+
+  it('Set NFT collection sponsor', async () => {
+    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+  });
+  it('Set Fungible collection sponsor', async () => {
+    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'Fungible');
+    await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+  });
+  it('Set ReFungible collection sponsor', async () => {
+    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'ReFungible');
+    await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+  });
+
+  it('Set the same sponsor repeatedly', async () => {
+    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+    await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+  });
+  it('Replace collection sponsor', async () => {
+    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+
+    const keyring = new Keyring({ type: 'sr25519' });
+    const charlie = keyring.addFromUri(`//Charlie`);
+    await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+    await setCollectionSponsorExpectSuccess(collectionId, charlie.address);
+  });
+});
+
+describe('(!negative test!) integration test: ext. setCollectionSponsor():', () => {
+  before(async () => {
+    await usingApi(async (api) => {
+      const keyring = new Keyring({ type: 'sr25519' });
+      bob = keyring.addFromUri(`//Bob`);
+    });
+  });
+
+  it('(!negative test!) Add sponsor to a collection that never existed', async () => {
+    // Find the collection that never existed
+    const collectionId = 0;
+    await usingApi(async (api) => {
+      const collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;
+    });
+
+    await setCollectionSponsorExpectFailure(collectionId, bob.address);
+  });
+  it('(!negative test!) Add sponsor to a collection that was destroyed', async () => {
+    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    await destroyCollectionExpectSuccess(collectionId);
+    await setCollectionSponsorExpectFailure(collectionId, bob.address);
+  });
+});
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
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 chai from 'chai';7import chaiAsPromised from 'chai-as-promised';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { ApiPromise, Keyring } from "@polkadot/api";10import { default as usingApi, submitTransactionAsync } from "../substrate/substrate-api";11import privateKey from '../substrate/privateKey';12import { alicesPublicKey } from "../accounts";13import { strToUTF16, utf16ToStr, hexToStr } from '../util/util';14import { IKeyringPair } from "@polkadot/types/types";15import { BigNumber } from 'bignumber.js';1617chai.use(chaiAsPromised);18const expect = chai.expect;1920type GenericResult = {21  success: boolean,22};2324type CreateCollectionResult = {25  success: boolean,26  collectionId: number27};2829export function getGenericResult(events: EventRecord[]): GenericResult {30  let result: GenericResult = {31    success: false32  }33  events.forEach(({ phase, event: { data, method, section } }) => {34    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);35    if (method == 'ExtrinsicSuccess') {36      result.success = true;37    }38  });39  return result;40}4142function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {43  let success = false;44  let collectionId: number = 0;45  events.forEach(({ phase, event: { data, method, section } }) => {46    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);47    if (method == 'ExtrinsicSuccess') {48      success = true;49    } else if ((section == 'nft') && (method == 'Created')) {50      collectionId = parseInt(data[0].toString());51    }52  });53  let result: CreateCollectionResult = {54    success,55    collectionId56  }57  return result;58}5960export async function createCollectionExpectSuccess(name: string, description: string, tokenPrefix: string, mode: string): Promise<number> {61  let collectionId: number = 0;62  await usingApi(async (api) => {63    // Get number of collections before the transaction64    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());6566    // Run the CreateCollection transaction67    const alicePrivateKey = privateKey('//Alice');68    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);69    const events = await submitTransactionAsync(alicePrivateKey, tx);70    const result = getCreateCollectionResult(events);7172    // Get number of collections after the transaction73    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());7475    // Get the collection 76    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();7778    // What to expect79    expect(result.success).to.be.true;80    expect(result.collectionId).to.be.equal(BcollectionCount);81    expect(collection).to.be.not.null;82    expect(BcollectionCount).to.be.equal(AcollectionCount+1, 'Error: NFT collection NOT created.');83    expect(collection.Owner).to.be.equal(alicesPublicKey);84    expect(utf16ToStr(collection.Name)).to.be.equal(name);85    expect(utf16ToStr(collection.Description)).to.be.equal(description);86    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);8788    collectionId = result.collectionId;89  });9091  return collectionId;92}93  94export async function createCollectionExpectFailure(name: string, description: string, tokenPrefix: string, mode: string) {95  await usingApi(async (api) => {96    // Get number of collections before the transaction97    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());9899    // Run the CreateCollection transaction100    const alicePrivateKey = privateKey('//Alice');101    const tx = api.tx.nft.createCollection(name, description, tokenPrefix, mode);102    const events = await submitTransactionAsync(alicePrivateKey, tx);103    const result = getCreateCollectionResult(events);104105    // Get number of collections after the transaction106    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());107108    // What to expect109    expect(result.success).to.be.false;110    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');111  });112}113  114export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {115  let bal = new BigNumber(0);116  let unused;117  do {118    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000));119    const keyring = new Keyring({ type: 'sr25519' });120    unused = keyring.addFromUri(`//${randomSeed}`);121    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());122  } while (bal.toFixed() != '0');123  return unused; 124}
after · tests/src/util/helpers.ts
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 chai from 'chai';7import chaiAsPromised from 'chai-as-promised';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { ApiPromise, Keyring } from "@polkadot/api";10import { default as usingApi, submitTransactionAsync } from "../substrate/substrate-api";11import privateKey from '../substrate/privateKey';12import { alicesPublicKey, nullPublicKey } from "../accounts";13import { strToUTF16, utf16ToStr, hexToStr } from '../util/util';14import { IKeyringPair } from "@polkadot/types/types";15import { BigNumber } from 'bignumber.js';1617chai.use(chaiAsPromised);18const expect = chai.expect;1920type GenericResult = {21  success: boolean,22};2324type CreateCollectionResult = {25  success: boolean,26  collectionId: number27};2829export function getGenericResult(events: EventRecord[]): GenericResult {30  let result: GenericResult = {31    success: false32  }33  events.forEach(({ phase, event: { data, method, section } }) => {34    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);35    if (method == 'ExtrinsicSuccess') {36      result.success = true;37    }38  });39  return result;40}4142function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {43  let success = false;44  let collectionId: number = 0;45  events.forEach(({ phase, event: { data, method, section } }) => {46    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);47    if (method == 'ExtrinsicSuccess') {48      success = true;49    } else if ((section == 'nft') && (method == 'Created')) {50      collectionId = parseInt(data[0].toString());51    }52  });53  let result: CreateCollectionResult = {54    success,55    collectionId56  }57  return result;58}5960export async function createCollectionExpectSuccess(name: string, description: string, tokenPrefix: string, mode: string): Promise<number> {61  let collectionId: number = 0;62  await usingApi(async (api) => {63    // Get number of collections before the transaction64    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());6566    // Run the CreateCollection transaction67    const alicePrivateKey = privateKey('//Alice');68    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);69    const events = await submitTransactionAsync(alicePrivateKey, tx);70    const result = getCreateCollectionResult(events);7172    // Get number of collections after the transaction73    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());7475    // Get the collection 76    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();7778    // What to expect79    expect(result.success).to.be.true;80    expect(result.collectionId).to.be.equal(BcollectionCount);81    expect(collection).to.be.not.null;82    expect(BcollectionCount).to.be.equal(AcollectionCount+1, 'Error: NFT collection NOT created.');83    expect(collection.Owner).to.be.equal(alicesPublicKey);84    expect(utf16ToStr(collection.Name)).to.be.equal(name);85    expect(utf16ToStr(collection.Description)).to.be.equal(description);86    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);8788    collectionId = result.collectionId;89  });9091  return collectionId;92}93  94export async function createCollectionExpectFailure(name: string, description: string, tokenPrefix: string, mode: string) {95  await usingApi(async (api) => {96    // Get number of collections before the transaction97    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());9899    // Run the CreateCollection transaction100    const alicePrivateKey = privateKey('//Alice');101    const tx = api.tx.nft.createCollection(name, description, tokenPrefix, mode);102    const events = await submitTransactionAsync(alicePrivateKey, tx);103    const result = getCreateCollectionResult(events);104105    // Get number of collections after the transaction106    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());107108    // What to expect109    expect(result.success).to.be.false;110    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');111  });112}113  114export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {115  let bal = new BigNumber(0);116  let unused;117  do {118    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000));119    const keyring = new Keyring({ type: 'sr25519' });120    unused = keyring.addFromUri(`//${randomSeed}`);121    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());122  } while (bal.toFixed() != '0');123  return unused; 124}125126function getDestroyResult(events: EventRecord[]): boolean {127  let success: boolean = false;128  events.forEach(({ phase, event: { data, method, section } }) => {129    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);130    if (method == 'ExtrinsicSuccess') {131      success = true;132    }133  });134  return success;135}136137export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {138  await usingApi(async (api) => {139140    // Run the transaction141    const alicePrivateKey = privateKey('//Alice');142    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);143    const events = await submitTransactionAsync(alicePrivateKey, tx);144    const result = getGenericResult(events);145146    // Get the collection 147    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();148149    // What to expect150    expect(result.success).to.be.true;151    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());152    expect(collection.SponsorConfirmed).to.be.false;153  });154}155156export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {157  await usingApi(async (api) => {158    // Run the DestroyCollection transaction159    const alicePrivateKey = privateKey(senderSeed);160    const tx = api.tx.nft.destroyCollection(collectionId);161    const events = await submitTransactionAsync(alicePrivateKey, tx);162    const result = getDestroyResult(events);163164    // What to expect165    expect(result).to.be.false;166  });167}168169export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {170  await usingApi(async (api) => {171    // Run the DestroyCollection transaction172    const alicePrivateKey = privateKey(senderSeed);173    const tx = api.tx.nft.destroyCollection(collectionId);174    const events = await submitTransactionAsync(alicePrivateKey, tx);175    const result = getDestroyResult(events);176177    // Get the collection 178    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();179180    // What to expect181    expect(result).to.be.true;182    expect(collection).to.be.not.null;183    expect(collection.Owner).to.be.equal(nullPublicKey);184  });185}186187export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string) {188  await usingApi(async (api) => {189190    // Run the transaction191    const alicePrivateKey = privateKey('//Alice');192    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);193    const events = await submitTransactionAsync(alicePrivateKey, tx);194    const result = getGenericResult(events);195196    // What to expect197    expect(result.success).to.be.false;198  });199}