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) =224 pallet_common::Pallet::<T>::get_collection_property(self.id, &schema_name_key())225 {226 let shema_name = shema_name.into_inner();227 shema_name == ERC721_METADATA228 } else {229 false230 }231 };232233 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;234235 if let Ok(url) = get_token_property(self, token_id_u32, &url_key()) {236 if !url.is_empty() {237 return Ok(url);238 }239 } else if !is_erc721() {240 return Err("tokenURI not set".into());241 } else if !is_erc721() {242 return Err("tokenURI not set".into());243 }244245 if let Some(base_uri) =246 pallet_common::Pallet::<T>::get_collection_property(self.id, &base_uri_key())247 {248 if !base_uri.is_empty() {249 let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {250 Error::Revert(alloc::format!(251 "Can not convert value \"baseURI\" to string with error \"{}\"",252 e253 ))254 })?;255 if let Ok(suffix) = get_token_property(self, token_id_u32, &suffix_key()) {256 if !suffix.is_empty() {257 return Ok(base_uri + suffix.as_str());258 }259 }260261 return Ok(base_uri + token_id.to_string().as_str());262 }263 }264265 Ok("".into())266 }267}268269270271#[solidity_interface(name = "ERC721Enumerable")]272impl<T: Config> NonfungibleHandle<T> {273 274 275 276 277 fn token_by_index(&self, index: uint256) -> Result<uint256> {278 Ok(index)279 }280281 282 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {283 284 Err("not implemented".into())285 }286287 288 289 290 fn total_supply(&self) -> Result<uint256> {291 self.consume_store_reads(1)?;292 Ok(<Pallet<T>>::total_supply(self).into())293 }294}295296297298#[solidity_interface(name = "ERC721", events(ERC721Events))]299impl<T: Config> NonfungibleHandle<T> {300 301 302 303 304 305 fn balance_of(&self, owner: address) -> Result<uint256> {306 self.consume_store_reads(1)?;307 let owner = T::CrossAccountId::from_eth(owner);308 let balance = <AccountBalance<T>>::get((self.id, owner));309 Ok(balance.into())310 }311 312 313 314 315 316 fn owner_of(&self, token_id: uint256) -> Result<address> {317 self.consume_store_reads(1)?;318 let token: TokenId = token_id.try_into()?;319 Ok(*<TokenData<T>>::get((self.id, token))320 .ok_or("token not found")?321 .owner322 .as_eth())323 }324 325 fn safe_transfer_from_with_data(326 &mut self,327 _from: address,328 _to: address,329 _token_id: uint256,330 _data: bytes,331 _value: value,332 ) -> Result<void> {333 334 Err("not implemented".into())335 }336 337 fn safe_transfer_from(338 &mut self,339 _from: address,340 _to: address,341 _token_id: uint256,342 _value: value,343 ) -> Result<void> {344 345 Err("not implemented".into())346 }347348 349 350 351 352 353 354 355 356 357 358 #[weight(<SelfWeightOf<T>>::transfer_from())]359 fn transfer_from(360 &mut self,361 caller: caller,362 from: address,363 to: address,364 token_id: uint256,365 _value: value,366 ) -> Result<void> {367 let caller = T::CrossAccountId::from_eth(caller);368 let from = T::CrossAccountId::from_eth(from);369 let to = T::CrossAccountId::from_eth(to);370 let token = token_id.try_into()?;371 let budget = self372 .recorder373 .weight_calls_budget(<StructureWeight<T>>::find_parent());374375 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)376 .map_err(dispatch_to_evm::<T>)?;377 Ok(())378 }379380 381 382 383 384 385 386 #[weight(<SelfWeightOf<T>>::approve())]387 fn approve(388 &mut self,389 caller: caller,390 approved: address,391 token_id: uint256,392 _value: value,393 ) -> Result<void> {394 let caller = T::CrossAccountId::from_eth(caller);395 let approved = T::CrossAccountId::from_eth(approved);396 let token = token_id.try_into()?;397398 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))399 .map_err(dispatch_to_evm::<T>)?;400 Ok(())401 }402403 404 fn set_approval_for_all(405 &mut self,406 _caller: caller,407 _operator: address,408 _approved: bool,409 ) -> Result<void> {410 411 Err("not implemented".into())412 }413414 415 fn get_approved(&self, _token_id: uint256) -> Result<address> {416 417 Err("not implemented".into())418 }419420 421 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {422 423 Err("not implemented".into())424 }425}426427428#[solidity_interface(name = "ERC721Burnable")]429impl<T: Config> NonfungibleHandle<T> {430 431 432 433 434 #[weight(<SelfWeightOf<T>>::burn_item())]435 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {436 let caller = T::CrossAccountId::from_eth(caller);437 let token = token_id.try_into()?;438439 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;440 Ok(())441 }442}443444445#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]446impl<T: Config> NonfungibleHandle<T> {447 fn minting_finished(&self) -> Result<bool> {448 Ok(false)449 }450451 452 453 454 455 456 #[weight(<SelfWeightOf<T>>::create_item())]457 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {458 let caller = T::CrossAccountId::from_eth(caller);459 let to = T::CrossAccountId::from_eth(to);460 let token_id: u32 = token_id.try_into()?;461 let budget = self462 .recorder463 .weight_calls_budget(<StructureWeight<T>>::find_parent());464465 if <TokensMinted<T>>::get(self.id)466 .checked_add(1)467 .ok_or("item id overflow")?468 != token_id469 {470 return Err("item id should be next".into());471 }472473 <Pallet<T>>::create_item(474 self,475 &caller,476 CreateItemData::<T> {477 properties: BoundedVec::default(),478 owner: to,479 },480 &budget,481 )482 .map_err(dispatch_to_evm::<T>)?;483484 Ok(true)485 }486487 488 489 490 491 492 493 #[solidity(rename_selector = "mintWithTokenURI")]494 #[weight(<SelfWeightOf<T>>::create_item())]495 fn mint_with_token_uri(496 &mut self,497 caller: caller,498 to: address,499 token_id: uint256,500 token_uri: string,501 ) -> Result<bool> {502 let key = u_key();503 let permission = get_token_permission::<T>(self.id, &key)?;504 if !permission.collection_admin {505 return Err("Operation is not allowed".into());506 }507508 let caller = T::CrossAccountId::from_eth(caller);509 let to = T::CrossAccountId::from_eth(to);510 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;511 let budget = self512 .recorder513 .weight_calls_budget(<StructureWeight<T>>::find_parent());514515 if <TokensMinted<T>>::get(self.id)516 .checked_add(1)517 .ok_or("item id overflow")?518 != token_id519 {520 return Err("item id should be next".into());521 }522523 let mut properties = CollectionPropertiesVec::default();524 properties525 .try_push(Property {526 key,527 value: token_uri528 .into_bytes()529 .try_into()530 .map_err(|_| "token uri is too long")?,531 })532 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;533534 <Pallet<T>>::create_item(535 self,536 &caller,537 CreateItemData::<T> {538 properties,539 owner: to,540 },541 &budget,542 )543 .map_err(dispatch_to_evm::<T>)?;544 Ok(true)545 }546547 548 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {549 Err("not implementable".into())550 }551}552553fn get_token_property<T: Config>(554 collection: &CollectionHandle<T>,555 token_id: u32,556 key: &up_data_structs::PropertyKey,557) -> Result<string> {558 collection.consume_store_reads(1)?;559 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))560 .map_err(|_| Error::Revert("Token properties not found".into()))?;561 if let Some(property) = properties.get(key) {562 return Ok(string::from_utf8_lossy(property).into());563 }564565 Err("Property tokenURI not found".into())566}567568fn get_token_permission<T: Config>(569 collection_id: CollectionId,570 key: &PropertyKey,571) -> Result<PropertyPermission> {572 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)573 .map_err(|_| Error::Revert("No permissions for collection".into()))?;574 let a = token_property_permissions575 .get(key)576 .map(Clone::clone)577 .ok_or_else(|| {578 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();579 Error::Revert(alloc::format!("No permission for key {}", key))580 })?;581 Ok(a)582}583584fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {585 if let Ok(token_property_permissions) =586 CollectionPropertyPermissions::<T>::try_get(collection_id)587 {588 return token_property_permissions.contains_key(key);589 }590591 false592}593594595#[solidity_interface(name = "ERC721UniqueExtensions")]596impl<T: Config> NonfungibleHandle<T> {597 598 599 600 601 602 603 #[weight(<SelfWeightOf<T>>::transfer())]604 fn transfer(605 &mut self,606 caller: caller,607 to: address,608 token_id: uint256,609 _value: value,610 ) -> Result<void> {611 let caller = T::CrossAccountId::from_eth(caller);612 let to = T::CrossAccountId::from_eth(to);613 let token = token_id.try_into()?;614 let budget = self615 .recorder616 .weight_calls_budget(<StructureWeight<T>>::find_parent());617618 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;619 Ok(())620 }621622 623 624 625 626 627 628 629 #[weight(<SelfWeightOf<T>>::burn_from())]630 fn burn_from(631 &mut self,632 caller: caller,633 from: address,634 token_id: uint256,635 _value: value,636 ) -> Result<void> {637 let caller = T::CrossAccountId::from_eth(caller);638 let from = T::CrossAccountId::from_eth(from);639 let token = token_id.try_into()?;640 let budget = self641 .recorder642 .weight_calls_budget(<StructureWeight<T>>::find_parent());643644 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)645 .map_err(dispatch_to_evm::<T>)?;646 Ok(())647 }648649 650 fn next_token_id(&self) -> Result<uint256> {651 self.consume_store_reads(1)?;652 Ok(<TokensMinted<T>>::get(self.id)653 .checked_add(1)654 .ok_or("item id overflow")?655 .into())656 }657658 659 660 661 662 663 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]664 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {665 let caller = T::CrossAccountId::from_eth(caller);666 let to = T::CrossAccountId::from_eth(to);667 let mut expected_index = <TokensMinted<T>>::get(self.id)668 .checked_add(1)669 .ok_or("item id overflow")?;670 let budget = self671 .recorder672 .weight_calls_budget(<StructureWeight<T>>::find_parent());673674 let total_tokens = token_ids.len();675 for id in token_ids.into_iter() {676 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;677 if id != expected_index {678 return Err("item id should be next".into());679 }680 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;681 }682 let data = (0..total_tokens)683 .map(|_| CreateItemData::<T> {684 properties: BoundedVec::default(),685 owner: to.clone(),686 })687 .collect();688689 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)690 .map_err(dispatch_to_evm::<T>)?;691 Ok(true)692 }693694 695 696 697 698 699 #[solidity(rename_selector = "mintBulkWithTokenURI")]700 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]701 fn mint_bulk_with_token_uri(702 &mut self,703 caller: caller,704 to: address,705 tokens: Vec<(uint256, string)>,706 ) -> Result<bool> {707 let key = url_key();708 let caller = T::CrossAccountId::from_eth(caller);709 let to = T::CrossAccountId::from_eth(to);710 let mut expected_index = <TokensMinted<T>>::get(self.id)711 .checked_add(1)712 .ok_or("item id overflow")?;713 let budget = self714 .recorder715 .weight_calls_budget(<StructureWeight<T>>::find_parent());716717 let mut data = Vec::with_capacity(tokens.len());718 for (id, token_uri) in tokens {719 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;720 if id != expected_index {721 return Err("item id should be next".into());722 }723 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;724725 let mut properties = CollectionPropertiesVec::default();726 properties727 .try_push(Property {728 key: key.clone(),729 value: token_uri730 .into_bytes()731 .try_into()732 .map_err(|_| "token uri is too long")?,733 })734 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;735736 data.push(CreateItemData::<T> {737 properties,738 owner: to.clone(),739 });740 }741742 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)743 .map_err(dispatch_to_evm::<T>)?;744 Ok(true)745 }746}747748#[solidity_interface(749 name = "UniqueNFT",750 is(751 ERC721,752 ERC721Metadata,753 ERC721Enumerable,754 ERC721UniqueExtensions,755 ERC721Mintable,756 ERC721Burnable,757 via("CollectionHandle<T>", common_mut, Collection),758 TokenProperties,759 )760)]761impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> {}762763764generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);765generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);766767impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>768where769 T::AccountId: From<[u8; 32]>,770{771 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");772773 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {774 call::<T, UniqueNFTCall<T>, _, _>(handle, self)775 }776}