difftreelog
Merge pull request #747 from UniqueNetwork/tests/refungible
in: master
Transfer tests
14 files changed
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -379,7 +379,7 @@
let balance_from = <Balance<T>>::get((collection.id, from))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
- let balance_to = if from != to {
+ let balance_to = if from != to && amount != 0 {
Some(
<Balance<T>>::get((collection.id, to))
.checked_add(amount)
@@ -391,16 +391,17 @@
// =========
- <PalletStructure<T>>::nest_if_sent_to_token(
- from.clone(),
- to,
- collection.id,
- TokenId::default(),
- nesting_budget,
- )?;
-
if let Some(balance_to) = balance_to {
- // from != to
+ // from != to && amount != 0
+
+ <PalletStructure<T>>::nest_if_sent_to_token(
+ from.clone(),
+ to,
+ collection.id,
+ TokenId::default(),
+ nesting_budget,
+ )?;
+
if balance_from == 0 {
<Balance<T>>::remove((collection.id, from));
<PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());
pallets/nonfungible/src/common.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use core::marker::PhantomData;1819use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};20use up_data_structs::{21 TokenId, CreateItemExData, CollectionId, budget::Budget, Property, PropertyKey,22 PropertyKeyPermission, PropertyValue,23};24use pallet_common::{25 CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,26 weights::WeightInfo as _,27};28use sp_runtime::DispatchError;29use sp_std::{vec::Vec, vec};3031use crate::{32 AccountBalance, Allowance, Config, CreateItemData, Error, NonfungibleHandle, Owned, Pallet,33 SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,34};3536pub struct CommonWeights<T: Config>(PhantomData<T>);37impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {38 fn create_item() -> Weight {39 <SelfWeightOf<T>>::create_item()40 }4142 fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {43 match data {44 CreateItemExData::NFT(t) => {45 <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32)46 + t.iter()47 .filter_map(|t| {48 if t.properties.len() > 0 {49 Some(Self::set_token_properties(t.properties.len() as u32))50 } else {51 None52 }53 })54 .fold(Weight::zero(), |a, b| a.saturating_add(b))55 }56 _ => Weight::zero(),57 }58 }5960 fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {61 <SelfWeightOf<T>>::create_multiple_items(data.len() as u32)62 + data63 .iter()64 .filter_map(|t| match t {65 up_data_structs::CreateItemData::NFT(n) if n.properties.len() > 0 => {66 Some(Self::set_token_properties(n.properties.len() as u32))67 }68 _ => None,69 })70 .fold(Weight::zero(), |a, b| a.saturating_add(b))71 }7273 fn burn_item() -> Weight {74 <SelfWeightOf<T>>::burn_item()75 }7677 fn set_collection_properties(amount: u32) -> Weight {78 <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)79 }8081 fn delete_collection_properties(amount: u32) -> Weight {82 <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)83 }8485 fn set_token_properties(amount: u32) -> Weight {86 <SelfWeightOf<T>>::set_token_properties(amount)87 }8889 fn delete_token_properties(amount: u32) -> Weight {90 <SelfWeightOf<T>>::delete_token_properties(amount)91 }9293 fn set_token_property_permissions(amount: u32) -> Weight {94 <SelfWeightOf<T>>::set_token_property_permissions(amount)95 }9697 fn transfer() -> Weight {98 <SelfWeightOf<T>>::transfer()99 }100101 fn approve() -> Weight {102 <SelfWeightOf<T>>::approve()103 }104105 fn transfer_from() -> Weight {106 <SelfWeightOf<T>>::transfer_from()107 }108109 fn burn_from() -> Weight {110 <SelfWeightOf<T>>::burn_from()111 }112113 fn burn_recursively_self_raw() -> Weight {114 <SelfWeightOf<T>>::burn_recursively_self_raw()115 }116117 fn burn_recursively_breadth_raw(amount: u32) -> Weight {118 <SelfWeightOf<T>>::burn_recursively_breadth_plus_self_plus_self_per_each_raw(amount)119 .saturating_sub(Self::burn_recursively_self_raw().saturating_mul(amount as u64 + 1))120 }121122 fn token_owner() -> Weight {123 <SelfWeightOf<T>>::token_owner()124 }125}126127fn map_create_data<T: Config>(128 data: up_data_structs::CreateItemData,129 to: &T::CrossAccountId,130) -> Result<CreateItemData<T>, DispatchError> {131 match data {132 up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {133 properties: data.properties,134 owner: to.clone(),135 }),136 _ => fail!(<Error<T>>::NotNonfungibleDataUsedToMintFungibleCollectionToken),137 }138}139140/// Implementation of `CommonCollectionOperations` for `NonfungibleHandle`. It wraps Nonfungible Pallete141/// methods and adds weight info.142impl<T: Config> CommonCollectionOperations<T> for NonfungibleHandle<T> {143 fn create_item(144 &self,145 sender: T::CrossAccountId,146 to: T::CrossAccountId,147 data: up_data_structs::CreateItemData,148 nesting_budget: &dyn Budget,149 ) -> DispatchResultWithPostInfo {150 with_weight(151 <Pallet<T>>::create_item(152 self,153 &sender,154 map_create_data::<T>(data, &to)?,155 nesting_budget,156 ),157 <CommonWeights<T>>::create_item(),158 )159 }160161 fn create_multiple_items(162 &self,163 sender: T::CrossAccountId,164 to: T::CrossAccountId,165 data: Vec<up_data_structs::CreateItemData>,166 nesting_budget: &dyn Budget,167 ) -> DispatchResultWithPostInfo {168 let weight = <CommonWeights<T>>::create_multiple_items(&data);169 let data = data170 .into_iter()171 .map(|d| map_create_data::<T>(d, &to))172 .collect::<Result<Vec<_>, DispatchError>>()?;173174 with_weight(175 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),176 weight,177 )178 }179180 fn create_multiple_items_ex(181 &self,182 sender: <T>::CrossAccountId,183 data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,184 nesting_budget: &dyn Budget,185 ) -> DispatchResultWithPostInfo {186 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);187 let data = match data {188 up_data_structs::CreateItemExData::NFT(nft) => nft,189 _ => fail!(Error::<T>::NotNonfungibleDataUsedToMintFungibleCollectionToken),190 };191192 with_weight(193 <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),194 weight,195 )196 }197198 fn set_collection_properties(199 &self,200 sender: T::CrossAccountId,201 properties: Vec<Property>,202 ) -> DispatchResultWithPostInfo {203 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);204205 with_weight(206 <Pallet<T>>::set_collection_properties(self, &sender, properties),207 weight,208 )209 }210211 fn delete_collection_properties(212 &self,213 sender: &T::CrossAccountId,214 property_keys: Vec<PropertyKey>,215 ) -> DispatchResultWithPostInfo {216 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);217218 with_weight(219 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),220 weight,221 )222 }223224 fn set_token_properties(225 &self,226 sender: T::CrossAccountId,227 token_id: TokenId,228 properties: Vec<Property>,229 nesting_budget: &dyn Budget,230 ) -> DispatchResultWithPostInfo {231 let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);232233 with_weight(234 <Pallet<T>>::set_token_properties(235 self,236 &sender,237 token_id,238 properties.into_iter(),239 false,240 nesting_budget,241 ),242 weight,243 )244 }245246 fn delete_token_properties(247 &self,248 sender: T::CrossAccountId,249 token_id: TokenId,250 property_keys: Vec<PropertyKey>,251 nesting_budget: &dyn Budget,252 ) -> DispatchResultWithPostInfo {253 let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);254255 with_weight(256 <Pallet<T>>::delete_token_properties(257 self,258 &sender,259 token_id,260 property_keys.into_iter(),261 nesting_budget,262 ),263 weight,264 )265 }266267 fn set_token_property_permissions(268 &self,269 sender: &T::CrossAccountId,270 property_permissions: Vec<PropertyKeyPermission>,271 ) -> DispatchResultWithPostInfo {272 let weight =273 <CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);274275 with_weight(276 <Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),277 weight,278 )279 }280281 fn burn_item(282 &self,283 sender: T::CrossAccountId,284 token: TokenId,285 amount: u128,286 ) -> DispatchResultWithPostInfo {287 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);288 if amount == 1 {289 with_weight(290 <Pallet<T>>::burn(self, &sender, token),291 <CommonWeights<T>>::burn_item(),292 )293 } else {294 Ok(().into())295 }296 }297298 fn burn_item_recursively(299 &self,300 sender: T::CrossAccountId,301 token: TokenId,302 self_budget: &dyn Budget,303 breadth_budget: &dyn Budget,304 ) -> DispatchResultWithPostInfo {305 <Pallet<T>>::burn_recursively(self, &sender, token, self_budget, breadth_budget)306 }307308 fn transfer(309 &self,310 from: T::CrossAccountId,311 to: T::CrossAccountId,312 token: TokenId,313 amount: u128,314 nesting_budget: &dyn Budget,315 ) -> DispatchResultWithPostInfo {316 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);317 if amount == 1 {318 with_weight(319 <Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),320 <CommonWeights<T>>::transfer(),321 )322 } else {323 Ok(().into())324 }325 }326327 fn approve(328 &self,329 sender: T::CrossAccountId,330 spender: T::CrossAccountId,331 token: TokenId,332 amount: u128,333 ) -> DispatchResultWithPostInfo {334 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);335336 with_weight(337 if amount == 1 {338 <Pallet<T>>::set_allowance(self, &sender, token, Some(&spender))339 } else {340 <Pallet<T>>::set_allowance(self, &sender, token, None)341 },342 <CommonWeights<T>>::approve(),343 )344 }345346 fn transfer_from(347 &self,348 sender: T::CrossAccountId,349 from: T::CrossAccountId,350 to: T::CrossAccountId,351 token: TokenId,352 amount: u128,353 nesting_budget: &dyn Budget,354 ) -> DispatchResultWithPostInfo {355 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);356357 if amount == 1 {358 with_weight(359 <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),360 <CommonWeights<T>>::transfer_from(),361 )362 } else {363 Ok(().into())364 }365 }366367 fn burn_from(368 &self,369 sender: T::CrossAccountId,370 from: T::CrossAccountId,371 token: TokenId,372 amount: u128,373 nesting_budget: &dyn Budget,374 ) -> DispatchResultWithPostInfo {375 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);376377 if amount == 1 {378 with_weight(379 <Pallet<T>>::burn_from(self, &sender, &from, token, nesting_budget),380 <CommonWeights<T>>::burn_from(),381 )382 } else {383 Ok(().into())384 }385 }386387 fn check_nesting(388 &self,389 sender: T::CrossAccountId,390 from: (CollectionId, TokenId),391 under: TokenId,392 nesting_budget: &dyn Budget,393 ) -> sp_runtime::DispatchResult {394 <Pallet<T>>::check_nesting(self, sender, from, under, nesting_budget)395 }396397 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId)) {398 <Pallet<T>>::nest((self.id, under), to_nest);399 }400401 fn unnest(&self, under: TokenId, to_unnest: (CollectionId, TokenId)) {402 <Pallet<T>>::unnest((self.id, under), to_unnest);403 }404405 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {406 <Owned<T>>::iter_prefix((self.id, account))407 .map(|(id, _)| id)408 .collect()409 }410411 fn collection_tokens(&self) -> Vec<TokenId> {412 <TokenData<T>>::iter_prefix((self.id,))413 .map(|(id, _)| id)414 .collect()415 }416417 fn token_exists(&self, token: TokenId) -> bool {418 <Pallet<T>>::token_exists(self, token)419 }420421 fn last_token_id(&self) -> TokenId {422 TokenId(<TokensMinted<T>>::get(self.id))423 }424425 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {426 <TokenData<T>>::get((self.id, token)).map(|t| t.owner)427 }428429 /// Returns token owners.430 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {431 self.token_owner(token).map_or_else(|| vec![], |t| vec![t])432 }433434 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {435 <Pallet<T>>::token_properties((self.id, token_id))436 .get(key)437 .cloned()438 }439440 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {441 let properties = <Pallet<T>>::token_properties((self.id, token_id));442443 keys.map(|keys| {444 keys.into_iter()445 .filter_map(|key| {446 properties.get(&key).map(|value| Property {447 key,448 value: value.clone(),449 })450 })451 .collect()452 })453 .unwrap_or_else(|| {454 properties455 .into_iter()456 .map(|(key, value)| Property { key, value })457 .collect()458 })459 }460461 fn total_supply(&self) -> u32 {462 <Pallet<T>>::total_supply(self)463 }464465 fn account_balance(&self, account: T::CrossAccountId) -> u32 {466 <AccountBalance<T>>::get((self.id, account))467 }468469 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {470 if <TokenData<T>>::get((self.id, token))471 .map(|a| a.owner == account)472 .unwrap_or(false)473 {474 1475 } else {476 0477 }478 }479480 fn allowance(481 &self,482 sender: T::CrossAccountId,483 spender: T::CrossAccountId,484 token: TokenId,485 ) -> u128 {486 if <TokenData<T>>::get((self.id, token))487 .map(|a| a.owner != sender)488 .unwrap_or(true)489 {490 0491 } else if <Allowance<T>>::get((self.id, token)) == Some(spender) {492 1493 } else {494 0495 }496 }497498 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {499 None500 }501502 fn total_pieces(&self, token: TokenId) -> Option<u128> {503 if <TokenData<T>>::contains_key((self.id, token)) {504 Some(1)505 } else {506 None507 }508 }509}pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -814,6 +814,20 @@
<PalletCommon<T>>::set_property_permission(collection, sender, permission)
}
+ pub fn check_token_immediate_ownership(
+ collection: &NonfungibleHandle<T>,
+ token: TokenId,
+ possible_owner: &T::CrossAccountId,
+ ) -> DispatchResult {
+ let token_data =
+ <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
+ ensure!(
+ &token_data.owner == possible_owner,
+ <CommonError<T>>::NoPermission
+ );
+ Ok(())
+ }
+
/// Transfer NFT token from one account to another.
///
/// `from` account stops being the owner and `to` account becomes the owner of the token.
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -34,6 +34,7 @@
CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
erc::{CommonEvmHandler, CollectionCall, static_property::key},
eth::EthCrossAccount,
+ Error as CommonError,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
@@ -508,6 +509,13 @@
) -> Result<()> {
collection.consume_store_reads(1)?;
let total_supply = <TotalSupply<T>>::get((collection.id, token));
+
+ if owner_balance == 0 {
+ return Err(dispatch_to_evm::<T>(
+ <CommonError<T>>::MustBeTokenOwner.into(),
+ ));
+ }
+
if total_supply != owner_balance {
return Err("token has multiple owners".into());
}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -452,6 +452,10 @@
token: TokenId,
amount: u128,
) -> DispatchResult {
+ if <Balance<T>>::get((collection.id, token, owner)) == 0 {
+ return Err(<CommonError<T>>::TokenValueTooLow.into());
+ }
+
let total_supply = <TotalSupply<T>>::get((collection.id, token))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
@@ -739,12 +743,17 @@
<PalletCommon<T>>::ensure_correct_receiver(to)?;
let initial_balance_from = <Balance<T>>::get((collection.id, token, from));
+
+ if initial_balance_from == 0 {
+ return Err(<CommonError<T>>::TokenValueTooLow.into());
+ }
+
let updated_balance_from = initial_balance_from
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
let mut create_target = false;
let from_to_differ = from != to;
- let updated_balance_to = if from != to {
+ let updated_balance_to = if from != to && amount != 0 {
let old_balance = <Balance<T>>::get((collection.id, token, to));
if old_balance == 0 {
create_target = true;
@@ -786,16 +795,17 @@
// =========
- <PalletStructure<T>>::nest_if_sent_to_token(
- from.clone(),
- to,
- collection.id,
- token,
- nesting_budget,
- )?;
+ if let Some(updated_balance_to) = updated_balance_to {
+ // from != to && amount != 0
+
+ <PalletStructure<T>>::nest_if_sent_to_token(
+ from.clone(),
+ to,
+ collection.id,
+ token,
+ nesting_budget,
+ )?;
- if let Some(updated_balance_to) = updated_balance_to {
- // from != to
if updated_balance_from == 0 {
<Balance<T>>::remove((collection.id, token, from));
<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);
tests/src/burnItem.test.tsdiffbeforeafterboth--- a/tests/src/burnItem.test.ts
+++ b/tests/src/burnItem.test.ts
@@ -140,6 +140,31 @@
await expect(token.burn(bob)).to.be.rejectedWith('common.NoPermission');
});
+ itSub.ifWithPallets('RFT: cannot burn non-owned token pieces', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice);
+ const aliceToken = await collection.mintToken(alice, 10n, {Substrate: alice.address});
+ const bobToken = await collection.mintToken(alice, 10n, {Substrate: bob.address});
+
+ // 1. Cannot burn non-owned token:
+ await expect(bobToken.burn(alice, 0n)).to.be.rejectedWith('common.TokenValueTooLow');
+ await expect(bobToken.burn(alice, 5n)).to.be.rejectedWith('common.TokenValueTooLow');
+ // 2. Cannot burn non-existing token:
+ await expect(helper.rft.burnToken(alice, 99999, 10)).to.be.rejectedWith('common.CollectionNotFound');
+ await expect(helper.rft.burnToken(alice, collection.collectionId, 99999)).to.be.rejectedWith('common.TokenValueTooLow');
+ // 3. Can burn zero amount of owned tokens (EIP-20)
+ await aliceToken.burn(alice, 0n);
+
+ // 4. Storage is not corrupted:
+ expect(await aliceToken.getTop10Owners()).to.deep.eq([{Substrate: alice.address}]);
+ expect(await bobToken.getTop10Owners()).to.deep.eq([{Substrate: bob.address}]);
+
+ // 4.1 Tokens can be transfered:
+ await aliceToken.transfer(alice, {Substrate: bob.address}, 10n);
+ await bobToken.transfer(bob, {Substrate: alice.address}, 10n);
+ expect(await aliceToken.getTop10Owners()).to.deep.eq([{Substrate: bob.address}]);
+ expect(await bobToken.getTop10Owners()).to.deep.eq([{Substrate: alice.address}]);
+ });
+
itSub('Transfer a burned token', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice);
const token = await collection.mintToken(alice);
@@ -155,4 +180,48 @@
await expect(collection.burnTokens(alice, 11n)).to.be.rejectedWith('common.TokenValueTooLow');
expect(await collection.getBalance({Substrate: alice.address})).to.eq(10n);
});
+
+ itSub('Zero burn NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Coll', description: 'Desc', tokenPrefix: 'T'});
+ const tokenAlice = await collection.mintToken(alice, {Substrate: alice.address});
+ const tokenBob = await collection.mintToken(alice, {Substrate: bob.address});
+
+ // 1. Zero burn of own tokens allowed:
+ await helper.executeExtrinsic(alice, 'api.tx.unique.burnItem', [collection.collectionId, tokenAlice.tokenId, 0]);
+ // 2. Zero burn of non-owned tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.burnItem', [collection.collectionId, tokenBob.tokenId, 0])).to.be.rejectedWith('common.NoPermission');
+ // 3. Zero burn of non-existing tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.burnItem', [collection.collectionId, 9999, 0])).to.be.rejectedWith('common.TokenNotFound');
+ expect(await tokenAlice.doesExist()).to.be.true;
+ expect(await tokenAlice.getOwner()).to.deep.eq({Substrate: alice.address});
+ expect(await tokenBob.getOwner()).to.deep.eq({Substrate: bob.address});
+ // 4. Storage is not corrupted:
+ await tokenAlice.transfer(alice, {Substrate: bob.address});
+ await tokenBob.transfer(bob, {Substrate: alice.address});
+ expect(await tokenAlice.getOwner()).to.deep.eq({Substrate: bob.address});
+ expect(await tokenBob.getOwner()).to.deep.eq({Substrate: alice.address});
+ });
+
+ itSub('zero burnFrom NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Zero', description: 'Zero transfer', tokenPrefix: 'TF'});
+ const notApprovedNft = await collection.mintToken(alice, {Substrate: bob.address});
+ const approvedNft = await collection.mintToken(alice, {Substrate: bob.address});
+ await approvedNft.approve(bob, {Substrate: alice.address});
+
+ // 1. Zero burnFrom of non-existing tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.burnFrom', [collection.collectionId, {Substrate: bob.address}, 9999, 0])).to.be.rejectedWith('common.ApprovedValueTooLow');
+ // 2. Zero burnFrom of not approved tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.burnFrom', [collection.collectionId, {Substrate: bob.address}, notApprovedNft.tokenId, 0])).to.be.rejectedWith('common.ApprovedValueTooLow');
+ // 3. Zero burnFrom of approved tokens allowed:
+ await helper.executeExtrinsic(alice, 'api.tx.unique.burnFrom', [collection.collectionId, {Substrate: bob.address}, approvedNft.tokenId, 0]);
+
+ // 4.1 approvedNft still approved:
+ expect(await approvedNft.isApproved({Substrate: alice.address})).to.be.true;
+ // 4.2 bob is still the owner:
+ expect(await approvedNft.getOwner()).to.deep.eq({Substrate: bob.address});
+ expect(await notApprovedNft.getOwner()).to.deep.eq({Substrate: bob.address});
+ // 4.3 Alice can burn approved nft:
+ await approvedNft.burnFrom(alice, {Substrate: bob.address});
+ expect(await approvedNft.doesExist()).to.be.false;
+ });
});
tests/src/eth/fungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -277,7 +277,7 @@
}
});
- itEth('Cannot transferCross() more than have', async ({helper}) => {
+ ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} incorrect amount`, async ({helper}) => {
const sender = await helper.eth.createAccountWithBalance(donor);
const receiverEth = await helper.eth.createAccountWithBalance(donor);
const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);
@@ -289,8 +289,13 @@
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'ft', sender);
- await expect(collectionEvm.methods.transferCross(receiverCrossEth, BALANCE_TO_TRANSFER).send({from: sender})).to.be.rejected;
- });
+ // 1. Cannot transfer more than have
+ const receiver = testCase === 'transfer' ? receiverEth : receiverCrossEth;
+ await expect(collectionEvm.methods[testCase](receiver, BALANCE_TO_TRANSFER).send({from: sender})).to.be.rejected;
+ // 2. Zero transfer allowed (EIP-20):
+ await collectionEvm.methods[testCase](receiver, 0n).send({from: sender});
+ }));
+
itEth('Can perform transfer()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -517,6 +517,26 @@
expect(receiverBalance).to.contain(tokenId);
}
});
+
+ ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} non-owned token`, async ({helper}) => {
+ const sender = await helper.eth.createAccountWithBalance(donor);
+ const tokenOwner = await helper.eth.createAccountWithBalance(donor);
+ const receiverSub = minter;
+ const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(minter);
+
+ const collection = await helper.nft.mintCollection(minter, {});
+ const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', sender);
+
+ await collection.mintToken(minter, {Ethereum: sender});
+ const nonSendersToken = await collection.mintToken(minter, {Ethereum: tokenOwner});
+
+ // Cannot transferCross someone else's token:
+ const receiver = testCase === 'transfer' ? helper.address.substrateToEth(receiverSub.address) : receiverCrossSub;
+ await expect(collectionEvm.methods[testCase](receiver, nonSendersToken.tokenId).send({from: sender})).to.be.rejected;
+ // Cannot transfer token if it does not exist:
+ await expect(collectionEvm.methods[testCase](receiver, 999999).send({from: sender})).to.be.rejected;
+ }));
});
describe('NFT: Fees', () => {
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -413,9 +413,10 @@
}
});
- itEth.skip('Cannot transferCross with invalid params', async ({helper}) => {
+ ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} non-owned token`, async ({helper}) => {
const sender = await helper.eth.createAccountWithBalance(donor);
const tokenOwner = await helper.eth.createAccountWithBalance(donor);
+ const receiverSub = minter;
const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(minter);
const collection = await helper.rft.mintCollection(minter, {});
@@ -423,12 +424,14 @@
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'rft', sender);
await collection.mintToken(minter, 50n, {Ethereum: sender});
- const notSendersToken = await collection.mintToken(minter, 50n, {Ethereum: tokenOwner});
+ const nonSendersToken = await collection.mintToken(minter, 50n, {Ethereum: tokenOwner});
+
// Cannot transferCross someone else's token:
- await expect(collectionEvm.methods.transferCross(receiverCrossSub, notSendersToken.tokenId).send({from: sender})).to.be.rejected;
- // FIXME: (transaction successful): Cannot transfer token if it does not exist:
- await expect(collectionEvm.methods.transferCross(receiverCrossSub, 999999).send({from: sender})).to.be.rejected;
- });
+ const receiver = testCase === 'transfer' ? helper.address.substrateToEth(receiverSub.address) : receiverCrossSub;
+ await expect(collectionEvm.methods[testCase](receiver, nonSendersToken.tokenId).send({from: sender})).to.be.rejected;
+ // Cannot transfer token if it does not exist:
+ await expect(collectionEvm.methods[testCase](receiver, 999999).send({from: sender})).to.be.rejected;
+ }));
itEth('transfer event on transfer from partial ownership to full ownership', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -227,6 +227,46 @@
}
});
+ [
+ 'transfer',
+ // 'transferCross', // TODO
+ ].map(testCase =>
+ itEth(`Cannot ${testCase}() non-owned token`, async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const receiver = await helper.eth.createAccountWithBalance(donor);
+ const collection = await helper.rft.mintCollection(alice);
+ const rftOwner = await collection.mintToken(alice, 10n, {Ethereum: owner});
+ const rftReceiver = await collection.mintToken(alice, 10n, {Ethereum: receiver});
+ const tokenIdNonExist = 9999999;
+
+ const tokenAddress1 = helper.ethAddress.fromTokenId(collection.collectionId, rftOwner.tokenId);
+ const tokenAddress2 = helper.ethAddress.fromTokenId(collection.collectionId, rftReceiver.tokenId);
+ const tokenAddressNonExist = helper.ethAddress.fromTokenId(collection.collectionId, tokenIdNonExist);
+ const tokenEvmOwner = helper.ethNativeContract.rftToken(tokenAddress1, owner);
+ const tokenEvmReceiver = helper.ethNativeContract.rftToken(tokenAddress2, owner);
+ const tokenEvmNonExist = helper.ethNativeContract.rftToken(tokenAddressNonExist, owner);
+
+ // 1. Can transfer zero amount (EIP-20):
+ await tokenEvmOwner.methods[testCase](receiver, 0).send({from: owner});
+ // 2. Cannot transfer non-owned token:
+ await expect(tokenEvmReceiver.methods[testCase](owner, 0).send({from: owner})).to.be.rejected;
+ await expect(tokenEvmReceiver.methods[testCase](owner, 5).send({from: owner})).to.be.rejected;
+ // 3. Cannot transfer non-existing token:
+ await expect(tokenEvmNonExist.methods[testCase](owner, 0).send({from: owner})).to.be.rejected;
+ await expect(tokenEvmNonExist.methods[testCase](owner, 5).send({from: owner})).to.be.rejected;
+
+ // 4. Storage is not corrupted:
+ expect(await rftOwner.getTop10Owners()).to.deep.eq([{Ethereum: owner.toLowerCase()}]);
+ expect(await rftReceiver.getTop10Owners()).to.deep.eq([{Ethereum: receiver.toLowerCase()}]);
+ expect(await helper.rft.getTokenTop10Owners(collection.collectionId, tokenIdNonExist)).to.deep.eq([]); // TODO
+
+ // 4.1 Tokens can be transferred:
+ await tokenEvmOwner.methods[testCase](receiver, 10).send({from: owner});
+ await tokenEvmReceiver.methods[testCase](owner, 10).send({from: receiver});
+ expect(await rftOwner.getTop10Owners()).to.deep.eq([{Ethereum: receiver.toLowerCase()}]);
+ expect(await rftReceiver.getTop10Owners()).to.deep.eq([{Ethereum: owner.toLowerCase()}]);
+ }));
+
itEth('Can perform repartition()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = await helper.eth.createAccountWithBalance(donor);
tests/src/fungible.test.tsdiffbeforeafterboth--- a/tests/src/fungible.test.ts
+++ b/tests/src/fungible.test.ts
@@ -15,7 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {itSub, usingPlaygrounds, expect} from './util';
+import {itSub, usingPlaygrounds, expect, requirePalletsOrSkip, Pallets} from './util';
const U128_MAX = (1n << 128n) - 1n;
@@ -145,3 +145,42 @@
expect(await collection.getBalance(ethAcc)).to.be.equal(10n);
});
});
+
+describe('Fungible negative tests', () => {
+ let donor: IKeyringPair;
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async function() {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ requirePalletsOrSkip(this, helper, [Pallets.Fungible]);
+
+ donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
+
+ itSub('Cannot transfer incorrect amount of tokens', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const nonExistingCollection = helper.ft.getCollectionObject(99999);
+ await collection.mint(alice, 10n, {Substrate: bob.address});
+
+ // 1. Alice cannot transfer more than 0 tokens if balance low:
+ await expect(collection.transfer(alice, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
+ await expect(collection.transfer(alice, {Substrate: charlie.address}, 100n)).to.be.rejectedWith('common.TokenValueTooLow');
+
+ // 2. Alice cannot transfer non-existing token:
+ await expect(nonExistingCollection.transfer(alice, {Substrate: charlie.address}, 0n)).to.be.rejectedWith('common.CollectionNotFound');
+ await expect(nonExistingCollection.transfer(alice, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.CollectionNotFound');
+
+ // 3. Zero transfer allowed (EIP-20):
+ await collection.transfer(bob, {Substrate: charlie.address}, 0n);
+ // 3.1 even if the balance = 0
+ await collection.transfer(alice, {Substrate: charlie.address}, 0n);
+
+ expect(await collection.getBalance({Substrate: alice.address})).to.eq(0n);
+ expect(await collection.getBalance({Substrate: bob.address})).to.eq(10n);
+ expect(await collection.getBalance({Substrate: charlie.address})).to.eq(0n);
+ });
+});
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -255,3 +255,43 @@
});
});
+describe('Refungible negative tests', () => {
+ let donor: IKeyringPair;
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async function() {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+
+ donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
+
+ itSub('Cannot transfer incorrect amount of token pieces', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const tokenAlice = await collection.mintToken(alice, 10n, {Substrate: alice.address});
+ const tokenBob = await collection.mintToken(alice, 10n, {Substrate: bob.address});
+
+ // 1. Alice cannot transfer Bob's token:
+ await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 0n)).to.be.rejectedWith('common.TokenValueTooLow');
+ await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
+ await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 10n)).to.be.rejectedWith('common.TokenValueTooLow');
+ await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 100n)).to.be.rejectedWith('common.TokenValueTooLow');
+
+ // 2. Alice cannot transfer non-existing token:
+ await expect(collection.transferToken(alice, 100, {Substrate: charlie.address}, 0n)).to.be.rejectedWith('common.TokenValueTooLow');
+ await expect(collection.transferToken(alice, 100, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
+
+ // 3. Zero transfer allowed (EIP-20):
+ await tokenAlice.transfer(alice, {Substrate: charlie.address}, 0n);
+
+ expect(await tokenAlice.getTop10Owners()).to.deep.eq([{Substrate: alice.address}]);
+ expect(await tokenBob.getTop10Owners()).to.deep.eq([{Substrate: bob.address}]);
+ expect(await tokenAlice.getBalance({Substrate: alice.address})).to.eq(10n);
+ expect(await tokenBob.getBalance({Substrate: bob.address})).to.eq(10n);
+ expect(await tokenBob.getBalance({Substrate: charlie.address})).to.eq(0n);
+ });
+});
tests/src/transfer.test.tsdiffbeforeafterboth--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -122,6 +122,7 @@
});
});
+
itSub('[nft] Transfer with not existed collection_id', async ({helper}) => {
const collectionId = (1 << 32) - 1;
await expect(helper.nft.transferToken(alice, collectionId, 1, {Substrate: bob.address}))
@@ -191,6 +192,25 @@
.to.be.rejectedWith(/common\.TokenValueTooLow/);
});
+ itSub('Zero transfer NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Transfer-Neg-3-NFT', description: '', tokenPrefix: 'T'});
+ const tokenAlice = await collection.mintToken(alice, {Substrate: alice.address});
+ const tokenBob = await collection.mintToken(alice, {Substrate: bob.address});
+ // 1. Zero transfer of own tokens allowed:
+ await helper.executeExtrinsic(alice, 'api.tx.unique.transfer', [{Substrate: bob.address}, collection.collectionId, tokenAlice.tokenId, 0]);
+ // 2. Zero transfer of non-owned tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.transfer', [{Substrate: alice.address}, collection.collectionId, tokenBob.tokenId, 0])).to.be.rejectedWith('common.NoPermission');
+ // 3. Zero transfer of non-existing tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.transfer', [{Substrate: alice.address}, collection.collectionId, 10, 0])).to.be.rejectedWith('common.TokenNotFound');
+ expect(await tokenAlice.getOwner()).to.deep.eq({Substrate: alice.address});
+ expect(await tokenBob.getOwner()).to.deep.eq({Substrate: bob.address});
+ // 4. Storage is not corrupted:
+ await tokenAlice.transfer(alice, {Substrate: bob.address});
+ await tokenBob.transfer(bob, {Substrate: alice.address});
+ expect(await tokenAlice.getOwner()).to.deep.eq({Substrate: bob.address});
+ expect(await tokenBob.getOwner()).to.deep.eq({Substrate: alice.address});
+ });
+
itSub('[nft] Transfer with deleted item_id', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {name: 'Transfer-Neg-3-NFT', description: '', tokenPrefix: 'T'});
const nft = await collection.mintToken(alice);
tests/src/transferFrom.test.tsdiffbeforeafterboth--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -349,4 +349,27 @@
{Substrate: charlie.address},
)).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
});
+
+ itSub('zero transfer NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Zero', description: 'Zero transfer', tokenPrefix: 'TF'});
+ const notApprovedNft = await collection.mintToken(alice, {Substrate: bob.address});
+ const approvedNft = await collection.mintToken(alice, {Substrate: bob.address});
+ await approvedNft.approve(bob, {Substrate: alice.address});
+
+ // 1. Cannot zero transferFrom (non-existing token)
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.transferFrom', [{Substrate: bob.address}, {Substrate: alice.address}, collection.collectionId, 9999, 0])).to.be.rejectedWith('common.ApprovedValueTooLow');
+ // 2. Cannot zero transferFrom (not approved token)
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.transferFrom', [{Substrate: bob.address}, {Substrate: alice.address}, collection.collectionId, notApprovedNft.tokenId, 0])).to.be.rejectedWith('common.ApprovedValueTooLow');
+ // 3. Can zero transferFrom (approved token):
+ await helper.executeExtrinsic(alice, 'api.tx.unique.transferFrom', [{Substrate: bob.address}, {Substrate: alice.address}, collection.collectionId, approvedNft.tokenId, 0]);
+
+ // 4.1 approvedNft still approved:
+ expect(await approvedNft.isApproved({Substrate: alice.address})).to.be.true;
+ // 4.2 bob is still the owner:
+ expect(await approvedNft.getOwner()).to.deep.eq({Substrate: bob.address});
+ expect(await notApprovedNft.getOwner()).to.deep.eq({Substrate: bob.address});
+ // 4.3 Alice can transfer approved nft:
+ await approvedNft.transferFrom(alice, {Substrate: bob.address}, {Substrate: alice.address});
+ expect(await approvedNft.getOwner()).to.deep.eq({Substrate: alice.address});
+ });
});