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
before · node/src/chain_spec.rs
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56// use nft_runtime::{7//     AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, Signature, SudoConfig,8//     SystemConfig, WASM_BINARY,9// };10// use nft_runtime::{ContractsConfig, ContractsSchedule, NftConfig, CollectionType};11use nft_runtime::*;12use sc_service::ChainType;13use sp_consensus_aura::sr25519::AuthorityId as AuraId;14use sp_core::{sr25519, Pair, Public};15use sp_finality_grandpa::AuthorityId as GrandpaId;16use sp_runtime::traits::{IdentifyAccount, Verify};17use serde_json::map::Map;1819// Note this is the URL for the telemetry server20//const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";2122/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.23pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>;2425/// Helper function to generate a crypto pair from seed26pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {27    TPublic::Pair::from_string(&format!("//{}", seed), None)28        .expect("static values are valid; qed")29        .public()30}3132type AccountPublic = <Signature as Verify>::Signer;3334/// Helper function to generate an account ID from seed35pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId36where37    AccountPublic: From<<TPublic::Pair as Pair>::Public>,38{39    AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()40}4142/// Helper function to generate an authority key for Aura43pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) {44    (get_from_seed::<AuraId>(s), get_from_seed::<GrandpaId>(s))45}4647pub fn development_config() -> Result<ChainSpec, String> {48	let wasm_binary = WASM_BINARY.ok_or("Development wasm binary not available".to_string())?;4950	let mut properties = Map::new();51	properties.insert("tokenSymbol".into(), "UniqueTest".into());52	properties.insert("tokenDecimals".into(), 15.into());53	properties.insert("ss58Format".into(), 42.into()); // Generic Substrate wildcard (SS58 checksum preimage)5455	Ok(ChainSpec::from_genesis(56		// Name57		"Development",58		// ID59		"dev",60		ChainType::Development,61		move || testnet_genesis(62			wasm_binary,63			// Initial PoA authorities64			vec![65				authority_keys_from_seed("Alice"),66			],67			// Sudo account68			get_account_id_from_seed::<sr25519::Public>("Alice"),69			// Pre-funded accounts70			vec![71				get_account_id_from_seed::<sr25519::Public>("Alice"),72				get_account_id_from_seed::<sr25519::Public>("Bob"),73				get_account_id_from_seed::<sr25519::Public>("Alice//stash"),74				get_account_id_from_seed::<sr25519::Public>("Bob//stash"),75			],76			true,77		),78		// Bootnodes79		vec![],80		// Telemetry81		None,82		// Protocol ID83		None,84		// Properties85		Some(properties),86		// Extensions87		None,88	))89}9091pub fn local_testnet_config() -> Result<ChainSpec, String> {92	let wasm_binary = WASM_BINARY.ok_or("Development wasm binary not available".to_string())?;9394	Ok(ChainSpec::from_genesis(95		// Name96		"Local Testnet",97		// ID98		"local_testnet",99		ChainType::Local,100		move || testnet_genesis(101			wasm_binary,102			// Initial PoA authorities103			vec![104				authority_keys_from_seed("Alice"),105				authority_keys_from_seed("Bob"),106			],107			// Sudo account108			get_account_id_from_seed::<sr25519::Public>("Alice"),109			// Pre-funded accounts110			vec![111				get_account_id_from_seed::<sr25519::Public>("Alice"),112				get_account_id_from_seed::<sr25519::Public>("Bob"),113				get_account_id_from_seed::<sr25519::Public>("Charlie"),114				get_account_id_from_seed::<sr25519::Public>("Dave"),115				get_account_id_from_seed::<sr25519::Public>("Eve"),116				get_account_id_from_seed::<sr25519::Public>("Ferdie"),117				get_account_id_from_seed::<sr25519::Public>("Alice//stash"),118				get_account_id_from_seed::<sr25519::Public>("Bob//stash"),119				get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),120				get_account_id_from_seed::<sr25519::Public>("Dave//stash"),121				get_account_id_from_seed::<sr25519::Public>("Eve//stash"),122				get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),123			],124			true,125		),126		// Bootnodes127		vec![],128		// Telemetry129		None,130		// Protocol ID131		None,132		// Properties133		None,134		// Extensions135		None,136	))137}138139fn testnet_genesis(140    wasm_binary: &[u8],141    initial_authorities: Vec<(AuraId, GrandpaId)>,142    root_key: AccountId,143    endowed_accounts: Vec<AccountId>,144    enable_println: bool,145) -> GenesisConfig {146147	let vested_accounts = vec![148		get_account_id_from_seed::<sr25519::Public>("Bob"),149	];150151    GenesisConfig {152        system: Some(SystemConfig {153            code: wasm_binary.to_vec(),154            changes_trie_config: Default::default(),155        }),156        pallet_balances: Some(BalancesConfig {157            balances: endowed_accounts158                .iter()159                .cloned()160                .map(|k| (k, 1 << 100))161                .collect(),162        }),163        pallet_aura: Some(AuraConfig {164            authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(),165        }),166		pallet_grandpa: Some(GrandpaConfig {167            authorities: initial_authorities168                .iter()169                .map(|x| (x.1.clone(), 1))170                .collect(),171		}),172		pallet_treasury: Some(Default::default()),173		pallet_sudo: Some(SudoConfig { key: root_key }),174		pallet_vesting: Some(VestingConfig {175            vesting: vested_accounts176                .iter()177                .cloned()178                .map(|k| (k, 1000, 100, 1 << 98))179                .collect(),180        }),181        pallet_nft: Some(NftConfig {182            collection: vec![(183                1,184                CollectionType {185                    owner: get_account_id_from_seed::<sr25519::Public>("Alice"),186                    mode: CollectionMode::NFT,187                    access: AccessMode::Normal,188                    decimal_points: 0,189                    name: vec![],190                    description: vec![],191                    token_prefix: vec![],192                    mint_mode: false,193					offchain_schema: vec![],194					schema_version: SchemaVersion::default(),195                    sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),196                    unconfirmed_sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),197                    const_on_chain_schema: vec![],198					variable_on_chain_schema: vec![],199					limits: CollectionLimits::default()200                },201            )],202            nft_item_id: vec![],203            fungible_item_id: vec![],204            refungible_item_id: vec![],205            chain_limit: ChainLimits {206                collection_numbers_limit: 100000,207                account_token_ownership_limit: 1000000,208                collections_admins_limit: 5,209                custom_data_limit: 2048,210                nft_sponsor_transfer_timeout: 15,211                fungible_sponsor_transfer_timeout: 15,212                refungible_sponsor_transfer_timeout: 15,213            },214        }),215        pallet_contracts: Some(ContractsConfig {216            current_schedule: ContractsSchedule {217                enable_println,218                ..Default::default()219            },220        }),221    }222}
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
--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -9,7 +9,7 @@
 import { ApiPromise, Keyring } from "@polkadot/api";
 import { default as usingApi, submitTransactionAsync } from "../substrate/substrate-api";
 import privateKey from '../substrate/privateKey';
-import { alicesPublicKey } from "../accounts";
+import { alicesPublicKey, nullPublicKey } from "../accounts";
 import { strToUTF16, utf16ToStr, hexToStr } from '../util/util';
 import { IKeyringPair } from "@polkadot/types/types";
 import { BigNumber } from 'bignumber.js';
@@ -121,4 +121,79 @@
     bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());
   } while (bal.toFixed() != '0');
   return unused; 
-}
\ No newline at end of file
+}
+
+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;
+}
+
+export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {
+  await usingApi(async (api) => {
+
+    // Run the transaction
+    const alicePrivateKey = privateKey('//Alice');
+    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);
+    const events = await submitTransactionAsync(alicePrivateKey, tx);
+    const result = getGenericResult(events);
+
+    // Get the collection 
+    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();
+
+    // What to expect
+    expect(result.success).to.be.true;
+    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());
+    expect(collection.SponsorConfirmed).to.be.false;
+  });
+}
+
+export 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;
+  });
+}
+
+export 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);
+  });
+}
+
+export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string) {
+  await usingApi(async (api) => {
+
+    // Run the transaction
+    const alicePrivateKey = privateKey('//Alice');
+    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);
+    const events = await submitTransactionAsync(alicePrivateKey, tx);
+    const result = getGenericResult(events);
+
+    // What to expect
+    expect(result.success).to.be.false;
+  });
+}