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 64 const CODE: &'static [u8];6566 67 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult>;68}697071#[solidity_interface(name = Collection)]72impl<T: Config> CollectionHandle<T>73where74 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,75{76 77 78 79 80 #[weight(<SelfWeightOf<T>>::set_collection_properties(1))]81 fn set_collection_property(82 &mut self,83 caller: caller,84 key: string,85 value: bytes,86 ) -> Result<void> {87 let caller = T::CrossAccountId::from_eth(caller);88 let key = <Vec<u8>>::from(key)89 .try_into()90 .map_err(|_| "key too large")?;91 let value = value.0.try_into().map_err(|_| "value too large")?;9293 <Pallet<T>>::set_collection_property(self, &caller, Property { key, value })94 .map_err(dispatch_to_evm::<T>)95 }9697 98 99 100 #[weight(<SelfWeightOf<T>>::set_collection_properties(properties.len() as u32))]101 fn set_collection_properties(102 &mut self,103 caller: caller,104 properties: Vec<(string, bytes)>,105 ) -> Result<void> {106 let caller = T::CrossAccountId::from_eth(caller);107108 let properties = properties109 .into_iter()110 .map(|(key, value)| {111 let key = <Vec<u8>>::from(key)112 .try_into()113 .map_err(|_| "key too large")?;114115 let value = value.0.try_into().map_err(|_| "value too large")?;116117 Ok(Property { key, value })118 })119 .collect::<Result<Vec<_>>>()?;120121 <Pallet<T>>::set_collection_properties(self, &caller, properties)122 .map_err(dispatch_to_evm::<T>)123 }124125 126 127 128 #[weight(<SelfWeightOf<T>>::delete_collection_properties(1))]129 fn delete_collection_property(&mut self, caller: caller, key: string) -> Result<()> {130 let caller = T::CrossAccountId::from_eth(caller);131 let key = <Vec<u8>>::from(key)132 .try_into()133 .map_err(|_| "key too large")?;134135 <Pallet<T>>::delete_collection_property(self, &caller, key).map_err(dispatch_to_evm::<T>)136 }137138 139 140 141 #[weight(<SelfWeightOf<T>>::delete_collection_properties(keys.len() as u32))]142 fn delete_collection_properties(&mut self, caller: caller, keys: Vec<string>) -> Result<()> {143 let caller = T::CrossAccountId::from_eth(caller);144 let keys = keys145 .into_iter()146 .map(|key| {147 <Vec<u8>>::from(key)148 .try_into()149 .map_err(|_| Error::Revert("key too large".into()))150 })151 .collect::<Result<Vec<_>>>()?;152153 <Pallet<T>>::delete_collection_properties(self, &caller, keys).map_err(dispatch_to_evm::<T>)154 }155156 157 158 159 160 161 162 fn collection_property(&self, key: string) -> Result<bytes> {163 let key = <Vec<u8>>::from(key)164 .try_into()165 .map_err(|_| "key too large")?;166167 let props = CollectionProperties::<T>::get(self.id);168 let prop = props.get(&key).ok_or("key not found")?;169170 Ok(bytes(prop.to_vec()))171 }172173 174 175 176 177 fn collection_properties(&self, keys: Vec<string>) -> Result<Vec<(string, bytes)>> {178 let keys = keys179 .into_iter()180 .map(|key| {181 <Vec<u8>>::from(key)182 .try_into()183 .map_err(|_| Error::Revert("key too large".into()))184 })185 .collect::<Result<Vec<_>>>()?;186187 let properties = Pallet::<T>::filter_collection_properties(188 self.id,189 if keys.is_empty() { None } else { Some(keys) },190 )191 .map_err(dispatch_to_evm::<T>)?;192193 let properties = properties194 .into_iter()195 .map(|p| {196 let key =197 string::from_utf8(p.key.into()).map_err(|e| Error::Revert(format!("{}", e)))?;198 let value = bytes(p.value.to_vec());199 Ok((key, value))200 })201 .collect::<Result<Vec<_>>>()?;202 Ok(properties)203 }204205 206 207 208 209 210 fn set_collection_sponsor(&mut self, caller: caller, sponsor: address) -> Result<void> {211 self.consume_store_reads_and_writes(1, 1)?;212213 check_is_owner_or_admin(caller, self)?;214215 let sponsor = T::CrossAccountId::from_eth(sponsor);216 self.set_sponsor(sponsor.as_sub().clone())217 .map_err(dispatch_to_evm::<T>)?;218 save(self)219 }220221 222 223 224 225 226 fn set_collection_sponsor_cross(227 &mut self,228 caller: caller,229 sponsor: EthCrossAccount,230 ) -> Result<void> {231 self.consume_store_reads_and_writes(1, 1)?;232233 check_is_owner_or_admin(caller, self)?;234235 let sponsor = sponsor.into_sub_cross_account::<T>()?;236 self.set_sponsor(sponsor.as_sub().clone())237 .map_err(dispatch_to_evm::<T>)?;238 save(self)239 }240241 242 fn has_collection_pending_sponsor(&self) -> Result<bool> {243 Ok(matches!(244 self.collection.sponsorship,245 SponsorshipState::Unconfirmed(_)246 ))247 }248249 250 251 252 fn confirm_collection_sponsorship(&mut self, caller: caller) -> Result<void> {253 self.consume_store_writes(1)?;254255 let caller = T::CrossAccountId::from_eth(caller);256 if !self257 .confirm_sponsorship(caller.as_sub())258 .map_err(dispatch_to_evm::<T>)?259 {260 return Err("caller is not set as sponsor".into());261 }262 save(self)263 }264265 266 fn remove_collection_sponsor(&mut self, caller: caller) -> Result<void> {267 self.consume_store_reads_and_writes(1, 1)?;268 check_is_owner_or_admin(caller, self)?;269 self.remove_sponsor().map_err(dispatch_to_evm::<T>)?;270 save(self)271 }272273 274 275 276 fn collection_sponsor(&self) -> Result<(address, uint256)> {277 let sponsor = match self.collection.sponsorship.sponsor() {278 Some(sponsor) => sponsor,279 None => return Ok(Default::default()),280 };281 let sponsor = T::CrossAccountId::from_sub(sponsor.clone());282 let result: (address, uint256) = if sponsor.is_canonical_substrate() {283 let sponsor = convert_cross_account_to_uint256::<T>(&sponsor);284 (Default::default(), sponsor)285 } else {286 let sponsor = *sponsor.as_eth();287 (sponsor, Default::default())288 };289 Ok(result)290 }291292 293 294 295 296 297 298 299 300 301 302 #[solidity(rename_selector = "setCollectionLimit")]303 fn set_int_limit(&mut self, caller: caller, limit: string, value: uint32) -> Result<void> {304 self.consume_store_reads_and_writes(1, 1)?;305306 check_is_owner_or_admin(caller, self)?;307 let mut limits = self.limits.clone();308309 match limit.as_str() {310 "accountTokenOwnershipLimit" => {311 limits.account_token_ownership_limit = Some(value);312 }313 "sponsoredDataSize" => {314 limits.sponsored_data_size = Some(value);315 }316 "sponsoredDataRateLimit" => {317 limits.sponsored_data_rate_limit = Some(SponsoringRateLimit::Blocks(value));318 }319 "tokenLimit" => {320 limits.token_limit = Some(value);321 }322 "sponsorTransferTimeout" => {323 limits.sponsor_transfer_timeout = Some(value);324 }325 "sponsorApproveTimeout" => {326 limits.sponsor_approve_timeout = Some(value);327 }328 _ => {329 return Err(Error::Revert(format!(330 "unknown integer limit \"{}\"",331 limit332 )))333 }334 }335 self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)336 .map_err(dispatch_to_evm::<T>)?;337 save(self)338 }339340 341 342 343 344 345 346 347 #[solidity(rename_selector = "setCollectionLimit")]348 fn set_bool_limit(&mut self, caller: caller, limit: string, value: bool) -> Result<void> {349 self.consume_store_reads_and_writes(1, 1)?;350351 check_is_owner_or_admin(caller, self)?;352 let mut limits = self.limits.clone();353354 match limit.as_str() {355 "ownerCanTransfer" => {356 limits.owner_can_transfer = Some(value);357 }358 "ownerCanDestroy" => {359 limits.owner_can_destroy = Some(value);360 }361 "transfersEnabled" => {362 limits.transfers_enabled = Some(value);363 }364 _ => {365 return Err(Error::Revert(format!(366 "unknown boolean limit \"{}\"",367 limit368 )))369 }370 }371 self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)372 .map_err(dispatch_to_evm::<T>)?;373 save(self)374 }375376 377 fn contract_address(&self) -> Result<address> {378 Ok(crate::eth::collection_id_to_address(self.id))379 }380381 382 383 fn add_collection_admin_cross(384 &mut self,385 caller: caller,386 new_admin: EthCrossAccount,387 ) -> Result<void> {388 self.consume_store_writes(2)?;389390 let caller = T::CrossAccountId::from_eth(caller);391 let new_admin = new_admin.into_sub_cross_account::<T>()?;392 <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;393 Ok(())394 }395396 397 398 fn remove_collection_admin_cross(399 &mut self,400 caller: caller,401 admin: EthCrossAccount,402 ) -> Result<void> {403 self.consume_store_writes(2)?;404405 let caller = T::CrossAccountId::from_eth(caller);406 let admin = admin.into_sub_cross_account::<T>()?;407 <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;408 Ok(())409 }410411 412 413 fn add_collection_admin(&mut self, caller: caller, new_admin: address) -> Result<void> {414 self.consume_store_writes(2)?;415416 let caller = T::CrossAccountId::from_eth(caller);417 let new_admin = T::CrossAccountId::from_eth(new_admin);418 <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;419 Ok(())420 }421422 423 424 425 fn remove_collection_admin(&mut self, caller: caller, admin: address) -> Result<void> {426 self.consume_store_writes(2)?;427428 let caller = T::CrossAccountId::from_eth(caller);429 let admin = T::CrossAccountId::from_eth(admin);430 <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;431 Ok(())432 }433434 435 436 437 #[solidity(rename_selector = "setCollectionNesting")]438 fn set_nesting_bool(&mut self, caller: caller, enable: bool) -> Result<void> {439 self.consume_store_reads_and_writes(1, 1)?;440441 check_is_owner_or_admin(caller, self)?;442443 let mut permissions = self.collection.permissions.clone();444 let mut nesting = permissions.nesting().clone();445 nesting.token_owner = enable;446 nesting.restricted = None;447 permissions.nesting = Some(nesting);448449 self.collection.permissions = <Pallet<T>>::clamp_permissions(450 self.collection.mode.clone(),451 &self.collection.permissions,452 permissions,453 )454 .map_err(dispatch_to_evm::<T>)?;455456 save(self)457 }458459 460 461 462 463 #[solidity(rename_selector = "setCollectionNesting")]464 fn set_nesting(465 &mut self,466 caller: caller,467 enable: bool,468 collections: Vec<address>,469 ) -> Result<void> {470 self.consume_store_reads_and_writes(1, 1)?;471472 if collections.is_empty() {473 return Err("no addresses provided".into());474 }475 check_is_owner_or_admin(caller, self)?;476477 let mut permissions = self.collection.permissions.clone();478 match enable {479 false => {480 let mut nesting = permissions.nesting().clone();481 nesting.token_owner = false;482 nesting.restricted = None;483 permissions.nesting = Some(nesting);484 }485 true => {486 let mut bv = OwnerRestrictedSet::new();487 for i in collections {488 bv.try_insert(crate::eth::map_eth_to_id(&i).ok_or_else(|| {489 Error::Revert("Can't convert address into collection id".into())490 })?)491 .map_err(|_| "too many collections")?;492 }493 let mut nesting = permissions.nesting().clone();494 nesting.token_owner = true;495 nesting.restricted = Some(bv);496 permissions.nesting = Some(nesting);497 }498 };499500 self.collection.permissions = <Pallet<T>>::clamp_permissions(501 self.collection.mode.clone(),502 &self.collection.permissions,503 permissions,504 )505 .map_err(dispatch_to_evm::<T>)?;506507 save(self)508 }509510 511 512 513 514 fn set_collection_access(&mut self, caller: caller, mode: uint8) -> Result<void> {515 self.consume_store_reads_and_writes(1, 1)?;516517 check_is_owner_or_admin(caller, self)?;518 let permissions = CollectionPermissions {519 access: Some(match mode {520 0 => AccessMode::Normal,521 1 => AccessMode::AllowList,522 _ => return Err("not supported access mode".into()),523 }),524 ..Default::default()525 };526 self.collection.permissions = <Pallet<T>>::clamp_permissions(527 self.collection.mode.clone(),528 &self.collection.permissions,529 permissions,530 )531 .map_err(dispatch_to_evm::<T>)?;532533 save(self)534 }535536 537 538 539 fn allowed(&self, user: address) -> Result<bool> {540 Ok(Pallet::<T>::allowed(541 self.id,542 T::CrossAccountId::from_eth(user),543 ))544 }545546 547 548 549 fn add_to_collection_allow_list(&mut self, caller: caller, user: address) -> Result<void> {550 self.consume_store_writes(1)?;551552 let caller = T::CrossAccountId::from_eth(caller);553 let user = T::CrossAccountId::from_eth(user);554 <Pallet<T>>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;555 Ok(())556 }557558 559 560 561 fn add_to_collection_allow_list_cross(562 &mut self,563 caller: caller,564 user: EthCrossAccount,565 ) -> Result<void> {566 self.consume_store_writes(1)?;567568 let caller = T::CrossAccountId::from_eth(caller);569 let user = user.into_sub_cross_account::<T>()?;570 Pallet::<T>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;571 Ok(())572 }573574 575 576 577 fn remove_from_collection_allow_list(&mut self, caller: caller, user: address) -> Result<void> {578 self.consume_store_writes(1)?;579580 let caller = T::CrossAccountId::from_eth(caller);581 let user = T::CrossAccountId::from_eth(user);582 <Pallet<T>>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;583 Ok(())584 }585586 587 588 589 fn remove_from_collection_allow_list_cross(590 &mut self,591 caller: caller,592 user: EthCrossAccount,593 ) -> Result<void> {594 self.consume_store_writes(1)?;595596 let caller = T::CrossAccountId::from_eth(caller);597 let user = user.into_sub_cross_account::<T>()?;598 Pallet::<T>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;599 Ok(())600 }601602 603 604 605 fn set_collection_mint_mode(&mut self, caller: caller, mode: bool) -> Result<void> {606 self.consume_store_reads_and_writes(1, 1)?;607608 check_is_owner_or_admin(caller, self)?;609 let permissions = CollectionPermissions {610 mint_mode: Some(mode),611 ..Default::default()612 };613 self.collection.permissions = <Pallet<T>>::clamp_permissions(614 self.collection.mode.clone(),615 &self.collection.permissions,616 permissions,617 )618 .map_err(dispatch_to_evm::<T>)?;619620 save(self)621 }622623 624 625 626 627 #[solidity(rename_selector = "isOwnerOrAdmin")]628 fn is_owner_or_admin_eth(&self, user: address) -> Result<bool> {629 let user = T::CrossAccountId::from_eth(user);630 Ok(self.is_owner_or_admin(&user))631 }632633 634 635 636 637 fn is_owner_or_admin_cross(&self, user: EthCrossAccount) -> Result<bool> {638 let user = user.into_sub_cross_account::<T>()?;639 Ok(self.is_owner_or_admin(&user))640 }641642 643 644 645 fn unique_collection_type(&self) -> Result<string> {646 let mode = match self.collection.mode {647 CollectionMode::Fungible(_) => "Fungible",648 CollectionMode::NFT => "NFT",649 CollectionMode::ReFungible => "ReFungible",650 };651 Ok(mode.into())652 }653654 655 656 657 658 fn collection_owner(&self) -> Result<EthCrossAccount> {659 Ok(EthCrossAccount::from_sub_cross_account::<T>(660 &T::CrossAccountId::from_sub(self.owner.clone()),661 ))662 }663664 665 666 667 668 #[solidity(rename_selector = "changeCollectionOwner")]669 fn set_owner(&mut self, caller: caller, new_owner: address) -> Result<void> {670 self.consume_store_writes(1)?;671672 let caller = T::CrossAccountId::from_eth(caller);673 let new_owner = T::CrossAccountId::from_eth(new_owner);674 self.set_owner_internal(caller, new_owner)675 .map_err(dispatch_to_evm::<T>)676 }677678 679 680 681 682 fn collection_admins(&self) -> Result<Vec<EthCrossAccount>> {683 let result = crate::IsAdmin::<T>::iter_prefix((self.id,))684 .map(|(admin, _)| EthCrossAccount::from_sub_cross_account::<T>(&admin))685 .collect();686 Ok(result)687 }688689 690 691 692 693 fn set_owner_cross(&mut self, caller: caller, new_owner: EthCrossAccount) -> Result<void> {694 self.consume_store_writes(1)?;695696 let caller = T::CrossAccountId::from_eth(caller);697 let new_owner = new_owner.into_sub_cross_account::<T>()?;698 self.set_owner_internal(caller, new_owner)699 .map_err(dispatch_to_evm::<T>)700 }701}702703704705fn check_is_owner_or_admin<T: Config>(706 caller: caller,707 collection: &CollectionHandle<T>,708) -> Result<T::CrossAccountId> {709 let caller = T::CrossAccountId::from_eth(caller);710 collection711 .check_is_owner_or_admin(&caller)712 .map_err(dispatch_to_evm::<T>)?;713 Ok(caller)714}715716717718fn save<T: Config>(collection: &CollectionHandle<T>) -> Result<void> {719 collection720 .check_is_internal()721 .map_err(dispatch_to_evm::<T>)?;722 collection.save().map_err(dispatch_to_evm::<T>)?;723 Ok(())724}725726727pub mod static_property {728 use evm_coder::{729 execution::{Result, Error},730 };731 use alloc::format;732733 const EXPECT_CONVERT_ERROR: &str = "length < limit";734735 736 pub mod key {737 use super::*;738739 740 pub fn base_uri() -> up_data_structs::PropertyKey {741 property_key_from_bytes(b"baseURI").expect(EXPECT_CONVERT_ERROR)742 }743744 745 pub fn url() -> up_data_structs::PropertyKey {746 property_key_from_bytes(b"URI").expect(EXPECT_CONVERT_ERROR)747 }748749 750 pub fn suffix() -> up_data_structs::PropertyKey {751 property_key_from_bytes(b"URISuffix").expect(EXPECT_CONVERT_ERROR)752 }753754 755 pub fn parent_nft() -> up_data_structs::PropertyKey {756 property_key_from_bytes(b"parentNft").expect(EXPECT_CONVERT_ERROR)757 }758 }759760 761 pub fn property_key_from_bytes(bytes: &[u8]) -> Result<up_data_structs::PropertyKey> {762 bytes.to_vec().try_into().map_err(|_| {763 Error::Revert(format!(764 "Property key is too long. Max length is {}.",765 up_data_structs::PropertyKey::bound()766 ))767 })768 }769770 771 pub fn property_value_from_bytes(bytes: &[u8]) -> Result<up_data_structs::PropertyValue> {772 bytes.to_vec().try_into().map_err(|_| {773 Error::Revert(format!(774 "Property key is too long. Max length is {}.",775 up_data_structs::PropertyKey::bound()776 ))777 })778 }779}