12345678910111213141516171819202122extern crate alloc;23use core::{24 char::{REPLACEMENT_CHARACTER, decode_utf16},25 convert::TryInto,26};27use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};28use frame_support::BoundedVec;29use up_data_structs::{30 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,31 CollectionPropertiesVec,32};33use pallet_evm_coder_substrate::dispatch_to_evm;34use sp_std::vec::Vec;35use pallet_common::{36 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property_key_value::*},37 CollectionHandle, CollectionPropertyPermissions,38};39use pallet_evm::{account::CrossAccountId, PrecompileHandle};40use pallet_evm_coder_substrate::call;41use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};42use alloc::string::ToString;4344use crate::{45 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,46 SelfWeightOf, weights::WeightInfo, TokenProperties,47};484950#[solidity_interface(name = "TokenProperties")]51impl<T: Config> NonfungibleHandle<T> {52 53 54 55 56 57 58 fn set_token_property_permission(59 &mut self,60 caller: caller,61 key: string,62 is_mutable: bool,63 collection_admin: bool,64 token_owner: bool,65 ) -> Result<()> {66 let caller = T::CrossAccountId::from_eth(caller);67 <Pallet<T>>::set_property_permission(68 self,69 &caller,70 PropertyKeyPermission {71 key: <Vec<u8>>::from(key)72 .try_into()73 .map_err(|_| "too long key")?,74 permission: PropertyPermission {75 mutable: is_mutable,76 collection_admin,77 token_owner,78 },79 },80 )81 .map_err(dispatch_to_evm::<T>)82 }8384 85 86 87 88 89 fn set_property(90 &mut self,91 caller: caller,92 token_id: uint256,93 key: string,94 value: bytes,95 ) -> Result<()> {96 let caller = T::CrossAccountId::from_eth(caller);97 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;98 let key = <Vec<u8>>::from(key)99 .try_into()100 .map_err(|_| "key too long")?;101 let value = value.try_into().map_err(|_| "value too long")?;102103 let nesting_budget = self104 .recorder105 .weight_calls_budget(<StructureWeight<T>>::find_parent());106107 <Pallet<T>>::set_token_property(108 self,109 &caller,110 TokenId(token_id),111 Property { key, value },112 &nesting_budget,113 )114 .map_err(dispatch_to_evm::<T>)115 }116117 118 119 120 121 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {122 let caller = T::CrossAccountId::from_eth(caller);123 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;124 let key = <Vec<u8>>::from(key)125 .try_into()126 .map_err(|_| "key too long")?;127128 let nesting_budget = self129 .recorder130 .weight_calls_budget(<StructureWeight<T>>::find_parent());131132 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)133 .map_err(dispatch_to_evm::<T>)134 }135136 137 138 139 140 141 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {142 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;143 let key = <Vec<u8>>::from(key)144 .try_into()145 .map_err(|_| "key too long")?;146147 let props = <TokenProperties<T>>::get((self.id, token_id));148 let prop = props.get(&key).ok_or("key not found")?;149150 Ok(prop.to_vec())151 }152}153154#[derive(ToLog)]155pub enum ERC721Events {156 157 158 159 160 161 Transfer {162 #[indexed]163 from: address,164 #[indexed]165 to: address,166 #[indexed]167 token_id: uint256,168 },169 170 171 172 173 Approval {174 #[indexed]175 owner: address,176 #[indexed]177 approved: address,178 #[indexed]179 token_id: uint256,180 },181 182 183 #[allow(dead_code)]184 ApprovalForAll {185 #[indexed]186 owner: address,187 #[indexed]188 operator: address,189 approved: bool,190 },191}192193#[derive(ToLog)]194pub enum ERC721MintableEvents {195 #[allow(dead_code)]196 MintingFinished {},197}198199200201#[solidity_interface(name = "ERC721Metadata")]202impl<T: Config> NonfungibleHandle<T> {203 204 fn name(&self) -> Result<string> {205 Ok(decode_utf16(self.name.iter().copied())206 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))207 .collect::<string>())208 }209210 211 fn symbol(&self) -> Result<string> {212 Ok(string::from_utf8_lossy(&self.token_prefix).into())213 }214215 216 217 218 219 220 #[solidity(rename_selector = "tokenURI")]221 fn token_uri(&self, token_id: uint256) -> Result<string> {222 let is_erc721 = || {223 if let Some(shema_name) = pallet_common::Pallet::<T>::get_collection_property(self.id, &schema_name_key()) {224 let shema_name = shema_name.into_inner();225 shema_name == b"ERC721"226 } else {227 false228 }229 };230231 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;232233 if let Ok(url) = get_token_property(self, token_id_u32, &u_key()) {234 if !url.is_empty() {235 return Ok(url);236 }237 } else if !is_erc721() {238 return Err("tokenURI not set".into());239 }240241 if let Some(base_uri) = pallet_common::Pallet::<T>::get_collection_property(self.id, &base_uri_key()) {242 if !base_uri.is_empty() {243 let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {244 Error::Revert(alloc::format!(245 "Can not convert value \"baseURI\" to string with error \"{}\"",246 e247 ))248 })?;249 if let Ok(suffix) = get_token_property(self, token_id_u32, &s_key()) {250 if !suffix.is_empty() {251 return Ok(base_uri + suffix.as_str());252 }253 }254255 return Ok(base_uri + token_id.to_string().as_str());256 }257 }258259 Ok("".into())260 }261}262263264265#[solidity_interface(name = "ERC721Enumerable")]266impl<T: Config> NonfungibleHandle<T> {267 268 269 270 271 fn token_by_index(&self, index: uint256) -> Result<uint256> {272 Ok(index)273 }274275 276 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {277 278 Err("not implemented".into())279 }280281 282 283 284 fn total_supply(&self) -> Result<uint256> {285 self.consume_store_reads(1)?;286 Ok(<Pallet<T>>::total_supply(self).into())287 }288}289290291292#[solidity_interface(name = "ERC721", events(ERC721Events))]293impl<T: Config> NonfungibleHandle<T> {294 295 296 297 298 299 fn balance_of(&self, owner: address) -> Result<uint256> {300 self.consume_store_reads(1)?;301 let owner = T::CrossAccountId::from_eth(owner);302 let balance = <AccountBalance<T>>::get((self.id, owner));303 Ok(balance.into())304 }305 306 307 308 309 310 fn owner_of(&self, token_id: uint256) -> Result<address> {311 self.consume_store_reads(1)?;312 let token: TokenId = token_id.try_into()?;313 Ok(*<TokenData<T>>::get((self.id, token))314 .ok_or("token not found")?315 .owner316 .as_eth())317 }318 319 fn safe_transfer_from_with_data(320 &mut self,321 _from: address,322 _to: address,323 _token_id: uint256,324 _data: bytes,325 _value: value,326 ) -> Result<void> {327 328 Err("not implemented".into())329 }330 331 fn safe_transfer_from(332 &mut self,333 _from: address,334 _to: address,335 _token_id: uint256,336 _value: value,337 ) -> Result<void> {338 339 Err("not implemented".into())340 }341342 343 344 345 346 347 348 349 350 351 352 #[weight(<SelfWeightOf<T>>::transfer_from())]353 fn transfer_from(354 &mut self,355 caller: caller,356 from: address,357 to: address,358 token_id: uint256,359 _value: value,360 ) -> Result<void> {361 let caller = T::CrossAccountId::from_eth(caller);362 let from = T::CrossAccountId::from_eth(from);363 let to = T::CrossAccountId::from_eth(to);364 let token = token_id.try_into()?;365 let budget = self366 .recorder367 .weight_calls_budget(<StructureWeight<T>>::find_parent());368369 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)370 .map_err(dispatch_to_evm::<T>)?;371 Ok(())372 }373374 375 376 377 378 379 380 #[weight(<SelfWeightOf<T>>::approve())]381 fn approve(382 &mut self,383 caller: caller,384 approved: address,385 token_id: uint256,386 _value: value,387 ) -> Result<void> {388 let caller = T::CrossAccountId::from_eth(caller);389 let approved = T::CrossAccountId::from_eth(approved);390 let token = token_id.try_into()?;391392 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))393 .map_err(dispatch_to_evm::<T>)?;394 Ok(())395 }396397 398 fn set_approval_for_all(399 &mut self,400 _caller: caller,401 _operator: address,402 _approved: bool,403 ) -> Result<void> {404 405 Err("not implemented".into())406 }407408 409 fn get_approved(&self, _token_id: uint256) -> Result<address> {410 411 Err("not implemented".into())412 }413414 415 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {416 417 Err("not implemented".into())418 }419}420421422#[solidity_interface(name = "ERC721Burnable")]423impl<T: Config> NonfungibleHandle<T> {424 425 426 427 428 #[weight(<SelfWeightOf<T>>::burn_item())]429 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {430 let caller = T::CrossAccountId::from_eth(caller);431 let token = token_id.try_into()?;432433 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;434 Ok(())435 }436}437438439#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]440impl<T: Config> NonfungibleHandle<T> {441 fn minting_finished(&self) -> Result<bool> {442 Ok(false)443 }444445 446 447 448 449 450 #[weight(<SelfWeightOf<T>>::create_item())]451 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {452 let caller = T::CrossAccountId::from_eth(caller);453 let to = T::CrossAccountId::from_eth(to);454 let token_id: u32 = token_id.try_into()?;455 let budget = self456 .recorder457 .weight_calls_budget(<StructureWeight<T>>::find_parent());458459 if <TokensMinted<T>>::get(self.id)460 .checked_add(1)461 .ok_or("item id overflow")?462 != token_id463 {464 return Err("item id should be next".into());465 }466467 <Pallet<T>>::create_item(468 self,469 &caller,470 CreateItemData::<T> {471 properties: BoundedVec::default(),472 owner: to,473 },474 &budget,475 )476 .map_err(dispatch_to_evm::<T>)?;477478 Ok(true)479 }480481 482 483 484 485 486 487 #[solidity(rename_selector = "mintWithTokenURI")]488 #[weight(<SelfWeightOf<T>>::create_item())]489 fn mint_with_token_uri(490 &mut self,491 caller: caller,492 to: address,493 token_id: uint256,494 token_uri: string,495 ) -> Result<bool> {496 let key = u_key();497 let permission = get_token_permission::<T>(self.id, &key)?;498 if !permission.collection_admin {499 return Err("Operation is not allowed".into());500 }501502 let caller = T::CrossAccountId::from_eth(caller);503 let to = T::CrossAccountId::from_eth(to);504 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;505 let budget = self506 .recorder507 .weight_calls_budget(<StructureWeight<T>>::find_parent());508509 if <TokensMinted<T>>::get(self.id)510 .checked_add(1)511 .ok_or("item id overflow")?512 != token_id513 {514 return Err("item id should be next".into());515 }516517 let mut properties = CollectionPropertiesVec::default();518 properties519 .try_push(Property {520 key,521 value: token_uri522 .into_bytes()523 .try_into()524 .map_err(|_| "token uri is too long")?,525 })526 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;527528 <Pallet<T>>::create_item(529 self,530 &caller,531 CreateItemData::<T> {532 properties,533 owner: to,534 },535 &budget,536 )537 .map_err(dispatch_to_evm::<T>)?;538 Ok(true)539 }540541 542 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {543 Err("not implementable".into())544 }545}546547fn get_token_property<T: Config>(548 collection: &CollectionHandle<T>,549 token_id: u32,550 key: &up_data_structs::PropertyKey,551) -> Result<string> {552 collection.consume_store_reads(1)?;553 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))554 .map_err(|_| Error::Revert("Token properties not found".into()))?;555 if let Some(property) = properties.get(key) {556 return Ok(string::from_utf8_lossy(property).into());557 }558559 Err("Property tokenURI not found".into())560}561562fn get_token_permission<T: Config>(563 collection_id: CollectionId,564 key: &PropertyKey,565) -> Result<PropertyPermission> {566 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)567 .map_err(|_| Error::Revert("No permissions for collection".into()))?;568 let a = token_property_permissions569 .get(key)570 .map(Clone::clone)571 .ok_or_else(|| {572 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();573 Error::Revert(alloc::format!("No permission for key {}", key))574 })?;575 Ok(a)576}577578fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {579 if let Ok(token_property_permissions) =580 CollectionPropertyPermissions::<T>::try_get(collection_id)581 {582 return token_property_permissions.contains_key(key);583 }584585 false586}587588589#[solidity_interface(name = "ERC721UniqueExtensions")]590impl<T: Config> NonfungibleHandle<T> {591 592 593 594 595 596 597 #[weight(<SelfWeightOf<T>>::transfer())]598 fn transfer(599 &mut self,600 caller: caller,601 to: address,602 token_id: uint256,603 _value: value,604 ) -> Result<void> {605 let caller = T::CrossAccountId::from_eth(caller);606 let to = T::CrossAccountId::from_eth(to);607 let token = token_id.try_into()?;608 let budget = self609 .recorder610 .weight_calls_budget(<StructureWeight<T>>::find_parent());611612 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;613 Ok(())614 }615616 617 618 619 620 621 622 623 #[weight(<SelfWeightOf<T>>::burn_from())]624 fn burn_from(625 &mut self,626 caller: caller,627 from: address,628 token_id: uint256,629 _value: value,630 ) -> Result<void> {631 let caller = T::CrossAccountId::from_eth(caller);632 let from = T::CrossAccountId::from_eth(from);633 let token = token_id.try_into()?;634 let budget = self635 .recorder636 .weight_calls_budget(<StructureWeight<T>>::find_parent());637638 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)639 .map_err(dispatch_to_evm::<T>)?;640 Ok(())641 }642643 644 fn next_token_id(&self) -> Result<uint256> {645 self.consume_store_reads(1)?;646 Ok(<TokensMinted<T>>::get(self.id)647 .checked_add(1)648 .ok_or("item id overflow")?649 .into())650 }651652 653 654 655 656 657 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]658 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {659 let caller = T::CrossAccountId::from_eth(caller);660 let to = T::CrossAccountId::from_eth(to);661 let mut expected_index = <TokensMinted<T>>::get(self.id)662 .checked_add(1)663 .ok_or("item id overflow")?;664 let budget = self665 .recorder666 .weight_calls_budget(<StructureWeight<T>>::find_parent());667668 let total_tokens = token_ids.len();669 for id in token_ids.into_iter() {670 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;671 if id != expected_index {672 return Err("item id should be next".into());673 }674 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;675 }676 let data = (0..total_tokens)677 .map(|_| CreateItemData::<T> {678 properties: BoundedVec::default(),679 owner: to.clone(),680 })681 .collect();682683 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)684 .map_err(dispatch_to_evm::<T>)?;685 Ok(true)686 }687688 689 690 691 692 693 #[solidity(rename_selector = "mintBulkWithTokenURI")]694 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]695 fn mint_bulk_with_token_uri(696 &mut self,697 caller: caller,698 to: address,699 tokens: Vec<(uint256, string)>,700 ) -> Result<bool> {701 let key = token_uri_key();702 let caller = T::CrossAccountId::from_eth(caller);703 let to = T::CrossAccountId::from_eth(to);704 let mut expected_index = <TokensMinted<T>>::get(self.id)705 .checked_add(1)706 .ok_or("item id overflow")?;707 let budget = self708 .recorder709 .weight_calls_budget(<StructureWeight<T>>::find_parent());710711 let mut data = Vec::with_capacity(tokens.len());712 for (id, token_uri) in tokens {713 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;714 if id != expected_index {715 return Err("item id should be next".into());716 }717 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;718719 let mut properties = CollectionPropertiesVec::default();720 properties721 .try_push(Property {722 key: key.clone(),723 value: token_uri724 .into_bytes()725 .try_into()726 .map_err(|_| "token uri is too long")?,727 })728 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;729730 data.push(CreateItemData::<T> {731 properties,732 owner: to.clone(),733 });734 }735736 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)737 .map_err(dispatch_to_evm::<T>)?;738 Ok(true)739 }740}741742#[solidity_interface(743 name = "UniqueNFT",744 is(745 ERC721,746 ERC721Metadata,747 ERC721Enumerable,748 ERC721UniqueExtensions,749 ERC721Mintable,750 ERC721Burnable,751 via("CollectionHandle<T>", common_mut, Collection),752 TokenProperties,753 )754)]755impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> {}756757758generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);759generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);760761impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>762where763 T::AccountId: From<[u8; 32]>,764{765 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");766767 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {768 call::<T, UniqueNFTCall<T>, _, _>(handle, self)769 }770}