1234567891011121314151617extern 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::{25 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,26 CollectionPropertiesVec,27};28use pallet_evm_coder_substrate::dispatch_to_evm;29use sp_core::{H160, U256};30use sp_std::vec::Vec;31use pallet_common::{32 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, token_uri_key},33 CollectionHandle, CollectionPropertyPermissions,34};35use pallet_evm::account::CrossAccountId;36use pallet_evm_coder_substrate::call;37use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};3839use crate::{40 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,41 SelfWeightOf, weights::WeightInfo, TokenProperties,42};4344#[solidity_interface(name = "TokenProperties")]45impl<T: Config> NonfungibleHandle<T> {46 fn set_token_property_permission(47 &mut self,48 caller: caller,49 key: string,50 is_mutable: bool,51 collection_admin: bool,52 token_owner: bool,53 ) -> Result<()> {54 let caller = T::CrossAccountId::from_eth(caller);55 <Pallet<T>>::set_property_permission(56 self,57 &caller,58 PropertyKeyPermission {59 key: <Vec<u8>>::from(key)60 .try_into()61 .map_err(|_| "too long key")?,62 permission: PropertyPermission {63 mutable: is_mutable,64 collection_admin,65 token_owner,66 },67 },68 )69 .map_err(dispatch_to_evm::<T>)70 }7172 fn set_property(73 &mut self,74 caller: caller,75 token_id: uint256,76 key: string,77 value: bytes,78 ) -> Result<()> {79 let caller = T::CrossAccountId::from_eth(caller);80 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;81 let key = <Vec<u8>>::from(key)82 .try_into()83 .map_err(|_| "key too long")?;84 let value = value.try_into().map_err(|_| "value too long")?;8586 <Pallet<T>>::set_token_property(self, &caller, TokenId(token_id), Property { key, value })87 .map_err(dispatch_to_evm::<T>)88 }8990 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {91 let caller = T::CrossAccountId::from_eth(caller);92 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;93 let key = <Vec<u8>>::from(key)94 .try_into()95 .map_err(|_| "key too long")?;9697 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key)98 .map_err(dispatch_to_evm::<T>)99 }100101 102 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {103 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;104 let key = <Vec<u8>>::from(key)105 .try_into()106 .map_err(|_| "key too long")?;107108 let props = <TokenProperties<T>>::get((self.id, token_id));109 let prop = props.get(&key).ok_or("key not found")?;110111 Ok(prop.to_vec())112 }113}114115#[derive(ToLog)]116pub enum ERC721Events {117 Transfer {118 #[indexed]119 from: address,120 #[indexed]121 to: address,122 #[indexed]123 token_id: uint256,124 },125 Approval {126 #[indexed]127 owner: address,128 #[indexed]129 approved: address,130 #[indexed]131 token_id: uint256,132 },133 #[allow(dead_code)]134 ApprovalForAll {135 #[indexed]136 owner: address,137 #[indexed]138 operator: address,139 approved: bool,140 },141}142143#[derive(ToLog)]144pub enum ERC721MintableEvents {145 #[allow(dead_code)]146 MintingFinished {},147}148149#[solidity_interface(name = "ERC721Metadata")]150impl<T: Config> NonfungibleHandle<T> {151 fn name(&self) -> Result<string> {152 Ok(decode_utf16(self.name.iter().copied())153 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))154 .collect::<string>())155 }156157 fn symbol(&self) -> Result<string> {158 Ok(string::from_utf8_lossy(&self.token_prefix).into())159 }160161 162 #[solidity(rename_selector = "tokenURI")]163 fn token_uri(&self, token_id: uint256) -> Result<string> {164 let key = token_uri_key();165 if !has_token_permission::<T>(self.id, &key) {166 return Err("No tokenURI permission".into());167 }168169 self.consume_store_reads(1)?;170 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;171172 let properties = <TokenProperties<T>>::try_get((self.id, token_id))173 .map_err(|_| Error::Revert("Token properties not found".into()))?;174 if let Some(property) = properties.get(&key) {175 return Ok(string::from_utf8_lossy(property).into());176 }177178 Err("Property tokenURI not found".into())179 }180}181182#[solidity_interface(name = "ERC721Enumerable")]183impl<T: Config> NonfungibleHandle<T> {184 fn token_by_index(&self, index: uint256) -> Result<uint256> {185 Ok(index)186 }187188 189 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {190 191 Err("not implemented".into())192 }193194 fn total_supply(&self) -> Result<uint256> {195 self.consume_store_reads(1)?;196 Ok(<Pallet<T>>::total_supply(self).into())197 }198}199200#[solidity_interface(name = "ERC721", events(ERC721Events))]201impl<T: Config> NonfungibleHandle<T> {202 fn balance_of(&self, owner: address) -> Result<uint256> {203 self.consume_store_reads(1)?;204 let owner = T::CrossAccountId::from_eth(owner);205 let balance = <AccountBalance<T>>::get((self.id, owner));206 Ok(balance.into())207 }208 fn owner_of(&self, token_id: uint256) -> Result<address> {209 self.consume_store_reads(1)?;210 let token: TokenId = token_id.try_into()?;211 Ok(*<TokenData<T>>::get((self.id, token))212 .ok_or("token not found")?213 .owner214 .as_eth())215 }216 217 fn safe_transfer_from_with_data(218 &mut self,219 _from: address,220 _to: address,221 _token_id: uint256,222 _data: bytes,223 _value: value,224 ) -> Result<void> {225 226 Err("not implemented".into())227 }228 229 fn safe_transfer_from(230 &mut self,231 _from: address,232 _to: address,233 _token_id: uint256,234 _value: value,235 ) -> Result<void> {236 237 Err("not implemented".into())238 }239240 #[weight(<SelfWeightOf<T>>::transfer_from())]241 fn transfer_from(242 &mut self,243 caller: caller,244 from: address,245 to: address,246 token_id: uint256,247 _value: value,248 ) -> Result<void> {249 let caller = T::CrossAccountId::from_eth(caller);250 let from = T::CrossAccountId::from_eth(from);251 let to = T::CrossAccountId::from_eth(to);252 let token = token_id.try_into()?;253 let budget = self254 .recorder255 .weight_calls_budget(<StructureWeight<T>>::find_parent());256257 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)258 .map_err(dispatch_to_evm::<T>)?;259 Ok(())260 }261262 #[weight(<SelfWeightOf<T>>::approve())]263 fn approve(264 &mut self,265 caller: caller,266 approved: address,267 token_id: uint256,268 _value: value,269 ) -> Result<void> {270 let caller = T::CrossAccountId::from_eth(caller);271 let approved = T::CrossAccountId::from_eth(approved);272 let token = token_id.try_into()?;273274 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))275 .map_err(dispatch_to_evm::<T>)?;276 Ok(())277 }278279 280 fn set_approval_for_all(281 &mut self,282 _caller: caller,283 _operator: address,284 _approved: bool,285 ) -> Result<void> {286 287 Err("not implemented".into())288 }289290 291 fn get_approved(&self, _token_id: uint256) -> Result<address> {292 293 Err("not implemented".into())294 }295296 297 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {298 299 Err("not implemented".into())300 }301}302303#[solidity_interface(name = "ERC721Burnable")]304impl<T: Config> NonfungibleHandle<T> {305 #[weight(<SelfWeightOf<T>>::burn_item())]306 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {307 let caller = T::CrossAccountId::from_eth(caller);308 let token = token_id.try_into()?;309310 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;311 Ok(())312 }313}314315#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]316impl<T: Config> NonfungibleHandle<T> {317 fn minting_finished(&self) -> Result<bool> {318 Ok(false)319 }320321 322 323 #[weight(<SelfWeightOf<T>>::create_item())]324 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {325 let caller = T::CrossAccountId::from_eth(caller);326 let to = T::CrossAccountId::from_eth(to);327 let token_id: u32 = token_id.try_into()?;328 let budget = self329 .recorder330 .weight_calls_budget(<StructureWeight<T>>::find_parent());331332 if <TokensMinted<T>>::get(self.id)333 .checked_add(1)334 .ok_or("item id overflow")?335 != token_id336 {337 return Err("item id should be next".into());338 }339340 <Pallet<T>>::create_item(341 self,342 &caller,343 CreateItemData::<T> {344 properties: BoundedVec::default(),345 owner: to,346 },347 &budget,348 )349 .map_err(dispatch_to_evm::<T>)?;350351 Ok(true)352 }353354 355 356 #[solidity(rename_selector = "mintWithTokenURI")]357 #[weight(<SelfWeightOf<T>>::create_item())]358 fn mint_with_token_uri(359 &mut self,360 caller: caller,361 to: address,362 token_id: uint256,363 token_uri: string,364 ) -> Result<bool> {365 let key = token_uri_key();366 let permission = get_token_permission::<T>(self.id, &key)?;367 if !permission.collection_admin {368 return Err("Operation is not allowed".into());369 }370371 let caller = T::CrossAccountId::from_eth(caller);372 let to = T::CrossAccountId::from_eth(to);373 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;374 let budget = self375 .recorder376 .weight_calls_budget(<StructureWeight<T>>::find_parent());377378 if <TokensMinted<T>>::get(self.id)379 .checked_add(1)380 .ok_or("item id overflow")?381 != token_id382 {383 return Err("item id should be next".into());384 }385386 let mut properties = CollectionPropertiesVec::default();387 properties388 .try_push(Property {389 key,390 value: token_uri391 .into_bytes()392 .try_into()393 .map_err(|_| "token uri is too long")?,394 })395 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;396397 <Pallet<T>>::create_item(398 self,399 &caller,400 CreateItemData::<T> {401 properties,402 owner: to,403 },404 &budget,405 )406 .map_err(dispatch_to_evm::<T>)?;407 Ok(true)408 }409410 411 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {412 Err("not implementable".into())413 }414}415416fn get_token_permission<T: Config>(417 collection_id: CollectionId,418 key: &PropertyKey,419) -> Result<PropertyPermission> {420 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)421 .map_err(|_| Error::Revert("No permissions for collection".into()))?;422 let a = token_property_permissions423 .get(key)424 .map(|p| p.clone())425 .ok_or_else(|| Error::Revert("No permission".into()))?;426 Ok(a)427}428429fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {430 if let Ok(token_property_permissions) =431 CollectionPropertyPermissions::<T>::try_get(collection_id)432 {433 return token_property_permissions.contains_key(key);434 }435436 false437}438439#[solidity_interface(name = "ERC721UniqueExtensions")]440impl<T: Config> NonfungibleHandle<T> {441 #[weight(<SelfWeightOf<T>>::transfer())]442 fn transfer(443 &mut self,444 caller: caller,445 to: address,446 token_id: uint256,447 _value: value,448 ) -> Result<void> {449 let caller = T::CrossAccountId::from_eth(caller);450 let to = T::CrossAccountId::from_eth(to);451 let token = token_id.try_into()?;452 let budget = self453 .recorder454 .weight_calls_budget(<StructureWeight<T>>::find_parent());455456 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;457 Ok(())458 }459460 #[weight(<SelfWeightOf<T>>::burn_from())]461 fn burn_from(462 &mut self,463 caller: caller,464 from: address,465 token_id: uint256,466 _value: value,467 ) -> Result<void> {468 let caller = T::CrossAccountId::from_eth(caller);469 let from = T::CrossAccountId::from_eth(from);470 let token = token_id.try_into()?;471 let budget = self472 .recorder473 .weight_calls_budget(<StructureWeight<T>>::find_parent());474475 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)476 .map_err(dispatch_to_evm::<T>)?;477 Ok(())478 }479480 fn next_token_id(&self) -> Result<uint256> {481 self.consume_store_reads(1)?;482 Ok(<TokensMinted<T>>::get(self.id)483 .checked_add(1)484 .ok_or("item id overflow")?485 .into())486 }487488 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]489 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {490 let caller = T::CrossAccountId::from_eth(caller);491 let to = T::CrossAccountId::from_eth(to);492 let mut expected_index = <TokensMinted<T>>::get(self.id)493 .checked_add(1)494 .ok_or("item id overflow")?;495 let budget = self496 .recorder497 .weight_calls_budget(<StructureWeight<T>>::find_parent());498499 let total_tokens = token_ids.len();500 for id in token_ids.into_iter() {501 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;502 if id != expected_index {503 return Err("item id should be next".into());504 }505 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;506 }507 let data = (0..total_tokens)508 .map(|_| CreateItemData::<T> {509 properties: BoundedVec::default(),510 owner: to.clone(),511 })512 .collect();513514 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)515 .map_err(dispatch_to_evm::<T>)?;516 Ok(true)517 }518519 #[solidity(rename_selector = "mintBulkWithTokenURI")]520 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]521 fn mint_bulk_with_token_uri(522 &mut self,523 caller: caller,524 to: address,525 tokens: Vec<(uint256, string)>,526 ) -> Result<bool> {527 let key = token_uri_key();528 let caller = T::CrossAccountId::from_eth(caller);529 let to = T::CrossAccountId::from_eth(to);530 let mut expected_index = <TokensMinted<T>>::get(self.id)531 .checked_add(1)532 .ok_or("item id overflow")?;533 let budget = self534 .recorder535 .weight_calls_budget(<StructureWeight<T>>::find_parent());536537 let mut data = Vec::with_capacity(tokens.len());538 for (id, token_uri) in tokens {539 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;540 if id != expected_index {541 return Err("item id should be next".into());542 }543 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;544545 let mut properties = CollectionPropertiesVec::default();546 properties547 .try_push(Property {548 key: key.clone(),549 value: token_uri550 .into_bytes()551 .try_into()552 .map_err(|_| "token uri is too long")?,553 })554 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;555556 data.push(CreateItemData::<T> {557 properties,558 owner: to.clone(),559 });560 }561562 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)563 .map_err(dispatch_to_evm::<T>)?;564 Ok(true)565 }566}567568#[solidity_interface(569 name = "UniqueNFT",570 is(571 ERC721,572 ERC721Metadata,573 ERC721Enumerable,574 ERC721UniqueExtensions,575 ERC721Mintable,576 ERC721Burnable,577 via("CollectionHandle<T>", common_mut, Collection),578 TokenProperties,579 )580)]581impl<T: Config> NonfungibleHandle<T> {}582583584generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);585generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);586587impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {588 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");589590 fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult> {591 call::<T, UniqueNFTCall<T>, _>(*source, self, value, input)592 }593}