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 = pallet_common::eth::KEY_TOKEN_URI.clone();162 let permission = get_token_permission::<T>(self.id, &key)?;163 if !permission.collection_admin {164 return Err("Operation is not allowed".into());165 }166167 self.consume_store_reads(1)?;168 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;169170 let properties = <TokenProperties<T>>::try_get((self.id, token_id))171 .map_err(|_| Error::Revert("Token properties not found".into()))?;172 if let Some(property) = properties.get(&key) {173 return Ok(string::from_utf8_lossy(property).into());174 }175176 Err("Property tokenURI not found".into())177 }178}179180#[solidity_interface(name = "ERC721Enumerable")]181impl<T: Config> NonfungibleHandle<T> {182 fn token_by_index(&self, index: uint256) -> Result<uint256> {183 Ok(index)184 }185186 187 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {188 189 Err("not implemented".into())190 }191192 fn total_supply(&self) -> Result<uint256> {193 self.consume_store_reads(1)?;194 Ok(<Pallet<T>>::total_supply(self).into())195 }196}197198#[solidity_interface(name = "ERC721", events(ERC721Events))]199impl<T: Config> NonfungibleHandle<T> {200 fn balance_of(&self, owner: address) -> Result<uint256> {201 self.consume_store_reads(1)?;202 let owner = T::CrossAccountId::from_eth(owner);203 let balance = <AccountBalance<T>>::get((self.id, owner));204 Ok(balance.into())205 }206 fn owner_of(&self, token_id: uint256) -> Result<address> {207 self.consume_store_reads(1)?;208 let token: TokenId = token_id.try_into()?;209 Ok(*<TokenData<T>>::get((self.id, token))210 .ok_or("token not found")?211 .owner212 .as_eth())213 }214 215 fn safe_transfer_from_with_data(216 &mut self,217 _from: address,218 _to: address,219 _token_id: uint256,220 _data: bytes,221 _value: value,222 ) -> Result<void> {223 224 Err("not implemented".into())225 }226 227 fn safe_transfer_from(228 &mut self,229 _from: address,230 _to: address,231 _token_id: uint256,232 _value: value,233 ) -> Result<void> {234 235 Err("not implemented".into())236 }237238 #[weight(<SelfWeightOf<T>>::transfer_from())]239 fn transfer_from(240 &mut self,241 caller: caller,242 from: address,243 to: address,244 token_id: uint256,245 _value: value,246 ) -> Result<void> {247 let caller = T::CrossAccountId::from_eth(caller);248 let from = T::CrossAccountId::from_eth(from);249 let to = T::CrossAccountId::from_eth(to);250 let token = token_id.try_into()?;251 let budget = self252 .recorder253 .weight_calls_budget(<StructureWeight<T>>::find_parent());254255 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)256 .map_err(dispatch_to_evm::<T>)?;257 Ok(())258 }259260 #[weight(<SelfWeightOf<T>>::approve())]261 fn approve(262 &mut self,263 caller: caller,264 approved: address,265 token_id: uint256,266 _value: value,267 ) -> Result<void> {268 let caller = T::CrossAccountId::from_eth(caller);269 let approved = T::CrossAccountId::from_eth(approved);270 let token = token_id.try_into()?;271272 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))273 .map_err(dispatch_to_evm::<T>)?;274 Ok(())275 }276277 278 fn set_approval_for_all(279 &mut self,280 _caller: caller,281 _operator: address,282 _approved: bool,283 ) -> Result<void> {284 285 Err("not implemented".into())286 }287288 289 fn get_approved(&self, _token_id: uint256) -> Result<address> {290 291 Err("not implemented".into())292 }293294 295 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {296 297 Err("not implemented".into())298 }299}300301#[solidity_interface(name = "ERC721Burnable")]302impl<T: Config> NonfungibleHandle<T> {303 #[weight(<SelfWeightOf<T>>::burn_item())]304 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {305 let caller = T::CrossAccountId::from_eth(caller);306 let token = token_id.try_into()?;307308 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;309 Ok(())310 }311}312313#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]314impl<T: Config> NonfungibleHandle<T> {315 fn minting_finished(&self) -> Result<bool> {316 Ok(false)317 }318319 320 321 #[weight(<SelfWeightOf<T>>::create_item())]322 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {323 let caller = T::CrossAccountId::from_eth(caller);324 let to = T::CrossAccountId::from_eth(to);325 let token_id: u32 = token_id.try_into()?;326 let budget = self327 .recorder328 .weight_calls_budget(<StructureWeight<T>>::find_parent());329330 if <TokensMinted<T>>::get(self.id)331 .checked_add(1)332 .ok_or("item id overflow")?333 != token_id334 {335 return Err("item id should be next".into());336 }337338 <Pallet<T>>::create_item(339 self,340 &caller,341 CreateItemData::<T> {342 properties: BoundedVec::default(),343 owner: to,344 },345 &budget,346 )347 .map_err(dispatch_to_evm::<T>)?;348349 Ok(true)350 }351352 353 354 #[solidity(rename_selector = "mintWithTokenURI")]355 #[weight(<SelfWeightOf<T>>::create_item())]356 fn mint_with_token_uri(357 &mut self,358 caller: caller,359 to: address,360 token_id: uint256,361 token_uri: string,362 ) -> Result<bool> {363 let key = pallet_common::eth::KEY_TOKEN_URI.clone();364 let permission = get_token_permission::<T>(self.id, &key)?;365 if !permission.collection_admin {366 return Err("Operation is not allowed".into());367 }368369 let caller = T::CrossAccountId::from_eth(caller);370 let to = T::CrossAccountId::from_eth(to);371 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;372 let budget = self373 .recorder374 .weight_calls_budget(<StructureWeight<T>>::find_parent());375376 if <TokensMinted<T>>::get(self.id)377 .checked_add(1)378 .ok_or("item id overflow")?379 != token_id380 {381 return Err("item id should be next".into());382 }383384 let mut properties = CollectionPropertiesVec::default();385 properties.try_push(Property{386 key,387 value: token_uri.into_bytes().try_into()388 .map_err(|_| "token uri is too long")?389 }).map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;390391 <Pallet<T>>::create_item(392 self,393 &caller,394 CreateItemData::<T> {395 properties,396 owner: to,397 },398 &budget,399 )400 .map_err(dispatch_to_evm::<T>)?;401 Ok(true)402 }403404 405 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {406 Err("not implementable".into())407 }408}409410fn get_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> Result<PropertyPermission> {411 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)412 .map_err(|_| Error::Revert("No permissions for collection".into()))?;413 let a = token_property_permissions.get(key)414 .map(|p| p.clone())415 .ok_or_else(|| Error::Revert("No permission for tokenURI".into()))?;416 Ok(a)417}418419#[solidity_interface(name = "ERC721UniqueExtensions")]420impl<T: Config> NonfungibleHandle<T> {421 #[weight(<SelfWeightOf<T>>::transfer())]422 fn transfer(423 &mut self,424 caller: caller,425 to: address,426 token_id: uint256,427 _value: value,428 ) -> Result<void> {429 let caller = T::CrossAccountId::from_eth(caller);430 let to = T::CrossAccountId::from_eth(to);431 let token = token_id.try_into()?;432 let budget = self433 .recorder434 .weight_calls_budget(<StructureWeight<T>>::find_parent());435436 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;437 Ok(())438 }439440 #[weight(<SelfWeightOf<T>>::burn_from())]441 fn burn_from(442 &mut self,443 caller: caller,444 from: address,445 token_id: uint256,446 _value: value,447 ) -> Result<void> {448 let caller = T::CrossAccountId::from_eth(caller);449 let from = T::CrossAccountId::from_eth(from);450 let token = token_id.try_into()?;451 let budget = self452 .recorder453 .weight_calls_budget(<StructureWeight<T>>::find_parent());454455 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)456 .map_err(dispatch_to_evm::<T>)?;457 Ok(())458 }459460 fn next_token_id(&self) -> Result<uint256> {461 self.consume_store_reads(1)?;462 Ok(<TokensMinted<T>>::get(self.id)463 .checked_add(1)464 .ok_or("item id overflow")?465 .into())466 }467468 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]469 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {470 let caller = T::CrossAccountId::from_eth(caller);471 let to = T::CrossAccountId::from_eth(to);472 let mut expected_index = <TokensMinted<T>>::get(self.id)473 .checked_add(1)474 .ok_or("item id overflow")?;475 let budget = self476 .recorder477 .weight_calls_budget(<StructureWeight<T>>::find_parent());478479 let total_tokens = token_ids.len();480 for id in token_ids.into_iter() {481 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;482 if id != expected_index {483 return Err("item id should be next".into());484 }485 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;486 }487 let data = (0..total_tokens)488 .map(|_| CreateItemData::<T> {489 properties: BoundedVec::default(),490 owner: to.clone(),491 })492 .collect();493494 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)495 .map_err(dispatch_to_evm::<T>)?;496 Ok(true)497 }498499 #[solidity(rename_selector = "mintBulkWithTokenURI")]500 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]501 fn mint_bulk_with_token_uri(502 &mut self,503 caller: caller,504 to: address,505 tokens: Vec<(uint256, string)>,506 ) -> Result<bool> {507 let caller = T::CrossAccountId::from_eth(caller);508 let to = T::CrossAccountId::from_eth(to);509 let mut expected_index = <TokensMinted<T>>::get(self.id)510 .checked_add(1)511 .ok_or("item id overflow")?;512 let budget = self513 .recorder514 .weight_calls_budget(<StructureWeight<T>>::find_parent());515516 let mut data = Vec::with_capacity(tokens.len());517 for (id, token_uri) in tokens {518 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;519 if id != expected_index {520 return Err("item id should be next".into());521 }522 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;523524 todo!("token uri");525 data.push(CreateItemData::<T> {526 properties: BoundedVec::default(),527 owner: to.clone(),528 });529 }530531 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)532 .map_err(dispatch_to_evm::<T>)?;533 Ok(true)534 }535}536537#[solidity_interface(538 name = "UniqueNFT",539 is(540 ERC721,541 ERC721Metadata,542 ERC721Enumerable,543 ERC721UniqueExtensions,544 ERC721Mintable,545 ERC721Burnable,546 via("CollectionHandle<T>", common_mut, Collection),547 TokenProperties,548 )549)]550impl<T: Config> NonfungibleHandle<T> {}551552553generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);554generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);555556impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {557 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");558559 fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult> {560 call::<T, UniqueNFTCall<T>, _>(*source, self, value, input)561 }562}