git.delta.rocks / unique-network / refs/commits / 1bd93c2627cf

difftreelog

manual merge of develop

Igor Kozyrev2021-10-27parents: #5164830 #65a56d5.patch.diff
in: master

9 files changed

modifiedpallets/nft/src/eth/erc.rsdiffbeforeafterboth
--- a/pallets/nft/src/eth/erc.rs
+++ b/pallets/nft/src/eth/erc.rs
@@ -194,7 +194,8 @@
 		let caller = T::CrossAccountId::from_eth(caller);
 		let token_id = token_id.try_into().map_err(|_| "amount overflow")?;
 
-		<Module<T>>::burn_item_internal(&caller, &self, token_id, 1).map_err(|_| "burn error")?;
+		<Module<T>>::burn_item_internal(&caller, &self, token_id, 1, true)
+			.map_err(|_| "burn error")?;
 		Ok(())
 	}
 }
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -992,11 +992,39 @@
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let target_collection = Self::get_collection(collection_id)?;
 
-			Self::burn_item_internal(&sender, &target_collection, item_id, value)?;
+			Self::burn_item_internal(&sender, &target_collection, item_id, value, true)?;
 
 			target_collection.submit_logs()
 		}
 
+		/// Destroys a concrete instance of NFT on behalf of the owner
+		/// See also: [`approve`]
+		///
+		/// # Permissions
+		///
+		/// * Collection Owner.
+		/// * Collection Admin.
+		/// * Current NFT Owner.
+		///
+		/// # Arguments
+		///
+		/// * collection_id: ID of the collection.
+		///
+		/// * item_id: ID of NFT to burn.
+		///
+		/// * from: owner of item
+		#[weight = <SelfWeightOf<T>>::burn_item()]
+		#[transactional]
+		pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResult {
+
+			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+			let target_collection = Self::get_collection(collection_id)?;
+
+			Self::burn_from_internal(&sender, &target_collection, &from, item_id, value)?;
+
+			target_collection.submit_logs()
+		}
+
 		/// Change ownership of the token.
 		///
 		/// # Permissions
@@ -1593,13 +1621,60 @@
 	}
 
 	pub fn burn_item_internal(
+		owner: &T::CrossAccountId,
+		collection: &CollectionHandle<T>,
+		item_id: TokenId,
+		value: u128,
+		allow_escalation: bool,
+	) -> DispatchResult {
+		ensure!(
+			Self::is_item_owner(owner, collection, item_id)?
+				|| (allow_escalation
+					&& collection.limits.owner_can_transfer
+					&& Self::is_owner_or_admin_permissions(collection, owner)?),
+			Error::<T>::NoPermission
+		);
+
+		if collection.access == AccessMode::WhiteList {
+			Self::check_white_list(collection, owner)?;
+		}
+
+		match collection.mode {
+			CollectionMode::NFT => match value {
+				1 => Self::burn_nft_item(collection, item_id)?,
+				0 => (),
+				_ => fail!(<Error<T>>::TokenValueTooLow),
+			},
+			CollectionMode::Fungible(_) => Self::burn_fungible_item(collection, owner, value)?,
+			CollectionMode::ReFungible => {
+				Self::burn_refungible_item(collection, item_id, owner, value)?
+			}
+			_ => (),
+		};
+
+		Ok(())
+	}
+
+	pub fn burn_from_internal(
 		sender: &T::CrossAccountId,
 		collection: &CollectionHandle<T>,
+		from: &T::CrossAccountId,
 		item_id: TokenId,
-		value: u128,
+		amount: u128,
 	) -> DispatchResult {
+		if sender == from {
+			// Transfer by `from`, because it is either equal to sender, or derived from him
+			return Self::burn_item_internal(from, collection, item_id, amount, true);
+		}
+
+		// Check approval
+		collection.consume_sload()?;
+		let approval: u128 =
+			<Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));
+
+		// Transfer permissions check
 		ensure!(
-			Self::is_item_owner(sender, collection, item_id)?
+			approval >= amount
 				|| (collection.limits.owner_can_transfer
 					&& Self::is_owner_or_admin_permissions(collection, sender)?),
 			Error::<T>::NoPermission
@@ -1609,11 +1684,29 @@
 			Self::check_white_list(collection, sender)?;
 		}
 
-		match collection.mode {
-			CollectionMode::NFT => Self::burn_nft_item(collection, item_id)?,
-			CollectionMode::Fungible(_) => Self::burn_fungible_item(sender, collection, value)?,
-			CollectionMode::ReFungible => Self::burn_refungible_item(collection, item_id, sender)?,
-		};
+		// Reduce approval by transferred amount or remove if remaining approval drops to 0
+		let allowance = approval.saturating_sub(amount);
+		collection.consume_sstore()?;
+		if allowance > 0 {
+			<Allowances<T>>::insert(
+				collection.id,
+				(item_id, from.as_sub(), sender.as_sub()),
+				allowance,
+			);
+		} else {
+			<Allowances<T>>::remove(collection.id, (item_id, from.as_sub(), sender.as_sub()));
+		}
+
+		// Escalation is disallowed here, because we need to be sure that passed owner is real
+		Self::burn_item_internal(from, collection, item_id, amount, false)?;
+
+		if matches!(collection.mode, CollectionMode::Fungible(_)) {
+			collection.log(ERC20Events::Approval {
+				owner: *from.as_eth(),
+				spender: *sender.as_eth(),
+				value: allowance.into(),
+			})?;
+		}
 
 		Ok(())
 	}
@@ -1884,31 +1977,42 @@
 		collection: &CollectionHandle<T>,
 		item_id: TokenId,
 		owner: &T::CrossAccountId,
+		value: u128,
 	) -> DispatchResult {
 		let collection_id = collection.id;
 
 		let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id)
 			.ok_or(Error::<T>::TokenNotFound)?;
-		let rft_balance = token
+		let mut rft_balance = token
 			.owner
 			.iter()
 			.find(|&i| i.owner == *owner)
-			.ok_or(Error::<T>::TokenNotFound)?;
+			.ok_or(Error::<T>::TokenNotFound)?
+			.clone();
 		Self::remove_token_index(collection, item_id, owner)?;
 
 		// update balance
 		let new_balance = <Balance<T>>::get(collection_id, rft_balance.owner.as_sub())
-			.checked_sub(rft_balance.fraction)
+			.checked_sub(value)
 			.ok_or(Error::<T>::NumOverflow)?;
 		<Balance<T>>::insert(collection_id, rft_balance.owner.as_sub(), new_balance);
 
-		// Re-create owners list with sender removed
+		rft_balance.fraction = (rft_balance.fraction)
+			.checked_sub(value)
+			.ok_or(Error::<T>::NumOverflow)?;
+
 		let index = token
 			.owner
 			.iter()
 			.position(|i| i.owner == *owner)
 			.expect("owned item is exists");
-		token.owner.remove(index);
+		if rft_balance.fraction == 0 {
+			// Re-create owners list with sender removed
+			token.owner.remove(index);
+		} else {
+			token.owner[index] = rft_balance;
+		}
+
 		let owner_count = token.owner.len();
 
 		// Burn the token completely if this was the last (only) owner
@@ -1947,8 +2051,8 @@
 	}
 
 	fn burn_fungible_item(
+		collection: &CollectionHandle<T>,
 		owner: &T::CrossAccountId,
-		collection: &CollectionHandle<T>,
 		value: u128,
 	) -> DispatchResult {
 		let collection_id = collection.id;
modifiedpallets/nft/src/tests.rsdiffbeforeafterboth
--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -707,9 +707,15 @@
 		assert_eq!(TemplateModule::balance_count(1, 1), 1);
 
 		// burn item
-		assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 5));
+		assert_ok!(TemplateModule::burn_item(
+			origin1.clone(),
+			1,
+			1,
+			account(1),
+			5
+		));
 		assert_noop!(
-			TemplateModule::burn_item(origin1, 1, 1, 5),
+			TemplateModule::burn_item(origin1, 1, 1, account(1), 5),
 			Error::<Test>::TokenNotFound
 		);
 
@@ -736,9 +742,15 @@
 		assert_eq!(TemplateModule::balance_count(1, 1), 5);
 
 		// burn item
-		assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 5));
+		assert_ok!(TemplateModule::burn_item(
+			origin1.clone(),
+			1,
+			1,
+			account(1),
+			5
+		));
 		assert_noop!(
-			TemplateModule::burn_item(origin1, 1, 1, 5),
+			TemplateModule::burn_item(origin1, 1, 1, account(1), 5),
 			Error::<Test>::TokenValueNotEnough
 		);
 
@@ -781,9 +793,15 @@
 		assert_eq!(TemplateModule::balance_count(1, 1), 1023);
 
 		// burn item
-		assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 1023));
+		assert_ok!(TemplateModule::burn_item(
+			origin1.clone(),
+			1,
+			1,
+			account(1),
+			1023
+		));
 		assert_noop!(
-			TemplateModule::burn_item(origin1, 1, 1, 1023),
+			TemplateModule::burn_item(origin1, 1, 1, account(1), 1023),
 			Error::<Test>::TokenNotFound
 		);
 
@@ -1378,7 +1396,7 @@
 			AccessMode::WhiteList
 		));
 		assert_noop!(
-			TemplateModule::burn_item(origin1, 1, 1, 5),
+			TemplateModule::burn_item(origin1.clone(), 1, 1, account(1), 5),
 			Error::<Test>::AddresNotInWhiteList
 		);
 	});
modifiedtests/.vscode/settings.jsondiffbeforeafterboth
--- a/tests/.vscode/settings.json
+++ b/tests/.vscode/settings.json
@@ -1,3 +1,5 @@
 {
-    "mocha.enabled": true
-}
\ No newline at end of file
+    "mocha.enabled": true,
+    "mochaExplorer.files": "**/*.test.ts",
+    "mochaExplorer.require": "ts-node/register"
+}
modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -20,6 +20,10 @@
     "tslint": "^6.1.3",
     "typescript": "^4.4.4"
   },
+  "mocha": {
+    "timeout": 9999999,
+    "require": "ts-node/register"
+  },
   "scripts": {
     "lint": "eslint --ext .ts,.js src/",
     "fix": "eslint --ext .ts,.js src/ --fix",
modifiedtests/src/burnItem.test.tsdiffbeforeafterboth
before · tests/src/burnItem.test.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 { 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  destroyCollectionExpectSuccess,14  normalizeAccountId,15  addCollectionAdminExpectSuccess,16} from './util/helpers';1718import chai from 'chai';19import chaiAsPromised from 'chai-as-promised';20chai.use(chaiAsPromised);21const expect = chai.expect;2223let alice: IKeyringPair;24let bob: IKeyringPair;2526describe('integration test: ext. burnItem():', () => {27  before(async () => {28    await usingApi(async () => {29      const keyring = new Keyring({ type: 'sr25519' });30      alice = keyring.addFromUri('//Alice');31      bob = keyring.addFromUri('//Bob');32    });33  });3435  it('Burn item in NFT collection', async () => {36    const createMode = 'NFT';37    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode}});38    const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);3940    await usingApi(async (api) => {41      const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);42      const events = await submitTransactionAsync(alice, tx);43      const result = getGenericResult(events);44      // Get the item45      const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();46      // What to expect47      // tslint:disable-next-line:no-unused-expression48      expect(result.success).to.be.true;49      // tslint:disable-next-line:no-unused-expression50      expect(item).to.be.null;51    });52  });5354  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);6566      // Get alice balance67      const balance: any = (await api.query.nft.fungibleItemList(collectionId, alice.address)).toJSON();6869      // 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    });74  });7576  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);8586      // Get alice balance87      const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();8889      // What to expect90      expect(result.success).to.be.true;91      expect(balance).to.be.null;92    });93  });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(normalizeAccountId(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 balances115      const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();116      // console.log(balance);117118      // 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.deep.equal(normalizeAccountId(alice.address));123      expect(balanceBefore.owner[0].fraction).to.be.equal(99);124      expect(balanceBefore.owner[1].owner).to.be.deep.equal(normalizeAccountId(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.deep.equal(normalizeAccountId(alice.address));133    });134135  });136137});138139describe('integration test: ext. burnItem() with admin permissions:', () => {140  before(async () => {141    await usingApi(async () => {142      const keyring = new Keyring({ type: 'sr25519' });143      alice = keyring.addFromUri('//Alice');144      bob = keyring.addFromUri('//Bob');145    });146  });147148  it('Burn item in NFT collection', async () => {149    const createMode = 'NFT';150    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode}});151    const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);152    await addCollectionAdminExpectSuccess(alice, collectionId, bob);153154    await usingApi(async (api) => {155      const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);156      const events = await submitTransactionAsync(bob, tx);157      const result = getGenericResult(events);158      // Get the item159      const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();160      // What to expect161      // tslint:disable-next-line:no-unused-expression162      expect(result.success).to.be.true;163      // tslint:disable-next-line:no-unused-expression164      expect(item).to.be.null;165    });166  });167});168169describe('Negative integration test: ext. burnItem():', () => {170  before(async () => {171    await usingApi(async () => {172      const keyring = new Keyring({ type: 'sr25519' });173      alice = keyring.addFromUri('//Alice');174      bob = keyring.addFromUri('//Bob');175    });176  });177178  it('Burn a token in a destroyed collection', async () => {179    const createMode = 'NFT';180    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});181    const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);182    await destroyCollectionExpectSuccess(collectionId);183184    await usingApi(async (api) => {185      const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);186      const badTransaction = async function () {187        await submitTransactionExpectFailAsync(alice, tx);188      };189      await expect(badTransaction()).to.be.rejected;190    });191192  });193194  it('Burn a token that was never created', async () => {195    const createMode = 'NFT';196    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});197    const tokenId = 10;198199    await usingApi(async (api) => {200      const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);201      const badTransaction = async function () {202        await submitTransactionExpectFailAsync(alice, tx);203      };204      await expect(badTransaction()).to.be.rejected;205    });206207  });208209  it('Burn a token using the address that does not own it', async () => {210    const createMode = 'NFT';211    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});212    const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);213214    await usingApi(async (api) => {215      const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);216      const badTransaction = async function () {217        await submitTransactionExpectFailAsync(bob, tx);218      };219      await expect(badTransaction()).to.be.rejected;220    });221222  });223224  it('Transfer a burned a token', async () => {225    const createMode = 'NFT';226    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});227    const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);228229    await usingApi(async (api) => {230231      const burntx = api.tx.nft.burnItem(collectionId, tokenId, 0);232      const events1 = await submitTransactionAsync(alice, burntx);233      const result1 = getGenericResult(events1);234      expect(result1.success).to.be.true;235236      const tx = api.tx.nft.transfer(normalizeAccountId(bob.address), collectionId, tokenId, 0);237      const badTransaction = async function () {238        await submitTransactionExpectFailAsync(alice, tx);239      };240      await expect(badTransaction()).to.be.rejected;241    });242243  });244245  it('Burn more than owned in Fungible collection', async () => {246    const createMode = 'Fungible';247    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0 }});248    // Helper creates 10 fungible tokens249    await createItemExpectSuccess(alice, collectionId, createMode);250    const tokenId = 0; // ignored251252    await usingApi(async (api) => {253      // Destroy 11 of 10254      const tx = api.tx.nft.burnItem(collectionId, tokenId, 11);255      const badTransaction = async function () {256        await submitTransactionExpectFailAsync(alice, tx);257      };258      await expect(badTransaction()).to.be.rejected;259260      // Get alice balance261      const balance: any = (await api.query.nft.fungibleItemList(collectionId, alice.address)).toJSON();262263      // What to expect264      expect(balance).to.be.not.null;265      expect(balance.value).to.be.equal(10);266    });267268  });269270});
modifiedtests/src/transfer.test.tsdiffbeforeafterboth
--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -199,7 +199,7 @@
     const reFungibleCollectionId = await
     createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
     const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
-    await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 1);
+    await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 100);
     await transferExpectFailure(
       reFungibleCollectionId,
       newReFungibleTokenId,
modifiedtests/src/transferFrom.test.tsdiffbeforeafterboth
--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -265,7 +265,7 @@
     await usingApi(async () => {
       const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
       const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
-      await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 1);
+      await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 100);
       await approveExpectFail(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);
       await transferFromExpectFail(reFungibleCollectionId, newReFungibleTokenId, Bob, Alice, Charlie, 1);
 
@@ -297,7 +297,7 @@
       const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
       const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
       await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);
-      await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 1);
+      await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 100);
       await transferFromExpectFail(reFungibleCollectionId, newReFungibleTokenId, Bob, Alice, Charlie, 1);
 
     });
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -700,10 +700,10 @@
   ReFungible: CreateReFungibleData;
 };
 
-export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {
+export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {
   await usingApi(async (api) => {
     const tx = api.tx.nft.burnItem(collectionId, tokenId, value);
-    const events = await submitTransactionAsync(owner, tx);
+    const events = await submitTransactionAsync(sender, tx);
     const result = getGenericResult(events);
     // Get the item
     const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();