difftreelog
Merge pull request #210 from UniqueNetwork/feature/CORE-180-v2
in: master
CORE-180. burnItem
10 files changed
launch-config.jsondiffbeforeafterboth--- a/launch-config.json
+++ b/launch-config.json
@@ -66,7 +66,9 @@
"name": "alice",
"flags": [
"--rpc-cors=all",
- "--rpc-port=9933", "--unsafe-ws-external"
+ "--rpc-port=9933",
+ "--unsafe-rpc-external",
+ "--unsafe-ws-external"
]
},
{
@@ -76,7 +78,9 @@
"name": "bob",
"flags": [
"--rpc-cors=all",
- "--rpc-port=9934", "--unsafe-rpc-external"
+ "--rpc-port=9934",
+ "--unsafe-rpc-external",
+ "--unsafe-ws-external"
]
}
]
pallets/nft/src/eth/erc.rsdiffbeforeafterboth1use core::char::{decode_utf16, REPLACEMENT_CHARACTER};2use evm_coder::{ToLog, execution::Result, generate_stubgen, solidity, solidity_interface, types::*};3use nft_data_structs::{CreateItemData, CreateNftData};4use core::convert::TryInto;5use crate::{6 Allowances, Module, Balance, CollectionHandle, CollectionMode, Config, NftItemList,7 ItemListIndex,8};9use frame_support::storage::{StorageMap, StorageDoubleMap};10use pallet_evm::AddressMapping;11use pallet_evm_coder_substrate::dispatch_to_evm;12use super::account::CrossAccountId;13use sp_std::{vec, vec::Vec};1415#[solidity_interface(name = "ERC165")]16impl<T: Config> CollectionHandle<T> {17 fn supports_interface(&self, interface_id: bytes4) -> Result<bool> {18 Ok(match self.mode {19 CollectionMode::Fungible(_) => UniqueFungibleCall::supports_interface(interface_id),20 CollectionMode::NFT => UniqueNFTCall::supports_interface(interface_id),21 _ => false,22 })23 }24}2526#[solidity_interface(name = "InlineNameSymbol")]27impl<T: Config> CollectionHandle<T> {28 fn name(&self) -> Result<string> {29 Ok(decode_utf16(self.name.iter().copied())30 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))31 .collect::<string>())32 }3334 fn symbol(&self) -> Result<string> {35 Ok(string::from_utf8_lossy(&self.token_prefix).into())36 }37}3839#[solidity_interface(name = "InlineTotalSupply")]40impl<T: Config> CollectionHandle<T> {41 fn total_supply(&self) -> Result<uint256> {42 // TODO: we do not track total amount of all tokens43 Ok(0.into())44 }45}4647#[solidity_interface(name = "ERC721Metadata", inline_is(InlineNameSymbol))]48impl<T: Config> CollectionHandle<T> {49 #[solidity(rename_selector = "tokenURI")]50 fn token_uri(&self, token_id: uint256) -> Result<string> {51 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;52 Ok(string::from_utf8_lossy(53 &<NftItemList<T>>::get(self.id, token_id)54 .ok_or("token not found")?55 .const_data,56 )57 .into())58 }59}6061#[solidity_interface(name = "ERC721Enumerable", inline_is(InlineTotalSupply))]62impl<T: Config> CollectionHandle<T> {63 fn token_by_index(&self, index: uint256) -> Result<uint256> {64 Ok(index)65 }6667 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {68 // TODO: Not implemetable69 Err("not implemented".into())70 }71}7273#[derive(ToLog)]74pub enum ERC721Events {75 Transfer {76 #[indexed]77 from: address,78 #[indexed]79 to: address,80 #[indexed]81 token_id: uint256,82 },83 Approval {84 #[indexed]85 owner: address,86 #[indexed]87 approved: address,88 #[indexed]89 token_id: uint256,90 },91 #[allow(dead_code)]92 ApprovalForAll {93 #[indexed]94 owner: address,95 #[indexed]96 operator: address,97 approved: bool,98 },99}100101#[solidity_interface(name = "ERC721", is(ERC165), events(ERC721Events))]102impl<T: Config> CollectionHandle<T> {103 #[solidity(rename_selector = "balanceOf")]104 fn balance_of_nft(&self, owner: address) -> Result<uint256> {105 let owner = T::EvmAddressMapping::into_account_id(owner);106 let balance = <Balance<T>>::get(self.id, owner);107 Ok(balance.into())108 }109 fn owner_of(&self, token_id: uint256) -> Result<address> {110 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;111 let token = <NftItemList<T>>::get(self.id, token_id).ok_or("unknown token")?;112 Ok(*token.owner.as_eth())113 }114 fn safe_transfer_from_with_data(115 &mut self,116 _from: address,117 _to: address,118 _token_id: uint256,119 _data: bytes,120 _value: value,121 ) -> Result<void> {122 // TODO: Not implemetable123 Err("not implemented".into())124 }125 fn safe_transfer_from(126 &mut self,127 _from: address,128 _to: address,129 _token_id: uint256,130 _value: value,131 ) -> Result<void> {132 // TODO: Not implemetable133 Err("not implemented".into())134 }135136 fn transfer_from(137 &mut self,138 caller: caller,139 from: address,140 to: address,141 token_id: uint256,142 _value: value,143 ) -> Result<void> {144 let caller = T::CrossAccountId::from_eth(caller);145 let from = T::CrossAccountId::from_eth(from);146 let to = T::CrossAccountId::from_eth(to);147 let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;148149 <Module<T>>::transfer_from_internal(&caller, &from, &to, self, token_id, 1)150 .map_err(|_| "transferFrom error")?;151 Ok(())152 }153154 fn approve(155 &mut self,156 caller: caller,157 approved: address,158 token_id: uint256,159 _value: value,160 ) -> Result<void> {161 let caller = T::CrossAccountId::from_eth(caller);162 let approved = T::CrossAccountId::from_eth(approved);163 let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;164165 <Module<T>>::approve_internal(&caller, &approved, self, token_id, 1)166 .map_err(|_| "approve internal")?;167 Ok(())168 }169170 fn set_approval_for_all(171 &mut self,172 _caller: caller,173 _operator: address,174 _approved: bool,175 ) -> Result<void> {176 // TODO: Not implemetable177 Err("not implemented".into())178 }179180 fn get_approved(&self, _token_id: uint256) -> Result<address> {181 // TODO: Not implemetable182 Err("not implemented".into())183 }184185 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {186 // TODO: Not implemetable187 Err("not implemented".into())188 }189}190191#[solidity_interface(name = "ERC721Burnable")]192impl<T: Config> CollectionHandle<T> {193 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {194 let caller = T::CrossAccountId::from_eth(caller);195 let token_id = token_id.try_into().map_err(|_| "amount overflow")?;196197 <Module<T>>::burn_item_internal(&caller, &self, token_id, 1).map_err(|_| "burn error")?;198 Ok(())199 }200}201202#[derive(ToLog)]203pub enum ERC721MintableEvents {204 #[allow(dead_code)]205 MintingFinished {},206}207208#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]209impl<T: Config> CollectionHandle<T> {210 fn minting_finished(&self) -> Result<bool> {211 Ok(false)212 }213214 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {215 let caller = T::CrossAccountId::from_eth(caller);216 let to = T::CrossAccountId::from_eth(to);217 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;218 if <ItemListIndex>::get(self.id)219 .checked_add(1)220 .ok_or("item id overflow")?221 != token_id222 {223 return Err("item id should be next".into());224 }225226 <Module<T>>::create_item_internal(227 &caller,228 &self,229 &to,230 CreateItemData::NFT(CreateNftData {231 const_data: vec![].try_into().unwrap(),232 variable_data: vec![].try_into().unwrap(),233 }),234 )235 .map_err(|_| "mint error")?;236 Ok(true)237 }238239 #[solidity(rename_selector = "mintWithTokenURI")]240 fn mint_with_token_uri(241 &mut self,242 caller: caller,243 to: address,244 token_id: uint256,245 token_uri: string,246 ) -> Result<bool> {247 let caller = T::CrossAccountId::from_eth(caller);248 let to = T::CrossAccountId::from_eth(to);249 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;250 if <ItemListIndex>::get(self.id)251 .checked_add(1)252 .ok_or("item id overflow")?253 != token_id254 {255 return Err("item id should be next".into());256 }257258 <Module<T>>::create_item_internal(259 &caller,260 &self,261 &to,262 CreateItemData::NFT(CreateNftData {263 const_data: Vec::<u8>::from(token_uri)264 .try_into()265 .map_err(|_| "token uri is too long")?,266 variable_data: vec![].try_into().unwrap(),267 }),268 )269 .map_err(|_| "mint error")?;270 Ok(true)271 }272273 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {274 Err("not implementable".into())275 }276}277278#[solidity_interface(name = "ERC721UniqueExtensions")]279impl<T: Config> CollectionHandle<T> {280 #[solidity(rename_selector = "transfer")]281 fn transfer_nft(282 &mut self,283 caller: caller,284 to: address,285 token_id: uint256,286 _value: value,287 ) -> Result<void> {288 let caller = T::CrossAccountId::from_eth(caller);289 let to = T::CrossAccountId::from_eth(to);290 let token_id = token_id.try_into().map_err(|_| "amount overflow")?;291292 <Module<T>>::transfer_internal(&caller, &to, self, token_id, 1)293 .map_err(|_| "transfer error")?;294 Ok(())295 }296297 fn next_token_id(&self) -> Result<uint256> {298 Ok(ItemListIndex::get(self.id)299 .checked_add(1)300 .ok_or("item id overflow")?301 .into())302 }303304 fn set_variable_metadata(305 &mut self,306 caller: caller,307 token_id: uint256,308 data: bytes,309 ) -> Result<void> {310 let caller = T::CrossAccountId::from_eth(caller);311 let token_id = token_id.try_into().map_err(|_| "token id overflow")?;312313 <Module<T>>::set_variable_meta_data_internal(&caller, self, token_id, data)314 .map_err(dispatch_to_evm::<T>)?;315 Ok(())316 }317318 fn get_variable_metadata(&self, token_id: uint256) -> Result<bytes> {319 let token_id = token_id.try_into().map_err(|_| "token id overflow")?;320321 <Module<T>>::get_variable_metadata(self, token_id).map_err(dispatch_to_evm::<T>)322 }323324 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {325 let caller = T::CrossAccountId::from_eth(caller);326 let to = T::CrossAccountId::from_eth(to);327 let mut expected_index = <ItemListIndex>::get(self.id)328 .checked_add(1)329 .ok_or("item id overflow")?;330331 let total_tokens = token_ids.len();332 for id in token_ids.into_iter() {333 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;334 if id != expected_index {335 return Err("item id should be next".into());336 }337 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;338 }339340 let data = (0..total_tokens)341 .map(|_| {342 CreateItemData::NFT(CreateNftData {343 const_data: vec![].try_into().unwrap(),344 variable_data: vec![].try_into().unwrap(),345 })346 })347 .collect();348349 <Module<T>>::create_multiple_items_internal(&caller, self, &to, data)350 .map_err(dispatch_to_evm::<T>)?;351 Ok(true)352 }353354 #[solidity(rename_selector = "mintBulkWithTokenURI")]355 fn mint_bulk_with_token_uri(356 &mut self,357 caller: caller,358 to: address,359 tokens: Vec<(uint256, string)>,360 ) -> Result<bool> {361 let caller = T::CrossAccountId::from_eth(caller);362 let to = T::CrossAccountId::from_eth(to);363 let mut expected_index = <ItemListIndex>::get(self.id)364 .checked_add(1)365 .ok_or("item id overflow")?;366367 let mut data = Vec::with_capacity(tokens.len());368 for (id, token_uri) in tokens {369 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;370 if id != expected_index {371 panic!("item id should be next ({}) but got {}", expected_index, id);372 }373 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;374375 data.push(CreateItemData::NFT(CreateNftData {376 const_data: Vec::<u8>::from(token_uri)377 .try_into()378 .map_err(|_| "token uri is too long")?,379 variable_data: vec![].try_into().unwrap(),380 }));381 }382383 <Module<T>>::create_multiple_items_internal(&caller, self, &to, data)384 .map_err(dispatch_to_evm::<T>)?;385 Ok(true)386 }387}388389#[solidity_interface(390 name = "UniqueNFT",391 is(392 ERC165,393 ERC721,394 ERC721Metadata,395 ERC721Enumerable,396 ERC721UniqueExtensions,397 ERC721Mintable,398 ERC721Burnable,399 )400)]401impl<T: Config> CollectionHandle<T> {}402403#[derive(ToLog)]404pub enum ERC20Events {405 Transfer {406 #[indexed]407 from: address,408 #[indexed]409 to: address,410 value: uint256,411 },412 Approval {413 #[indexed]414 owner: address,415 #[indexed]416 spender: address,417 value: uint256,418 },419}420421#[solidity_interface(422 name = "ERC20",423 inline_is(InlineNameSymbol, InlineTotalSupply),424 events(ERC20Events)425)]426impl<T: Config> CollectionHandle<T> {427 fn decimals(&self) -> Result<uint8> {428 Ok(if let CollectionMode::Fungible(decimals) = &self.mode {429 *decimals430 } else {431 unreachable!()432 })433 }434 fn balance_of(&self, owner: address) -> Result<uint256> {435 let owner = T::EvmAddressMapping::into_account_id(owner);436 let balance = <Balance<T>>::get(self.id, owner);437 Ok(balance.into())438 }439 fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {440 let caller = T::CrossAccountId::from_eth(caller);441 let to = T::CrossAccountId::from_eth(to);442 let amount = amount.try_into().map_err(|_| "amount overflow")?;443444 <Module<T>>::transfer_internal(&caller, &to, self, 1, amount)445 .map_err(|_| "transfer error")?;446 Ok(true)447 }448 #[solidity(rename_selector = "transferFrom")]449 fn transfer_from_fungible(450 &mut self,451 caller: caller,452 from: address,453 to: address,454 amount: uint256,455 ) -> Result<bool> {456 let caller = T::CrossAccountId::from_eth(caller);457 let from = T::CrossAccountId::from_eth(from);458 let to = T::CrossAccountId::from_eth(to);459 let amount = amount.try_into().map_err(|_| "amount overflow")?;460461 <Module<T>>::transfer_from_internal(&caller, &from, &to, self, 1, amount)462 .map_err(|_| "transferFrom error")?;463 Ok(true)464 }465 #[solidity(rename_selector = "approve")]466 fn approve_fungible(467 &mut self,468 caller: caller,469 spender: address,470 amount: uint256,471 ) -> Result<bool> {472 let caller = T::CrossAccountId::from_eth(caller);473 let spender = T::CrossAccountId::from_eth(spender);474 let amount = amount.try_into().map_err(|_| "amount overflow")?;475476 <Module<T>>::approve_internal(&caller, &spender, self, 1, amount)477 .map_err(|_| "approve internal")?;478 Ok(true)479 }480 fn allowance(&self, owner: address, spender: address) -> Result<uint256> {481 let owner = T::CrossAccountId::from_eth(owner);482 let spender = T::CrossAccountId::from_eth(spender);483484 Ok(<Allowances<T>>::get(self.id, (1, owner.as_sub(), spender.as_sub())).into())485 }486}487488#[solidity_interface(name = "UniqueFungible", is(ERC165, ERC20))]489impl<T: Config> CollectionHandle<T> {}490491// Not a tests, but code generators492generate_stubgen!(nft_impl, UniqueNFTCall, true);493generate_stubgen!(nft_iface, UniqueNFTCall, false);494495generate_stubgen!(fungible_impl, UniqueFungibleCall, true);496generate_stubgen!(fungible_iface, UniqueFungibleCall, false);1use core::char::{decode_utf16, REPLACEMENT_CHARACTER};2use evm_coder::{ToLog, execution::Result, generate_stubgen, solidity, solidity_interface, types::*};3use nft_data_structs::{CreateItemData, CreateNftData};4use core::convert::TryInto;5use crate::{6 Allowances, Module, Balance, CollectionHandle, CollectionMode, Config, NftItemList,7 ItemListIndex,8};9use frame_support::storage::{StorageMap, StorageDoubleMap};10use pallet_evm::AddressMapping;11use pallet_evm_coder_substrate::dispatch_to_evm;12use super::account::CrossAccountId;13use sp_std::{vec, vec::Vec};1415#[solidity_interface(name = "ERC165")]16impl<T: Config> CollectionHandle<T> {17 fn supports_interface(&self, interface_id: bytes4) -> Result<bool> {18 Ok(match self.mode {19 CollectionMode::Fungible(_) => UniqueFungibleCall::supports_interface(interface_id),20 CollectionMode::NFT => UniqueNFTCall::supports_interface(interface_id),21 _ => false,22 })23 }24}2526#[solidity_interface(name = "InlineNameSymbol")]27impl<T: Config> CollectionHandle<T> {28 fn name(&self) -> Result<string> {29 Ok(decode_utf16(self.name.iter().copied())30 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))31 .collect::<string>())32 }3334 fn symbol(&self) -> Result<string> {35 Ok(string::from_utf8_lossy(&self.token_prefix).into())36 }37}3839#[solidity_interface(name = "InlineTotalSupply")]40impl<T: Config> CollectionHandle<T> {41 fn total_supply(&self) -> Result<uint256> {42 // TODO: we do not track total amount of all tokens43 Ok(0.into())44 }45}4647#[solidity_interface(name = "ERC721Metadata", inline_is(InlineNameSymbol))]48impl<T: Config> CollectionHandle<T> {49 #[solidity(rename_selector = "tokenURI")]50 fn token_uri(&self, token_id: uint256) -> Result<string> {51 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;52 Ok(string::from_utf8_lossy(53 &<NftItemList<T>>::get(self.id, token_id)54 .ok_or("token not found")?55 .const_data,56 )57 .into())58 }59}6061#[solidity_interface(name = "ERC721Enumerable", inline_is(InlineTotalSupply))]62impl<T: Config> CollectionHandle<T> {63 fn token_by_index(&self, index: uint256) -> Result<uint256> {64 Ok(index)65 }6667 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {68 // TODO: Not implemetable69 Err("not implemented".into())70 }71}7273#[derive(ToLog)]74pub enum ERC721Events {75 Transfer {76 #[indexed]77 from: address,78 #[indexed]79 to: address,80 #[indexed]81 token_id: uint256,82 },83 Approval {84 #[indexed]85 owner: address,86 #[indexed]87 approved: address,88 #[indexed]89 token_id: uint256,90 },91 #[allow(dead_code)]92 ApprovalForAll {93 #[indexed]94 owner: address,95 #[indexed]96 operator: address,97 approved: bool,98 },99}100101#[solidity_interface(name = "ERC721", is(ERC165), events(ERC721Events))]102impl<T: Config> CollectionHandle<T> {103 #[solidity(rename_selector = "balanceOf")]104 fn balance_of_nft(&self, owner: address) -> Result<uint256> {105 let owner = T::EvmAddressMapping::into_account_id(owner);106 let balance = <Balance<T>>::get(self.id, owner);107 Ok(balance.into())108 }109 fn owner_of(&self, token_id: uint256) -> Result<address> {110 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;111 let token = <NftItemList<T>>::get(self.id, token_id).ok_or("unknown token")?;112 Ok(*token.owner.as_eth())113 }114 fn safe_transfer_from_with_data(115 &mut self,116 _from: address,117 _to: address,118 _token_id: uint256,119 _data: bytes,120 _value: value,121 ) -> Result<void> {122 // TODO: Not implemetable123 Err("not implemented".into())124 }125 fn safe_transfer_from(126 &mut self,127 _from: address,128 _to: address,129 _token_id: uint256,130 _value: value,131 ) -> Result<void> {132 // TODO: Not implemetable133 Err("not implemented".into())134 }135136 fn transfer_from(137 &mut self,138 caller: caller,139 from: address,140 to: address,141 token_id: uint256,142 _value: value,143 ) -> Result<void> {144 let caller = T::CrossAccountId::from_eth(caller);145 let from = T::CrossAccountId::from_eth(from);146 let to = T::CrossAccountId::from_eth(to);147 let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;148149 <Module<T>>::transfer_from_internal(&caller, &from, &to, self, token_id, 1)150 .map_err(|_| "transferFrom error")?;151 Ok(())152 }153154 fn approve(155 &mut self,156 caller: caller,157 approved: address,158 token_id: uint256,159 _value: value,160 ) -> Result<void> {161 let caller = T::CrossAccountId::from_eth(caller);162 let approved = T::CrossAccountId::from_eth(approved);163 let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;164165 <Module<T>>::approve_internal(&caller, &approved, self, token_id, 1)166 .map_err(|_| "approve internal")?;167 Ok(())168 }169170 fn set_approval_for_all(171 &mut self,172 _caller: caller,173 _operator: address,174 _approved: bool,175 ) -> Result<void> {176 // TODO: Not implemetable177 Err("not implemented".into())178 }179180 fn get_approved(&self, _token_id: uint256) -> Result<address> {181 // TODO: Not implemetable182 Err("not implemented".into())183 }184185 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {186 // TODO: Not implemetable187 Err("not implemented".into())188 }189}190191#[solidity_interface(name = "ERC721Burnable")]192impl<T: Config> CollectionHandle<T> {193 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {194 let caller = T::CrossAccountId::from_eth(caller);195 let token_id = token_id.try_into().map_err(|_| "amount overflow")?;196197 <Module<T>>::burn_item_internal(&caller, &self, token_id, 1, true)198 .map_err(|_| "burn error")?;199 Ok(())200 }201}202203#[derive(ToLog)]204pub enum ERC721MintableEvents {205 #[allow(dead_code)]206 MintingFinished {},207}208209#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]210impl<T: Config> CollectionHandle<T> {211 fn minting_finished(&self) -> Result<bool> {212 Ok(false)213 }214215 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {216 let caller = T::CrossAccountId::from_eth(caller);217 let to = T::CrossAccountId::from_eth(to);218 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;219 if <ItemListIndex>::get(self.id)220 .checked_add(1)221 .ok_or("item id overflow")?222 != token_id223 {224 return Err("item id should be next".into());225 }226227 <Module<T>>::create_item_internal(228 &caller,229 &self,230 &to,231 CreateItemData::NFT(CreateNftData {232 const_data: vec![].try_into().unwrap(),233 variable_data: vec![].try_into().unwrap(),234 }),235 )236 .map_err(|_| "mint error")?;237 Ok(true)238 }239240 #[solidity(rename_selector = "mintWithTokenURI")]241 fn mint_with_token_uri(242 &mut self,243 caller: caller,244 to: address,245 token_id: uint256,246 token_uri: string,247 ) -> Result<bool> {248 let caller = T::CrossAccountId::from_eth(caller);249 let to = T::CrossAccountId::from_eth(to);250 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;251 if <ItemListIndex>::get(self.id)252 .checked_add(1)253 .ok_or("item id overflow")?254 != token_id255 {256 return Err("item id should be next".into());257 }258259 <Module<T>>::create_item_internal(260 &caller,261 &self,262 &to,263 CreateItemData::NFT(CreateNftData {264 const_data: Vec::<u8>::from(token_uri)265 .try_into()266 .map_err(|_| "token uri is too long")?,267 variable_data: vec![].try_into().unwrap(),268 }),269 )270 .map_err(|_| "mint error")?;271 Ok(true)272 }273274 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {275 Err("not implementable".into())276 }277}278279#[solidity_interface(name = "ERC721UniqueExtensions")]280impl<T: Config> CollectionHandle<T> {281 #[solidity(rename_selector = "transfer")]282 fn transfer_nft(283 &mut self,284 caller: caller,285 to: address,286 token_id: uint256,287 _value: value,288 ) -> Result<void> {289 let caller = T::CrossAccountId::from_eth(caller);290 let to = T::CrossAccountId::from_eth(to);291 let token_id = token_id.try_into().map_err(|_| "amount overflow")?;292293 <Module<T>>::transfer_internal(&caller, &to, self, token_id, 1)294 .map_err(|_| "transfer error")?;295 Ok(())296 }297298 fn next_token_id(&self) -> Result<uint256> {299 Ok(ItemListIndex::get(self.id)300 .checked_add(1)301 .ok_or("item id overflow")?302 .into())303 }304305 fn set_variable_metadata(306 &mut self,307 caller: caller,308 token_id: uint256,309 data: bytes,310 ) -> Result<void> {311 let caller = T::CrossAccountId::from_eth(caller);312 let token_id = token_id.try_into().map_err(|_| "token id overflow")?;313314 <Module<T>>::set_variable_meta_data_internal(&caller, self, token_id, data)315 .map_err(dispatch_to_evm::<T>)?;316 Ok(())317 }318319 fn get_variable_metadata(&self, token_id: uint256) -> Result<bytes> {320 let token_id = token_id.try_into().map_err(|_| "token id overflow")?;321322 <Module<T>>::get_variable_metadata(self, token_id).map_err(dispatch_to_evm::<T>)323 }324325 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {326 let caller = T::CrossAccountId::from_eth(caller);327 let to = T::CrossAccountId::from_eth(to);328 let mut expected_index = <ItemListIndex>::get(self.id)329 .checked_add(1)330 .ok_or("item id overflow")?;331332 let total_tokens = token_ids.len();333 for id in token_ids.into_iter() {334 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;335 if id != expected_index {336 return Err("item id should be next".into());337 }338 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;339 }340341 let data = (0..total_tokens)342 .map(|_| {343 CreateItemData::NFT(CreateNftData {344 const_data: vec![].try_into().unwrap(),345 variable_data: vec![].try_into().unwrap(),346 })347 })348 .collect();349350 <Module<T>>::create_multiple_items_internal(&caller, self, &to, data)351 .map_err(dispatch_to_evm::<T>)?;352 Ok(true)353 }354355 #[solidity(rename_selector = "mintBulkWithTokenURI")]356 fn mint_bulk_with_token_uri(357 &mut self,358 caller: caller,359 to: address,360 tokens: Vec<(uint256, string)>,361 ) -> Result<bool> {362 let caller = T::CrossAccountId::from_eth(caller);363 let to = T::CrossAccountId::from_eth(to);364 let mut expected_index = <ItemListIndex>::get(self.id)365 .checked_add(1)366 .ok_or("item id overflow")?;367368 let mut data = Vec::with_capacity(tokens.len());369 for (id, token_uri) in tokens {370 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;371 if id != expected_index {372 panic!("item id should be next ({}) but got {}", expected_index, id);373 }374 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;375376 data.push(CreateItemData::NFT(CreateNftData {377 const_data: Vec::<u8>::from(token_uri)378 .try_into()379 .map_err(|_| "token uri is too long")?,380 variable_data: vec![].try_into().unwrap(),381 }));382 }383384 <Module<T>>::create_multiple_items_internal(&caller, self, &to, data)385 .map_err(dispatch_to_evm::<T>)?;386 Ok(true)387 }388}389390#[solidity_interface(391 name = "UniqueNFT",392 is(393 ERC165,394 ERC721,395 ERC721Metadata,396 ERC721Enumerable,397 ERC721UniqueExtensions,398 ERC721Mintable,399 ERC721Burnable,400 )401)]402impl<T: Config> CollectionHandle<T> {}403404#[derive(ToLog)]405pub enum ERC20Events {406 Transfer {407 #[indexed]408 from: address,409 #[indexed]410 to: address,411 value: uint256,412 },413 Approval {414 #[indexed]415 owner: address,416 #[indexed]417 spender: address,418 value: uint256,419 },420}421422#[solidity_interface(423 name = "ERC20",424 inline_is(InlineNameSymbol, InlineTotalSupply),425 events(ERC20Events)426)]427impl<T: Config> CollectionHandle<T> {428 fn decimals(&self) -> Result<uint8> {429 Ok(if let CollectionMode::Fungible(decimals) = &self.mode {430 *decimals431 } else {432 unreachable!()433 })434 }435 fn balance_of(&self, owner: address) -> Result<uint256> {436 let owner = T::EvmAddressMapping::into_account_id(owner);437 let balance = <Balance<T>>::get(self.id, owner);438 Ok(balance.into())439 }440 fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {441 let caller = T::CrossAccountId::from_eth(caller);442 let to = T::CrossAccountId::from_eth(to);443 let amount = amount.try_into().map_err(|_| "amount overflow")?;444445 <Module<T>>::transfer_internal(&caller, &to, self, 1, amount)446 .map_err(|_| "transfer error")?;447 Ok(true)448 }449 #[solidity(rename_selector = "transferFrom")]450 fn transfer_from_fungible(451 &mut self,452 caller: caller,453 from: address,454 to: address,455 amount: uint256,456 ) -> Result<bool> {457 let caller = T::CrossAccountId::from_eth(caller);458 let from = T::CrossAccountId::from_eth(from);459 let to = T::CrossAccountId::from_eth(to);460 let amount = amount.try_into().map_err(|_| "amount overflow")?;461462 <Module<T>>::transfer_from_internal(&caller, &from, &to, self, 1, amount)463 .map_err(|_| "transferFrom error")?;464 Ok(true)465 }466 #[solidity(rename_selector = "approve")]467 fn approve_fungible(468 &mut self,469 caller: caller,470 spender: address,471 amount: uint256,472 ) -> Result<bool> {473 let caller = T::CrossAccountId::from_eth(caller);474 let spender = T::CrossAccountId::from_eth(spender);475 let amount = amount.try_into().map_err(|_| "amount overflow")?;476477 <Module<T>>::approve_internal(&caller, &spender, self, 1, amount)478 .map_err(|_| "approve internal")?;479 Ok(true)480 }481 fn allowance(&self, owner: address, spender: address) -> Result<uint256> {482 let owner = T::CrossAccountId::from_eth(owner);483 let spender = T::CrossAccountId::from_eth(spender);484485 Ok(<Allowances<T>>::get(self.id, (1, owner.as_sub(), spender.as_sub())).into())486 }487}488489#[solidity_interface(name = "UniqueFungible", is(ERC165, ERC20))]490impl<T: Config> CollectionHandle<T> {}491492// Not a tests, but code generators493generate_stubgen!(nft_impl, UniqueNFTCall, true);494generate_stubgen!(nft_iface, UniqueNFTCall, false);495496generate_stubgen!(fungible_impl, UniqueFungibleCall, true);497generate_stubgen!(fungible_iface, UniqueFungibleCall, false);pallets/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;
pallets/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
);
});
tests/.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"
+}
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -20,6 +20,10 @@
"tslint": "^6.1.3",
"typescript": "^4.2.4"
},
+ "mocha": {
+ "timeout": 9999999,
+ "require": "ts-node/register"
+ },
"scripts": {
"lint": "eslint --ext .ts,.js src/",
"fix": "eslint --ext .ts,.js src/ --fix",
tests/src/burnItem.test.tsdiffbeforeafterboth--- a/tests/src/burnItem.test.ts
+++ b/tests/src/burnItem.test.ts
@@ -38,7 +38,7 @@
const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);
await usingApi(async (api) => {
- const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);
+ const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);
const events = await submitTransactionAsync(alice, tx);
const result = getGenericResult(events);
// Get the item
@@ -79,7 +79,7 @@
const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);
await usingApi(async (api) => {
- const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);
+ const tx = api.tx.nft.burnItem(collectionId, tokenId, 100);
const events = await submitTransactionAsync(alice, tx);
const result = getGenericResult(events);
@@ -107,14 +107,14 @@
const balanceBefore: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();
// Bob burns his portion
- const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);
+ const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);
const events2 = await submitTransactionAsync(bob, tx);
const result2 = getGenericResult(events2);
- // Get balances
+ // Get balances
const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();
// console.log(balance);
-
+
// What to expect before burning
expect(result1.success).to.be.true;
expect(balanceBefore).to.be.not.null;
@@ -152,7 +152,7 @@
await addCollectionAdminExpectSuccess(alice, collectionId, bob);
await usingApi(async (api) => {
- const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);
+ const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);
const events = await submitTransactionAsync(bob, tx);
const result = getGenericResult(events);
// Get the item
@@ -164,6 +164,48 @@
expect(item).to.be.null;
});
});
+
+
+ it('Burn item in Fungible collection', async () => {
+ const createMode = 'Fungible';
+ const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0 }});
+ const tokenId = await createItemExpectSuccess(alice, collectionId, createMode); // Helper creates 10 fungible tokens
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob);
+
+ await usingApi(async (api) => {
+ // Destroy 1 of 10
+ const tx = api.tx.nft.burnFrom(collectionId, normalizeAccountId(alice.address), tokenId, 1);
+ const events = await submitTransactionAsync(bob, tx);
+ const result = getGenericResult(events);
+
+ // Get alice balance
+ const balance: any = (await api.query.nft.fungibleItemList(collectionId, alice.address)).toJSON();
+
+ // What to expect
+ expect(result.success).to.be.true;
+ expect(balance).to.be.not.null;
+ expect(balance.Value).to.be.equal(9);
+ });
+ });
+
+ it('Burn item in ReFungible collection', async () => {
+ const createMode = 'ReFungible';
+ const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});
+ const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob);
+
+ await usingApi(async (api) => {
+ const tx = api.tx.nft.burnFrom(collectionId, normalizeAccountId(alice.address), tokenId, 100);
+ const events = await submitTransactionAsync(bob, tx);
+ const result = getGenericResult(events);
+ // Get alice balance
+ const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();
+
+ // What to expect
+ expect(result.success).to.be.true;
+ expect(balance).to.be.null;
+ });
+ });
});
describe('Negative integration test: ext. burnItem():', () => {
@@ -197,7 +239,7 @@
const tokenId = 10;
await usingApi(async (api) => {
- const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);
+ const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);
const badTransaction = async function () {
await submitTransactionExpectFailAsync(alice, tx);
};
@@ -228,7 +270,7 @@
await usingApi(async (api) => {
- const burntx = api.tx.nft.burnItem(collectionId, tokenId, 0);
+ const burntx = api.tx.nft.burnItem(collectionId, tokenId, 1);
const events1 = await submitTransactionAsync(alice, burntx);
const result1 = getGenericResult(events1);
expect(result1.success).to.be.true;
tests/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,
tests/src/transferFrom.test.tsdiffbeforeafterboth--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -248,7 +248,7 @@
const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
await burnItemExpectSuccess(Alice, nftCollectionId, newNftTokenId, 1);
await approveExpectFail(nftCollectionId, newNftTokenId, Alice, Bob);
- await transferFromExpectFail(nftCollectionId, newNftTokenId, Bob, Alice, Charlie, 1);
+ await transferFromExpectFail(nftCollectionId, newNftTokenId, Bob, Alice, Charlie, 1);
});
});
it( 'transferFrom burnt token before approve Fungible', async () => {
@@ -258,20 +258,20 @@
await burnItemExpectSuccess(Alice, fungibleCollectionId, 1, 10);
await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, Alice, Bob);
await transferFromExpectFail(fungibleCollectionId, newFungibleTokenId, Bob, Alice, Charlie, 1);
-
+
});
- });
+ });
it( 'transferFrom burnt token before approve ReFungible', async () => {
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);
-
+
});
});
-
+
it( 'transferFrom burnt token after approve NFT', async () => {
await usingApi(async () => {
// nft
@@ -279,7 +279,7 @@
const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
await approveExpectSuccess(nftCollectionId, newNftTokenId, Alice, Bob);
await burnItemExpectSuccess(Alice, nftCollectionId, newNftTokenId, 1);
- await transferFromExpectFail(nftCollectionId, newNftTokenId, Bob, Alice, Charlie, 1);
+ await transferFromExpectFail(nftCollectionId, newNftTokenId, Bob, Alice, Charlie, 1);
});
});
it( 'transferFrom burnt token after approve Fungible', async () => {
@@ -289,17 +289,17 @@
await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, Alice, Bob);
await burnItemExpectSuccess(Alice, fungibleCollectionId, 1, 10);
await transferFromExpectFail(fungibleCollectionId, newFungibleTokenId, Bob, Alice, Charlie, 1);
-
+
});
- });
+ });
it( 'transferFrom burnt token after approve ReFungible', async () => {
await usingApi(async () => {
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);
-
+
});
});
tests/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();