12345678910111213141516171819use evm_coder::{20 solidity_interface, solidity, ToLog,21 types::*,22 execution::{Result, Error},23 weight,24};25pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};26use pallet_evm_coder_substrate::dispatch_to_evm;27use sp_std::vec::Vec;28use up_data_structs::{29 AccessMode, CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property,30 SponsoringRateLimit, SponsorshipState,31};32use alloc::format;3334use crate::{35 Pallet, CollectionHandle, Config, CollectionProperties, SelfWeightOf,36 eth::convert_cross_account_to_uint256, weights::WeightInfo,37};383940#[derive(ToLog)]41pub enum CollectionHelpersEvents {42 43 CollectionCreated {44 45 #[indexed]46 owner: address,4748 49 #[indexed]50 collection_id: address,51 },52 53 CollectionDestroyed {54 55 #[indexed]56 collection_id: address,57 },58}59606162pub trait CommonEvmHandler {63 const CODE: &'static [u8];6465 66 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult>;67}686970#[solidity_interface(name = Collection)]71impl<T: Config> CollectionHandle<T>72where73 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,74{75 76 77 78 79 #[weight(<SelfWeightOf<T>>::set_collection_properties(1))]80 fn set_collection_property(81 &mut self,82 caller: caller,83 key: string,84 value: bytes,85 ) -> Result<void> {86 let caller = T::CrossAccountId::from_eth(caller);87 let key = <Vec<u8>>::from(key)88 .try_into()89 .map_err(|_| "key too large")?;90 let value = value.0.try_into().map_err(|_| "value too large")?;9192 <Pallet<T>>::set_collection_property(self, &caller, Property { key, value })93 .map_err(dispatch_to_evm::<T>)94 }9596 97 98 99 #[weight(<SelfWeightOf<T>>::set_collection_properties(properties.len() as u32))]100 fn set_collection_properties(101 &mut self,102 caller: caller,103 properties: Vec<(string, bytes)>,104 ) -> Result<void> {105 let caller = T::CrossAccountId::from_eth(caller);106107 let properties = properties108 .into_iter()109 .map(|(key, value)| {110 let key = <Vec<u8>>::from(key)111 .try_into()112 .map_err(|_| "key too large")?;113114 let value = value.0.try_into().map_err(|_| "value too large")?;115116 Ok(Property { key, value })117 })118 .collect::<Result<Vec<_>>>()?;119120 <Pallet<T>>::set_collection_properties(self, &caller, properties)121 .map_err(dispatch_to_evm::<T>)122 }123124 125 126 127 #[weight(<SelfWeightOf<T>>::delete_collection_properties(1))]128 fn delete_collection_property(&mut self, caller: caller, key: string) -> Result<()> {129 let caller = T::CrossAccountId::from_eth(caller);130 let key = <Vec<u8>>::from(key)131 .try_into()132 .map_err(|_| "key too large")?;133134 <Pallet<T>>::delete_collection_property(self, &caller, key).map_err(dispatch_to_evm::<T>)135 }136137 138 139 140 #[weight(<SelfWeightOf<T>>::delete_collection_properties(keys.len() as u32))]141 fn delete_collection_properties(&mut self, caller: caller, keys: Vec<string>) -> Result<()> {142 let caller = T::CrossAccountId::from_eth(caller);143 let keys = keys144 .into_iter()145 .map(|key| {146 <Vec<u8>>::from(key)147 .try_into()148 .map_err(|_| Error::Revert("key too large".into()))149 })150 .collect::<Result<Vec<_>>>()?;151152 <Pallet<T>>::delete_collection_properties(self, &caller, keys).map_err(dispatch_to_evm::<T>)153 }154155 156 157 158 159 160 161 fn collection_property(&self, key: string) -> Result<bytes> {162 let key = <Vec<u8>>::from(key)163 .try_into()164 .map_err(|_| "key too large")?;165166 let props = CollectionProperties::<T>::get(self.id);167 let prop = props.get(&key).ok_or("key not found")?;168169 Ok(bytes(prop.to_vec()))170 }171172 173 174 175 176 fn collection_properties(&self, keys: Vec<string>) -> Result<Vec<(string, bytes)>> {177 let keys = keys178 .into_iter()179 .map(|key| {180 <Vec<u8>>::from(key)181 .try_into()182 .map_err(|_| Error::Revert("key too large".into()))183 })184 .collect::<Result<Vec<_>>>()?;185186 let properties = Pallet::<T>::filter_collection_properties(187 self.id,188 if keys.is_empty() { None } else { Some(keys) },189 )190 .map_err(dispatch_to_evm::<T>)?;191192 let properties = properties193 .into_iter()194 .map(|p| {195 let key =196 string::from_utf8(p.key.into()).map_err(|e| Error::Revert(format!("{}", e)))?;197 let value = bytes(p.value.to_vec());198 Ok((key, value))199 })200 .collect::<Result<Vec<_>>>()?;201 Ok(properties)202 }203204 205 206 207 208 209 fn set_collection_sponsor(&mut self, caller: caller, sponsor: address) -> Result<void> {210 self.consume_store_reads_and_writes(1, 1)?;211212 check_is_owner_or_admin(caller, self)?;213214 let sponsor = T::CrossAccountId::from_eth(sponsor);215 self.set_sponsor(sponsor.as_sub().clone())216 .map_err(dispatch_to_evm::<T>)?;217 save(self)218 }219220 221 222 223 224 225 fn set_collection_sponsor_cross(226 &mut self,227 caller: caller,228 sponsor: EthCrossAccount,229 ) -> Result<void> {230 self.consume_store_reads_and_writes(1, 1)?;231232 check_is_owner_or_admin(caller, self)?;233234 let sponsor = sponsor.into_sub_cross_account::<T>()?;235 self.set_sponsor(sponsor.as_sub().clone())236 .map_err(dispatch_to_evm::<T>)?;237 save(self)238 }239240 241 fn has_collection_pending_sponsor(&self) -> Result<bool> {242 Ok(matches!(243 self.collection.sponsorship,244 SponsorshipState::Unconfirmed(_)245 ))246 }247248 249 250 251 fn confirm_collection_sponsorship(&mut self, caller: caller) -> Result<void> {252 self.consume_store_writes(1)?;253254 let caller = T::CrossAccountId::from_eth(caller);255 if !self256 .confirm_sponsorship(caller.as_sub())257 .map_err(dispatch_to_evm::<T>)?258 {259 return Err("caller is not set as sponsor".into());260 }261 save(self)262 }263264 265 fn remove_collection_sponsor(&mut self, caller: caller) -> Result<void> {266 self.consume_store_reads_and_writes(1, 1)?;267 check_is_owner_or_admin(caller, self)?;268 self.remove_sponsor().map_err(dispatch_to_evm::<T>)?;269 save(self)270 }271272 273 274 275 fn collection_sponsor(&self) -> Result<(address, uint256)> {276 let sponsor = match self.collection.sponsorship.sponsor() {277 Some(sponsor) => sponsor,278 None => return Ok(Default::default()),279 };280 let sponsor = T::CrossAccountId::from_sub(sponsor.clone());281 let result: (address, uint256) = if sponsor.is_canonical_substrate() {282 let sponsor = convert_cross_account_to_uint256::<T>(&sponsor);283 (Default::default(), sponsor)284 } else {285 let sponsor = *sponsor.as_eth();286 (sponsor, Default::default())287 };288 Ok(result)289 }290291 292 293 294 295 296 297 298 299 300 301 #[solidity(rename_selector = "setCollectionLimit")]302 fn set_int_limit(&mut self, caller: caller, limit: string, value: uint32) -> Result<void> {303 self.consume_store_reads_and_writes(1, 1)?;304305 check_is_owner_or_admin(caller, self)?;306 let mut limits = self.limits.clone();307308 match limit.as_str() {309 "accountTokenOwnershipLimit" => {310 limits.account_token_ownership_limit = Some(value);311 }312 "sponsoredDataSize" => {313 limits.sponsored_data_size = Some(value);314 }315 "sponsoredDataRateLimit" => {316 limits.sponsored_data_rate_limit = Some(SponsoringRateLimit::Blocks(value));317 }318 "tokenLimit" => {319 limits.token_limit = Some(value);320 }321 "sponsorTransferTimeout" => {322 limits.sponsor_transfer_timeout = Some(value);323 }324 "sponsorApproveTimeout" => {325 limits.sponsor_approve_timeout = Some(value);326 }327 _ => {328 return Err(Error::Revert(format!(329 "unknown integer limit \"{}\"",330 limit331 )))332 }333 }334 self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)335 .map_err(dispatch_to_evm::<T>)?;336 save(self)337 }338339 340 341 342 343 344 345 346 #[solidity(rename_selector = "setCollectionLimit")]347 fn set_bool_limit(&mut self, caller: caller, limit: string, value: bool) -> Result<void> {348 self.consume_store_reads_and_writes(1, 1)?;349350 check_is_owner_or_admin(caller, self)?;351 let mut limits = self.limits.clone();352353 match limit.as_str() {354 "ownerCanTransfer" => {355 limits.owner_can_transfer = Some(value);356 }357 "ownerCanDestroy" => {358 limits.owner_can_destroy = Some(value);359 }360 "transfersEnabled" => {361 limits.transfers_enabled = Some(value);362 }363 _ => {364 return Err(Error::Revert(format!(365 "unknown boolean limit \"{}\"",366 limit367 )))368 }369 }370 self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)371 .map_err(dispatch_to_evm::<T>)?;372 save(self)373 }374375 376 fn contract_address(&self) -> Result<address> {377 Ok(crate::eth::collection_id_to_address(self.id))378 }379380 381 382 fn add_collection_admin_cross(383 &mut self,384 caller: caller,385 new_admin: EthCrossAccount,386 ) -> Result<void> {387 self.consume_store_writes(2)?;388389 let caller = T::CrossAccountId::from_eth(caller);390 let new_admin = new_admin.into_sub_cross_account::<T>()?;391 <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;392 Ok(())393 }394395 396 397 fn remove_collection_admin_cross(398 &mut self,399 caller: caller,400 admin: EthCrossAccount,401 ) -> Result<void> {402 self.consume_store_writes(2)?;403404 let caller = T::CrossAccountId::from_eth(caller);405 let admin = admin.into_sub_cross_account::<T>()?;406 <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;407 Ok(())408 }409410 411 412 fn add_collection_admin(&mut self, caller: caller, new_admin: address) -> Result<void> {413 self.consume_store_writes(2)?;414415 let caller = T::CrossAccountId::from_eth(caller);416 let new_admin = T::CrossAccountId::from_eth(new_admin);417 <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;418 Ok(())419 }420421 422 423 424 fn remove_collection_admin(&mut self, caller: caller, admin: address) -> Result<void> {425 self.consume_store_writes(2)?;426427 let caller = T::CrossAccountId::from_eth(caller);428 let admin = T::CrossAccountId::from_eth(admin);429 <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;430 Ok(())431 }432433 434 435 436 #[solidity(rename_selector = "setCollectionNesting")]437 fn set_nesting_bool(&mut self, caller: caller, enable: bool) -> Result<void> {438 self.consume_store_reads_and_writes(1, 1)?;439440 check_is_owner_or_admin(caller, self)?;441442 let mut permissions = self.collection.permissions.clone();443 let mut nesting = permissions.nesting().clone();444 nesting.token_owner = enable;445 nesting.restricted = None;446 permissions.nesting = Some(nesting);447448 self.collection.permissions = <Pallet<T>>::clamp_permissions(449 self.collection.mode.clone(),450 &self.collection.permissions,451 permissions,452 )453 .map_err(dispatch_to_evm::<T>)?;454455 save(self)456 }457458 459 460 461 462 #[solidity(rename_selector = "setCollectionNesting")]463 fn set_nesting(464 &mut self,465 caller: caller,466 enable: bool,467 collections: Vec<address>,468 ) -> Result<void> {469 self.consume_store_reads_and_writes(1, 1)?;470471 if collections.is_empty() {472 return Err("no addresses provided".into());473 }474 check_is_owner_or_admin(caller, self)?;475476 let mut permissions = self.collection.permissions.clone();477 match enable {478 false => {479 let mut nesting = permissions.nesting().clone();480 nesting.token_owner = false;481 nesting.restricted = None;482 permissions.nesting = Some(nesting);483 }484 true => {485 let mut bv = OwnerRestrictedSet::new();486 for i in collections {487 bv.try_insert(crate::eth::map_eth_to_id(&i).ok_or_else(|| {488 Error::Revert("Can't convert address into collection id".into())489 })?)490 .map_err(|_| "too many collections")?;491 }492 let mut nesting = permissions.nesting().clone();493 nesting.token_owner = true;494 nesting.restricted = Some(bv);495 permissions.nesting = Some(nesting);496 }497 };498499 self.collection.permissions = <Pallet<T>>::clamp_permissions(500 self.collection.mode.clone(),501 &self.collection.permissions,502 permissions,503 )504 .map_err(dispatch_to_evm::<T>)?;505506 save(self)507 }508509 510 511 512 513 fn set_collection_access(&mut self, caller: caller, mode: uint8) -> Result<void> {514 self.consume_store_reads_and_writes(1, 1)?;515516 check_is_owner_or_admin(caller, self)?;517 let permissions = CollectionPermissions {518 access: Some(match mode {519 0 => AccessMode::Normal,520 1 => AccessMode::AllowList,521 _ => return Err("not supported access mode".into()),522 }),523 ..Default::default()524 };525 self.collection.permissions = <Pallet<T>>::clamp_permissions(526 self.collection.mode.clone(),527 &self.collection.permissions,528 permissions,529 )530 .map_err(dispatch_to_evm::<T>)?;531532 save(self)533 }534535 536 537 538 fn allowed(&self, user: address) -> Result<bool> {539 Ok(Pallet::<T>::allowed(540 self.id,541 T::CrossAccountId::from_eth(user),542 ))543 }544545 546 547 548 fn add_to_collection_allow_list(&mut self, caller: caller, user: address) -> Result<void> {549 self.consume_store_writes(1)?;550551 let caller = T::CrossAccountId::from_eth(caller);552 let user = T::CrossAccountId::from_eth(user);553 <Pallet<T>>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;554 Ok(())555 }556557 558 559 560 fn add_to_collection_allow_list_cross(561 &mut self,562 caller: caller,563 user: EthCrossAccount,564 ) -> Result<void> {565 self.consume_store_writes(1)?;566567 let caller = T::CrossAccountId::from_eth(caller);568 let user = user.into_sub_cross_account::<T>()?;569 Pallet::<T>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;570 Ok(())571 }572573 574 575 576 fn remove_from_collection_allow_list(&mut self, caller: caller, user: address) -> Result<void> {577 self.consume_store_writes(1)?;578579 let caller = T::CrossAccountId::from_eth(caller);580 let user = T::CrossAccountId::from_eth(user);581 <Pallet<T>>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;582 Ok(())583 }584585 586 587 588 fn remove_from_collection_allow_list_cross(589 &mut self,590 caller: caller,591 user: EthCrossAccount,592 ) -> Result<void> {593 self.consume_store_writes(1)?;594595 let caller = T::CrossAccountId::from_eth(caller);596 let user = user.into_sub_cross_account::<T>()?;597 Pallet::<T>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;598 Ok(())599 }600601 602 603 604 fn set_collection_mint_mode(&mut self, caller: caller, mode: bool) -> Result<void> {605 self.consume_store_reads_and_writes(1, 1)?;606607 check_is_owner_or_admin(caller, self)?;608 let permissions = CollectionPermissions {609 mint_mode: Some(mode),610 ..Default::default()611 };612 self.collection.permissions = <Pallet<T>>::clamp_permissions(613 self.collection.mode.clone(),614 &self.collection.permissions,615 permissions,616 )617 .map_err(dispatch_to_evm::<T>)?;618619 save(self)620 }621622 623 624 625 626 #[solidity(rename_selector = "isOwnerOrAdmin")]627 fn is_owner_or_admin_eth(&self, user: address) -> Result<bool> {628 let user = T::CrossAccountId::from_eth(user);629 Ok(self.is_owner_or_admin(&user))630 }631632 633 634 635 636 fn is_owner_or_admin_cross(&self, user: EthCrossAccount) -> Result<bool> {637 let user = user.into_sub_cross_account::<T>()?;638 Ok(self.is_owner_or_admin(&user))639 }640641 642 643 644 fn unique_collection_type(&self) -> Result<string> {645 let mode = match self.collection.mode {646 CollectionMode::Fungible(_) => "Fungible",647 CollectionMode::NFT => "NFT",648 CollectionMode::ReFungible => "ReFungible",649 };650 Ok(mode.into())651 }652653 654 655 656 657 fn collection_owner(&self) -> Result<EthCrossAccount> {658 Ok(EthCrossAccount::from_sub_cross_account::<T>(659 &T::CrossAccountId::from_sub(self.owner.clone()),660 ))661 }662663 664 665 666 667 #[solidity(rename_selector = "changeCollectionOwner")]668 fn set_owner(&mut self, caller: caller, new_owner: address) -> Result<void> {669 self.consume_store_writes(1)?;670671 let caller = T::CrossAccountId::from_eth(caller);672 let new_owner = T::CrossAccountId::from_eth(new_owner);673 self.set_owner_internal(caller, new_owner)674 .map_err(dispatch_to_evm::<T>)675 }676677 678 679 680 681 fn collection_admins(&self) -> Result<Vec<EthCrossAccount>> {682 let result = crate::IsAdmin::<T>::iter_prefix((self.id,))683 .map(|(admin, _)| EthCrossAccount::from_sub_cross_account::<T>(&admin))684 .collect();685 Ok(result)686 }687688 689 690 691 692 fn set_owner_cross(&mut self, caller: caller, new_owner: EthCrossAccount) -> Result<void> {693 self.consume_store_writes(1)?;694695 let caller = T::CrossAccountId::from_eth(caller);696 let new_owner = new_owner.into_sub_cross_account::<T>()?;697 self.set_owner_internal(caller, new_owner)698 .map_err(dispatch_to_evm::<T>)699 }700}701702703704fn check_is_owner_or_admin<T: Config>(705 caller: caller,706 collection: &CollectionHandle<T>,707) -> Result<T::CrossAccountId> {708 let caller = T::CrossAccountId::from_eth(caller);709 collection710 .check_is_owner_or_admin(&caller)711 .map_err(dispatch_to_evm::<T>)?;712 Ok(caller)713}714715716717fn save<T: Config>(collection: &CollectionHandle<T>) -> Result<void> {718 collection719 .check_is_internal()720 .map_err(dispatch_to_evm::<T>)?;721 collection.save().map_err(dispatch_to_evm::<T>)?;722 Ok(())723}724725726pub mod static_property {727 use evm_coder::{728 execution::{Result, Error},729 };730 use alloc::format;731732 const EXPECT_CONVERT_ERROR: &str = "length < limit";733734 735 pub mod key {736 use super::*;737738 739 pub fn base_uri() -> up_data_structs::PropertyKey {740 property_key_from_bytes(b"baseURI").expect(EXPECT_CONVERT_ERROR)741 }742743 744 pub fn url() -> up_data_structs::PropertyKey {745 property_key_from_bytes(b"URI").expect(EXPECT_CONVERT_ERROR)746 }747748 749 pub fn suffix() -> up_data_structs::PropertyKey {750 property_key_from_bytes(b"URISuffix").expect(EXPECT_CONVERT_ERROR)751 }752753 754 pub fn parent_nft() -> up_data_structs::PropertyKey {755 property_key_from_bytes(b"parentNft").expect(EXPECT_CONVERT_ERROR)756 }757 }758759 760 pub fn property_key_from_bytes(bytes: &[u8]) -> Result<up_data_structs::PropertyKey> {761 bytes.to_vec().try_into().map_err(|_| {762 Error::Revert(format!(763 "Property key is too long. Max length is {}.",764 up_data_structs::PropertyKey::bound()765 ))766 })767 }768769 770 pub fn property_value_from_bytes(bytes: &[u8]) -> Result<up_data_structs::PropertyValue> {771 bytes.to_vec().try_into().map_err(|_| {772 Error::Revert(format!(773 "Property key is too long. Max length is {}.",774 up_data_structs::PropertyKey::bound()775 ))776 })777 }778}