difftreelog
Merge pull request #135 from usetech-llc/feature/NFTPAR-299_storage_option_refactor
in: master
Optional collections related review
11 files changed
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -199,7 +199,7 @@
}
}
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
+#[derive(Encode, Decode, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct NftItemType<AccountId> {
pub owner: AccountId,
@@ -213,7 +213,7 @@
pub value: u128,
}
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
+#[derive(Encode, Decode, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct ReFungibleItemType<AccountId> {
pub owner: Vec<Ownership<AccountId>>,
@@ -537,15 +537,16 @@
/// Amount of items which spender can transfer out of owners account (via transferFrom)
/// Collection id (controlled?2), (token id (controlled ?2) + owner account id (real) + spender account id (controlled?3))
+ /// TODO: Off chain worker should remove from this map when token gets removed
pub Allowances get(fn approved): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) (TokenId, T::AccountId, T::AccountId) => u128;
//#region Item collections
/// Collection id (controlled?2), token id (controlled?1)
- pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => NftItemType<T::AccountId>;
+ pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<NftItemType<T::AccountId>>;
/// Collection id (controlled?2), owner (controlled?2)
pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;
/// Collection id (controlled?2), token id (controlled?1)
- pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => ReFungibleItemType<T::AccountId>;
+ pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<ReFungibleItemType<T::AccountId>>;
//#endregion
//#region Index list
@@ -555,6 +556,7 @@
//#region Tokens transfer rate limit baskets
/// (Collection id (controlled?2), who created (real))
+ /// TODO: Off chain worker should remove from this map when collection gets removed
pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => T::BlockNumber;
/// Collection id (controlled?2), token id (controlled?2)
pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;
@@ -570,7 +572,7 @@
//#region Contract Sponsorship and Ownership
/// Contract address (real)
- pub ContractOwner get(fn contract_owner): map hasher(twox_64_concat) T::AccountId => T::AccountId;
+ pub ContractOwner get(fn contract_owner): map hasher(twox_64_concat) T::AccountId => Option<T::AccountId>;
/// Contract address (real)
pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;
/// (Contract address(real), caller (real))
@@ -968,20 +970,17 @@
let sender = ensure_signed(origin)?;
let collection = Self::get_collection(collection_id)?;
Self::check_owner_or_admin_permissions(&collection, sender)?;
- let mut admin_arr: Vec<T::AccountId> = Vec::new();
+ let mut admin_arr = <AdminList<T>>::get(collection_id);
- if <AdminList<T>>::contains_key(collection_id)
- {
- admin_arr = <AdminList<T>>::get(collection_id);
- ensure!(!admin_arr.contains(&new_admin_id), Error::<T>::AlreadyAdmin);
+ match admin_arr.binary_search(&new_admin_id) {
+ Ok(_) => {},
+ Err(idx) => {
+ let limits = ChainLimit::get();
+ ensure!(admin_arr.len() < limits.collections_admins_limit as usize, Error::<T>::CollectionAdminsLimitExceeded);
+ admin_arr.insert(idx, new_admin_id);
+ <AdminList<T>>::insert(collection_id, admin_arr);
+ }
}
-
- // Number of collection admins
- ensure!((admin_arr.len() as u64) < ChainLimit::get().collections_admins_limit, Error::<T>::CollectionAdminsLimitExceeded);
-
- admin_arr.push(new_admin_id);
- <AdminList<T>>::insert(collection_id, admin_arr);
-
Ok(())
}
@@ -1004,12 +1003,15 @@
let sender = ensure_signed(origin)?;
let collection = Self::get_collection(collection_id)?;
Self::check_owner_or_admin_permissions(&collection, sender)?;
- ensure!(<AdminList<T>>::contains_key(collection_id), Error::<T>::AdminNotFound);
-
let mut admin_arr = <AdminList<T>>::get(collection_id);
- admin_arr.retain(|i| *i != account_id);
- <AdminList<T>>::insert(collection_id, admin_arr);
+ match admin_arr.binary_search(&account_id) {
+ Ok(idx) => {
+ admin_arr.remove(idx);
+ <AdminList<T>>::insert(collection_id, admin_arr);
+ },
+ Err(_) => {}
+ }
Ok(())
}
@@ -1267,7 +1269,7 @@
let sender = ensure_signed(origin)?;
let target_collection = Self::get_collection(collection_id)?;
- Self::token_exists(&target_collection, item_id, &sender)?;
+ Self::token_exists(&target_collection, item_id)?;
// Transfer permissions check
let bypasses_limits = target_collection.limits.owner_can_transfer &&
@@ -1419,7 +1421,7 @@
let sender = ensure_signed(origin)?;
let target_collection = Self::get_collection(collection_id)?;
- Self::token_exists(&target_collection, item_id, &sender)?;
+ Self::token_exists(&target_collection, item_id)?;
ensure!(ChainLimit::get().custom_data_limit >= data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);
@@ -1668,7 +1670,11 @@
<ContractOwner<T>>::insert(contract_address.clone(), sender.clone());
Self::ensure_contract_owned(sender, &contract_address)?;
- <ContractWhiteListEnabled<T>>::insert(contract_address, enable);
+ if enable {
+ <ContractWhiteListEnabled<T>>::insert(contract_address, true);
+ } else {
+ <ContractWhiteListEnabled<T>>::remove(contract_address);
+ }
Ok(())
}
@@ -1901,14 +1907,11 @@
let collection_id = collection.id;
// Does new owner already have an account?
- let mut balance: u128 = 0;
- if <FungibleItemList<T>>::contains_key(collection_id, owner) {
- balance = <FungibleItemList<T>>::get(collection_id, owner).value;
- }
+ let balance: u128 = <FungibleItemList<T>>::get(collection_id, owner).value;
// Mint
let item = FungibleItemType {
- value: balance + value
+ value: balance.checked_add(value).ok_or(Error::<T>::NumOverflow)?,
};
<FungibleItemList<T>>::insert(collection_id, (*owner).clone(), item);
@@ -1984,11 +1987,8 @@
) -> DispatchResult {
let collection_id = collection.id;
- ensure!(
- <ReFungibleItemList<T>>::contains_key(collection_id, item_id),
- Error::<T>::TokenNotFound
- );
- let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id);
+ let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id)
+ .ok_or(Error::<T>::TokenNotFound)?;
let rft_balance = token
.owner
.iter()
@@ -2026,11 +2026,8 @@
fn burn_nft_item(collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {
let collection_id = collection.id;
- ensure!(
- <NftItemList<T>>::contains_key(collection_id, item_id),
- Error::<T>::TokenNotFound
- );
- let item = <NftItemList<T>>::get(collection_id, item_id);
+ let item = <NftItemList<T>>::get(collection_id, item_id)
+ .ok_or(Error::<T>::TokenNotFound)?;
Self::remove_token_index(collection_id, item_id, &item.owner)?;
// update balance
@@ -2047,10 +2044,6 @@
fn burn_fungible_item(owner: &T::AccountId, collection: &CollectionHandle<T>, value: u128) -> DispatchResult {
let collection_id = collection.id;
- ensure!(
- <FungibleItemList<T>>::contains_key(collection_id, owner),
- Error::<T>::TokenNotFound
- );
let mut balance = <FungibleItemList<T>>::get(collection_id, owner);
ensure!(balance.value >= value, Error::<T>::TokenValueNotEnough);
@@ -2094,28 +2087,15 @@
}
fn is_owner_or_admin_permissions(collection: &CollectionHandle<T>, subject: T::AccountId) -> bool {
- let mut result: bool = subject == collection.owner;
- let exists = <AdminList<T>>::contains_key(collection.id);
-
- if !result & exists {
- if <AdminList<T>>::get(collection.id).contains(&subject) {
- result = true
- }
- }
-
- result
+ subject == collection.owner || <AdminList<T>>::get(collection.id).contains(&subject)
}
fn check_owner_or_admin_permissions(
collection: &CollectionHandle<T>,
subject: T::AccountId,
) -> DispatchResult {
- let result = Self::is_owner_or_admin_permissions(collection, subject.clone());
+ ensure!(Self::is_owner_or_admin_permissions(collection, subject), Error::<T>::NoPermission);
- ensure!(
- result,
- Error::<T>::NoPermission
- );
Ok(())
}
@@ -2127,20 +2107,11 @@
let collection_id = target_collection.id;
match target_collection.mode {
- CollectionMode::NFT => {
- if <NftItemList<T>>::get(collection_id, item_id).owner == subject {
- return Some(1)
- }
- None
- },
- CollectionMode::Fungible(_) => {
- if <FungibleItemList<T>>::contains_key(collection_id, &subject) {
- return Some(<FungibleItemList<T>>::get(collection_id, &subject)
- .value);
- }
- None
- },
- CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)
+ CollectionMode::NFT => (<NftItemList<T>>::get(collection_id, item_id)?.owner == subject)
+ .then(|| 1),
+ CollectionMode::Fungible(_) => Some(<FungibleItemList<T>>::get(collection_id, &subject)
+ .value),
+ CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)?
.owner
.iter()
.find(|i| i.owner == subject)
@@ -2150,22 +2121,9 @@
}
fn is_item_owner(subject: T::AccountId, target_collection: &CollectionHandle<T>, item_id: TokenId) -> bool {
- let collection_id = target_collection.id;
-
match target_collection.mode {
- CollectionMode::NFT => {
- <NftItemList<T>>::get(collection_id, item_id).owner == subject
- }
- CollectionMode::Fungible(_) => {
- <FungibleItemList<T>>::contains_key(collection_id, &subject)
- }
- CollectionMode::ReFungible => {
- <ReFungibleItemList<T>>::get(collection_id, item_id)
- .owner
- .iter()
- .any(|i| i.owner == subject)
- }
- CollectionMode::Invalid => false,
+ CollectionMode::Fungible(_) => true,
+ _ => Self::owned_amount(subject, target_collection, item_id).is_some(),
}
}
@@ -2183,13 +2141,12 @@
fn token_exists(
target_collection: &CollectionHandle<T>,
item_id: TokenId,
- owner: &T::AccountId
) -> DispatchResult {
let collection_id = target_collection.id;
let exists = match target_collection.mode
{
CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),
- CollectionMode::Fungible(_) => <FungibleItemList<T>>::contains_key(collection_id, owner),
+ CollectionMode::Fungible(_) => true,
CollectionMode::ReFungible => <ReFungibleItemList<T>>::contains_key(collection_id, item_id),
_ => false
};
@@ -2205,7 +2162,6 @@
recipient: &T::AccountId,
) -> DispatchResult {
let collection_id = collection.id;
- Self::token_exists(&collection, 0, owner)?;
let mut balance = <FungibleItemList<T>>::get(collection_id, owner);
ensure!(balance.value >= value, Error::<T>::TokenValueTooLow);
@@ -2236,9 +2192,9 @@
new_owner: T::AccountId,
) -> DispatchResult {
let collection_id = collection.id;
- Self::token_exists(collection, item_id, &owner)?;
+ let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id)
+ .ok_or(Error::<T>::TokenNotFound)?;
- let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);
let item = full_item
.owner
.iter()
@@ -2318,10 +2274,9 @@
new_owner: T::AccountId,
) -> DispatchResult {
let collection_id = collection.id;
- Self::token_exists(&collection, item_id, &sender)?;
+ let mut item = <NftItemList<T>>::get(collection_id, item_id)
+ .ok_or(Error::<T>::TokenNotFound)?;
- let mut item = <NftItemList<T>>::get(collection_id, item_id);
-
ensure!(
sender == item.owner,
Error::<T>::MustBeTokenOwner
@@ -2355,7 +2310,8 @@
data: Vec<u8>
) -> DispatchResult {
let collection_id = collection.id;
- let mut item = <ReFungibleItemList<T>>::get(collection_id, item_id);
+ let mut item = <ReFungibleItemList<T>>::get(collection_id, item_id)
+ .ok_or(Error::<T>::TokenNotFound)?;
item.variable_data = data;
@@ -2370,7 +2326,8 @@
data: Vec<u8>
) -> DispatchResult {
let collection_id = collection.id;
- let mut item = <NftItemList<T>>::get(collection_id, item_id);
+ let mut item = <NftItemList<T>>::get(collection_id, item_id)
+ .ok_or(Error::<T>::TokenNotFound)?;
item.variable_data = data;
@@ -2533,12 +2490,7 @@
}
fn ensure_contract_owned(account: T::AccountId, contract: &T::AccountId) -> DispatchResult {
- if <ContractOwner<T>>::contains_key(contract.clone()) {
- let owner = <ContractOwner<T>>::get(contract);
- ensure!(account == owner, Error::<T>::NoPermission);
- } else {
- fail!(Error::<T>::NoPermission);
- }
+ ensure!(<ContractOwner<T>>::get(contract) == Some(account), Error::<T>::NoPermission);
Ok(())
}
@@ -2787,9 +2739,8 @@
let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());
- let owned_contract = <ContractOwner<T>>::contains_key(called_contract.clone())
- && <ContractOwner<T>>::get(called_contract.clone()) == *who;
- let white_list_enabled = <ContractWhiteListEnabled<T>>::contains_key(called_contract.clone()) && <ContractWhiteListEnabled<T>>::get(called_contract.clone());
+ let owned_contract = <ContractOwner<T>>::get(called_contract.clone()).as_ref() == Some(who);
+ let white_list_enabled = <ContractWhiteListEnabled<T>>::contains_key(called_contract.clone());
if !owned_contract && white_list_enabled {
if !<ContractWhiteList<T>>::contains_key(called_contract.clone(), who) {
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -32,6 +32,7 @@
"testRemoveFromWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromWhiteList.test.ts",
"testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",
"testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
+ "testContracts": "mocha --timeout 9999999 -r ts-node/register ./**/contracts.test.ts",
"testCreateItem": "mocha --timeout 9999999 -r ts-node/register ./**/createItem.test.ts",
"testCreateMultipleItems": "mocha --timeout 9999999 -r ts-node/register ./**/createMultipleItems.test.ts",
"testApprove": "mocha --timeout 9999999 -r ts-node/register ./**/approve.test.ts",
@@ -44,6 +45,7 @@
"testSetMintPermission": "mocha --timeout 9999999 -r ts-node/register ./**/setMintPermission.test.ts",
"testCreditFeesToTreasury": "mocha --timeout 9999999 -r ts-node/register ./**/creditFeesToTreasury.test.ts",
"testEnableContractSponsoring": "mocha --timeout 9999999 -r ts-node/register ./**/enableContractSponsoring.test.ts",
+ "testRemoveFromContractWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromContractWhiteList.test.ts",
"testSetContractSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setContractSponsoringRateLimit.test.ts",
"testSetOffchainSchema": "mocha --timeout 9999999 -r ts-node/register ./**/setOffchainSchema.test.ts",
"testOverflow": "mocha --timeout 9999999 -r ts-node/register ./**/overflow.test.ts",
tests/src/approve.test.tsdiffbeforeafterboth--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -123,9 +123,6 @@
// nft
const nftCollectionId = await createCollectionExpectSuccess();
await approveExpectFail(nftCollectionId, 2, Alice, Bob);
- // fungible
- const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- await approveExpectFail(fungibleCollectionId, 2, Alice, Bob);
// reFungible
const reFungibleCollectionId =
await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
tests/src/burnItem.test.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';7import { Keyring } from "@polkadot/api";8import { IKeyringPair } from "@polkadot/types/types";9import { 10 createCollectionExpectSuccess, 11 createItemExpectSuccess,12 getGenericResult,13 destroyCollectionExpectSuccess14} from './util/helpers';15import { nullPublicKey } from "./accounts";1617import chai from 'chai';18import chaiAsPromised from 'chai-as-promised';19chai.use(chaiAsPromised);20const expect = chai.expect;2122let alice: IKeyringPair;23let bob: IKeyringPair;2425describe('integration test: ext. burnItem():', () => {26 before(async () => {27 await usingApi(async (api) => {28 const keyring = new Keyring({ type: 'sr25519' });29 alice = keyring.addFromUri(`//Alice`);30 bob = keyring.addFromUri(`//Bob`);31 });32 });3334 it('Burn item in NFT collection', async () => {35 const createMode = 'NFT';36 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode}});37 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);3839 await usingApi(async (api) => {40 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);41 const events = await submitTransactionAsync(alice, tx);42 const result = getGenericResult(events);43 // Get the item44 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();45 // What to expect46 // tslint:disable-next-line:no-unused-expression47 expect(result.success).to.be.true;48 // tslint:disable-next-line:no-unused-expression49 expect(item).to.be.not.null;50 expect(item.Owner).to.be.equal(nullPublicKey);51 });5253 });54 it('Burn item in Fungible collection', async () => {55 const createMode = 'Fungible';56 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0 }});57 await createItemExpectSuccess(alice, collectionId, createMode); // Helper creates 10 fungible tokens58 const tokenId = 0; // ignored5960 await usingApi(async (api) => {61 // Destroy 1 of 1062 const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);63 const events = await submitTransactionAsync(alice, tx);64 const result = getGenericResult(events);65 66 // Get alice balance 67 const balance: any = (await api.query.nft.fungibleItemList(collectionId, alice.address)).toJSON();68 69 // What to expect70 expect(result.success).to.be.true;71 expect(balance).to.be.not.null;72 expect(balance.Value).to.be.equal(9);73 });7475 });76 it('Burn item in ReFungible collection', async () => {77 const createMode = 'ReFungible';78 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});79 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);8081 await usingApi(async (api) => {82 const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);83 const events = await submitTransactionAsync(alice, tx);84 const result = getGenericResult(events);85 86 // Get alice balance 87 const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();88 89 // What to expect90 expect(result.success).to.be.true;91 expect(balance).to.be.not.null;92 expect(balance.Owner.length).to.be.equal(0);93 });9495 });9697 it('Burn owned portion of item in ReFungible collection', async () => {98 const createMode = 'ReFungible';99 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode}});100 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);101102 await usingApi(async (api) => {103 // Transfer 1/100 of the token to Bob104 const transfertx = api.tx.nft.transfer(bob.address, collectionId, tokenId, 1);105 const events1 = await submitTransactionAsync(alice, transfertx);106 const result1 = getGenericResult(events1);107108 // Get balances109 const balanceBefore: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();110111 // Bob burns his portion112 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);113 const events2 = await submitTransactionAsync(bob, tx);114 const result2 = getGenericResult(events2);115116 // Get balances 117 const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();118 // console.log(balance);119 120 // What to expect before burning121 expect(result1.success).to.be.true;122 expect(balanceBefore).to.be.not.null;123 expect(balanceBefore.Owner.length).to.be.equal(2);124 expect(balanceBefore.Owner[0].Owner).to.be.equal(alice.address);125 expect(balanceBefore.Owner[0].Fraction).to.be.equal(99);126 expect(balanceBefore.Owner[1].Owner).to.be.equal(bob.address);127 expect(balanceBefore.Owner[1].Fraction).to.be.equal(1);128129 // What to expect after burning130 expect(result2.success).to.be.true;131 expect(balance).to.be.not.null;132 expect(balance.Owner.length).to.be.equal(1);133 expect(balance.Owner[0].Fraction).to.be.equal(99);134 expect(balance.Owner[0].Owner).to.be.equal(alice.address);135 });136137 });138139});140141describe('Negative integration test: ext. burnItem():', () => {142 before(async () => {143 await usingApi(async (api) => {144 const keyring = new Keyring({ type: 'sr25519' });145 alice = keyring.addFromUri(`//Alice`);146 bob = keyring.addFromUri(`//Bob`);147 });148 });149150 it('Burn a token in a destroyed collection', async () => {151 const createMode = 'NFT';152 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});153 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);154 await destroyCollectionExpectSuccess(collectionId);155156 await usingApi(async (api) => {157 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);158 const badTransaction = async function () { 159 await submitTransactionExpectFailAsync(alice, tx);160 };161 await expect(badTransaction()).to.be.rejected;162 });163164 });165166 it('Burn a token that was never created', async () => {167 const createMode = 'NFT';168 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});169 const tokenId = 10;170171 await usingApi(async (api) => {172 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);173 const badTransaction = async function () { 174 await submitTransactionExpectFailAsync(alice, tx);175 };176 await expect(badTransaction()).to.be.rejected;177 });178179 });180181 it('Burn a token using the address that does not own it', async () => {182 const createMode = 'NFT';183 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});184 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);185186 await usingApi(async (api) => {187 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);188 const badTransaction = async function () { 189 await submitTransactionExpectFailAsync(bob, tx);190 };191 await expect(badTransaction()).to.be.rejected;192 });193194 });195196 it('Transfer a burned a token', async () => {197 const createMode = 'NFT';198 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});199 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);200201 await usingApi(async (api) => {202203 const burntx = api.tx.nft.burnItem(collectionId, tokenId, 0);204 const events1 = await submitTransactionAsync(alice, burntx);205 const result1 = getGenericResult(events1);206 expect(result1.success).to.be.true;207 208 const tx = api.tx.nft.transfer(bob.address, collectionId, tokenId, 0);209 const badTransaction = async function () { 210 await submitTransactionExpectFailAsync(alice, tx);211 };212 await expect(badTransaction()).to.be.rejected;213 });214215 });216217 it('Burn more than owned in Fungible collection', async () => {218 const createMode = 'Fungible';219 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0 }});220 // Helper creates 10 fungible tokens221 await createItemExpectSuccess(alice, collectionId, createMode);222 const tokenId = 0; // ignored223224 await usingApi(async (api) => {225 // Destroy 11 of 10226 const tx = api.tx.nft.burnItem(collectionId, tokenId, 11);227 const badTransaction = async function () { 228 await submitTransactionExpectFailAsync(alice, tx);229 };230 await expect(badTransaction()).to.be.rejected;231 232 // Get alice balance 233 const balance: any = (await api.query.nft.fungibleItemList(collectionId, alice.address)).toJSON();234 235 // What to expect236 expect(balance).to.be.not.null;237 expect(balance.Value).to.be.equal(10);238 });239240 });241242});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 { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';7import { Keyring } from "@polkadot/api";8import { IKeyringPair } from "@polkadot/types/types";9import { 10 createCollectionExpectSuccess, 11 createItemExpectSuccess,12 getGenericResult,13 destroyCollectionExpectSuccess14} from './util/helpers';15import { nullPublicKey } from "./accounts";1617import chai from 'chai';18import chaiAsPromised from 'chai-as-promised';19chai.use(chaiAsPromised);20const expect = chai.expect;2122let alice: IKeyringPair;23let bob: IKeyringPair;2425describe('integration test: ext. burnItem():', () => {26 before(async () => {27 await usingApi(async (api) => {28 const keyring = new Keyring({ type: 'sr25519' });29 alice = keyring.addFromUri(`//Alice`);30 bob = keyring.addFromUri(`//Bob`);31 });32 });3334 it('Burn item in NFT collection', async () => {35 const createMode = 'NFT';36 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode}});37 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);3839 await usingApi(async (api) => {40 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);41 const events = await submitTransactionAsync(alice, tx);42 const result = getGenericResult(events);43 // Get the item44 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();45 // What to expect46 // tslint:disable-next-line:no-unused-expression47 expect(result.success).to.be.true;48 // tslint:disable-next-line:no-unused-expression49 expect(item).to.be.null;50 });5152 });53 it('Burn item in Fungible collection', async () => {54 const createMode = 'Fungible';55 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0 }});56 await createItemExpectSuccess(alice, collectionId, createMode); // Helper creates 10 fungible tokens57 const tokenId = 0; // ignored5859 await usingApi(async (api) => {60 // Destroy 1 of 1061 const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);62 const events = await submitTransactionAsync(alice, tx);63 const result = getGenericResult(events);64 65 // Get alice balance 66 const balance: any = (await api.query.nft.fungibleItemList(collectionId, alice.address)).toJSON();67 68 // What to expect69 expect(result.success).to.be.true;70 expect(balance).to.be.not.null;71 expect(balance.Value).to.be.equal(9);72 });7374 });75 it('Burn item in ReFungible collection', async () => {76 const createMode = 'ReFungible';77 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});78 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);7980 await usingApi(async (api) => {81 const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);82 const events = await submitTransactionAsync(alice, tx);83 const result = getGenericResult(events);84 85 // Get alice balance 86 const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();87 88 // What to expect89 expect(result.success).to.be.true;90 expect(balance).to.be.null;91 });9293 });9495 it('Burn owned portion of item in ReFungible collection', async () => {96 const createMode = 'ReFungible';97 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode}});98 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);99100 await usingApi(async (api) => {101 // Transfer 1/100 of the token to Bob102 const transfertx = api.tx.nft.transfer(bob.address, collectionId, tokenId, 1);103 const events1 = await submitTransactionAsync(alice, transfertx);104 const result1 = getGenericResult(events1);105106 // Get balances107 const balanceBefore: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();108109 // Bob burns his portion110 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);111 const events2 = await submitTransactionAsync(bob, tx);112 const result2 = getGenericResult(events2);113114 // Get balances 115 const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();116 // console.log(balance);117 118 // What to expect before burning119 expect(result1.success).to.be.true;120 expect(balanceBefore).to.be.not.null;121 expect(balanceBefore.Owner.length).to.be.equal(2);122 expect(balanceBefore.Owner[0].Owner).to.be.equal(alice.address);123 expect(balanceBefore.Owner[0].Fraction).to.be.equal(99);124 expect(balanceBefore.Owner[1].Owner).to.be.equal(bob.address);125 expect(balanceBefore.Owner[1].Fraction).to.be.equal(1);126127 // What to expect after burning128 expect(result2.success).to.be.true;129 expect(balance).to.be.not.null;130 expect(balance.Owner.length).to.be.equal(1);131 expect(balance.Owner[0].Fraction).to.be.equal(99);132 expect(balance.Owner[0].Owner).to.be.equal(alice.address);133 });134135 });136137});138139describe('Negative integration test: ext. burnItem():', () => {140 before(async () => {141 await usingApi(async (api) => {142 const keyring = new Keyring({ type: 'sr25519' });143 alice = keyring.addFromUri(`//Alice`);144 bob = keyring.addFromUri(`//Bob`);145 });146 });147148 it('Burn a token in a destroyed collection', async () => {149 const createMode = 'NFT';150 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});151 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);152 await destroyCollectionExpectSuccess(collectionId);153154 await usingApi(async (api) => {155 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);156 const badTransaction = async function () { 157 await submitTransactionExpectFailAsync(alice, tx);158 };159 await expect(badTransaction()).to.be.rejected;160 });161162 });163164 it('Burn a token that was never created', async () => {165 const createMode = 'NFT';166 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});167 const tokenId = 10;168169 await usingApi(async (api) => {170 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);171 const badTransaction = async function () { 172 await submitTransactionExpectFailAsync(alice, tx);173 };174 await expect(badTransaction()).to.be.rejected;175 });176177 });178179 it('Burn a token using the address that does not own it', async () => {180 const createMode = 'NFT';181 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});182 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);183184 await usingApi(async (api) => {185 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);186 const badTransaction = async function () { 187 await submitTransactionExpectFailAsync(bob, tx);188 };189 await expect(badTransaction()).to.be.rejected;190 });191192 });193194 it('Transfer a burned a token', async () => {195 const createMode = 'NFT';196 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});197 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);198199 await usingApi(async (api) => {200201 const burntx = api.tx.nft.burnItem(collectionId, tokenId, 0);202 const events1 = await submitTransactionAsync(alice, burntx);203 const result1 = getGenericResult(events1);204 expect(result1.success).to.be.true;205 206 const tx = api.tx.nft.transfer(bob.address, collectionId, tokenId, 0);207 const badTransaction = async function () { 208 await submitTransactionExpectFailAsync(alice, tx);209 };210 await expect(badTransaction()).to.be.rejected;211 });212213 });214215 it('Burn more than owned in Fungible collection', async () => {216 const createMode = 'Fungible';217 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0 }});218 // Helper creates 10 fungible tokens219 await createItemExpectSuccess(alice, collectionId, createMode);220 const tokenId = 0; // ignored221222 await usingApi(async (api) => {223 // Destroy 11 of 10224 const tx = api.tx.nft.burnItem(collectionId, tokenId, 11);225 const badTransaction = async function () { 226 await submitTransactionExpectFailAsync(alice, tx);227 };228 await expect(badTransaction()).to.be.rejected;229 230 // Get alice balance 231 const balance: any = (await api.query.nft.fungibleItemList(collectionId, alice.address)).toJSON();232 233 // What to expect234 expect(balance).to.be.not.null;235 expect(balance.Value).to.be.equal(10);236 });237238 });239240});tests/src/contracts.test.tsdiffbeforeafterboth--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -63,13 +63,13 @@
const collectionId = await createCollectionExpectSuccess();
const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
const [contract, deployer] = await deployTransferContract(api);
- const tokenBefore: any = await api.query.nft.nftItemList(collectionId, tokenId);
+ const tokenBefore: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap();
// Transfer
const transferTx = contract.tx.transfer(value, gasLimit, bob.address, collectionId, tokenId, 1);
const events = await submitTransactionAsync(alice, transferTx);
const result = getGenericResult(events);
- const tokenAfter: any = await api.query.nft.nftItemList(collectionId, tokenId);
+ const tokenAfter: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap();
// tslint:disable-next-line:no-unused-expression
expect(result.success).to.be.true;
tests/src/createMultipleItems.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -38,9 +38,9 @@
await submitTransactionAsync(Alice, createMultipleItemsTx);
const itemsListIndexAfter = await api.query.nft.itemListIndex(collectionId) as unknown as BN;
expect(itemsListIndexAfter.toNumber()).to.be.equal(3);
- const token1Data = await api.query.nft.nftItemList(collectionId, 1) as unknown as ITokenDataType;
- const token2Data = await api.query.nft.nftItemList(collectionId, 2) as unknown as ITokenDataType;
- const token3Data = await api.query.nft.nftItemList(collectionId, 3) as unknown as ITokenDataType;
+ const token1Data = (await api.query.nft.nftItemList(collectionId, 1)).toJSON() as unknown as ITokenDataType;
+ const token2Data = (await api.query.nft.nftItemList(collectionId, 2)).toJSON() as unknown as ITokenDataType;
+ const token3Data = (await api.query.nft.nftItemList(collectionId, 3)).toJSON() as unknown as ITokenDataType;
expect(token1Data.Owner.toString()).to.be.equal(Alice.address);
expect(token2Data.Owner.toString()).to.be.equal(Alice.address);
@@ -72,9 +72,9 @@
await submitTransactionAsync(Alice, createMultipleItemsTx);
const itemsListIndexAfter = await api.query.nft.itemListIndex(collectionId) as unknown as BN;
expect(itemsListIndexAfter.toNumber()).to.be.equal(3);
- const token1Data = await api.query.nft.reFungibleItemList(collectionId, 1) as unknown as IReFungibleTokenDataType;
- const token2Data = await api.query.nft.reFungibleItemList(collectionId, 2) as unknown as IReFungibleTokenDataType;
- const token3Data = await api.query.nft.reFungibleItemList(collectionId, 3) as unknown as IReFungibleTokenDataType;
+ const token1Data = (await api.query.nft.reFungibleItemList(collectionId, 1) as any).unwrap() as unknown as IReFungibleTokenDataType;
+ const token2Data = (await api.query.nft.reFungibleItemList(collectionId, 2) as any).unwrap() as unknown as IReFungibleTokenDataType;
+ const token3Data = (await api.query.nft.reFungibleItemList(collectionId, 3) as any).unwrap() as unknown as IReFungibleTokenDataType;
expect(token1Data.Owner[0].Owner.toString()).to.be.equal(Alice.address);
expect(token1Data.Owner[0].Fraction.toNumber()).to.be.equal(1);
tests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionAdmin.test.ts
+++ b/tests/src/removeCollectionAdmin.test.ts
@@ -36,6 +36,19 @@
expect(adminListAfterRemoveAdmin).not.to.be.contains(Bob.address);
});
});
+
+ it('Remove admin from collection that has no admins', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const Alice = privateKey('//Alice');
+ const collectionId = await createCollectionExpectSuccess();
+
+ const adminListBeforeAddAdmin: any = (await api.query.nft.adminList(collectionId));
+ expect(adminListBeforeAddAdmin).to.have.lengthOf(0);
+
+ const tx = api.tx.nft.removeCollectionAdmin(collectionId, Alice.address);
+ await submitTransactionAsync(Alice, tx);
+ });
+ });
});
describe('Negative Integration Test removeCollectionAdmin(collection_id, account_id):', () => {
@@ -68,19 +81,6 @@
// Verifying that nothing bad happened (network is live, new collections can be created, etc.)
await createCollectionExpectSuccess();
- });
- });
-
- it('Remove admin from collection that has no admins', async () => {
- await usingApi(async (api: ApiPromise) => {
- const Alice = privateKey('//Alice');
- const collectionId = await createCollectionExpectSuccess();
-
- const adminListBeforeAddAdmin: any = (await api.query.nft.adminList(collectionId));
- expect(adminListBeforeAddAdmin).to.have.lengthOf(0);
-
- const tx = api.tx.nft.removeCollectionAdmin(collectionId, Alice.address);
- await expect(submitTransactionExpectFailAsync(Alice, tx)).to.be.rejected;
});
});
});
tests/src/removeFromContractWhiteList.test.tsdiffbeforeafterboth--- a/tests/src/removeFromContractWhiteList.test.ts
+++ b/tests/src/removeFromContractWhiteList.test.ts
@@ -13,8 +13,10 @@
describe('Integration Test removeFromContractWhiteList', () => {
let bob: IKeyringPair;
- before(() => {
- bob = privateKey('//Bob');
+ before(async () => {
+ await usingApi(async () => {
+ bob = privateKey('//Bob');
+ });
});
it('user is no longer whitelisted after removal', async () => {
@@ -56,9 +58,11 @@
let alice: IKeyringPair;
let bob: IKeyringPair;
- before(() => {
- alice = privateKey('//Alice');
- bob = privateKey('//Bob');
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
});
it('fails when called with non-contract address', async () => {
tests/src/setVariableMetaData.test.tsdiffbeforeafterboth--- a/tests/src/setVariableMetaData.test.ts
+++ b/tests/src/setVariableMetaData.test.ts
@@ -41,7 +41,7 @@
it('verify data was set', async () => {
await usingApi(async api => {
- const item: any = await api.query.nft.nftItemList(collectionId, tokenId);
+ const item: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap();
expect(Array.from(item.VariableData)).to.deep.equal(Array.from(data));
});
tests/src/transferFrom.test.tsdiffbeforeafterboth--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -237,7 +237,7 @@
const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');
await burnItemExpectSuccess(Alice, fungibleCollectionId, 1, 10);
- await approveExpectFail(fungibleCollectionId, newFungibleTokenId, Alice, Bob);
+ await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, Alice, Bob);
await transferFromExpectFail(fungibleCollectionId, newFungibleTokenId, Bob, Alice, Charlie, 1);
});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -599,8 +599,7 @@
// tslint:disable-next-line:no-unused-expression
expect(result.success).to.be.true;
// tslint:disable-next-line:no-unused-expression
- expect(item).to.be.not.null;
- expect(item.Owner).to.be.equal(nullPublicKey);
+ expect(item).to.be.null;
});
}
@@ -641,16 +640,16 @@
// tslint:disable-next-line:no-unused-expression
expect(result.success).to.be.true;
if (type === 'NFT') {
- const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;
+ const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap() as ITokenDataType;
expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);
}
if (type === 'Fungible') {
- const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;
+ const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, accountTo.address) as any).Value as unknown as BN;
expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());
}
if (type === 'ReFungible') {
const nftItemData =
- await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;
+ (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).unwrap() as IReFungibleTokenDataType;
expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);
expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);
}
@@ -697,18 +696,18 @@
expect(result.recipient).to.be.equal(recipient.address);
expect(result.value.toString()).to.be.equal(value.toString());
if (type === 'NFT') {
- const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;
+ const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;
expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);
}
if (type === 'Fungible') {
- const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;
+ const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, recipient.address) as any).Value as unknown as BN;
expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());
}
if (type === 'ReFungible') {
const nftItemData =
- await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;
+ (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;
expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);
- expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);
+ expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());
}
});
}