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::{37 CommonEvmHandler, PrecompileResult, CollectionCall,38 static_property::{key, value as property_value},39 },40 CollectionHandle, CollectionPropertyPermissions,41};42use pallet_evm::{account::CrossAccountId, PrecompileHandle};43use pallet_evm_coder_substrate::call;44use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};45use alloc::string::ToString;4647use crate::{48 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,49 SelfWeightOf, weights::WeightInfo, TokenProperties,50};515253#[solidity_interface(name = TokenProperties)]54impl<T: Config> NonfungibleHandle<T> {55 56 57 58 59 60 61 fn set_token_property_permission(62 &mut self,63 caller: caller,64 key: string,65 is_mutable: bool,66 collection_admin: bool,67 token_owner: bool,68 ) -> Result<()> {69 let caller = T::CrossAccountId::from_eth(caller);70 <Pallet<T>>::set_property_permission(71 self,72 &caller,73 PropertyKeyPermission {74 key: <Vec<u8>>::from(key)75 .try_into()76 .map_err(|_| "too long key")?,77 permission: PropertyPermission {78 mutable: is_mutable,79 collection_admin,80 token_owner,81 },82 },83 )84 .map_err(dispatch_to_evm::<T>)85 }8687 88 89 90 91 92 fn set_property(93 &mut self,94 caller: caller,95 token_id: uint256,96 key: string,97 value: bytes,98 ) -> Result<()> {99 let caller = T::CrossAccountId::from_eth(caller);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")?;104 let value = value.try_into().map_err(|_| "value too long")?;105106 let nesting_budget = self107 .recorder108 .weight_calls_budget(<StructureWeight<T>>::find_parent());109110 <Pallet<T>>::set_token_property(111 self,112 &caller,113 TokenId(token_id),114 Property { key, value },115 &nesting_budget,116 )117 .map_err(dispatch_to_evm::<T>)118 }119120 121 122 123 124 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {125 let caller = T::CrossAccountId::from_eth(caller);126 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;127 let key = <Vec<u8>>::from(key)128 .try_into()129 .map_err(|_| "key too long")?;130131 let nesting_budget = self132 .recorder133 .weight_calls_budget(<StructureWeight<T>>::find_parent());134135 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)136 .map_err(dispatch_to_evm::<T>)137 }138139 140 141 142 143 144 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {145 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;146 let key = <Vec<u8>>::from(key)147 .try_into()148 .map_err(|_| "key too long")?;149150 let props = <TokenProperties<T>>::get((self.id, token_id));151 let prop = props.get(&key).ok_or("key not found")?;152153 Ok(prop.to_vec())154 }155}156157#[derive(ToLog)]158pub enum ERC721Events {159 160 161 162 163 164 Transfer {165 #[indexed]166 from: address,167 #[indexed]168 to: address,169 #[indexed]170 token_id: uint256,171 },172 173 174 175 176 Approval {177 #[indexed]178 owner: address,179 #[indexed]180 approved: address,181 #[indexed]182 token_id: uint256,183 },184 185 186 #[allow(dead_code)]187 ApprovalForAll {188 #[indexed]189 owner: address,190 #[indexed]191 operator: address,192 approved: bool,193 },194}195196#[derive(ToLog)]197pub enum ERC721MintableEvents {198 #[allow(dead_code)]199 MintingFinished {},200}201202203204#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]205impl<T: Config> NonfungibleHandle<T> {206 207 fn name(&self) -> Result<string> {208 Ok(decode_utf16(self.name.iter().copied())209 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))210 .collect::<string>())211 }212213 214 fn symbol(&self) -> Result<string> {215 Ok(string::from_utf8_lossy(&self.token_prefix).into())216 }217218 219 220 221 222 223 224 225 226 227 #[solidity(rename_selector = "tokenURI")]228 fn token_uri(&self, token_id: uint256) -> Result<string> {229 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;230231 if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {232 if !url.is_empty() {233 return Ok(url);234 }235 } else if !is_erc721_metadata_compatible::<T>(self.id) {236 return Err("tokenURI not set".into());237 }238239 if let Some(base_uri) =240 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())241 {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, &key::suffix()) {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, expect_selector = 0x780e9d63)]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), expect_selector = 0x80ac58cd)]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 #[solidity(rename_selector = "safeTransferFrom")]320 fn safe_transfer_from_with_data(321 &mut self,322 _from: address,323 _to: address,324 _token_id: uint256,325 _data: bytes,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 ) -> Result<void> {337 338 Err("not implemented".into())339 }340341 342 343 344 345 346 347 348 349 350 #[weight(<SelfWeightOf<T>>::transfer_from())]351 fn transfer_from(352 &mut self,353 caller: caller,354 from: address,355 to: address,356 token_id: uint256,357 ) -> Result<void> {358 let caller = T::CrossAccountId::from_eth(caller);359 let from = T::CrossAccountId::from_eth(from);360 let to = T::CrossAccountId::from_eth(to);361 let token = token_id.try_into()?;362 let budget = self363 .recorder364 .weight_calls_budget(<StructureWeight<T>>::find_parent());365366 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)367 .map_err(dispatch_to_evm::<T>)?;368 Ok(())369 }370371 372 373 374 375 376 377 #[weight(<SelfWeightOf<T>>::approve())]378 fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {379 let caller = T::CrossAccountId::from_eth(caller);380 let approved = T::CrossAccountId::from_eth(approved);381 let token = token_id.try_into()?;382383 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))384 .map_err(dispatch_to_evm::<T>)?;385 Ok(())386 }387388 389 fn set_approval_for_all(390 &mut self,391 _caller: caller,392 _operator: address,393 _approved: bool,394 ) -> Result<void> {395 396 Err("not implemented".into())397 }398399 400 fn get_approved(&self, _token_id: uint256) -> Result<address> {401 402 Err("not implemented".into())403 }404405 406 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {407 408 Err("not implemented".into())409 }410}411412413#[solidity_interface(name = ERC721Burnable)]414impl<T: Config> NonfungibleHandle<T> {415 416 417 418 419 #[weight(<SelfWeightOf<T>>::burn_item())]420 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {421 let caller = T::CrossAccountId::from_eth(caller);422 let token = token_id.try_into()?;423424 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;425 Ok(())426 }427}428429430#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]431impl<T: Config> NonfungibleHandle<T> {432 fn minting_finished(&self) -> Result<bool> {433 Ok(false)434 }435436 437 438 439 440 441 #[weight(<SelfWeightOf<T>>::create_item())]442 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {443 let caller = T::CrossAccountId::from_eth(caller);444 let to = T::CrossAccountId::from_eth(to);445 let token_id: u32 = token_id.try_into()?;446 let budget = self447 .recorder448 .weight_calls_budget(<StructureWeight<T>>::find_parent());449450 if <TokensMinted<T>>::get(self.id)451 .checked_add(1)452 .ok_or("item id overflow")?453 != token_id454 {455 return Err("item id should be next".into());456 }457458 <Pallet<T>>::create_item(459 self,460 &caller,461 CreateItemData::<T> {462 properties: BoundedVec::default(),463 owner: to,464 },465 &budget,466 )467 .map_err(dispatch_to_evm::<T>)?;468469 Ok(true)470 }471472 473 474 475 476 477 478 #[solidity(rename_selector = "mintWithTokenURI")]479 #[weight(<SelfWeightOf<T>>::create_item())]480 fn mint_with_token_uri(481 &mut self,482 caller: caller,483 to: address,484 token_id: uint256,485 token_uri: string,486 ) -> Result<bool> {487 let key = key::url();488 let permission = get_token_permission::<T>(self.id, &key)?;489 if !permission.collection_admin {490 return Err("Operation is not allowed".into());491 }492493 let caller = T::CrossAccountId::from_eth(caller);494 let to = T::CrossAccountId::from_eth(to);495 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;496 let budget = self497 .recorder498 .weight_calls_budget(<StructureWeight<T>>::find_parent());499500 if <TokensMinted<T>>::get(self.id)501 .checked_add(1)502 .ok_or("item id overflow")?503 != token_id504 {505 return Err("item id should be next".into());506 }507508 let mut properties = CollectionPropertiesVec::default();509 properties510 .try_push(Property {511 key,512 value: token_uri513 .into_bytes()514 .try_into()515 .map_err(|_| "token uri is too long")?,516 })517 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;518519 <Pallet<T>>::create_item(520 self,521 &caller,522 CreateItemData::<T> {523 properties,524 owner: to,525 },526 &budget,527 )528 .map_err(dispatch_to_evm::<T>)?;529 Ok(true)530 }531532 533 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {534 Err("not implementable".into())535 }536}537538fn get_token_property<T: Config>(539 collection: &CollectionHandle<T>,540 token_id: u32,541 key: &up_data_structs::PropertyKey,542) -> Result<string> {543 collection.consume_store_reads(1)?;544 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))545 .map_err(|_| Error::Revert("Token properties not found".into()))?;546 if let Some(property) = properties.get(key) {547 return Ok(string::from_utf8_lossy(property).into());548 }549550 Err("Property tokenURI not found".into())551}552553fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {554 if let Some(shema_name) =555 pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())556 {557 let shema_name = shema_name.into_inner();558 shema_name == property_value::ERC721_METADATA559 } else {560 false561 }562}563564fn get_token_permission<T: Config>(565 collection_id: CollectionId,566 key: &PropertyKey,567) -> Result<PropertyPermission> {568 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)569 .map_err(|_| Error::Revert("No permissions for collection".into()))?;570 let a = token_property_permissions571 .get(key)572 .map(Clone::clone)573 .ok_or_else(|| {574 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();575 Error::Revert(alloc::format!("No permission for key {}", key))576 })?;577 Ok(a)578}579580fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {581 if let Ok(token_property_permissions) =582 CollectionPropertyPermissions::<T>::try_get(collection_id)583 {584 return token_property_permissions.contains_key(key);585 }586587 false588}589590591#[solidity_interface(name = ERC721UniqueExtensions)]592impl<T: Config> NonfungibleHandle<T> {593 594 595 596 597 598 #[weight(<SelfWeightOf<T>>::transfer())]599 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {600 let caller = T::CrossAccountId::from_eth(caller);601 let to = T::CrossAccountId::from_eth(to);602 let token = token_id.try_into()?;603 let budget = self604 .recorder605 .weight_calls_budget(<StructureWeight<T>>::find_parent());606607 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;608 Ok(())609 }610611 612 613 614 615 616 617 #[weight(<SelfWeightOf<T>>::burn_from())]618 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {619 let caller = T::CrossAccountId::from_eth(caller);620 let from = T::CrossAccountId::from_eth(from);621 let token = token_id.try_into()?;622 let budget = self623 .recorder624 .weight_calls_budget(<StructureWeight<T>>::find_parent());625626 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)627 .map_err(dispatch_to_evm::<T>)?;628 Ok(())629 }630631 632 fn next_token_id(&self) -> Result<uint256> {633 self.consume_store_reads(1)?;634 Ok(<TokensMinted<T>>::get(self.id)635 .checked_add(1)636 .ok_or("item id overflow")?637 .into())638 }639640 641 642 643 644 645 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]646 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {647 let caller = T::CrossAccountId::from_eth(caller);648 let to = T::CrossAccountId::from_eth(to);649 let mut expected_index = <TokensMinted<T>>::get(self.id)650 .checked_add(1)651 .ok_or("item id overflow")?;652 let budget = self653 .recorder654 .weight_calls_budget(<StructureWeight<T>>::find_parent());655656 let total_tokens = token_ids.len();657 for id in token_ids.into_iter() {658 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;659 if id != expected_index {660 return Err("item id should be next".into());661 }662 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;663 }664 let data = (0..total_tokens)665 .map(|_| CreateItemData::<T> {666 properties: BoundedVec::default(),667 owner: to.clone(),668 })669 .collect();670671 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)672 .map_err(dispatch_to_evm::<T>)?;673 Ok(true)674 }675676 677 678 679 680 681 #[solidity(rename_selector = "mintBulkWithTokenURI")]682 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]683 fn mint_bulk_with_token_uri(684 &mut self,685 caller: caller,686 to: address,687 tokens: Vec<(uint256, string)>,688 ) -> Result<bool> {689 let key = key::url();690 let caller = T::CrossAccountId::from_eth(caller);691 let to = T::CrossAccountId::from_eth(to);692 let mut expected_index = <TokensMinted<T>>::get(self.id)693 .checked_add(1)694 .ok_or("item id overflow")?;695 let budget = self696 .recorder697 .weight_calls_budget(<StructureWeight<T>>::find_parent());698699 let mut data = Vec::with_capacity(tokens.len());700 for (id, token_uri) in tokens {701 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;702 if id != expected_index {703 return Err("item id should be next".into());704 }705 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;706707 let mut properties = CollectionPropertiesVec::default();708 properties709 .try_push(Property {710 key: key.clone(),711 value: token_uri712 .into_bytes()713 .try_into()714 .map_err(|_| "token uri is too long")?,715 })716 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;717718 data.push(CreateItemData::<T> {719 properties,720 owner: to.clone(),721 });722 }723724 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)725 .map_err(dispatch_to_evm::<T>)?;726 Ok(true)727 }728}729730#[solidity_interface(731 name = UniqueNFT,732 is(733 ERC721,734 ERC721Metadata,735 ERC721Enumerable,736 ERC721UniqueExtensions,737 ERC721Mintable,738 ERC721Burnable,739 Collection(common_mut, CollectionHandle<T>),740 TokenProperties,741 )742)]743impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> {}744745746generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);747generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);748749impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>750where751 T::AccountId: From<[u8; 32]>,752{753 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");754755 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {756 call::<T, UniqueNFTCall<T>, _, _>(handle, self)757 }758}