difftreelog
Merge pull request #210 from UniqueNetwork/feature/CORE-180-v2
in: master
CORE-180. burnItem
10 files changed
launch-config.jsondiffbeforeafterboth67 "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 ]pallets/nft/src/eth/erc.rsdiffbeforeafterboth194 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")?;196196197 <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 }pallets/nft/src/lib.rsdiffbeforeafterboth992 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)?;994994995 Self::burn_item_internal(&sender, &target_collection, item_id, value)?;995 Self::burn_item_internal(&sender, &target_collection, item_id, value, true)?;996996997 target_collection.submit_logs()997 target_collection.submit_logs()998 }998 }9991000 /// Destroys a concrete instance of NFT on behalf of the owner1001 /// See also: [`approve`]1002 ///1003 /// # Permissions1004 ///1005 /// * Collection Owner.1006 /// * Collection Admin.1007 /// * Current NFT Owner.1008 ///1009 /// # Arguments1010 ///1011 /// * collection_id: ID of the collection.1012 ///1013 /// * item_id: ID of NFT to burn.1014 ///1015 /// * from: owner of item1016 #[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 {10191020 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1021 let target_collection = Self::get_collection(collection_id)?;10221023 Self::burn_from_internal(&sender, &target_collection, &from, item_id, value)?;10241025 target_collection.submit_logs()1026 }99910271000 /// Change ownership of the token.1028 /// Change ownership of the token.1001 ///1029 ///1593 }1621 }159416221595 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_escalation1633 && collection.limits.owner_can_transfer1604 && Self::is_owner_or_admin_permissions(collection, sender)?),1634 && Self::is_owner_or_admin_permissions(collection, owner)?),1605 Error::<T>::NoPermission1635 Error::<T>::NoPermission1606 );1636 );160716371608 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 }161116411612 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 };161716541618 Ok(())1655 Ok(())1619 }1656 }16571658 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 him1667 return Self::burn_item_internal(from, collection, item_id, amount, true);1668 }16691670 // Check approval1671 collection.consume_sload()?;1672 let approval: u128 =1673 <Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));16741675 // Transfer permissions check1676 ensure!(1677 approval >= amount1678 || (collection.limits.owner_can_transfer1679 && Self::is_owner_or_admin_permissions(collection, sender)?),1680 Error::<T>::NoPermission1681 );16821683 if collection.access == AccessMode::WhiteList {1684 Self::check_white_list(collection, sender)?;1685 }16861687 // Reduce approval by transferred amount or remove if remaining approval drops to 01688 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 }16991700 // Escalation is disallowed here, because we need to be sure that passed owner is real1701 Self::burn_item_internal(from, collection, item_id, amount, false)?;17021703 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 }17101711 Ok(())1712 }162017131621 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;188919831890 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 = token1893 .owner1987 .owner1894 .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)?;189819931899 // update balance1994 // update balance1900 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);190419991905 // Re-create owners list with sender removed2000 rft_balance.fraction = (rft_balance.fraction)2001 .checked_sub(value)2002 .ok_or(Error::<T>::NumOverflow)?;20031906 let index = token2004 let index = token1907 .owner2005 .owner1908 .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 removed1911 token.owner.remove(index);2011 token.owner.remove(index);2012 } else {2013 token.owner[index] = rft_balance;2014 }20151912 let owner_count = token.owner.len();2016 let owner_count = token.owner.len();191320171947 }2051 }194820521949 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;pallets/nft/src/tests.rsdiffbeforeafterboth711 origin1.clone(),712 1,713 1,714 account(1),715 5716 ));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>::TokenNotFound714 );720 );715721746 origin1.clone(),747 1,748 1,749 account(1),750 5751 ));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>::TokenValueNotEnough743 );755 );744756797 origin1.clone(),798 1,799 1,800 account(1),801 1023802 ));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>::TokenNotFound788 );806 );7898071378 AccessMode::WhiteList1396 AccessMode::WhiteList1379 ));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>::AddresNotInWhiteList1383 );1401 );1384 });1402 });tests/.vscode/settings.jsondiffbeforeafterboth1{1{2 "mocha.enabled": true2 "mocha.enabled": true,3 "mochaExplorer.files": "**/*.test.ts",4 "mochaExplorer.require": "ts-node/register"3}5}6tests/package.jsondiffbeforeafterboth20 "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",tests/src/burnItem.test.tsdiffbeforeafterboth38 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);38 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);393940 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 item79 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);79 const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);808081 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();108108109 // Bob burns his portion109 // Bob burns his portion110 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);113113114 // Get balances 114 // Get balances115 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 117152 await addCollectionAdminExpectSuccess(alice, collectionId, bob);152 await addCollectionAdminExpectSuccess(alice, collectionId, bob);153153154 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 item166 });166 });167168169 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 tokens173 await addCollectionAdminExpectSuccess(alice, collectionId, bob);174175 await usingApi(async (api) => {176 // Destroy 1 of 10177 const tx = api.tx.nft.burnFrom(collectionId, normalizeAccountId(alice.address), tokenId, 1);178 const events = await submitTransactionAsync(bob, tx);179 const result = getGenericResult(events);180181 // Get alice balance182 const balance: any = (await api.query.nft.fungibleItemList(collectionId, alice.address)).toJSON();183184 // What to expect185 expect(result.success).to.be.true;186 expect(balance).to.be.not.null;187 expect(balance.Value).to.be.equal(9);188 });189 });190191 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);196197 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 balance202 const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();203204 // What to expect205 expect(result.success).to.be.true;206 expect(balance).to.be.null;207 });208 });167});209});168210169describe('Negative integration test: ext. burnItem():', () => {211describe('Negative integration test: ext. burnItem():', () => {197 const tokenId = 10;239 const tokenId = 10;198240199 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 };228270229 await usingApi(async (api) => {271 await usingApi(async (api) => {230272231 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;tests/src/transfer.test.tsdiffbeforeafterboth199 const reFungibleCollectionId = await199 const reFungibleCollectionId = await200 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,tests/src/transferFrom.test.tsdiffbeforeafterboth265 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 271297 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 302303 });303 });tests/src/util/helpers.tsdiffbeforeafterboth700 ReFungible: CreateReFungibleData;700 ReFungible: CreateReFungibleData;701};701};702702703export 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 item709 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();709 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();