difftreelog
CORE-346 Fix recieving tokenURI
in: master
2 files changed
pallets/nonfungible/src/erc.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/>.1617extern crate alloc;18use core::{19 char::{REPLACEMENT_CHARACTER, decode_utf16},20 convert::TryInto,21};22use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};23use frame_support::BoundedVec;24use up_data_structs::{TokenId, SchemaVersion, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey, CollectionPropertiesVec};25use pallet_evm_coder_substrate::dispatch_to_evm;26use sp_core::{H160, U256};27use sp_std::vec::Vec;28use pallet_common::{29 erc::{CommonEvmHandler, PrecompileResult, CollectionCall},30 CollectionHandle, CollectionPropertyPermissions,31};32use pallet_evm::account::CrossAccountId;33use pallet_evm_coder_substrate::call;34use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};3536use crate::{37 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,38 SelfWeightOf, weights::WeightInfo, TokenProperties,39};4041#[solidity_interface(name = "TokenProperties")]42impl<T: Config> NonfungibleHandle<T> {43 fn set_token_property_permission(44 &mut self,45 caller: caller,46 key: string,47 is_mutable: bool,48 collection_admin: bool,49 token_owner: bool,50 ) -> Result<()> {51 let caller = T::CrossAccountId::from_eth(caller);52 <Pallet<T>>::set_property_permission(53 self,54 &caller,55 PropertyKeyPermission {56 key: <Vec<u8>>::from(key)57 .try_into()58 .map_err(|_| "too long key")?,59 permission: PropertyPermission {60 mutable: is_mutable,61 collection_admin,62 token_owner,63 },64 },65 )66 .map_err(dispatch_to_evm::<T>)67 }6869 fn set_property(70 &mut self,71 caller: caller,72 token_id: uint256,73 key: string,74 value: bytes,75 ) -> Result<()> {76 let caller = T::CrossAccountId::from_eth(caller);77 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;78 let key = <Vec<u8>>::from(key)79 .try_into()80 .map_err(|_| "key too long")?;81 let value = value.try_into().map_err(|_| "value too long")?;8283 <Pallet<T>>::set_token_property(self, &caller, TokenId(token_id), Property { key, value })84 .map_err(dispatch_to_evm::<T>)85 }8687 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {88 let caller = T::CrossAccountId::from_eth(caller);89 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;90 let key = <Vec<u8>>::from(key)91 .try_into()92 .map_err(|_| "key too long")?;9394 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key)95 .map_err(dispatch_to_evm::<T>)96 }9798 /// Throws error if key not found99 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {100 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;101 let key = <Vec<u8>>::from(key)102 .try_into()103 .map_err(|_| "key too long")?;104105 let props = <TokenProperties<T>>::get((self.id, token_id));106 let prop = props.get(&key).ok_or("key not found")?;107108 Ok(prop.to_vec())109 }110}111112#[derive(ToLog)]113pub enum ERC721Events {114 Transfer {115 #[indexed]116 from: address,117 #[indexed]118 to: address,119 #[indexed]120 token_id: uint256,121 },122 Approval {123 #[indexed]124 owner: address,125 #[indexed]126 approved: address,127 #[indexed]128 token_id: uint256,129 },130 #[allow(dead_code)]131 ApprovalForAll {132 #[indexed]133 owner: address,134 #[indexed]135 operator: address,136 approved: bool,137 },138}139140#[derive(ToLog)]141pub enum ERC721MintableEvents {142 #[allow(dead_code)]143 MintingFinished {},144}145146#[solidity_interface(name = "ERC721Metadata")]147impl<T: Config> NonfungibleHandle<T> {148 fn name(&self) -> Result<string> {149 Ok(decode_utf16(self.name.iter().copied())150 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))151 .collect::<string>())152 }153154 fn symbol(&self) -> Result<string> {155 Ok(string::from_utf8_lossy(&self.token_prefix).into())156 }157158 /// Returns token's const_metadata159 #[solidity(rename_selector = "tokenURI")]160 fn token_uri(&self, token_id: uint256) -> Result<string> {161 let key: string = "tokenURI".into(); //TODO: make static162 let key: up_data_structs::PropertyKey = key.into_bytes().try_into()163 .map_err(|_| Error::Revert("".into()))?;164 let permission = get_permission::<T>(self.id, &key)?;165 if !permission.collection_admin {166 return Err("Operation is not allowed".into());167 }168169 self.consume_store_reads(1)?;170 let _token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;171 Ok(string::from_utf8_lossy(172 todo!()173 )174 .into())175 }176}177178#[solidity_interface(name = "ERC721Enumerable")]179impl<T: Config> NonfungibleHandle<T> {180 fn token_by_index(&self, index: uint256) -> Result<uint256> {181 Ok(index)182 }183184 /// Not implemented185 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {186 // TODO: Not implemetable187 Err("not implemented".into())188 }189190 fn total_supply(&self) -> Result<uint256> {191 self.consume_store_reads(1)?;192 Ok(<Pallet<T>>::total_supply(self).into())193 }194}195196#[solidity_interface(name = "ERC721", events(ERC721Events))]197impl<T: Config> NonfungibleHandle<T> {198 fn balance_of(&self, owner: address) -> Result<uint256> {199 self.consume_store_reads(1)?;200 let owner = T::CrossAccountId::from_eth(owner);201 let balance = <AccountBalance<T>>::get((self.id, owner));202 Ok(balance.into())203 }204 fn owner_of(&self, token_id: uint256) -> Result<address> {205 self.consume_store_reads(1)?;206 let token: TokenId = token_id.try_into()?;207 Ok(*<TokenData<T>>::get((self.id, token))208 .ok_or("token not found")?209 .owner210 .as_eth())211 }212 /// Not implemented213 fn safe_transfer_from_with_data(214 &mut self,215 _from: address,216 _to: address,217 _token_id: uint256,218 _data: bytes,219 _value: value,220 ) -> Result<void> {221 // TODO: Not implemetable222 Err("not implemented".into())223 }224 /// Not implemented225 fn safe_transfer_from(226 &mut self,227 _from: address,228 _to: address,229 _token_id: uint256,230 _value: value,231 ) -> Result<void> {232 // TODO: Not implemetable233 Err("not implemented".into())234 }235236 #[weight(<SelfWeightOf<T>>::transfer_from())]237 fn transfer_from(238 &mut self,239 caller: caller,240 from: address,241 to: address,242 token_id: uint256,243 _value: value,244 ) -> Result<void> {245 let caller = T::CrossAccountId::from_eth(caller);246 let from = T::CrossAccountId::from_eth(from);247 let to = T::CrossAccountId::from_eth(to);248 let token = token_id.try_into()?;249 let budget = self250 .recorder251 .weight_calls_budget(<StructureWeight<T>>::find_parent());252253 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)254 .map_err(dispatch_to_evm::<T>)?;255 Ok(())256 }257258 #[weight(<SelfWeightOf<T>>::approve())]259 fn approve(260 &mut self,261 caller: caller,262 approved: address,263 token_id: uint256,264 _value: value,265 ) -> Result<void> {266 let caller = T::CrossAccountId::from_eth(caller);267 let approved = T::CrossAccountId::from_eth(approved);268 let token = token_id.try_into()?;269270 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))271 .map_err(dispatch_to_evm::<T>)?;272 Ok(())273 }274275 /// Not implemented276 fn set_approval_for_all(277 &mut self,278 _caller: caller,279 _operator: address,280 _approved: bool,281 ) -> Result<void> {282 // TODO: Not implemetable283 Err("not implemented".into())284 }285286 /// Not implemented287 fn get_approved(&self, _token_id: uint256) -> Result<address> {288 // TODO: Not implemetable289 Err("not implemented".into())290 }291292 /// Not implemented293 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {294 // TODO: Not implemetable295 Err("not implemented".into())296 }297}298299#[solidity_interface(name = "ERC721Burnable")]300impl<T: Config> NonfungibleHandle<T> {301 #[weight(<SelfWeightOf<T>>::burn_item())]302 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {303 let caller = T::CrossAccountId::from_eth(caller);304 let token = token_id.try_into()?;305306 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;307 Ok(())308 }309}310311#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]312impl<T: Config> NonfungibleHandle<T> {313 fn minting_finished(&self) -> Result<bool> {314 Ok(false)315 }316317 /// `token_id` should be obtained with `next_token_id` method,318 /// unlike standard, you can't specify it manually319 #[weight(<SelfWeightOf<T>>::create_item())]320 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {321 let caller = T::CrossAccountId::from_eth(caller);322 let to = T::CrossAccountId::from_eth(to);323 let token_id: u32 = token_id.try_into()?;324 let budget = self325 .recorder326 .weight_calls_budget(<StructureWeight<T>>::find_parent());327328 if <TokensMinted<T>>::get(self.id)329 .checked_add(1)330 .ok_or("item id overflow")?331 != token_id332 {333 return Err("item id should be next".into());334 }335336 <Pallet<T>>::create_item(337 self,338 &caller,339 CreateItemData::<T> {340 properties: BoundedVec::default(),341 owner: to,342 },343 &budget,344 )345 .map_err(dispatch_to_evm::<T>)?;346347 Ok(true)348 }349350 /// `token_id` should be obtained with `next_token_id` method,351 /// unlike standard, you can't specify it manually352 #[solidity(rename_selector = "mintWithTokenURI")]353 #[weight(<SelfWeightOf<T>>::create_item())]354 fn mint_with_token_uri(355 &mut self,356 caller: caller,357 to: address,358 token_id: uint256,359 token_uri: string,360 ) -> Result<bool> {361 let key: string = "tokenURI".into(); //TODO: make static362 let key: up_data_structs::PropertyKey = key.into_bytes().try_into()363 .map_err(|_| Error::Revert("".into()))?;364 let permission = get_permission::<T>(self.id, &key)?;365 if !permission.collection_admin {366 return Err("Operation is not allowed".into());367 }368369 let caller = T::CrossAccountId::from_eth(caller);370 let to = T::CrossAccountId::from_eth(to);371 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;372 let budget = self373 .recorder374 .weight_calls_budget(<StructureWeight<T>>::find_parent());375376 if <TokensMinted<T>>::get(self.id)377 .checked_add(1)378 .ok_or("item id overflow")?379 != token_id380 {381 return Err("item id should be next".into());382 }383384 let mut properties = CollectionPropertiesVec::default();385 properties.try_push(Property{386 key,387 value: token_uri.into_bytes().try_into()388 .map_err(|_| "token uri is too long")?389 }).map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;390391 <Pallet<T>>::create_item(392 self,393 &caller,394 CreateItemData::<T> {395 properties,396 owner: to,397 },398 &budget,399 )400 .map_err(dispatch_to_evm::<T>)?;401 Ok(true)402 }403404 /// Not implemented405 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {406 Err("not implementable".into())407 }408}409410fn get_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> Result<PropertyPermission> {411 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)412 .map_err(|_| Error::Revert("No permissions for collection".into()))?;413 Ok(token_property_permissions.get(key)414 .map(|p| p.clone())415 .ok_or_else(|| Error::Revert("No permission for tokenURI".into()))?)416}417418#[solidity_interface(name = "ERC721UniqueExtensions")]419impl<T: Config> NonfungibleHandle<T> {420 #[weight(<SelfWeightOf<T>>::transfer())]421 fn transfer(422 &mut self,423 caller: caller,424 to: address,425 token_id: uint256,426 _value: value,427 ) -> Result<void> {428 let caller = T::CrossAccountId::from_eth(caller);429 let to = T::CrossAccountId::from_eth(to);430 let token = token_id.try_into()?;431 let budget = self432 .recorder433 .weight_calls_budget(<StructureWeight<T>>::find_parent());434435 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;436 Ok(())437 }438439 #[weight(<SelfWeightOf<T>>::burn_from())]440 fn burn_from(441 &mut self,442 caller: caller,443 from: address,444 token_id: uint256,445 _value: value,446 ) -> Result<void> {447 let caller = T::CrossAccountId::from_eth(caller);448 let from = T::CrossAccountId::from_eth(from);449 let token = token_id.try_into()?;450 let budget = self451 .recorder452 .weight_calls_budget(<StructureWeight<T>>::find_parent());453454 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)455 .map_err(dispatch_to_evm::<T>)?;456 Ok(())457 }458459 fn next_token_id(&self) -> Result<uint256> {460 self.consume_store_reads(1)?;461 Ok(<TokensMinted<T>>::get(self.id)462 .checked_add(1)463 .ok_or("item id overflow")?464 .into())465 }466467 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]468 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {469 let caller = T::CrossAccountId::from_eth(caller);470 let to = T::CrossAccountId::from_eth(to);471 let mut expected_index = <TokensMinted<T>>::get(self.id)472 .checked_add(1)473 .ok_or("item id overflow")?;474 let budget = self475 .recorder476 .weight_calls_budget(<StructureWeight<T>>::find_parent());477478 let total_tokens = token_ids.len();479 for id in token_ids.into_iter() {480 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;481 if id != expected_index {482 return Err("item id should be next".into());483 }484 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;485 }486 let data = (0..total_tokens)487 .map(|_| CreateItemData::<T> {488 properties: BoundedVec::default(),489 owner: to.clone(),490 })491 .collect();492493 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)494 .map_err(dispatch_to_evm::<T>)?;495 Ok(true)496 }497498 #[solidity(rename_selector = "mintBulkWithTokenURI")]499 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]500 fn mint_bulk_with_token_uri(501 &mut self,502 caller: caller,503 to: address,504 tokens: Vec<(uint256, string)>,505 ) -> Result<bool> {506 let caller = T::CrossAccountId::from_eth(caller);507 let to = T::CrossAccountId::from_eth(to);508 let mut expected_index = <TokensMinted<T>>::get(self.id)509 .checked_add(1)510 .ok_or("item id overflow")?;511 let budget = self512 .recorder513 .weight_calls_budget(<StructureWeight<T>>::find_parent());514515 let mut data = Vec::with_capacity(tokens.len());516 for (id, token_uri) in tokens {517 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;518 if id != expected_index {519 return Err("item id should be next".into());520 }521 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;522523 todo!("token uri");524 data.push(CreateItemData::<T> {525 properties: BoundedVec::default(),526 owner: to.clone(),527 });528 }529530 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)531 .map_err(dispatch_to_evm::<T>)?;532 Ok(true)533 }534}535536#[solidity_interface(537 name = "UniqueNFT",538 is(539 ERC721,540 ERC721Metadata,541 ERC721Enumerable,542 ERC721UniqueExtensions,543 ERC721Mintable,544 ERC721Burnable,545 via("CollectionHandle<T>", common_mut, Collection),546 TokenProperties,547 )548)]549impl<T: Config> NonfungibleHandle<T> {}550551// Not a tests, but code generators552generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);553generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);554555impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {556 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");557558 fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult> {559 call::<T, UniqueNFTCall<T>, _>(*source, self, value, input)560 }561}tests/src/eth/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createCollection.test.ts
+++ b/tests/src/eth/createCollection.test.ts
@@ -187,7 +187,7 @@
.isCollectionExist(collectionAddressForNonexistentCollection).call())
.to.be.false;
- const result = await collectionHelper.methods.create721Collection('Const collection', '5', '5').send();
+ const result = await collectionHelper.methods.create721Collection('Collection address exist', '7', '7').send();
const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
expect(await collectionHelper.methods
.isCollectionExist(collectionIdAddress).call())