difftreelog
Merge pull request #46 from usetech-llc/feature/NFTPAR-242_destroy_collection_test
in: master
NFTPAR-242 Add destroy collection integration tests
4 files changed
node/src/chain_spec.rsdiffbeforeafterboth1// use nft_runtime::{2// AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, Signature, SudoConfig,3// SystemConfig, WASM_BINARY,4// };5// use nft_runtime::{ContractsConfig, ContractsSchedule, NftConfig, CollectionType};6use nft_runtime::*;7use sc_service::ChainType;8use sp_consensus_aura::sr25519::AuthorityId as AuraId;9use sp_core::{sr25519, Pair, Public};10use sp_finality_grandpa::AuthorityId as GrandpaId;11use sp_runtime::traits::{IdentifyAccount, Verify};12use serde_json::map::Map;1314// Note this is the URL for the telemetry server15//const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";1617/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.18pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>;1920/// Helper function to generate a crypto pair from seed21pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {22 TPublic::Pair::from_string(&format!("//{}", seed), None)23 .expect("static values are valid; qed")24 .public()25}2627type AccountPublic = <Signature as Verify>::Signer;2829/// Helper function to generate an account ID from seed30pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId31where32 AccountPublic: From<<TPublic::Pair as Pair>::Public>,33{34 AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()35}3637/// Helper function to generate an authority key for Aura38pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) {39 (get_from_seed::<AuraId>(s), get_from_seed::<GrandpaId>(s))40}4142pub fn development_config() -> Result<ChainSpec, String> {43 let wasm_binary = WASM_BINARY.ok_or("Development wasm binary not available".to_string())?;4445 let mut properties = Map::new();46 properties.insert("tokenSymbol".into(), "UniqueTest".into());47 properties.insert("tokenDecimals".into(), 15.into());48 properties.insert("ss58Format".into(), 0.into());4950 Ok(ChainSpec::from_genesis(51 // Name52 "Development",53 // ID54 "dev",55 ChainType::Development,56 move || testnet_genesis(57 wasm_binary,58 // Initial PoA authorities59 vec![60 authority_keys_from_seed("Alice"),61 ],62 // Sudo account63 get_account_id_from_seed::<sr25519::Public>("Alice"),64 // Pre-funded accounts65 vec![66 get_account_id_from_seed::<sr25519::Public>("Alice"),67 get_account_id_from_seed::<sr25519::Public>("Bob"),68 get_account_id_from_seed::<sr25519::Public>("Alice//stash"),69 get_account_id_from_seed::<sr25519::Public>("Bob//stash"),70 ],71 true,72 ),73 // Bootnodes74 vec![],75 // Telemetry76 None,77 // Protocol ID78 None,79 // Properties80 Some(properties),81 // Extensions82 None,83 ))84}8586pub fn local_testnet_config() -> Result<ChainSpec, String> {87 let wasm_binary = WASM_BINARY.ok_or("Development wasm binary not available".to_string())?;8889 Ok(ChainSpec::from_genesis(90 // Name91 "Local Testnet",92 // ID93 "local_testnet",94 ChainType::Local,95 move || testnet_genesis(96 wasm_binary,97 // Initial PoA authorities98 vec![99 authority_keys_from_seed("Alice"),100 authority_keys_from_seed("Bob"),101 ],102 // Sudo account103 get_account_id_from_seed::<sr25519::Public>("Alice"),104 // Pre-funded accounts105 vec![106 get_account_id_from_seed::<sr25519::Public>("Alice"),107 get_account_id_from_seed::<sr25519::Public>("Bob"),108 get_account_id_from_seed::<sr25519::Public>("Charlie"),109 get_account_id_from_seed::<sr25519::Public>("Dave"),110 get_account_id_from_seed::<sr25519::Public>("Eve"),111 get_account_id_from_seed::<sr25519::Public>("Ferdie"),112 get_account_id_from_seed::<sr25519::Public>("Alice//stash"),113 get_account_id_from_seed::<sr25519::Public>("Bob//stash"),114 get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),115 get_account_id_from_seed::<sr25519::Public>("Dave//stash"),116 get_account_id_from_seed::<sr25519::Public>("Eve//stash"),117 get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),118 ],119 true,120 ),121 // Bootnodes122 vec![],123 // Telemetry124 None,125 // Protocol ID126 None,127 // Properties128 None,129 // Extensions130 None,131 ))132}133134fn testnet_genesis(135 wasm_binary: &[u8],136 initial_authorities: Vec<(AuraId, GrandpaId)>,137 root_key: AccountId,138 endowed_accounts: Vec<AccountId>,139 enable_println: bool,140) -> GenesisConfig {141142 let vested_accounts = vec![143 get_account_id_from_seed::<sr25519::Public>("Bob"),144 ];145146 GenesisConfig {147 system: Some(SystemConfig {148 code: wasm_binary.to_vec(),149 changes_trie_config: Default::default(),150 }),151 pallet_balances: Some(BalancesConfig {152 balances: endowed_accounts153 .iter()154 .cloned()155 .map(|k| (k, 1 << 100))156 .collect(),157 }),158 pallet_aura: Some(AuraConfig {159 authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(),160 }),161 pallet_grandpa: Some(GrandpaConfig {162 authorities: initial_authorities163 .iter()164 .map(|x| (x.1.clone(), 1))165 .collect(),166 }),167 pallet_treasury: Some(Default::default()),168 pallet_sudo: Some(SudoConfig { key: root_key }),169 pallet_vesting: Some(VestingConfig {170 vesting: vested_accounts171 .iter()172 .cloned()173 .map(|k| (k, 1000, 100, 1 << 98))174 .collect(),175 }),176 pallet_nft: Some(NftConfig {177 collection: vec![(178 1,179 CollectionType {180 owner: get_account_id_from_seed::<sr25519::Public>("Alice"),181 mode: CollectionMode::NFT,182 access: AccessMode::Normal,183 decimal_points: 0,184 name: vec![],185 description: vec![],186 token_prefix: vec![],187 mint_mode: false,188 offchain_schema: vec![],189 schema_version: SchemaVersion::default(),190 sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),191 unconfirmed_sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),192 const_on_chain_schema: vec![],193 variable_on_chain_schema: vec![],194 limits: CollectionLimits::default()195 },196 )],197 nft_item_id: vec![],198 fungible_item_id: vec![],199 refungible_item_id: vec![],200 chain_limit: ChainLimits {201 collection_numbers_limit: 100000,202 account_token_ownership_limit: 1000000,203 collections_admins_limit: 5,204 custom_data_limit: 2048,205 nft_sponsor_transfer_timeout: 15,206 fungible_sponsor_transfer_timeout: 15,207 refungible_sponsor_transfer_timeout: 15,208 },209 }),210 pallet_contracts: Some(ContractsConfig {211 current_schedule: ContractsSchedule {212 enable_println,213 ..Default::default()214 },215 }),216 }217}1// use nft_runtime::{2// AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, Signature, SudoConfig,3// SystemConfig, WASM_BINARY,4// };5// use nft_runtime::{ContractsConfig, ContractsSchedule, NftConfig, CollectionType};6use nft_runtime::*;7use sc_service::ChainType;8use sp_consensus_aura::sr25519::AuthorityId as AuraId;9use sp_core::{sr25519, Pair, Public};10use sp_finality_grandpa::AuthorityId as GrandpaId;11use sp_runtime::traits::{IdentifyAccount, Verify};12use serde_json::map::Map;1314// Note this is the URL for the telemetry server15//const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";1617/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.18pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>;1920/// Helper function to generate a crypto pair from seed21pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {22 TPublic::Pair::from_string(&format!("//{}", seed), None)23 .expect("static values are valid; qed")24 .public()25}2627type AccountPublic = <Signature as Verify>::Signer;2829/// Helper function to generate an account ID from seed30pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId31where32 AccountPublic: From<<TPublic::Pair as Pair>::Public>,33{34 AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()35}3637/// Helper function to generate an authority key for Aura38pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) {39 (get_from_seed::<AuraId>(s), get_from_seed::<GrandpaId>(s))40}4142pub fn development_config() -> Result<ChainSpec, String> {43 let wasm_binary = WASM_BINARY.ok_or("Development wasm binary not available".to_string())?;4445 let mut properties = Map::new();46 properties.insert("tokenSymbol".into(), "UniqueTest".into());47 properties.insert("tokenDecimals".into(), 15.into());48 properties.insert("ss58Format".into(), 42.into()); // Generic Substrate wildcard (SS58 checksum preimage)4950 Ok(ChainSpec::from_genesis(51 // Name52 "Development",53 // ID54 "dev",55 ChainType::Development,56 move || testnet_genesis(57 wasm_binary,58 // Initial PoA authorities59 vec![60 authority_keys_from_seed("Alice"),61 ],62 // Sudo account63 get_account_id_from_seed::<sr25519::Public>("Alice"),64 // Pre-funded accounts65 vec![66 get_account_id_from_seed::<sr25519::Public>("Alice"),67 get_account_id_from_seed::<sr25519::Public>("Bob"),68 get_account_id_from_seed::<sr25519::Public>("Alice//stash"),69 get_account_id_from_seed::<sr25519::Public>("Bob//stash"),70 ],71 true,72 ),73 // Bootnodes74 vec![],75 // Telemetry76 None,77 // Protocol ID78 None,79 // Properties80 Some(properties),81 // Extensions82 None,83 ))84}8586pub fn local_testnet_config() -> Result<ChainSpec, String> {87 let wasm_binary = WASM_BINARY.ok_or("Development wasm binary not available".to_string())?;8889 Ok(ChainSpec::from_genesis(90 // Name91 "Local Testnet",92 // ID93 "local_testnet",94 ChainType::Local,95 move || testnet_genesis(96 wasm_binary,97 // Initial PoA authorities98 vec![99 authority_keys_from_seed("Alice"),100 authority_keys_from_seed("Bob"),101 ],102 // Sudo account103 get_account_id_from_seed::<sr25519::Public>("Alice"),104 // Pre-funded accounts105 vec![106 get_account_id_from_seed::<sr25519::Public>("Alice"),107 get_account_id_from_seed::<sr25519::Public>("Bob"),108 get_account_id_from_seed::<sr25519::Public>("Charlie"),109 get_account_id_from_seed::<sr25519::Public>("Dave"),110 get_account_id_from_seed::<sr25519::Public>("Eve"),111 get_account_id_from_seed::<sr25519::Public>("Ferdie"),112 get_account_id_from_seed::<sr25519::Public>("Alice//stash"),113 get_account_id_from_seed::<sr25519::Public>("Bob//stash"),114 get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),115 get_account_id_from_seed::<sr25519::Public>("Dave//stash"),116 get_account_id_from_seed::<sr25519::Public>("Eve//stash"),117 get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),118 ],119 true,120 ),121 // Bootnodes122 vec![],123 // Telemetry124 None,125 // Protocol ID126 None,127 // Properties128 None,129 // Extensions130 None,131 ))132}133134fn testnet_genesis(135 wasm_binary: &[u8],136 initial_authorities: Vec<(AuraId, GrandpaId)>,137 root_key: AccountId,138 endowed_accounts: Vec<AccountId>,139 enable_println: bool,140) -> GenesisConfig {141142 let vested_accounts = vec![143 get_account_id_from_seed::<sr25519::Public>("Bob"),144 ];145146 GenesisConfig {147 system: Some(SystemConfig {148 code: wasm_binary.to_vec(),149 changes_trie_config: Default::default(),150 }),151 pallet_balances: Some(BalancesConfig {152 balances: endowed_accounts153 .iter()154 .cloned()155 .map(|k| (k, 1 << 100))156 .collect(),157 }),158 pallet_aura: Some(AuraConfig {159 authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(),160 }),161 pallet_grandpa: Some(GrandpaConfig {162 authorities: initial_authorities163 .iter()164 .map(|x| (x.1.clone(), 1))165 .collect(),166 }),167 pallet_treasury: Some(Default::default()),168 pallet_sudo: Some(SudoConfig { key: root_key }),169 pallet_vesting: Some(VestingConfig {170 vesting: vested_accounts171 .iter()172 .cloned()173 .map(|k| (k, 1000, 100, 1 << 98))174 .collect(),175 }),176 pallet_nft: Some(NftConfig {177 collection: vec![(178 1,179 CollectionType {180 owner: get_account_id_from_seed::<sr25519::Public>("Alice"),181 mode: CollectionMode::NFT,182 access: AccessMode::Normal,183 decimal_points: 0,184 name: vec![],185 description: vec![],186 token_prefix: vec![],187 mint_mode: false,188 offchain_schema: vec![],189 schema_version: SchemaVersion::default(),190 sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),191 unconfirmed_sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),192 const_on_chain_schema: vec![],193 variable_on_chain_schema: vec![],194 limits: CollectionLimits::default()195 },196 )],197 nft_item_id: vec![],198 fungible_item_id: vec![],199 refungible_item_id: vec![],200 chain_limit: ChainLimits {201 collection_numbers_limit: 100000,202 account_token_ownership_limit: 1000000,203 collections_admins_limit: 5,204 custom_data_limit: 2048,205 nft_sponsor_transfer_timeout: 15,206 fungible_sponsor_transfer_timeout: 15,207 refungible_sponsor_transfer_timeout: 15,208 },209 }),210 pallet_contracts: Some(ContractsConfig {211 current_schedule: ContractsSchedule {212 enable_println,213 ..Default::default()214 },215 }),216 }217}tests/src/accounts.tsdiffbeforeafterboth--- a/tests/src/accounts.ts
+++ b/tests/src/accounts.ts
@@ -1,3 +1,4 @@
export const bobsPublicKey = '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty';
export const alicesPublicKey = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
export const ferdiesPublicKey = '5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL';
+export const nullPublicKey = '5C4hrfjw9DjXZTzV3MwzrrAr9P1MJhSrvWGWqi1eSuyUpnhM';
\ No newline at end of file
tests/src/destroyCollection.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/destroyCollection.test.ts
@@ -0,0 +1,87 @@
+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 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 () => {
+ const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ await destroyCollectionExpectSuccess(collectionId);
+ });
+ it('Fungible collection can be destroyed', async () => {
+ const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'Fungible');
+ await destroyCollectionExpectSuccess(collectionId);
+ });
+ it('ReFungible collection can be destroyed', async () => {
+ const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'ReFungible');
+ await destroyCollectionExpectSuccess(collectionId);
+ });
+});
+
+describe('(!negative test!) integration test: ext. destroyCollection():', () => {
+ it('(!negative test!) Destroy a collection that never existed', async () => {
+ await usingApi(async (api) => {
+ // Find the collection that never existed
+ const collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;
+ await destroyCollectionExpectFailure(collectionId);
+ });
+ });
+ it('(!negative test!) Destroy a collection that has already been destroyed', async () => {
+ const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ await destroyCollectionExpectSuccess(collectionId);
+ await destroyCollectionExpectFailure(collectionId);
+ });
+ it('(!negative test!) Destroy a collection using non-owner account', async () => {
+ const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+ await destroyCollectionExpectFailure(collectionId, '//Bob');
+ await destroyCollectionExpectSuccess(collectionId, '//Alice');
+ });
+});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -52,7 +52,8 @@
return result;
}
-export async function createCollectionExpectSuccess(name: string, description: string, tokenPrefix: string, mode: string) {
+export async function createCollectionExpectSuccess(name: string, description: string, tokenPrefix: string, mode: string): Promise<number> {
+ let collectionId: number = 0;
await usingApi(async (api) => {
// Get number of collections before the transaction
const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());
@@ -78,7 +79,11 @@
expect(utf16ToStr(collection.Name)).to.be.equal(name);
expect(utf16ToStr(collection.Description)).to.be.equal(description);
expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);
+
+ collectionId = result.collectionId;
});
+
+ return collectionId;
}
export async function createCollectionExpectFailure(name: string, description: string, tokenPrefix: string, mode: string) {