12345678910111213141516171819pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};20use pallet_evm_coder_substrate::{21 abi::AbiType,22 solidity_interface, ToLog,23 types::*,24 execution::{Result, Error, PreDispatch},25 frontier_contract,26};27use pallet_evm_coder_substrate::dispatch_to_evm;28use sp_std::{vec, vec::Vec};29use sp_core::U256;30use up_data_structs::{31 CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property, SponsoringRateLimit,32 SponsorshipState,33};3435use crate::{36 Pallet, CollectionHandle, Config, CollectionProperties, eth, SelfWeightOf, weights::WeightInfo,37};3839frontier_contract! {40 macro_rules! CollectionHandle_result {...}41 impl<T: Config> Contract for CollectionHandle<T> {...}42}434445#[derive(ToLog)]46pub enum CollectionHelpersEvents {47 48 CollectionCreated {49 50 #[indexed]51 owner: Address,5253 54 #[indexed]55 collection_id: Address,56 },57 58 CollectionDestroyed {59 60 #[indexed]61 collection_id: Address,62 },63 64 CollectionChanged {65 66 #[indexed]67 collection_id: Address,68 },6970 71 TokenChanged {72 73 #[indexed]74 collection_id: Address,75 76 token_id: U256,77 },78}79808182pub trait CommonEvmHandler {83 84 const CODE: &'static [u8];8586 87 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult>;88}899091#[solidity_interface(name = Collection, enum(derive(PreDispatch)), enum_attr(weight))]92impl<T: Config> CollectionHandle<T>93where94 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,95{96 97 98 99 100 #[solidity(hide)]101 #[weight(<SelfWeightOf<T>>::set_collection_properties(1))]102 fn set_collection_property(&mut self, caller: Caller, key: String, value: Bytes) -> Result<()> {103 let caller = T::CrossAccountId::from_eth(caller);104 let key = <Vec<u8>>::from(key)105 .try_into()106 .map_err(|_| "key too large")?;107 let value = value.0.try_into().map_err(|_| "value too large")?;108109 <Pallet<T>>::set_collection_property(self, &caller, Property { key, value })110 .map_err(dispatch_to_evm::<T>)111 }112113 114 115 116 #[weight(<SelfWeightOf<T>>::set_collection_properties(properties.len() as u32))]117 fn set_collection_properties(118 &mut self,119 caller: Caller,120 properties: Vec<eth::Property>,121 ) -> Result<()> {122 let caller = T::CrossAccountId::from_eth(caller);123124 let properties = properties125 .into_iter()126 .map(eth::Property::try_into)127 .collect::<Result<Vec<_>>>()?;128129 <Pallet<T>>::set_collection_properties(self, &caller, properties.into_iter())130 .map_err(dispatch_to_evm::<T>)131 }132133 134 135 136 #[solidity(hide)]137 #[weight(<SelfWeightOf<T>>::delete_collection_properties(1))]138 fn delete_collection_property(&mut self, caller: Caller, key: String) -> Result<()> {139 let caller = T::CrossAccountId::from_eth(caller);140 let key = <Vec<u8>>::from(key)141 .try_into()142 .map_err(|_| "key too large")?;143144 <Pallet<T>>::delete_collection_property(self, &caller, key).map_err(dispatch_to_evm::<T>)145 }146147 148 149 150 #[weight(<SelfWeightOf<T>>::delete_collection_properties(keys.len() as u32))]151 fn delete_collection_properties(&mut self, caller: Caller, keys: Vec<String>) -> Result<()> {152 let caller = T::CrossAccountId::from_eth(caller);153 let keys = keys154 .into_iter()155 .map(|key| {156 <Vec<u8>>::from(key)157 .try_into()158 .map_err(|_| Error::Revert("key too large".into()))159 })160 .collect::<Result<Vec<_>>>()?;161162 <Pallet<T>>::delete_collection_properties(self, &caller, keys.into_iter())163 .map_err(dispatch_to_evm::<T>)164 }165166 167 168 169 170 171 172 fn collection_property(&self, key: String) -> Result<Bytes> {173 let key = <Vec<u8>>::from(key)174 .try_into()175 .map_err(|_| "key too large")?;176177 let props = CollectionProperties::<T>::get(self.id);178 let prop = props.get(&key).ok_or("key not found")?;179180 Ok(Bytes(prop.to_vec()))181 }182183 184 185 186 187 fn collection_properties(&self, keys: Vec<String>) -> Result<Vec<eth::Property>> {188 let keys = keys189 .into_iter()190 .map(|key| {191 <Vec<u8>>::from(key)192 .try_into()193 .map_err(|_| Error::Revert("key too large".into()))194 })195 .collect::<Result<Vec<_>>>()?;196197 let properties = Pallet::<T>::filter_collection_properties(198 self.id,199 if keys.is_empty() { None } else { Some(keys) },200 )201 .map_err(dispatch_to_evm::<T>)?;202203 let properties = properties204 .into_iter()205 .map(Property::try_into)206 .collect::<Result<Vec<_>>>()?;207 Ok(properties)208 }209210 211 212 213 214 215 #[solidity(hide)]216 fn set_collection_sponsor(&mut self, caller: Caller, sponsor: Address) -> Result<()> {217 self.consume_store_reads_and_writes(1, 1)?;218219 let caller = T::CrossAccountId::from_eth(caller);220221 let sponsor = T::CrossAccountId::from_eth(sponsor);222 self.set_sponsor(&caller, sponsor.as_sub().clone())223 .map_err(dispatch_to_evm::<T>)224 }225226 227 228 229 230 231 fn set_collection_sponsor_cross(232 &mut self,233 caller: Caller,234 sponsor: eth::CrossAddress,235 ) -> Result<()> {236 self.consume_store_reads_and_writes(1, 1)?;237238 let caller = T::CrossAccountId::from_eth(caller);239240 let sponsor = sponsor.into_sub_cross_account::<T>()?;241 self.set_sponsor(&caller, sponsor.as_sub().clone())242 .map_err(dispatch_to_evm::<T>)243 }244245 246 fn has_collection_pending_sponsor(&self) -> Result<bool> {247 Ok(matches!(248 self.collection.sponsorship,249 SponsorshipState::Unconfirmed(_)250 ))251 }252253 254 255 256 fn confirm_collection_sponsorship(&mut self, caller: Caller) -> Result<()> {257 self.consume_store_writes(1)?;258259 let caller = T::CrossAccountId::from_eth(caller);260 self.confirm_sponsorship(caller.as_sub())261 .map_err(dispatch_to_evm::<T>)262 }263264 265 fn remove_collection_sponsor(&mut self, caller: Caller) -> Result<()> {266 self.consume_store_reads_and_writes(1, 1)?;267 let caller = T::CrossAccountId::from_eth(caller);268 self.remove_sponsor(&caller).map_err(dispatch_to_evm::<T>)269 }270271 272 273 274 fn collection_sponsor(&self) -> Result<eth::CrossAddress> {275 let sponsor = match self.collection.sponsorship.sponsor() {276 Some(sponsor) => sponsor,277 None => return Ok(Default::default()),278 };279280 Ok(eth::CrossAddress::from_sub::<T>(sponsor))281 }282283 284 285 286 fn collection_limits(&self) -> Result<Vec<eth::CollectionLimit>> {287 let limits = &self.collection.limits;288289 Ok(vec![290 eth::CollectionLimit::new(291 eth::CollectionLimitField::AccountTokenOwnership,292 limits.account_token_ownership_limit,293 ),294 eth::CollectionLimit::new(295 eth::CollectionLimitField::SponsoredDataSize,296 limits.sponsored_data_size,297 ),298 limits299 .sponsored_data_rate_limit300 .and_then(|limit| {301 if let SponsoringRateLimit::Blocks(blocks) = limit {302 Some(eth::CollectionLimit::new(303 eth::CollectionLimitField::SponsoredDataRateLimit,304 Some(blocks),305 ))306 } else {307 None308 }309 })310 .unwrap_or_else(|| {311 eth::CollectionLimit::new(312 eth::CollectionLimitField::SponsoredDataRateLimit,313 Default::default(),314 )315 }),316 eth::CollectionLimit::new(eth::CollectionLimitField::TokenLimit, limits.token_limit),317 eth::CollectionLimit::new(318 eth::CollectionLimitField::SponsorTransferTimeout,319 limits.sponsor_transfer_timeout,320 ),321 eth::CollectionLimit::new(322 eth::CollectionLimitField::SponsorApproveTimeout,323 limits.sponsor_approve_timeout,324 ),325 eth::CollectionLimit::new(326 eth::CollectionLimitField::OwnerCanTransfer,327 limits.owner_can_transfer.map(u32::from),328 ),329 eth::CollectionLimit::new(330 eth::CollectionLimitField::OwnerCanDestroy,331 limits.owner_can_destroy.map(u32::from),332 ),333 eth::CollectionLimit::new(334 eth::CollectionLimitField::TransferEnabled,335 limits.transfers_enabled.map(u32::from),336 ),337 ])338 }339340 341 342 343 #[solidity(rename_selector = "setCollectionLimit")]344 fn set_collection_limit(&mut self, caller: Caller, limit: eth::CollectionLimit) -> Result<()> {345 self.consume_store_reads_and_writes(1, 1)?;346347 if !limit.has_value() {348 return Err(Error::Revert("user can't disable limits".into()));349 }350351 let caller = T::CrossAccountId::from_eth(caller);352 <Pallet<T>>::update_limits(&caller, self, limit.try_into()?).map_err(dispatch_to_evm::<T>)353 }354355 356 fn contract_address(&self) -> Result<Address> {357 Ok(crate::eth::collection_id_to_address(self.id))358 }359360 361 362 fn add_collection_admin_cross(363 &mut self,364 caller: Caller,365 new_admin: eth::CrossAddress,366 ) -> Result<()> {367 self.consume_store_reads_and_writes(2, 2)?;368369 let caller = T::CrossAccountId::from_eth(caller);370 let new_admin = new_admin.into_sub_cross_account::<T>()?;371 <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;372 Ok(())373 }374375 376 377 fn remove_collection_admin_cross(378 &mut self,379 caller: Caller,380 admin: eth::CrossAddress,381 ) -> Result<()> {382 self.consume_store_reads_and_writes(2, 2)?;383384 let caller = T::CrossAccountId::from_eth(caller);385 let admin = admin.into_sub_cross_account::<T>()?;386 <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;387 Ok(())388 }389390 391 392 #[solidity(hide)]393 fn add_collection_admin(&mut self, caller: Caller, new_admin: Address) -> Result<()> {394 self.consume_store_reads_and_writes(2, 2)?;395396 let caller = T::CrossAccountId::from_eth(caller);397 let new_admin = T::CrossAccountId::from_eth(new_admin);398 <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;399 Ok(())400 }401402 403 404 405 #[solidity(hide)]406 fn remove_collection_admin(&mut self, caller: Caller, admin: Address) -> Result<()> {407 self.consume_store_reads_and_writes(2, 2)?;408409 let caller = T::CrossAccountId::from_eth(caller);410 let admin = T::CrossAccountId::from_eth(admin);411 <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;412 Ok(())413 }414415 416 417 418 #[solidity(rename_selector = "setCollectionNesting")]419 fn set_nesting_bool(&mut self, caller: Caller, enable: bool) -> Result<()> {420 self.consume_store_reads_and_writes(1, 1)?;421422 let caller = T::CrossAccountId::from_eth(caller);423424 let mut permissions = self.collection.permissions.clone();425 let mut nesting = permissions.nesting().clone();426 nesting.token_owner = enable;427 nesting.restricted = None;428 permissions.nesting = Some(nesting);429430 <Pallet<T>>::update_permissions(&caller, self, permissions).map_err(dispatch_to_evm::<T>)431 }432433 434 435 436 437 #[solidity(rename_selector = "setCollectionNesting")]438 fn set_nesting(439 &mut self,440 caller: Caller,441 enable: bool,442 collections: Vec<Address>,443 ) -> Result<()> {444 self.consume_store_reads_and_writes(1, 1)?;445446 if collections.is_empty() {447 return Err("no addresses provided".into());448 }449 let caller = T::CrossAccountId::from_eth(caller);450451 let mut permissions = self.collection.permissions.clone();452 match enable {453 false => {454 let mut nesting = permissions.nesting().clone();455 nesting.token_owner = false;456 nesting.restricted = None;457 permissions.nesting = Some(nesting);458 }459 true => {460 let mut bv = OwnerRestrictedSet::new();461 for i in collections {462 bv.try_insert(crate::eth::map_eth_to_id(&i).ok_or_else(|| {463 Error::Revert("Can't convert address into collection id".into())464 })?)465 .map_err(|_| "too many collections")?;466 }467 let mut nesting = permissions.nesting().clone();468 nesting.token_owner = true;469 nesting.restricted = Some(bv);470 permissions.nesting = Some(nesting);471 }472 };473474 <Pallet<T>>::update_permissions(&caller, self, permissions).map_err(dispatch_to_evm::<T>)475 }476477 478 #[solidity(rename_selector = "collectionNestingRestrictedCollectionIds")]479 fn collection_nesting_restricted_ids(&self) -> Result<eth::CollectionNesting> {480 let nesting = self.collection.permissions.nesting();481482 Ok(eth::CollectionNesting::new(483 nesting.token_owner,484 nesting485 .restricted486 .clone()487 .map(|b| b.0.into_inner().iter().map(|id| id.0.into()).collect())488 .unwrap_or_default(),489 ))490 }491492 493 fn collection_nesting_permissions(&self) -> Result<Vec<eth::CollectionNestingPermission>> {494 let nesting = self.collection.permissions.nesting();495 Ok(vec![496 eth::CollectionNestingPermission::new(497 eth::CollectionPermissionField::CollectionAdmin,498 nesting.collection_admin,499 ),500 eth::CollectionNestingPermission::new(501 eth::CollectionPermissionField::TokenOwner,502 nesting.token_owner,503 ),504 ])505 }506 507 508 fn set_collection_access(&mut self, caller: Caller, mode: eth::AccessMode) -> Result<()> {509 self.consume_store_reads_and_writes(1, 1)?;510511 let caller = T::CrossAccountId::from_eth(caller);512 let permissions = CollectionPermissions {513 access: Some(mode.into()),514 ..Default::default()515 };516 <Pallet<T>>::update_permissions(&caller, self, permissions).map_err(dispatch_to_evm::<T>)517 }518519 520 521 522 fn allowlisted_cross(&self, user: eth::CrossAddress) -> Result<bool> {523 let user = user.into_sub_cross_account::<T>()?;524 Ok(Pallet::<T>::allowed(self.id, user))525 }526527 528 529 530 #[solidity(hide)]531 fn add_to_collection_allow_list(&mut self, caller: Caller, user: Address) -> Result<()> {532 self.consume_store_writes(1)?;533534 let caller = T::CrossAccountId::from_eth(caller);535 let user = T::CrossAccountId::from_eth(user);536 <Pallet<T>>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;537 Ok(())538 }539540 541 542 543 fn add_to_collection_allow_list_cross(544 &mut self,545 caller: Caller,546 user: eth::CrossAddress,547 ) -> Result<()> {548 self.consume_store_writes(1)?;549550 let caller = T::CrossAccountId::from_eth(caller);551 let user = user.into_sub_cross_account::<T>()?;552 Pallet::<T>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;553 Ok(())554 }555556 557 558 559 #[solidity(hide)]560 fn remove_from_collection_allow_list(&mut self, caller: Caller, user: Address) -> Result<()> {561 self.consume_store_writes(1)?;562563 let caller = T::CrossAccountId::from_eth(caller);564 let user = T::CrossAccountId::from_eth(user);565 <Pallet<T>>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;566 Ok(())567 }568569 570 571 572 fn remove_from_collection_allow_list_cross(573 &mut self,574 caller: Caller,575 user: eth::CrossAddress,576 ) -> Result<()> {577 self.consume_store_writes(1)?;578579 let caller = T::CrossAccountId::from_eth(caller);580 let user = user.into_sub_cross_account::<T>()?;581 Pallet::<T>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;582 Ok(())583 }584585 586 587 588 fn set_collection_mint_mode(&mut self, caller: Caller, mode: bool) -> Result<()> {589 self.consume_store_reads_and_writes(1, 1)?;590591 let caller = T::CrossAccountId::from_eth(caller);592 let permissions = CollectionPermissions {593 mint_mode: Some(mode),594 ..Default::default()595 };596 <Pallet<T>>::update_permissions(&caller, self, permissions).map_err(dispatch_to_evm::<T>)597 }598599 600 601 602 603 #[solidity(hide, rename_selector = "isOwnerOrAdmin")]604 fn is_owner_or_admin_eth(&self, user: Address) -> Result<bool> {605 let user = T::CrossAccountId::from_eth(user);606 Ok(self.is_owner_or_admin(&user))607 }608609 610 611 612 613 fn is_owner_or_admin_cross(&self, user: eth::CrossAddress) -> Result<bool> {614 let user = user.into_sub_cross_account::<T>()?;615 Ok(self.is_owner_or_admin(&user))616 }617618 619 620 621 fn unique_collection_type(&self) -> Result<String> {622 let mode = match self.collection.mode {623 CollectionMode::Fungible(_) => "Fungible",624 CollectionMode::NFT => "NFT",625 CollectionMode::ReFungible => "ReFungible",626 };627 Ok(mode.into())628 }629630 631 632 633 634 fn collection_owner(&self) -> Result<eth::CrossAddress> {635 Ok(eth::CrossAddress::from_sub_cross_account::<T>(636 &T::CrossAccountId::from_sub(self.owner.clone()),637 ))638 }639640 641 642 643 644 #[solidity(hide, rename_selector = "changeCollectionOwner")]645 fn set_owner(&mut self, caller: Caller, new_owner: Address) -> Result<()> {646 self.consume_store_writes(1)?;647648 let caller = T::CrossAccountId::from_eth(caller);649 let new_owner = T::CrossAccountId::from_eth(new_owner);650 self.change_owner(caller, new_owner)651 .map_err(dispatch_to_evm::<T>)652 }653654 655 656 657 658 fn collection_admins(&self) -> Result<Vec<eth::CrossAddress>> {659 let result = crate::IsAdmin::<T>::iter_prefix((self.id,))660 .map(|(admin, _)| eth::CrossAddress::from_sub_cross_account::<T>(&admin))661 .collect();662 Ok(result)663 }664665 666 667 668 669 fn change_collection_owner_cross(670 &mut self,671 caller: Caller,672 new_owner: eth::CrossAddress,673 ) -> Result<()> {674 self.consume_store_writes(1)?;675676 let caller = T::CrossAccountId::from_eth(caller);677 let new_owner = new_owner.into_sub_cross_account::<T>()?;678 self.change_owner(caller, new_owner)679 .map_err(dispatch_to_evm::<T>)680 }681}682683684pub mod static_property {685 use pallet_evm_coder_substrate::{686 execution::{Result, Error},687 };688 use alloc::format;689690 const EXPECT_CONVERT_ERROR: &str = "length < limit";691692 693 pub mod key {694 use super::*;695696 697 pub fn base_uri() -> up_data_structs::PropertyKey {698 property_key_from_bytes(b"baseURI").expect(EXPECT_CONVERT_ERROR)699 }700701 702 pub fn url() -> up_data_structs::PropertyKey {703 property_key_from_bytes(b"URI").expect(EXPECT_CONVERT_ERROR)704 }705706 707 pub fn suffix() -> up_data_structs::PropertyKey {708 property_key_from_bytes(b"URISuffix").expect(EXPECT_CONVERT_ERROR)709 }710711 712 pub fn parent_nft() -> up_data_structs::PropertyKey {713 property_key_from_bytes(b"parentNft").expect(EXPECT_CONVERT_ERROR)714 }715 }716717 718 pub fn property_key_from_bytes(bytes: &[u8]) -> Result<up_data_structs::PropertyKey> {719 bytes.to_vec().try_into().map_err(|_| {720 Error::Revert(format!(721 "Property key is too long. Max length is {}.",722 up_data_structs::PropertyKey::bound()723 ))724 })725 }726727 728 pub fn property_value_from_bytes(bytes: &[u8]) -> Result<up_data_structs::PropertyValue> {729 bytes.to_vec().try_into().map_err(|_| {730 Error::Revert(format!(731 "Property key is too long. Max length is {}.",732 up_data_structs::PropertyKey::bound()733 ))734 })735 }736}