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::{TokenId, SchemaVersion, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey, CollectionPropertiesVec};25use pallet_evm_coder_substrate::dispatch_to_evm;26use sp_core::{H160, U256};27use sp_std::vec::Vec;28use pallet_common::{29 erc::{CommonEvmHandler, PrecompileResult, CollectionCall},30 CollectionHandle, CollectionPropertyPermissions,31};32use pallet_evm::account::CrossAccountId;33use pallet_evm_coder_substrate::call;34use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};3536use crate::{37 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,38 SelfWeightOf, weights::WeightInfo, TokenProperties,39};4041#[solidity_interface(name = "TokenProperties")]42impl<T: Config> NonfungibleHandle<T> {43 fn set_token_property_permission(44 &mut self,45 caller: caller,46 key: string,47 is_mutable: bool,48 collection_admin: bool,49 token_owner: bool,50 ) -> Result<()> {51 let caller = T::CrossAccountId::from_eth(caller);52 <Pallet<T>>::set_property_permission(53 self,54 &caller,55 PropertyKeyPermission {56 key: <Vec<u8>>::from(key)57 .try_into()58 .map_err(|_| "too long key")?,59 permission: PropertyPermission {60 mutable: is_mutable,61 collection_admin,62 token_owner,63 },64 },65 )66 .map_err(dispatch_to_evm::<T>)67 }6869 fn set_property(70 &mut self,71 caller: caller,72 token_id: uint256,73 key: string,74 value: bytes,75 ) -> Result<()> {76 let caller = T::CrossAccountId::from_eth(caller);77 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;78 let key = <Vec<u8>>::from(key)79 .try_into()80 .map_err(|_| "key too long")?;81 let value = value.try_into().map_err(|_| "value too long")?;8283 <Pallet<T>>::set_token_property(self, &caller, TokenId(token_id), Property { key, value })84 .map_err(dispatch_to_evm::<T>)85 }8687 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {88 let caller = T::CrossAccountId::from_eth(caller);89 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;90 let key = <Vec<u8>>::from(key)91 .try_into()92 .map_err(|_| "key too long")?;9394 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key)95 .map_err(dispatch_to_evm::<T>)96 }9798 99 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {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")?;104105 let props = <TokenProperties<T>>::get((self.id, token_id));106 let prop = props.get(&key).ok_or("key not found")?;107108 Ok(prop.to_vec())109 }110}111112#[derive(ToLog)]113pub enum ERC721Events {114 Transfer {115 #[indexed]116 from: address,117 #[indexed]118 to: address,119 #[indexed]120 token_id: uint256,121 },122 Approval {123 #[indexed]124 owner: address,125 #[indexed]126 approved: address,127 #[indexed]128 token_id: uint256,129 },130 #[allow(dead_code)]131 ApprovalForAll {132 #[indexed]133 owner: address,134 #[indexed]135 operator: address,136 approved: bool,137 },138}139140#[derive(ToLog)]141pub enum ERC721MintableEvents {142 #[allow(dead_code)]143 MintingFinished {},144}145146#[solidity_interface(name = "ERC721Metadata")]147impl<T: Config> NonfungibleHandle<T> {148 fn name(&self) -> Result<string> {149 Ok(decode_utf16(self.name.iter().copied())150 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))151 .collect::<string>())152 }153154 fn symbol(&self) -> Result<string> {155 Ok(string::from_utf8_lossy(&self.token_prefix).into())156 }157158 159 #[solidity(rename_selector = "tokenURI")]160 fn token_uri(&self, token_id: uint256) -> Result<string> {161 let key: string = "tokenURI".into(); 162 let key: up_data_structs::PropertyKey = key.into_bytes().try_into()163 .map_err(|_| Error::Revert("".into()))?;164 let permission = get_token_permission::<T>(self.id, &key)?;165 if !permission.collection_admin {166 return Err("Operation is not allowed".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: string = "tokenURI".into(); 366 let key: up_data_structs::PropertyKey = key.into_bytes().try_into()367 .map_err(|_| Error::Revert("".into()))?;368 let permission = get_token_permission::<T>(self.id, &key)?;369 if !permission.collection_admin {370 return Err("Operation is not allowed".into());371 }372373 let caller = T::CrossAccountId::from_eth(caller);374 let to = T::CrossAccountId::from_eth(to);375 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;376 let budget = self377 .recorder378 .weight_calls_budget(<StructureWeight<T>>::find_parent());379380 if <TokensMinted<T>>::get(self.id)381 .checked_add(1)382 .ok_or("item id overflow")?383 != token_id384 {385 return Err("item id should be next".into());386 }387388 let mut properties = CollectionPropertiesVec::default();389 properties.try_push(Property{390 key,391 value: token_uri.into_bytes().try_into()392 .map_err(|_| "token uri is too long")?393 }).map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;394395 <Pallet<T>>::create_item(396 self,397 &caller,398 CreateItemData::<T> {399 properties,400 owner: to,401 },402 &budget,403 )404 .map_err(dispatch_to_evm::<T>)?;405 Ok(true)406 }407408 409 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {410 Err("not implementable".into())411 }412}413414fn get_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> Result<PropertyPermission> {415 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)416 .map_err(|_| Error::Revert("No permissions for collection".into()))?;417 let a = token_property_permissions.get(key)418 .map(|p| p.clone())419 .ok_or_else(|| Error::Revert("No permission for tokenURI".into()))?;420 Ok(a)421}422423#[solidity_interface(name = "ERC721UniqueExtensions")]424impl<T: Config> NonfungibleHandle<T> {425 #[weight(<SelfWeightOf<T>>::transfer())]426 fn transfer(427 &mut self,428 caller: caller,429 to: address,430 token_id: uint256,431 _value: value,432 ) -> Result<void> {433 let caller = T::CrossAccountId::from_eth(caller);434 let to = T::CrossAccountId::from_eth(to);435 let token = token_id.try_into()?;436 let budget = self437 .recorder438 .weight_calls_budget(<StructureWeight<T>>::find_parent());439440 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;441 Ok(())442 }443444 #[weight(<SelfWeightOf<T>>::burn_from())]445 fn burn_from(446 &mut self,447 caller: caller,448 from: address,449 token_id: uint256,450 _value: value,451 ) -> Result<void> {452 let caller = T::CrossAccountId::from_eth(caller);453 let from = T::CrossAccountId::from_eth(from);454 let token = token_id.try_into()?;455 let budget = self456 .recorder457 .weight_calls_budget(<StructureWeight<T>>::find_parent());458459 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)460 .map_err(dispatch_to_evm::<T>)?;461 Ok(())462 }463464 fn next_token_id(&self) -> Result<uint256> {465 self.consume_store_reads(1)?;466 Ok(<TokensMinted<T>>::get(self.id)467 .checked_add(1)468 .ok_or("item id overflow")?469 .into())470 }471472 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]473 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {474 let caller = T::CrossAccountId::from_eth(caller);475 let to = T::CrossAccountId::from_eth(to);476 let mut expected_index = <TokensMinted<T>>::get(self.id)477 .checked_add(1)478 .ok_or("item id overflow")?;479 let budget = self480 .recorder481 .weight_calls_budget(<StructureWeight<T>>::find_parent());482483 let total_tokens = token_ids.len();484 for id in token_ids.into_iter() {485 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;486 if id != expected_index {487 return Err("item id should be next".into());488 }489 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;490 }491 let data = (0..total_tokens)492 .map(|_| CreateItemData::<T> {493 properties: BoundedVec::default(),494 owner: to.clone(),495 })496 .collect();497498 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)499 .map_err(dispatch_to_evm::<T>)?;500 Ok(true)501 }502503 #[solidity(rename_selector = "mintBulkWithTokenURI")]504 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]505 fn mint_bulk_with_token_uri(506 &mut self,507 caller: caller,508 to: address,509 tokens: Vec<(uint256, string)>,510 ) -> Result<bool> {511 let caller = T::CrossAccountId::from_eth(caller);512 let to = T::CrossAccountId::from_eth(to);513 let mut expected_index = <TokensMinted<T>>::get(self.id)514 .checked_add(1)515 .ok_or("item id overflow")?;516 let budget = self517 .recorder518 .weight_calls_budget(<StructureWeight<T>>::find_parent());519520 let mut data = Vec::with_capacity(tokens.len());521 for (id, token_uri) in tokens {522 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;523 if id != expected_index {524 return Err("item id should be next".into());525 }526 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;527528 todo!("token uri");529 data.push(CreateItemData::<T> {530 properties: BoundedVec::default(),531 owner: to.clone(),532 });533 }534535 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)536 .map_err(dispatch_to_evm::<T>)?;537 Ok(true)538 }539}540541#[solidity_interface(542 name = "UniqueNFT",543 is(544 ERC721,545 ERC721Metadata,546 ERC721Enumerable,547 ERC721UniqueExtensions,548 ERC721Mintable,549 ERC721Burnable,550 via("CollectionHandle<T>", common_mut, Collection),551 TokenProperties,552 )553)]554impl<T: Config> NonfungibleHandle<T> {}555556557generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);558generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);559560impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {561 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");562563 fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult> {564 call::<T, UniqueNFTCall<T>, _>(*source, self, value, input)565 }566}