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, SchemaVersion, PropertyPermission, PropertyKeyPermission, Property, CollectionId,26 PropertyKey, 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},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 = pallet_common::eth::KEY_TOKEN_URI.clone();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 = pallet_common::eth::KEY_TOKEN_URI.clone();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>(430 collection_id: CollectionId,431 key: &PropertyKey,432) -> bool {433 if let Ok(token_property_permissions) = CollectionPropertyPermissions::<T>::try_get(collection_id) {434 return token_property_permissions.contains_key(key);435 }436437 false438}439440#[solidity_interface(name = "ERC721UniqueExtensions")]441impl<T: Config> NonfungibleHandle<T> {442 #[weight(<SelfWeightOf<T>>::transfer())]443 fn transfer(444 &mut self,445 caller: caller,446 to: address,447 token_id: uint256,448 _value: value,449 ) -> Result<void> {450 let caller = T::CrossAccountId::from_eth(caller);451 let to = T::CrossAccountId::from_eth(to);452 let token = token_id.try_into()?;453 let budget = self454 .recorder455 .weight_calls_budget(<StructureWeight<T>>::find_parent());456457 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;458 Ok(())459 }460461 #[weight(<SelfWeightOf<T>>::burn_from())]462 fn burn_from(463 &mut self,464 caller: caller,465 from: address,466 token_id: uint256,467 _value: value,468 ) -> Result<void> {469 let caller = T::CrossAccountId::from_eth(caller);470 let from = T::CrossAccountId::from_eth(from);471 let token = token_id.try_into()?;472 let budget = self473 .recorder474 .weight_calls_budget(<StructureWeight<T>>::find_parent());475476 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)477 .map_err(dispatch_to_evm::<T>)?;478 Ok(())479 }480481 fn next_token_id(&self) -> Result<uint256> {482 self.consume_store_reads(1)?;483 Ok(<TokensMinted<T>>::get(self.id)484 .checked_add(1)485 .ok_or("item id overflow")?486 .into())487 }488489 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]490 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {491 let caller = T::CrossAccountId::from_eth(caller);492 let to = T::CrossAccountId::from_eth(to);493 let mut expected_index = <TokensMinted<T>>::get(self.id)494 .checked_add(1)495 .ok_or("item id overflow")?;496 let budget = self497 .recorder498 .weight_calls_budget(<StructureWeight<T>>::find_parent());499500 let total_tokens = token_ids.len();501 for id in token_ids.into_iter() {502 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;503 if id != expected_index {504 return Err("item id should be next".into());505 }506 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;507 }508 let data = (0..total_tokens)509 .map(|_| CreateItemData::<T> {510 properties: BoundedVec::default(),511 owner: to.clone(),512 })513 .collect();514515 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)516 .map_err(dispatch_to_evm::<T>)?;517 Ok(true)518 }519520 #[solidity(rename_selector = "mintBulkWithTokenURI")]521 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]522 fn mint_bulk_with_token_uri(523 &mut self,524 caller: caller,525 to: address,526 tokens: Vec<(uint256, string)>,527 ) -> Result<bool> {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 data.push(CreateItemData::<T> {546 properties: BoundedVec::default(),547 owner: to.clone(),548 });549 }550551 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)552 .map_err(dispatch_to_evm::<T>)?;553 Ok(true)554 }555}556557#[solidity_interface(558 name = "UniqueNFT",559 is(560 ERC721,561 ERC721Metadata,562 ERC721Enumerable,563 ERC721UniqueExtensions,564 ERC721Mintable,565 ERC721Burnable,566 via("CollectionHandle<T>", common_mut, Collection),567 TokenProperties,568 )569)]570impl<T: Config> NonfungibleHandle<T> {}571572573generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);574generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);575576impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {577 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");578579 fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult> {580 call::<T, UniqueNFTCall<T>, _>(*source, self, value, input)581 }582}