git.delta.rocks / unique-network / refs/commits / 65a56d5f7b5d

difftreelog

Merge pull request #210 from UniqueNetwork/feature/CORE-180-v2

kozyrevdev2021-10-27parents: #01d9f60 #7bd33ea.patch.diff
in: master
CORE-180. burnItem

10 files changed

modifiedlaunch-config.jsondiffbeforeafterboth
67 "flags": [67 "flags": [
68 "--rpc-cors=all",68 "--rpc-cors=all",
69 "--rpc-port=9933", "--unsafe-ws-external"69 "--rpc-port=9933",
70 "--unsafe-rpc-external",
71 "--unsafe-ws-external"
70 ]72 ]
71 },73 },
77 "flags": [79 "flags": [
78 "--rpc-cors=all",80 "--rpc-cors=all",
79 "--rpc-port=9934", "--unsafe-rpc-external"81 "--rpc-port=9934",
82 "--unsafe-rpc-external",
83 "--unsafe-ws-external"
80 ]84 ]
81 }85 }
82 ]86 ]
modifiedpallets/nft/src/eth/erc.rsdiffbeforeafterboth
194 let caller = T::CrossAccountId::from_eth(caller);194 let caller = T::CrossAccountId::from_eth(caller);
195 let token_id = token_id.try_into().map_err(|_| "amount overflow")?;195 let token_id = token_id.try_into().map_err(|_| "amount overflow")?;
196196
197 <Module<T>>::burn_item_internal(&caller, &self, token_id, 1).map_err(|_| "burn error")?;197 <Module<T>>::burn_item_internal(&caller, &self, token_id, 1, true)
198 .map_err(|_| "burn error")?;
198 Ok(())199 Ok(())
199 }200 }
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
992 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);992 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
993 let target_collection = Self::get_collection(collection_id)?;993 let target_collection = Self::get_collection(collection_id)?;
994994
995 Self::burn_item_internal(&sender, &target_collection, item_id, value)?;995 Self::burn_item_internal(&sender, &target_collection, item_id, value, true)?;
996996
997 target_collection.submit_logs()997 target_collection.submit_logs()
998 }998 }
999
1000 /// Destroys a concrete instance of NFT on behalf of the owner
1001 /// See also: [`approve`]
1002 ///
1003 /// # Permissions
1004 ///
1005 /// * Collection Owner.
1006 /// * Collection Admin.
1007 /// * Current NFT Owner.
1008 ///
1009 /// # Arguments
1010 ///
1011 /// * collection_id: ID of the collection.
1012 ///
1013 /// * item_id: ID of NFT to burn.
1014 ///
1015 /// * from: owner of item
1016 #[weight = <SelfWeightOf<T>>::burn_item()]
1017 #[transactional]
1018 pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResult {
1019
1020 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1021 let target_collection = Self::get_collection(collection_id)?;
1022
1023 Self::burn_from_internal(&sender, &target_collection, &from, item_id, value)?;
1024
1025 target_collection.submit_logs()
1026 }
9991027
1000 /// Change ownership of the token.1028 /// Change ownership of the token.
1001 ///1029 ///
1593 }1621 }
15941622
1595 pub fn burn_item_internal(1623 pub fn burn_item_internal(
1596 sender: &T::CrossAccountId,1624 owner: &T::CrossAccountId,
1597 collection: &CollectionHandle<T>,1625 collection: &CollectionHandle<T>,
1598 item_id: TokenId,1626 item_id: TokenId,
1599 value: u128,1627 value: u128,
1628 allow_escalation: bool,
1600 ) -> DispatchResult {1629 ) -> DispatchResult {
1601 ensure!(1630 ensure!(
1602 Self::is_item_owner(sender, collection, item_id)?1631 Self::is_item_owner(owner, collection, item_id)?
1603 || (collection.limits.owner_can_transfer1632 || (allow_escalation
1633 && collection.limits.owner_can_transfer
1604 && Self::is_owner_or_admin_permissions(collection, sender)?),1634 && Self::is_owner_or_admin_permissions(collection, owner)?),
1605 Error::<T>::NoPermission1635 Error::<T>::NoPermission
1606 );1636 );
16071637
1608 if collection.access == AccessMode::WhiteList {1638 if collection.access == AccessMode::WhiteList {
1609 Self::check_white_list(collection, sender)?;1639 Self::check_white_list(collection, owner)?;
1610 }1640 }
16111641
1612 match collection.mode {1642 match collection.mode {
1613 CollectionMode::NFT => Self::burn_nft_item(collection, item_id)?,1643 CollectionMode::NFT => match value {
1644 1 => Self::burn_nft_item(collection, item_id)?,
1645 0 => (),
1646 _ => fail!(<Error<T>>::TokenValueTooLow),
1647 },
1614 CollectionMode::Fungible(_) => Self::burn_fungible_item(sender, collection, value)?,1648 CollectionMode::Fungible(_) => Self::burn_fungible_item(collection, owner, value)?,
1615 CollectionMode::ReFungible => Self::burn_refungible_item(collection, item_id, sender)?,1649 CollectionMode::ReFungible => {
1650 Self::burn_refungible_item(collection, item_id, owner, value)?
1651 }
1652 _ => (),
1616 };1653 };
16171654
1618 Ok(())1655 Ok(())
1619 }1656 }
1657
1658 pub fn burn_from_internal(
1659 sender: &T::CrossAccountId,
1660 collection: &CollectionHandle<T>,
1661 from: &T::CrossAccountId,
1662 item_id: TokenId,
1663 amount: u128,
1664 ) -> DispatchResult {
1665 if sender == from {
1666 // Transfer by `from`, because it is either equal to sender, or derived from him
1667 return Self::burn_item_internal(from, collection, item_id, amount, true);
1668 }
1669
1670 // Check approval
1671 collection.consume_sload()?;
1672 let approval: u128 =
1673 <Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));
1674
1675 // Transfer permissions check
1676 ensure!(
1677 approval >= amount
1678 || (collection.limits.owner_can_transfer
1679 && Self::is_owner_or_admin_permissions(collection, sender)?),
1680 Error::<T>::NoPermission
1681 );
1682
1683 if collection.access == AccessMode::WhiteList {
1684 Self::check_white_list(collection, sender)?;
1685 }
1686
1687 // Reduce approval by transferred amount or remove if remaining approval drops to 0
1688 let allowance = approval.saturating_sub(amount);
1689 collection.consume_sstore()?;
1690 if allowance > 0 {
1691 <Allowances<T>>::insert(
1692 collection.id,
1693 (item_id, from.as_sub(), sender.as_sub()),
1694 allowance,
1695 );
1696 } else {
1697 <Allowances<T>>::remove(collection.id, (item_id, from.as_sub(), sender.as_sub()));
1698 }
1699
1700 // Escalation is disallowed here, because we need to be sure that passed owner is real
1701 Self::burn_item_internal(from, collection, item_id, amount, false)?;
1702
1703 if matches!(collection.mode, CollectionMode::Fungible(_)) {
1704 collection.log(ERC20Events::Approval {
1705 owner: *from.as_eth(),
1706 spender: *sender.as_eth(),
1707 value: allowance.into(),
1708 })?;
1709 }
1710
1711 Ok(())
1712 }
16201713
1621 pub fn toggle_white_list_internal(1714 pub fn toggle_white_list_internal(
1622 sender: &T::CrossAccountId,1715 sender: &T::CrossAccountId,
1884 collection: &CollectionHandle<T>,1977 collection: &CollectionHandle<T>,
1885 item_id: TokenId,1978 item_id: TokenId,
1886 owner: &T::CrossAccountId,1979 owner: &T::CrossAccountId,
1980 value: u128,
1887 ) -> DispatchResult {1981 ) -> DispatchResult {
1888 let collection_id = collection.id;1982 let collection_id = collection.id;
18891983
1890 let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id)1984 let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id)
1891 .ok_or(Error::<T>::TokenNotFound)?;1985 .ok_or(Error::<T>::TokenNotFound)?;
1892 let rft_balance = token1986 let mut rft_balance = token
1893 .owner1987 .owner
1894 .iter()1988 .iter()
1895 .find(|&i| i.owner == *owner)1989 .find(|&i| i.owner == *owner)
1896 .ok_or(Error::<T>::TokenNotFound)?;1990 .ok_or(Error::<T>::TokenNotFound)?
1991 .clone();
1897 Self::remove_token_index(collection, item_id, owner)?;1992 Self::remove_token_index(collection, item_id, owner)?;
18981993
1899 // update balance1994 // update balance
1900 let new_balance = <Balance<T>>::get(collection_id, rft_balance.owner.as_sub())1995 let new_balance = <Balance<T>>::get(collection_id, rft_balance.owner.as_sub())
1901 .checked_sub(rft_balance.fraction)1996 .checked_sub(value)
1902 .ok_or(Error::<T>::NumOverflow)?;1997 .ok_or(Error::<T>::NumOverflow)?;
1903 <Balance<T>>::insert(collection_id, rft_balance.owner.as_sub(), new_balance);1998 <Balance<T>>::insert(collection_id, rft_balance.owner.as_sub(), new_balance);
19041999
1905 // Re-create owners list with sender removed2000 rft_balance.fraction = (rft_balance.fraction)
2001 .checked_sub(value)
2002 .ok_or(Error::<T>::NumOverflow)?;
2003
1906 let index = token2004 let index = token
1907 .owner2005 .owner
1908 .iter()2006 .iter()
1909 .position(|i| i.owner == *owner)2007 .position(|i| i.owner == *owner)
1910 .expect("owned item is exists");2008 .expect("owned item is exists");
2009 if rft_balance.fraction == 0 {
2010 // Re-create owners list with sender removed
1911 token.owner.remove(index);2011 token.owner.remove(index);
2012 } else {
2013 token.owner[index] = rft_balance;
2014 }
2015
1912 let owner_count = token.owner.len();2016 let owner_count = token.owner.len();
19132017
1947 }2051 }
19482052
1949 fn burn_fungible_item(2053 fn burn_fungible_item(
1950 owner: &T::CrossAccountId,2054 collection: &CollectionHandle<T>,
1951 collection: &CollectionHandle<T>,2055 owner: &T::CrossAccountId,
1952 value: u128,2056 value: u128,
1953 ) -> DispatchResult {2057 ) -> DispatchResult {
1954 let collection_id = collection.id;2058 let collection_id = collection.id;
modifiedpallets/nft/src/tests.rsdiffbeforeafterboth
711 origin1.clone(),
712 1,
713 1,
714 account(1),
715 5
716 ));
711 assert_noop!(717 assert_noop!(
712 TemplateModule::burn_item(origin1, 1, 1, 5),718 TemplateModule::burn_item(origin1, 1, 1, account(1), 5),
713 Error::<Test>::TokenNotFound719 Error::<Test>::TokenNotFound
714 );720 );
715721
746 origin1.clone(),
747 1,
748 1,
749 account(1),
750 5
751 ));
740 assert_noop!(752 assert_noop!(
741 TemplateModule::burn_item(origin1, 1, 1, 5),753 TemplateModule::burn_item(origin1, 1, 1, account(1), 5),
742 Error::<Test>::TokenValueNotEnough754 Error::<Test>::TokenValueNotEnough
743 );755 );
744756
797 origin1.clone(),
798 1,
799 1,
800 account(1),
801 1023
802 ));
785 assert_noop!(803 assert_noop!(
786 TemplateModule::burn_item(origin1, 1, 1, 1023),804 TemplateModule::burn_item(origin1, 1, 1, account(1), 1023),
787 Error::<Test>::TokenNotFound805 Error::<Test>::TokenNotFound
788 );806 );
789807
1378 AccessMode::WhiteList1396 AccessMode::WhiteList
1379 ));1397 ));
1380 assert_noop!(1398 assert_noop!(
1381 TemplateModule::burn_item(origin1, 1, 1, 5),1399 TemplateModule::burn_item(origin1.clone(), 1, 1, account(1), 5),
1382 Error::<Test>::AddresNotInWhiteList1400 Error::<Test>::AddresNotInWhiteList
1383 );1401 );
1384 });1402 });
modifiedtests/.vscode/settings.jsondiffbeforeafterboth
1{1{
2 "mocha.enabled": true2 "mocha.enabled": true,
3 "mochaExplorer.files": "**/*.test.ts",
4 "mochaExplorer.require": "ts-node/register"
3}5}
6
modifiedtests/package.jsondiffbeforeafterboth
20 "tslint": "^6.1.3",20 "tslint": "^6.1.3",
21 "typescript": "^4.2.4"21 "typescript": "^4.2.4"
22 },22 },
23 "mocha": {
24 "timeout": 9999999,
25 "require": "ts-node/register"
26 },
23 "scripts": {27 "scripts": {
24 "lint": "eslint --ext .ts,.js src/",28 "lint": "eslint --ext .ts,.js src/",
25 "fix": "eslint --ext .ts,.js src/ --fix",29 "fix": "eslint --ext .ts,.js src/ --fix",
modifiedtests/src/burnItem.test.tsdiffbeforeafterboth
38 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);38 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);
3939
40 await usingApi(async (api) => {40 await usingApi(async (api) => {
41 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);41 const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);
42 const events = await submitTransactionAsync(alice, tx);42 const events = await submitTransactionAsync(alice, tx);
43 const result = getGenericResult(events);43 const result = getGenericResult(events);
44 // Get the item44 // Get the item
79 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);79 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);
8080
81 await usingApi(async (api) => {81 await usingApi(async (api) => {
82 const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);82 const tx = api.tx.nft.burnItem(collectionId, tokenId, 100);
83 const events = await submitTransactionAsync(alice, tx);83 const events = await submitTransactionAsync(alice, tx);
84 const result = getGenericResult(events);84 const result = getGenericResult(events);
85 85
107 const balanceBefore: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();107 const balanceBefore: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();
108108
109 // Bob burns his portion109 // Bob burns his portion
110 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);110 const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);
111 const events2 = await submitTransactionAsync(bob, tx);111 const events2 = await submitTransactionAsync(bob, tx);
112 const result2 = getGenericResult(events2);112 const result2 = getGenericResult(events2);
113113
114 // Get balances 114 // Get balances
115 const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();115 const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();
116 // console.log(balance);116 // console.log(balance);
117 117
152 await addCollectionAdminExpectSuccess(alice, collectionId, bob);152 await addCollectionAdminExpectSuccess(alice, collectionId, bob);
153153
154 await usingApi(async (api) => {154 await usingApi(async (api) => {
155 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);155 const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);
156 const events = await submitTransactionAsync(bob, tx);156 const events = await submitTransactionAsync(bob, tx);
157 const result = getGenericResult(events);157 const result = getGenericResult(events);
158 // Get the item158 // Get the item
166 });166 });
167
168
169 it('Burn item in Fungible collection', async () => {
170 const createMode = 'Fungible';
171 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0 }});
172 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode); // Helper creates 10 fungible tokens
173 await addCollectionAdminExpectSuccess(alice, collectionId, bob);
174
175 await usingApi(async (api) => {
176 // Destroy 1 of 10
177 const tx = api.tx.nft.burnFrom(collectionId, normalizeAccountId(alice.address), tokenId, 1);
178 const events = await submitTransactionAsync(bob, tx);
179 const result = getGenericResult(events);
180
181 // Get alice balance
182 const balance: any = (await api.query.nft.fungibleItemList(collectionId, alice.address)).toJSON();
183
184 // What to expect
185 expect(result.success).to.be.true;
186 expect(balance).to.be.not.null;
187 expect(balance.Value).to.be.equal(9);
188 });
189 });
190
191 it('Burn item in ReFungible collection', async () => {
192 const createMode = 'ReFungible';
193 const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});
194 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);
195 await addCollectionAdminExpectSuccess(alice, collectionId, bob);
196
197 await usingApi(async (api) => {
198 const tx = api.tx.nft.burnFrom(collectionId, normalizeAccountId(alice.address), tokenId, 100);
199 const events = await submitTransactionAsync(bob, tx);
200 const result = getGenericResult(events);
201 // Get alice balance
202 const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();
203
204 // What to expect
205 expect(result.success).to.be.true;
206 expect(balance).to.be.null;
207 });
208 });
167});209});
168210
169describe('Negative integration test: ext. burnItem():', () => {211describe('Negative integration test: ext. burnItem():', () => {
197 const tokenId = 10;239 const tokenId = 10;
198240
199 await usingApi(async (api) => {241 await usingApi(async (api) => {
200 const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);242 const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);
201 const badTransaction = async function () { 243 const badTransaction = async function () {
202 await submitTransactionExpectFailAsync(alice, tx);244 await submitTransactionExpectFailAsync(alice, tx);
203 };245 };
228270
229 await usingApi(async (api) => {271 await usingApi(async (api) => {
230272
231 const burntx = api.tx.nft.burnItem(collectionId, tokenId, 0);273 const burntx = api.tx.nft.burnItem(collectionId, tokenId, 1);
232 const events1 = await submitTransactionAsync(alice, burntx);274 const events1 = await submitTransactionAsync(alice, burntx);
233 const result1 = getGenericResult(events1);275 const result1 = getGenericResult(events1);
234 expect(result1.success).to.be.true;276 expect(result1.success).to.be.true;
modifiedtests/src/transfer.test.tsdiffbeforeafterboth
199 const reFungibleCollectionId = await199 const reFungibleCollectionId = await
200 createCollectionExpectSuccess({mode: {type: 'ReFungible'}});200 createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
201 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');201 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
202 await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 1);202 await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 100);
203 await transferExpectFailure(203 await transferExpectFailure(
204 reFungibleCollectionId,204 reFungibleCollectionId,
205 newReFungibleTokenId,205 newReFungibleTokenId,
modifiedtests/src/transferFrom.test.tsdiffbeforeafterboth
265 await usingApi(async () => {265 await usingApi(async () => {
266 const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});266 const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
267 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');267 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
268 await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 1);268 await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 100);
269 await approveExpectFail(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);269 await approveExpectFail(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);
270 await transferFromExpectFail(reFungibleCollectionId, newReFungibleTokenId, Bob, Alice, Charlie, 1);270 await transferFromExpectFail(reFungibleCollectionId, newReFungibleTokenId, Bob, Alice, Charlie, 1);
271 271
297 const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});297 const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
298 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');298 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
299 await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);299 await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);
300 await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 1);300 await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 100);
301 await transferFromExpectFail(reFungibleCollectionId, newReFungibleTokenId, Bob, Alice, Charlie, 1);301 await transferFromExpectFail(reFungibleCollectionId, newReFungibleTokenId, Bob, Alice, Charlie, 1);
302 302
303 });303 });
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
700 ReFungible: CreateReFungibleData;700 ReFungible: CreateReFungibleData;
701};701};
702702
703export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {703export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {
704 await usingApi(async (api) => {704 await usingApi(async (api) => {
705 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);705 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);
706 const events = await submitTransactionAsync(owner, tx);706 const events = await submitTransactionAsync(sender, tx);
707 const result = getGenericResult(events);707 const result = getGenericResult(events);
708 // Get the item708 // Get the item
709 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();709 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();