difftreelog
refactor Generalization some operations.
in: master
13 files changed
pallets/common/src/erc.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! This module contains the implementation of pallet methods for evm.1819pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};20use evm_coder::{21 abi::AbiType,22 solidity_interface, solidity, ToLog,23 types::*,24 types::Property as PropertyStruct,25 execution::{Result, Error},26 weight,27};28use pallet_evm_coder_substrate::dispatch_to_evm;29use sp_std::vec::Vec;30use up_data_structs::{31 AccessMode, CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property,32 SponsoringRateLimit, SponsorshipState,33};34use alloc::format;3536use crate::{37 Pallet, CollectionHandle, Config, CollectionProperties, SelfWeightOf,38 eth::{EthCrossAccount, convert_cross_account_to_uint256},39 weights::WeightInfo,40};4142/// Events for ethereum collection helper.43#[derive(ToLog)]44pub enum CollectionHelpersEvents {45 /// The collection has been created.46 CollectionCreated {47 /// Collection owner.48 #[indexed]49 owner: address,5051 /// Collection ID.52 #[indexed]53 collection_id: address,54 },55 /// The collection has been destroyed.56 CollectionDestroyed {57 /// Collection ID.58 #[indexed]59 collection_id: address,60 },61 /// The collection has been changed.62 CollectionChanged {63 /// Collection ID.64 #[indexed]65 collection_id: address,66 },67}6869/// Does not always represent a full collection, for RFT it is either70/// collection (Implementing ERC721), or specific collection token (Implementing ERC20).71pub trait CommonEvmHandler {72 /// Raw compiled binary code of the contract stub73 const CODE: &'static [u8];7475 /// Call precompiled handle.76 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult>;77}7879/// @title A contract that allows you to work with collections.80#[solidity_interface(name = Collection)]81impl<T: Config> CollectionHandle<T>82where83 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,84{85 /// Set collection property.86 ///87 /// @param key Property key.88 /// @param value Propery value.89 #[solidity(hide)]90 #[weight(<SelfWeightOf<T>>::set_collection_properties(1))]91 fn set_collection_property(92 &mut self,93 caller: caller,94 key: string,95 value: bytes,96 ) -> Result<void> {97 let caller = T::CrossAccountId::from_eth(caller);98 let key = <Vec<u8>>::from(key)99 .try_into()100 .map_err(|_| "key too large")?;101 let value = value.0.try_into().map_err(|_| "value too large")?;102103 <Pallet<T>>::set_collection_property(self, &caller, Property { key, value })104 .map_err(dispatch_to_evm::<T>)105 }106107 /// Set collection properties.108 ///109 /// @param properties Vector of properties key/value pair.110 #[weight(<SelfWeightOf<T>>::set_collection_properties(properties.len() as u32))]111 fn set_collection_properties(112 &mut self,113 caller: caller,114 properties: Vec<PropertyStruct>,115 ) -> Result<void> {116 let caller = T::CrossAccountId::from_eth(caller);117118 let properties = properties119 .into_iter()120 .map(|PropertyStruct { key, value }| {121 let key = <Vec<u8>>::from(key)122 .try_into()123 .map_err(|_| "key too large")?;124125 let value = value.0.try_into().map_err(|_| "value too large")?;126127 Ok(Property { key, value })128 })129 .collect::<Result<Vec<_>>>()?;130131 <Pallet<T>>::set_collection_properties(self, &caller, properties)132 .map_err(dispatch_to_evm::<T>)133 }134135 /// Delete collection property.136 ///137 /// @param key Property key.138 #[solidity(hide)]139 #[weight(<SelfWeightOf<T>>::delete_collection_properties(1))]140 fn delete_collection_property(&mut self, caller: caller, key: string) -> Result<()> {141 let caller = T::CrossAccountId::from_eth(caller);142 let key = <Vec<u8>>::from(key)143 .try_into()144 .map_err(|_| "key too large")?;145146 <Pallet<T>>::delete_collection_property(self, &caller, key).map_err(dispatch_to_evm::<T>)147 }148149 /// Delete collection properties.150 ///151 /// @param keys Properties keys.152 #[weight(<SelfWeightOf<T>>::delete_collection_properties(keys.len() as u32))]153 fn delete_collection_properties(&mut self, caller: caller, keys: Vec<string>) -> Result<()> {154 let caller = T::CrossAccountId::from_eth(caller);155 let keys = keys156 .into_iter()157 .map(|key| {158 <Vec<u8>>::from(key)159 .try_into()160 .map_err(|_| Error::Revert("key too large".into()))161 })162 .collect::<Result<Vec<_>>>()?;163164 <Pallet<T>>::delete_collection_properties(self, &caller, keys).map_err(dispatch_to_evm::<T>)165 }166167 /// Get collection property.168 ///169 /// @dev Throws error if key not found.170 ///171 /// @param key Property key.172 /// @return bytes The property corresponding to the key.173 fn collection_property(&self, key: string) -> Result<bytes> {174 let key = <Vec<u8>>::from(key)175 .try_into()176 .map_err(|_| "key too large")?;177178 let props = CollectionProperties::<T>::get(self.id);179 let prop = props.get(&key).ok_or("key not found")?;180181 Ok(bytes(prop.to_vec()))182 }183184 /// Get collection properties.185 ///186 /// @param keys Properties keys. Empty keys for all propertyes.187 /// @return Vector of properties key/value pairs.188 fn collection_properties(&self, keys: Vec<string>) -> Result<Vec<PropertyStruct>> {189 let keys = keys190 .into_iter()191 .map(|key| {192 <Vec<u8>>::from(key)193 .try_into()194 .map_err(|_| Error::Revert("key too large".into()))195 })196 .collect::<Result<Vec<_>>>()?;197198 let properties = Pallet::<T>::filter_collection_properties(199 self.id,200 if keys.is_empty() { None } else { Some(keys) },201 )202 .map_err(dispatch_to_evm::<T>)?;203204 let properties = properties205 .into_iter()206 .map(|p| {207 let key =208 string::from_utf8(p.key.into()).map_err(|e| Error::Revert(format!("{}", e)))?;209 let value = bytes(p.value.to_vec());210 Ok(PropertyStruct { key, value })211 })212 .collect::<Result<Vec<_>>>()?;213 Ok(properties)214 }215216 /// Set the sponsor of the collection.217 ///218 /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.219 ///220 /// @param sponsor Address of the sponsor from whose account funds will be debited for operations with the contract.221 #[solidity(hide)]222 fn set_collection_sponsor(&mut self, caller: caller, sponsor: address) -> Result<void> {223 self.consume_store_reads_and_writes(1, 1)?;224225 check_is_owner_or_admin(caller, self)?;226227 let sponsor = T::CrossAccountId::from_eth(sponsor);228 self.set_sponsor(sponsor.as_sub().clone())229 .map_err(dispatch_to_evm::<T>)?;230 save(self)231 }232233 /// Set the sponsor of the collection.234 ///235 /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.236 ///237 /// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.238 fn set_collection_sponsor_cross(239 &mut self,240 caller: caller,241 sponsor: EthCrossAccount,242 ) -> Result<void> {243 self.consume_store_reads_and_writes(1, 1)?;244245 check_is_owner_or_admin(caller, self)?;246247 let sponsor = sponsor.into_sub_cross_account::<T>()?;248 self.set_sponsor(sponsor.as_sub().clone())249 .map_err(dispatch_to_evm::<T>)?;250 save(self)251 }252253 /// Whether there is a pending sponsor.254 fn has_collection_pending_sponsor(&self) -> Result<bool> {255 Ok(matches!(256 self.collection.sponsorship,257 SponsorshipState::Unconfirmed(_)258 ))259 }260261 /// Collection sponsorship confirmation.262 ///263 /// @dev After setting the sponsor for the collection, it must be confirmed with this function.264 fn confirm_collection_sponsorship(&mut self, caller: caller) -> Result<void> {265 self.consume_store_writes(1)?;266267 let caller = T::CrossAccountId::from_eth(caller);268 if !self269 .confirm_sponsorship(caller.as_sub())270 .map_err(dispatch_to_evm::<T>)?271 {272 return Err("caller is not set as sponsor".into());273 }274 save(self)275 }276277 /// Remove collection sponsor.278 fn remove_collection_sponsor(&mut self, caller: caller) -> Result<void> {279 self.consume_store_reads_and_writes(1, 1)?;280 check_is_owner_or_admin(caller, self)?;281 self.remove_sponsor().map_err(dispatch_to_evm::<T>)?;282 save(self)283 }284285 /// Get current sponsor.286 ///287 /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.288 fn collection_sponsor(&self) -> Result<(address, uint256)> {289 let sponsor = match self.collection.sponsorship.sponsor() {290 Some(sponsor) => sponsor,291 None => return Ok(Default::default()),292 };293 let sponsor = T::CrossAccountId::from_sub(sponsor.clone());294 let result: (address, uint256) = if sponsor.is_canonical_substrate() {295 let sponsor = convert_cross_account_to_uint256::<T>(&sponsor);296 (Default::default(), sponsor)297 } else {298 let sponsor = *sponsor.as_eth();299 (sponsor, Default::default())300 };301 Ok(result)302 }303304 /// Set limits for the collection.305 /// @dev Throws error if limit not found.306 /// @param limit Name of the limit. Valid names:307 /// "accountTokenOwnershipLimit",308 /// "sponsoredDataSize",309 /// "sponsoredDataRateLimit",310 /// "tokenLimit",311 /// "sponsorTransferTimeout",312 /// "sponsorApproveTimeout"313 /// "ownerCanTransfer",314 /// "ownerCanDestroy",315 /// "transfersEnabled"316 /// @param value Value of the limit.317 #[solidity(rename_selector = "setCollectionLimit")]318 fn set_int_limit(&mut self, caller: caller, limit: string, value: uint256) -> Result<void> {319 self.consume_store_reads_and_writes(1, 1)?;320321 let value = value322 .try_into()323 .map_err(|_| Error::Revert(format!("can't convert value to u32 \"{}\"", value)))?;324325 let convert_value_to_bool = || match value {326 0 => Ok(false),327 1 => Ok(true),328 _ => {329 return Err(Error::Revert(format!(330 "can't convert value to boolean \"{}\"",331 value332 )))333 }334 };335336 check_is_owner_or_admin(caller, self)?;337 let mut limits = self.limits.clone();338339 match limit.as_str() {340 "accountTokenOwnershipLimit" => {341 limits.account_token_ownership_limit = Some(value);342 }343 "sponsoredDataSize" => {344 limits.sponsored_data_size = Some(value);345 }346 "sponsoredDataRateLimit" => {347 limits.sponsored_data_rate_limit = Some(SponsoringRateLimit::Blocks(value));348 }349 "tokenLimit" => {350 limits.token_limit = Some(value);351 }352 "sponsorTransferTimeout" => {353 limits.sponsor_transfer_timeout = Some(value);354 }355 "sponsorApproveTimeout" => {356 limits.sponsor_approve_timeout = Some(value);357 }358 "ownerCanTransfer" => {359 limits.owner_can_transfer = Some(convert_value_to_bool()?);360 }361 "ownerCanDestroy" => {362 limits.owner_can_destroy = Some(convert_value_to_bool()?);363 }364 "transfersEnabled" => {365 limits.transfers_enabled = Some(convert_value_to_bool()?);366 }367 _ => return Err(Error::Revert(format!("unknown limit \"{}\"", limit))),368 }369 self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)370 .map_err(dispatch_to_evm::<T>)?;371 save(self)372 }373374 /// Get contract address.375 fn contract_address(&self) -> Result<address> {376 Ok(crate::eth::collection_id_to_address(self.id))377 }378379 /// Add collection admin.380 /// @param newAdmin Cross account administrator address.381 fn add_collection_admin_cross(382 &mut self,383 caller: caller,384 new_admin: EthCrossAccount,385 ) -> Result<void> {386 self.consume_store_writes(2)?;387388 let caller = T::CrossAccountId::from_eth(caller);389 let new_admin = new_admin.into_sub_cross_account::<T>()?;390 <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;391 Ok(())392 }393394 /// Remove collection admin.395 /// @param admin Cross account administrator address.396 fn remove_collection_admin_cross(397 &mut self,398 caller: caller,399 admin: EthCrossAccount,400 ) -> Result<void> {401 self.consume_store_writes(2)?;402403 let caller = T::CrossAccountId::from_eth(caller);404 let admin = admin.into_sub_cross_account::<T>()?;405 <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;406 Ok(())407 }408409 /// Add collection admin.410 /// @param newAdmin Address of the added administrator.411 #[solidity(hide)]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 /// Remove collection admin.422 ///423 /// @param admin Address of the removed administrator.424 #[solidity(hide)]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 /// Toggle accessibility of collection nesting.435 ///436 /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'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 /// Toggle accessibility of collection nesting.460 ///461 /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'462 /// @param collections Addresses of collections that will be available for nesting.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 /// Set the collection access method.511 /// @param mode Access mode512 /// 0 for Normal513 /// 1 for AllowList514 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 /// Checks that user allowed to operate with collection.537 ///538 /// @param user User address to check.539 fn allowlisted_cross(&self, user: EthCrossAccount) -> Result<bool> {540 let user = user.into_sub_cross_account::<T>()?;541 Ok(Pallet::<T>::allowed(self.id, user))542 }543544 /// Add the user to the allowed list.545 ///546 /// @param user Address of a trusted user.547 #[solidity(hide)]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 /// Add user to allowed list.558 ///559 /// @param user User cross account address.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 /// Remove the user from the allowed list.574 ///575 /// @param user Address of a removed user.576 #[solidity(hide)]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 /// Remove user from allowed list.587 ///588 /// @param user User cross account address.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 /// Switch permission for minting.603 ///604 /// @param mode Enable if "true".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 /// Check that account is the owner or admin of the collection624 ///625 /// @param user account to verify626 /// @return "true" if account is the owner or admin627 #[solidity(hide, 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 /// Check that account is the owner or admin of the collection634 ///635 /// @param user User cross account to verify636 /// @return "true" if account is the owner or admin637 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 /// Returns collection type643 ///644 /// @return `Fungible` or `NFT` or `ReFungible`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 /// Get collection owner.655 ///656 /// @return Tuble with sponsor address and his substrate mirror.657 /// If address is canonical then substrate mirror is zero and vice versa.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 /// Changes collection owner to another account665 ///666 /// @dev Owner can be changed only by current owner667 /// @param newOwner new owner account668 #[solidity(hide, 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 /// Get collection administrators679 ///680 /// @return Vector of tuples with admins address and his substrate mirror.681 /// If address is canonical then substrate mirror is zero and vice versa.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 /// Changes collection owner to another account690 ///691 /// @dev Owner can be changed only by current owner692 /// @param newOwner new owner cross account693 fn change_collection_owner_cross(694 &mut self,695 caller: caller,696 new_owner: EthCrossAccount,697 ) -> Result<void> {698 self.consume_store_writes(1)?;699700 let caller = T::CrossAccountId::from_eth(caller);701 let new_owner = new_owner.into_sub_cross_account::<T>()?;702 self.set_owner_internal(caller, new_owner)703 .map_err(dispatch_to_evm::<T>)704 }705}706707/// ### Note708/// Do not forget to add: `self.consume_store_reads(1)?;`709fn check_is_owner_or_admin<T: Config>(710 caller: caller,711 collection: &CollectionHandle<T>,712) -> Result<T::CrossAccountId> {713 let caller = T::CrossAccountId::from_eth(caller);714 collection715 .check_is_owner_or_admin(&caller)716 .map_err(dispatch_to_evm::<T>)?;717 Ok(caller)718}719720/// ### Note721/// Do not forget to add: `self.consume_store_writes(1)?;`722fn save<T: Config>(collection: &CollectionHandle<T>) -> Result<void> {723 collection724 .check_is_internal()725 .map_err(dispatch_to_evm::<T>)?;726 collection.save().map_err(dispatch_to_evm::<T>)?;727 Ok(())728}729730/// Contains static property keys and values.731pub mod static_property {732 use evm_coder::{733 execution::{Result, Error},734 };735 use alloc::format;736737 const EXPECT_CONVERT_ERROR: &str = "length < limit";738739 /// Keys.740 pub mod key {741 use super::*;742743 /// Key "baseURI".744 pub fn base_uri() -> up_data_structs::PropertyKey {745 property_key_from_bytes(b"baseURI").expect(EXPECT_CONVERT_ERROR)746 }747748 /// Key "url".749 pub fn url() -> up_data_structs::PropertyKey {750 property_key_from_bytes(b"URI").expect(EXPECT_CONVERT_ERROR)751 }752753 /// Key "suffix".754 pub fn suffix() -> up_data_structs::PropertyKey {755 property_key_from_bytes(b"URISuffix").expect(EXPECT_CONVERT_ERROR)756 }757758 /// Key "parentNft".759 pub fn parent_nft() -> up_data_structs::PropertyKey {760 property_key_from_bytes(b"parentNft").expect(EXPECT_CONVERT_ERROR)761 }762 }763764 /// Convert `byte` to [`PropertyKey`].765 pub fn property_key_from_bytes(bytes: &[u8]) -> Result<up_data_structs::PropertyKey> {766 bytes.to_vec().try_into().map_err(|_| {767 Error::Revert(format!(768 "Property key is too long. Max length is {}.",769 up_data_structs::PropertyKey::bound()770 ))771 })772 }773774 /// Convert `bytes` to [`PropertyValue`].775 pub fn property_value_from_bytes(bytes: &[u8]) -> Result<up_data_structs::PropertyValue> {776 bytes.to_vec().try_into().map_err(|_| {777 Error::Revert(format!(778 "Property key is too long. Max length is {}.",779 up_data_structs::PropertyKey::bound()780 ))781 })782 }783}pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -229,28 +229,111 @@
/// Unique collections allows sponsoring for certain actions.
/// This method allows you to set the sponsor of the collection.
/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].
- pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {
- self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);
- Ok(())
+ pub fn set_sponsor(
+ &mut self,
+ sender: &T::CrossAccountId,
+ sponsor: T::AccountId,
+ ) -> DispatchResult {
+ self.check_is_internal()?;
+ self.check_is_owner_or_admin(sender)?;
+
+ self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());
+
+ <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));
+ <PalletEvm<T>>::deposit_log(
+ erc::CollectionHelpersEvents::CollectionChanged {
+ collection_id: eth::collection_id_to_address(self.id),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
+
+ self.save()
+ }
+
+ /// Force set `sponsor`.
+ ///
+ /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation
+ /// from the `sponsor` is not required.
+ ///
+ /// # Arguments
+ ///
+ /// * `sender`: Caller's account.
+ /// * `sponsor`: ID of the account of the sponsor-to-be.
+ pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {
+ self.check_is_internal()?;
+
+ self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());
+
+ <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));
+ <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));
+ <PalletEvm<T>>::deposit_log(
+ erc::CollectionHelpersEvents::CollectionChanged {
+ collection_id: eth::collection_id_to_address(self.id),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
+
+ self.save()
}
/// Confirm sponsorship
///
/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.
/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].
- pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {
- if self.collection.sponsorship.pending_sponsor() != Some(sender) {
- return Ok(false);
- }
+ pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {
+ self.check_is_internal()?;
+ ensure!(
+ self.collection.sponsorship.pending_sponsor() == Some(sender),
+ Error::<T>::ConfirmUnsetSponsorFail
+ );
self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());
- Ok(true)
+
+ <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));
+ <PalletEvm<T>>::deposit_log(
+ erc::CollectionHelpersEvents::CollectionChanged {
+ collection_id: eth::collection_id_to_address(self.id),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
+
+ self.save()
}
/// Remove collection sponsor.
- pub fn remove_sponsor(&mut self) -> DispatchResult {
+ pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {
+ self.check_is_internal()?;
+ self.check_is_owner(sender)?;
+
+ self.collection.sponsorship = SponsorshipState::Disabled;
+
+ <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));
+ <PalletEvm<T>>::deposit_log(
+ erc::CollectionHelpersEvents::CollectionChanged {
+ collection_id: eth::collection_id_to_address(self.id),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
+ self.save()
+ }
+
+ /// Force remove `sponsor`.
+ ///
+ /// Differs from `remove_sponsor` in that
+ /// it doesn't require consent from the `owner` of the collection.
+ pub fn force_remove_sponsor(&mut self) -> DispatchResult {
+ self.check_is_internal()?;
+
self.collection.sponsorship = SponsorshipState::Disabled;
- Ok(())
+
+ <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));
+ <PalletEvm<T>>::deposit_log(
+ erc::CollectionHelpersEvents::CollectionChanged {
+ collection_id: eth::collection_id_to_address(self.id),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
+ self.save()
}
/// Checks that the collection was created with, and must be operated upon through **Unique API**.
@@ -328,13 +411,26 @@
/// Changes collection owner to another account
/// #### Store read/writes
/// 1 writes
- fn set_owner_internal(
+ pub fn change_owner(
&mut self,
caller: T::CrossAccountId,
new_owner: T::CrossAccountId,
) -> DispatchResult {
+ self.check_is_internal()?;
self.check_is_owner(&caller)?;
self.collection.owner = new_owner.as_sub().clone();
+
+ <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnedChanged(
+ self.id,
+ new_owner.as_sub().clone(),
+ ));
+ <PalletEvm<T>>::deposit_log(
+ erc::CollectionHelpersEvents::CollectionChanged {
+ collection_id: eth::collection_id_to_address(self.id),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
+
self.save()
}
}
@@ -527,6 +623,80 @@
/// The property permission that was set.
PropertyKey,
),
+
+ /// Address was added to the allow list.
+ AllowListAddressAdded(
+ /// ID of the affected collection.
+ CollectionId,
+ /// Address of the added account.
+ T::CrossAccountId,
+ ),
+
+ /// Address was removed from the allow list.
+ AllowListAddressRemoved(
+ /// ID of the affected collection.
+ CollectionId,
+ /// Address of the removed account.
+ T::CrossAccountId,
+ ),
+
+ /// Collection admin was added.
+ CollectionAdminAdded(
+ /// ID of the affected collection.
+ CollectionId,
+ /// Admin address.
+ T::CrossAccountId,
+ ),
+
+ /// Collection admin was removed.
+ CollectionAdminRemoved(
+ /// ID of the affected collection.
+ CollectionId,
+ /// Removed admin address.
+ T::CrossAccountId,
+ ),
+
+ /// Collection limits were set.
+ CollectionLimitSet(
+ /// ID of the affected collection.
+ CollectionId,
+ ),
+
+ /// Collection owned was changed.
+ CollectionOwnedChanged(
+ /// ID of the affected collection.
+ CollectionId,
+ /// New owner address.
+ T::AccountId,
+ ),
+
+ /// Collection permissions were set.
+ CollectionPermissionSet(
+ /// ID of the affected collection.
+ CollectionId,
+ ),
+
+ /// Collection sponsor was set.
+ CollectionSponsorSet(
+ /// ID of the affected collection.
+ CollectionId,
+ /// New sponsor address.
+ T::AccountId,
+ ),
+
+ /// New sponsor was confirm.
+ SponsorshipConfirmed(
+ /// ID of the affected collection.
+ CollectionId,
+ /// New sponsor address.
+ T::AccountId,
+ ),
+
+ /// Collection sponsor was removed.
+ CollectionSponsorRemoved(
+ /// ID of the affected collection.
+ CollectionId,
+ ),
}
#[pallet::error]
@@ -613,6 +783,12 @@
/// Tried to access an internal collection with an external API
CollectionIsInternal,
+
+ /// This address is not set as sponsor, use setCollectionSponsor first.
+ ConfirmUnsetSponsorFail,
+
+ /// The user is not an administrator.
+ UserIsNotAdmin,
}
/// Storage of the count of created collections. Essentially contains the last collection ID.
@@ -1363,27 +1539,47 @@
if allowed {
<Allowlist<T>>::insert((collection.id, user), true);
+ Self::deposit_event(Event::<T>::AllowListAddressAdded(
+ collection.id,
+ user.clone(),
+ ));
} else {
<Allowlist<T>>::remove((collection.id, user));
+ Self::deposit_event(Event::<T>::AllowListAddressRemoved(
+ collection.id,
+ user.clone(),
+ ));
}
+ <PalletEvm<T>>::deposit_log(
+ erc::CollectionHelpersEvents::CollectionChanged {
+ collection_id: eth::collection_id_to_address(collection.id),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
+
Ok(())
}
/// Toggle `user` participation in the `collection`'s admin list.
/// #### Store read/writes
- /// 2 writes
+ /// 2 reads, 2 writes
pub fn toggle_admin(
collection: &CollectionHandle<T>,
sender: &T::CrossAccountId,
user: &T::CrossAccountId,
admin: bool,
) -> DispatchResult {
+ collection.check_is_internal()?;
collection.check_is_owner(sender)?;
- let was_admin = <IsAdmin<T>>::get((collection.id, user));
- if was_admin == admin {
- return Ok(());
+ let is_admin = <IsAdmin<T>>::get((collection.id, user));
+ if is_admin == admin {
+ if admin {
+ return Ok(());
+ } else {
+ ensure!(false, Error::<T>::UserIsNotAdmin);
+ }
}
let amount = <AdminAmount<T>>::get(collection.id);
@@ -1400,16 +1596,56 @@
<AdminAmount<T>>::insert(collection.id, amount);
<IsAdmin<T>>::insert((collection.id, user), true);
+
+ Self::deposit_event(Event::<T>::CollectionAdminAdded(
+ collection.id,
+ user.clone(),
+ ));
} else {
<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));
<IsAdmin<T>>::remove((collection.id, user));
+
+ Self::deposit_event(Event::<T>::CollectionAdminRemoved(
+ collection.id,
+ user.clone(),
+ ));
}
+ <PalletEvm<T>>::deposit_log(
+ erc::CollectionHelpersEvents::CollectionChanged {
+ collection_id: eth::collection_id_to_address(collection.id),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
+
Ok(())
}
+ /// Update collection limits.
+ pub fn update_limits(
+ user: &T::CrossAccountId,
+ collection: &mut CollectionHandle<T>,
+ new_limit: CollectionLimits,
+ ) -> DispatchResult {
+ collection.check_is_internal()?;
+ collection.check_is_owner_or_admin(user)?;
+
+ collection.limits =
+ Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;
+
+ Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));
+ <PalletEvm<T>>::deposit_log(
+ erc::CollectionHelpersEvents::CollectionChanged {
+ collection_id: eth::collection_id_to_address(collection.id),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
+
+ collection.save()
+ }
+
/// Merge set fields from `new_limit` to `old_limit`.
- pub fn clamp_limits(
+ fn clamp_limits(
mode: CollectionMode,
old_limit: &CollectionLimits,
mut new_limit: CollectionLimits,
@@ -1454,8 +1690,33 @@
Ok(new_limit)
}
+ /// Update collection permissions.
+ pub fn update_permissions(
+ user: &T::CrossAccountId,
+ collection: &mut CollectionHandle<T>,
+ new_permission: CollectionPermissions,
+ ) -> DispatchResult {
+ collection.check_is_internal()?;
+ collection.check_is_owner_or_admin(user)?;
+ collection.permissions = Self::clamp_permissions(
+ collection.mode.clone(),
+ &collection.permissions,
+ new_permission,
+ )?;
+
+ Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));
+ <PalletEvm<T>>::deposit_log(
+ erc::CollectionHelpersEvents::CollectionChanged {
+ collection_id: eth::collection_id_to_address(collection.id),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
+
+ collection.save()
+ }
+
/// Merge set fields from `new_permission` to `old_permission`.
- pub fn clamp_permissions(
+ fn clamp_permissions(
_mode: CollectionMode,
old_permission: &CollectionPermissions,
mut new_permission: CollectionPermissions,
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -89,10 +89,9 @@
MAX_PROPERTIES_PER_ITEM, MAX_PROPERTY_KEY_LENGTH, MAX_PROPERTY_VALUE_LENGTH,
MAX_COLLECTION_PROPERTIES_SIZE, COLLECTION_ADMINS_LIMIT, MAX_TOKEN_PROPERTIES_SIZE,
CreateItemData, CollectionLimits, CollectionPermissions, CollectionId, CollectionMode, TokenId,
- SponsorshipState, CreateCollectionData, CreateItemExData, budget, Property, PropertyKey,
- PropertyKeyPermission,
+ CreateCollectionData, CreateItemExData, budget, Property, PropertyKey, PropertyKeyPermission,
};
-use pallet_evm::account::CrossAccountId;
+use pallet_evm::{account::CrossAccountId};
use pallet_common::{
CollectionHandle, Pallet as PalletCommon, CommonWeightInfo, dispatch::dispatch_tx,
dispatch::CollectionDispatch, RefungibleExtensionsWeightInfo,
@@ -112,8 +111,6 @@
pub enum Error for Module<T: Config> {
/// Decimal_points parameter must be lower than [`up_data_structs::MAX_DECIMAL_POINTS`].
CollectionDecimalPointLimitExceeded,
- /// This address is not set as sponsor, use setCollectionSponsor first.
- ConfirmUnsetSponsorFail,
/// Length of items properties must be greater than 0.
EmptyArgument,
/// Repertition is only supported by refungible collection.
@@ -140,27 +137,12 @@
pub enum Event<T>
where
<T as frame_system::Config>::AccountId,
- <T as pallet_evm::Config>::CrossAccountId,
{
/// Collection sponsor was removed
///
/// # Arguments
/// * collection_id: ID of the affected collection.
CollectionSponsorRemoved(CollectionId),
-
- /// Collection admin was added
- ///
- /// # Arguments
- /// * collection_id: ID of the affected collection.
- /// * admin: Admin address.
- CollectionAdminAdded(CollectionId, CrossAccountId),
-
- /// Collection owned was changed
- ///
- /// # Arguments
- /// * collection_id: ID of the affected collection.
- /// * owner: New owner address.
- CollectionOwnedChanged(CollectionId, AccountId),
/// Collection sponsor was set
///
@@ -168,46 +150,7 @@
/// * collection_id: ID of the affected collection.
/// * owner: New sponsor address.
CollectionSponsorSet(CollectionId, AccountId),
-
- /// New sponsor was confirm
- ///
- /// # Arguments
- /// * collection_id: ID of the affected collection.
- /// * sponsor: New sponsor address.
- SponsorshipConfirmed(CollectionId, AccountId),
-
- /// Collection admin was removed
- ///
- /// # Arguments
- /// * collection_id: ID of the affected collection.
- /// * admin: Removed admin address.
- CollectionAdminRemoved(CollectionId, CrossAccountId),
- /// Address was removed from the allow list
- ///
- /// # Arguments
- /// * collection_id: ID of the affected collection.
- /// * user: Address of the removed account.
- AllowListAddressRemoved(CollectionId, CrossAccountId),
-
- /// Address was added to the allow list
- ///
- /// # Arguments
- /// * collection_id: ID of the affected collection.
- /// * user: Address of the added account.
- AllowListAddressAdded(CollectionId, CrossAccountId),
-
- /// Collection limits were set
- ///
- /// # Arguments
- /// * collection_id: ID of the affected collection.
- CollectionLimitSet(CollectionId),
-
- /// Collection permissions were set
- ///
- /// # Arguments
- /// * collection_id: ID of the affected collection.
- CollectionPermissionSet(CollectionId),
}
}
@@ -432,11 +375,6 @@
&address,
true,
)?;
-
- Self::deposit_event(Event::<T>::AllowListAddressAdded(
- collection_id,
- address
- ));
Ok(())
}
@@ -466,11 +404,6 @@
false,
)?;
- <Pallet<T>>::deposit_event(Event::<T>::AllowListAddressRemoved(
- collection_id,
- address
- ));
-
Ok(())
}
@@ -486,20 +419,10 @@
/// * `new_owner`: ID of the account that will become the owner.
#[weight = <SelfWeightOf<T>>::change_collection_owner()]
pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {
-
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
+ let new_owner = T::CrossAccountId::from_sub(new_owner);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.check_is_internal()?;
- target_collection.check_is_owner(&sender)?;
-
- target_collection.owner = new_owner.clone();
- <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnedChanged(
- collection_id,
- new_owner
- ));
-
- target_collection.save()
+ target_collection.change_owner(sender, new_owner.clone())
}
/// Add an admin to a collection.
@@ -522,13 +445,6 @@
pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let collection = <CollectionHandle<T>>::try_get(collection_id)?;
- collection.check_is_internal()?;
-
- <Pallet<T>>::deposit_event(Event::<T>::CollectionAdminAdded(
- collection_id,
- new_admin_id.clone()
- ));
-
<PalletCommon<T>>::toggle_admin(&collection, &sender, &new_admin_id, true)
}
@@ -550,13 +466,6 @@
pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let collection = <CollectionHandle<T>>::try_get(collection_id)?;
- collection.check_is_internal()?;
-
- <Pallet<T>>::deposit_event(Event::<T>::CollectionAdminRemoved(
- collection_id,
- account_id.clone()
- ));
-
<PalletCommon<T>>::toggle_admin(&collection, &sender, &account_id, false)
}
@@ -576,19 +485,8 @@
#[weight = <SelfWeightOf<T>>::set_collection_sponsor()]
pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.check_is_owner_or_admin(&sender)?;
- target_collection.check_is_internal()?;
-
- target_collection.set_sponsor(new_sponsor.clone())?;
-
- <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(
- collection_id,
- new_sponsor
- ));
-
- target_collection.save()
+ target_collection.set_sponsor(&sender, new_sponsor.clone())
}
/// Confirm own sponsorship of a collection, becoming the sponsor.
@@ -607,20 +505,8 @@
#[weight = <SelfWeightOf<T>>::confirm_sponsorship()]
pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {
let sender = ensure_signed(origin)?;
-
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.check_is_internal()?;
- ensure!(
- target_collection.confirm_sponsorship(&sender)?,
- Error::<T>::ConfirmUnsetSponsorFail
- );
-
- <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(
- collection_id,
- sender
- ));
-
- target_collection.save()
+ target_collection.confirm_sponsorship(&sender)
}
/// Remove a collection's a sponsor, making everyone pay for their own transactions.
@@ -635,17 +521,8 @@
#[weight = <SelfWeightOf<T>>::remove_collection_sponsor()]
pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.check_is_internal()?;
- target_collection.check_is_owner(&sender)?;
-
- target_collection.sponsorship = SponsorshipState::Disabled;
-
- <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(
- collection_id
- ));
- target_collection.save()
+ target_collection.remove_sponsor(&sender)
}
/// Mint an item within a collection.
@@ -1053,17 +930,7 @@
) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.check_is_internal()?;
- target_collection.check_is_owner_or_admin(&sender)?;
- let old_limit = &target_collection.limits;
-
- target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;
-
- <Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(
- collection_id
- ));
-
- target_collection.save()
+ <PalletCommon<T>>::update_limits(&sender, &mut target_collection, new_limit)
}
/// Set specific permissions of a collection. Empty, or None fields mean chain default.
@@ -1086,17 +953,11 @@
) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.check_is_internal()?;
- target_collection.check_is_owner_or_admin(&sender)?;
- let old_limit = &target_collection.permissions;
-
- target_collection.permissions = <PalletCommon<T>>::clamp_permissions(target_collection.mode.clone(), &old_limit, new_permission)?;
-
- <Pallet<T>>::deposit_event(Event::<T>::CollectionPermissionSet(
- collection_id
- ));
-
- target_collection.save()
+ <PalletCommon<T>>::update_permissions(
+ &sender,
+ &mut target_collection,
+ new_permission
+ )
}
/// Re-partition a refungible token, while owning all of its parts/pieces.
@@ -1163,22 +1024,7 @@
/// * `collection_id`: ID of the modified collection.
pub fn force_set_sponsor(sponsor: T::AccountId, collection_id: CollectionId) -> DispatchResult {
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.check_is_internal()?;
- target_collection.set_sponsor(sponsor.clone())?;
-
- Self::deposit_event(Event::<T>::CollectionSponsorSet(
- collection_id,
- sponsor.clone(),
- ));
-
- ensure!(
- target_collection.confirm_sponsorship(&sponsor)?,
- Error::<T>::ConfirmUnsetSponsorFail
- );
-
- Self::deposit_event(Event::<T>::SponsorshipConfirmed(collection_id, sponsor));
-
- target_collection.save()
+ target_collection.force_set_sponsor(sponsor.clone())
}
/// Force remove `sponsor` for `collection`.
@@ -1191,12 +1037,7 @@
/// * `collection_id`: ID of the modified collection.
pub fn force_remove_collection_sponsor(collection_id: CollectionId) -> DispatchResult {
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.check_is_internal()?;
- target_collection.sponsorship = SponsorshipState::Disabled;
-
- Self::deposit_event(Event::<T>::CollectionSponsorRemoved(collection_id));
-
- target_collection.save()
+ target_collection.force_remove_sponsor()
}
#[inline(always)]
tests/src/change-collection-owner.test.tsdiffbeforeafterboth--- a/tests/src/change-collection-owner.test.ts
+++ b/tests/src/change-collection-owner.test.ts
@@ -146,7 +146,7 @@
const confirmSponsorshipTx = () => collection.confirmSponsorship(alice);
const removeSponsorTx = () => collection.removeSponsor(alice);
await expect(setSponsorTx()).to.be.rejectedWith(/common\.NoPermission/);
- await expect(confirmSponsorshipTx()).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+ await expect(confirmSponsorshipTx()).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
await expect(removeSponsorTx()).to.be.rejectedWith(/common\.NoPermission/);
const limits = {
tests/src/confirmSponsorship.test.tsdiffbeforeafterboth--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -207,14 +207,14 @@
const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
await collection.setSponsor(alice, bob.address);
const confirmSponsorshipTx = () => collection.confirmSponsorship(charlie);
- await expect(confirmSponsorshipTx()).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+ await expect(confirmSponsorshipTx()).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
});
itSub('(!negative test!) Confirm sponsorship using owner address', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
await collection.setSponsor(alice, bob.address);
const confirmSponsorshipTx = () => collection.confirmSponsorship(alice);
- await expect(confirmSponsorshipTx()).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+ await expect(confirmSponsorshipTx()).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
});
itSub('(!negative test!) Confirm sponsorship by collection admin', async ({helper}) => {
@@ -222,13 +222,13 @@
await collection.setSponsor(alice, bob.address);
await collection.addAdmin(alice, {Substrate: charlie.address});
const confirmSponsorshipTx = () => collection.confirmSponsorship(charlie);
- await expect(confirmSponsorshipTx()).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+ await expect(confirmSponsorshipTx()).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
});
itSub('(!negative test!) Confirm sponsorship without sponsor being set with setCollectionSponsor', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
const confirmSponsorshipTx = () => collection.confirmSponsorship(charlie);
- await expect(confirmSponsorshipTx()).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+ await expect(confirmSponsorshipTx()).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
});
itSub('(!negative test!) Confirm sponsorship in a collection that was destroyed', async ({helper}) => {
tests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -258,7 +258,7 @@
await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsor : sponsorCross).send();
let collectionData = (await collectionSub.getData())!;
expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
- await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+ await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
collectionData = (await collectionSub.getData())!;
tests/src/eth/createFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createFTCollection.test.ts
+++ b/tests/src/eth/createFTCollection.test.ts
@@ -46,7 +46,7 @@
let data = (await helper.rft.getData(collectionId))!;
expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
- await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+ await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor, true);
await sponsorCollection.methods.confirmCollectionSponsorship().send();
@@ -69,7 +69,7 @@
let data = (await helper.rft.getData(collectionId))!;
expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
- await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+ await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor);
await sponsorCollection.methods.confirmCollectionSponsorship().send();
@@ -192,11 +192,11 @@
const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'ft', sponsor, true);
await expect(sponsorCollection.methods
.confirmCollectionSponsorship()
- .call()).to.be.rejectedWith('caller is not set as sponsor');
+ .call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
}
{
await expect(peasantCollection.methods
- .setCollectionLimit('account_token_ownership_limit', '1000')
+ .setCollectionLimit('accountTokenOwnershipLimit', '1000')
.call()).to.be.rejectedWith(EXPECTED_ERROR);
}
});
@@ -217,11 +217,11 @@
const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'ft', sponsor);
await expect(sponsorCollection.methods
.confirmCollectionSponsorship()
- .call()).to.be.rejectedWith('caller is not set as sponsor');
+ .call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
}
{
await expect(peasantCollection.methods
- .setCollectionLimit('account_token_ownership_limit', '1000')
+ .setCollectionLimit('accountTokenOwnershipLimit', '1000')
.call()).to.be.rejectedWith(EXPECTED_ERROR);
}
});
tests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -86,7 +86,7 @@
let data = (await helper.nft.getData(collectionId))!;
expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
- await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+ await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', sponsor, true);
await sponsorCollection.methods.confirmCollectionSponsorship().send();
@@ -109,7 +109,7 @@
let data = (await helper.nft.getData(collectionId))!;
expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
- await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+ await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', sponsor);
await sponsorCollection.methods.confirmCollectionSponsorship().send();
@@ -203,11 +203,11 @@
const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', sponsor, true);
await expect(sponsorCollection.methods
.confirmCollectionSponsorship()
- .call()).to.be.rejectedWith('caller is not set as sponsor');
+ .call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
}
{
await expect(malfeasantCollection.methods
- .setCollectionLimit('account_token_ownership_limit', '1000')
+ .setCollectionLimit('accountTokenOwnershipLimit', '1000')
.call()).to.be.rejectedWith(EXPECTED_ERROR);
}
});
@@ -228,11 +228,11 @@
const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', sponsor);
await expect(sponsorCollection.methods
.confirmCollectionSponsorship()
- .call()).to.be.rejectedWith('caller is not set as sponsor');
+ .call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
}
{
await expect(malfeasantCollection.methods
- .setCollectionLimit('account_token_ownership_limit', '1000')
+ .setCollectionLimit('accountTokenOwnershipLimit', '1000')
.call()).to.be.rejectedWith(EXPECTED_ERROR);
}
});
tests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -121,7 +121,7 @@
let data = (await helper.rft.getData(collectionId))!;
expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
- await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+ await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor, true);
await sponsorCollection.methods.confirmCollectionSponsorship().send();
@@ -143,7 +143,7 @@
let data = (await helper.rft.getData(collectionId))!;
expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
- await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+ await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor);
await sponsorCollection.methods.confirmCollectionSponsorship().send();
@@ -235,11 +235,11 @@
const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor, true);
await expect(sponsorCollection.methods
.confirmCollectionSponsorship()
- .call()).to.be.rejectedWith('caller is not set as sponsor');
+ .call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
}
{
await expect(peasantCollection.methods
- .setCollectionLimit('account_token_ownership_limit', '1000')
+ .setCollectionLimit('accountTokenOwnershipLimit', '1000')
.call()).to.be.rejectedWith(EXPECTED_ERROR);
}
});
@@ -260,11 +260,11 @@
const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor);
await expect(sponsorCollection.methods
.confirmCollectionSponsorship()
- .call()).to.be.rejectedWith('caller is not set as sponsor');
+ .call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
}
{
await expect(peasantCollection.methods
- .setCollectionLimit('account_token_ownership_limit', '1000')
+ .setCollectionLimit('accountTokenOwnershipLimit', '1000')
.call()).to.be.rejectedWith(EXPECTED_ERROR);
}
});
tests/src/eth/events.test.tsdiffbeforeafterboth--- a/tests/src/eth/events.test.ts
+++ b/tests/src/eth/events.test.ts
@@ -14,11 +14,11 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+import { expect } from 'chai';
import {IKeyringPair} from '@polkadot/types/types';
-import { expect } from 'chai';
import { itEth, usingEthPlaygrounds } from './util';
-describe.only('NFT events', () => {
+describe('NFT events', () => {
let donor: IKeyringPair;
before(async function () {
@@ -29,8 +29,9 @@
itEth('Create event', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, events} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
- expect(events).to.be.like([
+ const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionCreated']}]);
+ const {collectionAddress, events: ethEvents} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+ expect(ethEvents).to.be.like([
{
event: 'CollectionCreated',
args: {
@@ -39,20 +40,25 @@
}
}
]);
+ expect(subEvents).to.be.like([{method: 'CollectionCreated'}]);
+ unsubscribe();
});
itEth('Destroy event', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- let resutl = await collectionHelper.methods.destroyCollection(collectionAddress).send({from:owner});
- expect(resutl.events).to.be.like({
+ const {unsubscribe, collectedEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionDestroyed']}]);
+ let result = await collectionHelper.methods.destroyCollection(collectionAddress).send({from:owner});
+ expect(result.events).to.be.like({
CollectionDestroyed: {
returnValues: {
collectionId: collectionAddress
}
}
});
+ expect(collectedEvents).to.be.like([{method: 'CollectionDestroyed'}]);
+ unsubscribe();
});
itEth('CollectionChanged event for CollectionPropertySet and CollectionPropertyDeleted', async ({helper}) => {
@@ -61,13 +67,14 @@
const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+ let {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionPropertySet', 'CollectionPropertyDeleted']}]);
{
- const events: any = [];
+ const ethEvents: any = [];
collectionHelper.events.allEvents((_: any, event: any) => {
- events.push(event);
+ ethEvents.push(event);
});
await collection.methods.setCollectionProperties([{key: 'A', value: [0,1,2,3]}]).send({from:owner});
- expect(events).to.be.like([
+ expect(ethEvents).to.be.like([
{
event: 'CollectionChanged',
returnValues: {
@@ -75,14 +82,16 @@
}
}
]);
+ expect(subEvents).to.be.like([{method: 'CollectionPropertySet'}]);
+ subEvents.pop();
}
{
- const events: any = [];
+ const ethEvents: any = [];
collectionHelper.events.allEvents((_: any, event: any) => {
- events.push(event);
+ ethEvents.push(event);
});
await collection.methods.deleteCollectionProperties(['A']).send({from:owner});
- expect(events).to.be.like([
+ expect(ethEvents).to.be.like([
{
event: 'CollectionChanged',
returnValues: {
@@ -90,8 +99,9 @@
}
}
]);
+ expect(subEvents).to.be.like([{method: 'CollectionPropertyDeleted'}]);
}
-
+ unsubscribe();
});
itEth('CollectionChanged event for PropertyPermissionSet', async ({helper}) => {
@@ -99,12 +109,13 @@
const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- const events: any = [];
+ const eethEvents: any = [];
collectionHelper.events.allEvents((_: any, event: any) => {
- events.push(event);
+ eethEvents.push(event);
});
+ const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['PropertyPermissionSet']}]);
await collection.methods.setTokenPropertyPermission('testKey', true, true, true).send({from: owner});
- expect(events).to.be.like([
+ expect(eethEvents).to.be.like([
{
event: 'CollectionChanged',
returnValues: {
@@ -112,28 +123,236 @@
}
}
]);
+ expect(subEvents).to.be.like([{method: 'PropertyPermissionSet'}]);
+ unsubscribe();
+ });
+
+ itEth('CollectionChanged event for AllowListAddressAdded, AllowListAddressRemoved', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const user = helper.ethCrossAccount.createAccount();
+ const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+ const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+ const ethEvents: any[] = [];
+ collectionHelper.events.allEvents((_: any, event: any) => {
+ ethEvents.push(event);
+ });
+
+ const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['AllowListAddressAdded', 'AllowListAddressRemoved']}]);
+ {
+ await collection.methods.addToCollectionAllowListCross(user).send({from: owner});
+ expect(ethEvents).to.be.like([
+ {
+ event: 'CollectionChanged',
+ returnValues: {
+ collectionId: collectionAddress
+ }
+ }
+ ]);
+ expect(subEvents).to.be.like([{method: 'AllowListAddressAdded'}]);
+ ethEvents.pop();
+ subEvents.pop();
+ }
+ {
+ await collection.methods.removeFromCollectionAllowListCross(user).send({from: owner});
+ expect(ethEvents.length).to.be.eq(1);
+ expect(ethEvents).to.be.like([
+ {
+ event: 'CollectionChanged',
+ returnValues: {
+ collectionId: collectionAddress
+ }
+ }
+ ]);
+ expect(subEvents).to.be.like([{method: 'AllowListAddressRemoved'}]);
+ }
+ unsubscribe();
});
- // itEth('CollectionChanged event for AllowListAddressAdded', async ({helper}) => {
- // const owner = await helper.eth.createAccountWithBalance(donor);
- // const user = await helper.eth.createAccount();
- // const userCross = helper.ethCrossAccount.fromAddress(user);
- // const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- // // allow list does not need to be enabled to add someone in advance
- // const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- // const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- // const events: any = [];
- // collectionHelper.events.allEvents((_: any, event: any) => {
- // events.push(event);
- // });
- // await helper.nft.addToAllowList(alice, collectionId, {Substrate: bob.address});
- // expect(events).to.be.like([
- // {
- // event: 'CollectionChanged',
- // returnValues: {
- // collectionId: collectionAddress
- // }
- // }
- // ]);
- // });
+ itEth('CollectionChanged event for CollectionAdminAdded, CollectionAdminRemoved', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const user = helper.ethCrossAccount.createAccount();
+ const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+ const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+ const ethEvents: any = [];
+ collectionHelper.events.allEvents((_: any, event: any) => {
+ ethEvents.push(event);
+ });
+ const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionAdminAdded', 'CollectionAdminRemoved']}]);
+ {
+ await collection.methods.addCollectionAdminCross(user).send({from: owner});
+ expect(ethEvents).to.be.like([
+ {
+ event: 'CollectionChanged',
+ returnValues: {
+ collectionId: collectionAddress
+ }
+ }
+ ]);
+ expect(subEvents).to.be.like([{method: 'CollectionAdminAdded'}]);
+ ethEvents.pop();
+ subEvents.pop();
+ }
+ {
+ await collection.methods.removeCollectionAdminCross(user).send({from: owner});
+ expect(ethEvents).to.be.like([
+ {
+ event: 'CollectionChanged',
+ returnValues: {
+ collectionId: collectionAddress
+ }
+ }
+ ]);
+ expect(subEvents).to.be.like([{method: 'CollectionAdminRemoved'}]);
+ }
+ unsubscribe();
+ });
+
+ itEth('CollectionChanged event for CollectionLimitSet', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+ const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+ const ethEvents: any = [];
+ collectionHelper.events.allEvents((_: any, event: any) => {
+ ethEvents.push(event);
+ });
+ const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionLimitSet']}]);
+ {
+ await collection.methods.setCollectionLimit('ownerCanTransfer', 0n).send({from: owner});
+ expect(ethEvents).to.be.like([
+ {
+ event: 'CollectionChanged',
+ returnValues: {
+ collectionId: collectionAddress
+ }
+ }
+ ]);
+ expect(subEvents).to.be.like([{method: 'CollectionLimitSet'}]);
+ }
+ unsubscribe();
+ });
+
+ itEth('CollectionChanged event for CollectionOwnedChanged', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const new_owner = helper.ethCrossAccount.createAccount();
+ const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+ const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+ const ethEvents: any = [];
+ collectionHelper.events.allEvents((_: any, event: any) => {
+ ethEvents.push(event);
+ });
+ const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionOwnedChanged']}]);
+ {
+ await collection.methods.changeCollectionOwnerCross(new_owner).send({from: owner});
+ expect(ethEvents).to.be.like([
+ {
+ event: 'CollectionChanged',
+ returnValues: {
+ collectionId: collectionAddress
+ }
+ }
+ ]);
+ expect(subEvents).to.be.like([{method: 'CollectionOwnedChanged'}]);
+ }
+ unsubscribe();
+ });
+
+ itEth('CollectionChanged event for CollectionPermissionSet', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+ const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+ const ethEvents: any = [];
+ collectionHelper.events.allEvents((_: any, event: any) => {
+ ethEvents.push(event);
+ });
+ const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionPermissionSet']}]);
+ {
+ await collection.methods.setCollectionMintMode(true).send({from: owner});
+ expect(ethEvents).to.be.like([
+ {
+ event: 'CollectionChanged',
+ returnValues: {
+ collectionId: collectionAddress
+ }
+ }
+ ]);
+ expect(subEvents).to.be.like([{method: 'CollectionPermissionSet'}]);
+ ethEvents.pop();
+ subEvents.pop();
+ }
+ {
+ await collection.methods.setCollectionAccess(1).send({from: owner});
+ expect(ethEvents).to.be.like([
+ {
+ event: 'CollectionChanged',
+ returnValues: {
+ collectionId: collectionAddress
+ }
+ }
+ ]);
+ expect(subEvents).to.be.like([{method: 'CollectionPermissionSet'}]);
+ }
+ unsubscribe();
+ });
+
+ itEth('CollectionChanged event for CollectionSponsorSet, SponsorshipConfirmed, CollectionSponsorRemoved', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.ethCrossAccount.createAccountWithBalance(donor);
+ const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+ const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+ const ethEvents: any = [];
+ collectionHelper.events.allEvents((_: any, event: any) => {
+ ethEvents.push(event);
+ });
+ const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{
+ section: 'common', names: ['CollectionSponsorSet', 'SponsorshipConfirmed', 'CollectionSponsorRemoved'
+ ]}]);
+ {
+ await collection.methods.setCollectionSponsorCross(sponsor).send({from: owner});
+ expect(ethEvents).to.be.like([
+ {
+ event: 'CollectionChanged',
+ returnValues: {
+ collectionId: collectionAddress
+ }
+ }
+ ]);
+ expect(subEvents).to.be.like([{method: 'CollectionSponsorSet'}]);
+ ethEvents.pop();
+ subEvents.pop();
+ }
+ {
+ await collection.methods.confirmCollectionSponsorship().send({from: sponsor.eth});
+ expect(ethEvents).to.be.like([
+ {
+ event: 'CollectionChanged',
+ returnValues: {
+ collectionId: collectionAddress
+ }
+ }
+ ]);
+ expect(subEvents).to.be.like([{method: 'SponsorshipConfirmed'}]);
+ ethEvents.pop();
+ subEvents.pop();
+ }
+ {
+ await collection.methods.removeCollectionSponsor().send({from: owner});
+ expect(ethEvents).to.be.like([
+ {
+ event: 'CollectionChanged',
+ returnValues: {
+ collectionId: collectionAddress
+ }
+ }
+ ]);
+ expect(subEvents).to.be.like([{method: 'CollectionSponsorRemoved'}]);
+ }
+ unsubscribe();
+ });
+
});
\ No newline at end of file
tests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionAdmin.test.ts
+++ b/tests/src/removeCollectionAdmin.test.ts
@@ -51,7 +51,7 @@
const adminListBeforeAddAdmin = await collection.getAdmins();
expect(adminListBeforeAddAdmin).to.have.lengthOf(0);
- await collection.removeAdmin(alice, {Substrate: alice.address});
+ await expect(collection.removeAdmin(alice, {Substrate: alice.address})).to.be.rejectedWith('common.UserIsNotAdmin');
});
});
tests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionSponsor.test.ts
+++ b/tests/src/removeCollectionSponsor.test.ts
@@ -112,7 +112,7 @@
const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionSponsor-Neg-4', tokenPrefix: 'RCS'});
await collection.setSponsor(alice, bob.address);
await collection.removeSponsor(alice);
- await expect(collection.confirmSponsorship(bob)).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+ await expect(collection.confirmSponsorship(bob)).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
});
itSub('Set - confirm - remove - confirm: Sponsor cannot come back', async ({helper}) => {
@@ -120,6 +120,6 @@
await collection.setSponsor(alice, bob.address);
await collection.confirmSponsorship(bob);
await collection.removeSponsor(alice);
- await expect(collection.confirmSponsorship(bob)).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+ await expect(collection.confirmSponsorship(bob)).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
});
});
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -43,6 +43,8 @@
IEthCrossAccountId,
} from './types';
import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';
+import type {Vec} from '@polkadot/types-codec';
+import { FrameSystemEventRecord } from '@polkadot/types/lookup';
export class CrossAccountId implements ICrossAccountId {
Substrate?: TSubstrateAccount;
@@ -404,6 +406,21 @@
return this.api;
}
+ async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {
+ const collectedEvents: IEvent[] = [];
+ const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {
+ const ievents = this.eventHelper.extractEvents(events);
+ ievents.forEach((event) => {
+ expectedEvents.forEach((e => {
+ if (event.section === e.section && e.names.includes(event.method)) {
+ collectedEvents.push(event);
+ }
+ }))
+ });
+ });
+ return {unsubscribe: unsubscribe as any, collectedEvents};
+}
+
clearChainLog(): void {
this.chainLog = [];
}
@@ -834,7 +851,7 @@
true,
);
- return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');
+ return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');
}
/**
@@ -852,7 +869,7 @@
true,
);
- return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');
+ return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');
}
/**
@@ -870,7 +887,7 @@
true,
);
- return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');
+ return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');
}
/**
@@ -897,7 +914,7 @@
true,
);
- return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');
+ return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');
}
/**
@@ -916,7 +933,7 @@
true,
);
- return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');
+ return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnedChanged');
}
/**
@@ -935,7 +952,7 @@
true,
);
- return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');
+ return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');
}
/**
@@ -954,7 +971,7 @@
true,
);
- return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');
+ return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');
}
/**
@@ -983,7 +1000,7 @@
true,
);
- return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');
+ return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');
}
/**
@@ -1001,7 +1018,7 @@
true,
);
- return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');
+ return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');
}
/**
@@ -1020,7 +1037,7 @@
true,
);
- return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');
+ return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');
}
/**