difftreelog
Merge branch 'develop' into tests/eth-helpers
in: master
59 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2274,7 +2274,7 @@
"hash256-std-hasher",
"rlp",
"rlp-derive",
- "sha3",
+ "sha3 0.10.6",
"triehash",
]
@@ -2292,7 +2292,7 @@
"rlp",
"scale-info",
"serde",
- "sha3",
+ "sha3 0.10.6",
"triehash",
]
@@ -2350,7 +2350,7 @@
"rlp",
"scale-info",
"serde",
- "sha3",
+ "sha3 0.10.6",
]
[[package]]
@@ -2380,7 +2380,7 @@
"hex",
"proc-macro2",
"quote",
- "sha3",
+ "sha3 0.10.6",
"syn",
]
@@ -2415,7 +2415,7 @@
"environmental",
"evm-core",
"primitive-types 0.12.1",
- "sha3",
+ "sha3 0.10.6",
]
[[package]]
@@ -4958,7 +4958,7 @@
"digest 0.10.6",
"multihash-derive",
"sha2 0.10.6",
- "sha3",
+ "sha3 0.10.6",
"unsigned-varint",
]
@@ -5280,6 +5280,7 @@
"cumulus-primitives-utility",
"derivative",
"evm-coder",
+ "fp-evm",
"fp-evm-mapping",
"fp-rpc",
"fp-self-contained",
@@ -5294,6 +5295,7 @@
"impl-trait-for-tuples",
"log",
"logtest",
+ "num_enum",
"orml-tokens",
"orml-traits",
"orml-vesting",
@@ -5309,6 +5311,7 @@
"pallet-evm-coder-substrate",
"pallet-evm-contract-helpers",
"pallet-evm-migration",
+ "pallet-evm-precompile-simple",
"pallet-evm-transaction-payment",
"pallet-foreign-assets",
"pallet-fungible",
@@ -5333,6 +5336,7 @@
"parachain-info",
"parity-scale-codec 3.2.1",
"polkadot-parachain",
+ "precompile-utils-macro",
"rmrk-rpc",
"scale-info",
"serde",
@@ -6005,6 +6009,16 @@
]
[[package]]
+name = "pallet-evm-precompile-simple"
+version = "2.0.0-dev"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.33#c37ced433a29baad45899d6ab364fe437f97570e"
+dependencies = [
+ "fp-evm",
+ "ripemd",
+ "sp-io",
+]
+
+[[package]]
name = "pallet-evm-transaction-payment"
version = "0.1.1"
dependencies = [
@@ -6328,7 +6342,7 @@
[[package]]
name = "pallet-nonfungible"
-version = "0.1.9"
+version = "0.1.11"
dependencies = [
"ethereum 0.14.0",
"evm-coder",
@@ -6487,7 +6501,7 @@
[[package]]
name = "pallet-refungible"
-version = "0.2.8"
+version = "0.2.10"
dependencies = [
"derivative",
"ethereum 0.14.0",
@@ -8595,6 +8609,17 @@
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
+name = "precompile-utils-macro"
+version = "0.1.0"
+dependencies = [
+ "num_enum",
+ "proc-macro2",
+ "quote",
+ "sha3 0.8.2",
+ "syn",
+]
+
+[[package]]
name = "predicates"
version = "2.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -8850,6 +8875,7 @@
"cumulus-primitives-utility",
"derivative",
"evm-coder",
+ "fp-evm",
"fp-evm-mapping",
"fp-rpc",
"fp-self-contained",
@@ -8864,6 +8890,7 @@
"impl-trait-for-tuples",
"log",
"logtest",
+ "num_enum",
"orml-tokens",
"orml-traits",
"orml-vesting",
@@ -8879,6 +8906,7 @@
"pallet-evm-coder-substrate",
"pallet-evm-contract-helpers",
"pallet-evm-migration",
+ "pallet-evm-precompile-simple",
"pallet-evm-transaction-payment",
"pallet-foreign-assets",
"pallet-fungible",
@@ -8901,6 +8929,7 @@
"parachain-info",
"parity-scale-codec 3.2.1",
"polkadot-parachain",
+ "precompile-utils-macro",
"rmrk-rpc",
"scale-info",
"serde",
@@ -9249,6 +9278,15 @@
]
[[package]]
+name = "ripemd"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f"
+dependencies = [
+ "digest 0.10.6",
+]
+
+[[package]]
name = "rlp"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -10961,6 +10999,19 @@
[[package]]
name = "sha3"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd26bc0e7a2e3a7c959bc494caf58b72ee0c71d67704e9520f736ca7e4853ecf"
+dependencies = [
+ "block-buffer 0.7.3",
+ "byte-tools",
+ "digest 0.8.1",
+ "keccak",
+ "opaque-debug 0.2.3",
+]
+
+[[package]]
+name = "sha3"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdf0c33fae925bdc080598b84bc15c55e7b9a4a43b3c704da051f977469691c9"
@@ -11396,7 +11447,7 @@
"byteorder",
"digest 0.10.6",
"sha2 0.10.6",
- "sha3",
+ "sha3 0.10.6",
"sp-std",
"twox-hash",
]
@@ -13026,6 +13077,7 @@
"cumulus-primitives-utility",
"derivative",
"evm-coder",
+ "fp-evm",
"fp-evm-mapping",
"fp-rpc",
"fp-self-contained",
@@ -13040,6 +13092,7 @@
"impl-trait-for-tuples",
"log",
"logtest",
+ "num_enum",
"orml-tokens",
"orml-traits",
"orml-vesting",
@@ -13055,6 +13108,7 @@
"pallet-evm-coder-substrate",
"pallet-evm-contract-helpers",
"pallet-evm-migration",
+ "pallet-evm-precompile-simple",
"pallet-evm-transaction-payment",
"pallet-foreign-assets",
"pallet-fungible",
@@ -13077,6 +13131,7 @@
"parachain-info",
"parity-scale-codec 3.2.1",
"polkadot-parachain",
+ "precompile-utils-macro",
"rmrk-rpc",
"scale-info",
"serde",
crates/evm-coder/tests/abi_derive_generation.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/abi_derive_generation.rs
+++ b/crates/evm-coder/tests/abi_derive_generation.rs
@@ -740,7 +740,7 @@
/// Some docs
/// At multi
/// line
- #[derive(AbiCoder, Debug, PartialEq, Default)]
+ #[derive(AbiCoder, Debug, PartialEq, Default, Clone, Copy)]
#[repr(u8)]
enum Color {
/// Docs for Red
pallets/app-promotion/src/lib.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -564,7 +564,7 @@
/// # Arguments
///
/// * `stakers_number`: the number of stakers for which recalculation will be performed
- #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(20) as u32))]
+ #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]
pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {
let admin_id = ensure_signed(admin)?;
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -162,3 +162,18 @@
CollectionAdmin,
TokenOwner,
}
+
+/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.
+#[derive(AbiCoder, Copy, Clone, Default, Debug)]
+#[repr(u8)]
+pub enum EthTokenPermissions {
+ /// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]
+ #[default]
+ Mutable,
+
+ /// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]
+ TokenOwner,
+
+ /// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]
+ CollectionAdmin,
+}
pallets/common/src/lib.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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63 ensure,64 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65 dispatch::Pays,66 transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70 COLLECTION_NUMBER_LIMIT,71 Collection,72 RpcCollection,73 CollectionFlags,74 RpcCollectionFlags,75 CollectionId,76 CreateItemData,77 MAX_TOKEN_PREFIX_LENGTH,78 COLLECTION_ADMINS_LIMIT,79 TokenId,80 TokenChild,81 CollectionStats,82 MAX_TOKEN_OWNERSHIP,83 CollectionMode,84 NFT_SPONSOR_TRANSFER_TIMEOUT,85 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87 MAX_SPONSOR_TIMEOUT,88 CUSTOM_DATA_LIMIT,89 CollectionLimits,90 CreateCollectionData,91 SponsorshipState,92 CreateItemExData,93 SponsoringRateLimit,94 budget::Budget,95 PhantomType,96 Property,97 Properties,98 PropertiesPermissionMap,99 PropertyKey,100 PropertyValue,101 PropertyPermission,102 PropertiesError,103 PropertyKeyPermission,104 TokenData,105 TrySetProperty,106 PropertyScope,107 // RMRK108 RmrkCollectionInfo,109 RmrkInstanceInfo,110 RmrkResourceInfo,111 RmrkPropertyInfo,112 RmrkBaseInfo,113 RmrkPartType,114 RmrkBoundedTheme,115 RmrkNftChild,116 CollectionPermissions,117};118119pub use pallet::*;120use sp_core::H160;121use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};122#[cfg(feature = "runtime-benchmarks")]123pub mod benchmarking;124pub mod dispatch;125pub mod erc;126pub mod eth;127pub mod weights;128129/// Weight info.130pub type SelfWeightOf<T> = <T as Config>::WeightInfo;131132/// Collection handle contains information about collection data and id.133/// Also provides functionality to count consumed gas.134///135/// CollectionHandle is used as a generic wrapper for collections of all types.136/// It allows to perform common operations and queries on any collection type,137/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].138#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]139pub struct CollectionHandle<T: Config> {140 /// Collection id141 pub id: CollectionId,142 collection: Collection<T::AccountId>,143 /// Substrate recorder for counting consumed gas144 pub recorder: SubstrateRecorder<T>,145}146147impl<T: Config> WithRecorder<T> for CollectionHandle<T> {148 fn recorder(&self) -> &SubstrateRecorder<T> {149 &self.recorder150 }151 fn into_recorder(self) -> SubstrateRecorder<T> {152 self.recorder153 }154}155156impl<T: Config> CollectionHandle<T> {157 /// Same as [CollectionHandle::new] but with an explicit gas limit.158 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {159 <CollectionById<T>>::get(id).map(|collection| Self {160 id,161 collection,162 recorder: SubstrateRecorder::new(gas_limit),163 })164 }165166 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].167 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {168 <CollectionById<T>>::get(id).map(|collection| Self {169 id,170 collection,171 recorder,172 })173 }174175 /// Retrives collection data from storage and creates collection handle with default parameters.176 /// If collection not found return `None`177 pub fn new(id: CollectionId) -> Option<Self> {178 Self::new_with_gas_limit(id, u64::MAX)179 }180181 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.182 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {183 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)184 }185186 /// Consume gas for reading.187 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {188 self.recorder189 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(190 <T as frame_system::Config>::DbWeight::get()191 .read192 .saturating_mul(reads),193 )))194 }195196 /// Consume gas for writing.197 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {198 self.recorder199 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(200 <T as frame_system::Config>::DbWeight::get()201 .write202 .saturating_mul(writes),203 )))204 }205206 /// Consume gas for reading and writing.207 pub fn consume_store_reads_and_writes(208 &self,209 reads: u64,210 writes: u64,211 ) -> evm_coder::execution::Result<()> {212 let weight = <T as frame_system::Config>::DbWeight::get();213 let reads = weight.read.saturating_mul(reads);214 let writes = weight.read.saturating_mul(writes);215 self.recorder216 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(217 reads.saturating_add(writes),218 )))219 }220221 /// Save collection to storage.222 pub fn save(&self) -> DispatchResult {223 <CollectionById<T>>::insert(self.id, &self.collection);224 Ok(())225 }226227 /// Set collection sponsor.228 ///229 /// Unique collections allows sponsoring for certain actions.230 /// This method allows you to set the sponsor of the collection.231 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].232 pub fn set_sponsor(233 &mut self,234 sender: &T::CrossAccountId,235 sponsor: T::AccountId,236 ) -> DispatchResult {237 self.check_is_internal()?;238 self.check_is_owner_or_admin(sender)?;239240 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());241242 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));243 <PalletEvm<T>>::deposit_log(244 erc::CollectionHelpersEvents::CollectionChanged {245 collection_id: eth::collection_id_to_address(self.id),246 }247 .to_log(T::ContractAddress::get()),248 );249250 self.save()251 }252253 /// Force set `sponsor`.254 ///255 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation256 /// from the `sponsor` is not required.257 ///258 /// # Arguments259 ///260 /// * `sender`: Caller's account.261 /// * `sponsor`: ID of the account of the sponsor-to-be.262 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {263 self.check_is_internal()?;264265 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());266267 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));268 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));269 <PalletEvm<T>>::deposit_log(270 erc::CollectionHelpersEvents::CollectionChanged {271 collection_id: eth::collection_id_to_address(self.id),272 }273 .to_log(T::ContractAddress::get()),274 );275276 self.save()277 }278279 /// Confirm sponsorship280 ///281 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.282 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].283 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {284 self.check_is_internal()?;285 ensure!(286 self.collection.sponsorship.pending_sponsor() == Some(sender),287 Error::<T>::ConfirmSponsorshipFail288 );289290 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());291292 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));293 <PalletEvm<T>>::deposit_log(294 erc::CollectionHelpersEvents::CollectionChanged {295 collection_id: eth::collection_id_to_address(self.id),296 }297 .to_log(T::ContractAddress::get()),298 );299300 self.save()301 }302303 /// Remove collection sponsor.304 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {305 self.check_is_internal()?;306 self.check_is_owner_or_admin(sender)?;307308 self.collection.sponsorship = SponsorshipState::Disabled;309310 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));311 <PalletEvm<T>>::deposit_log(312 erc::CollectionHelpersEvents::CollectionChanged {313 collection_id: eth::collection_id_to_address(self.id),314 }315 .to_log(T::ContractAddress::get()),316 );317 self.save()318 }319320 /// Force remove `sponsor`.321 ///322 /// Differs from `remove_sponsor` in that323 /// it doesn't require consent from the `owner` of the collection.324 pub fn force_remove_sponsor(&mut self) -> DispatchResult {325 self.check_is_internal()?;326327 self.collection.sponsorship = SponsorshipState::Disabled;328329 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));330 <PalletEvm<T>>::deposit_log(331 erc::CollectionHelpersEvents::CollectionChanged {332 collection_id: eth::collection_id_to_address(self.id),333 }334 .to_log(T::ContractAddress::get()),335 );336 self.save()337 }338339 /// Checks that the collection was created with, and must be operated upon through **Unique API**.340 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.341 pub fn check_is_internal(&self) -> DispatchResult {342 if self.flags.external {343 return Err(<Error<T>>::CollectionIsExternal)?;344 }345346 Ok(())347 }348349 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.350 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.351 pub fn check_is_external(&self) -> DispatchResult {352 if !self.flags.external {353 return Err(<Error<T>>::CollectionIsInternal)?;354 }355356 Ok(())357 }358}359360impl<T: Config> Deref for CollectionHandle<T> {361 type Target = Collection<T::AccountId>;362363 fn deref(&self) -> &Self::Target {364 &self.collection365 }366}367368impl<T: Config> DerefMut for CollectionHandle<T> {369 fn deref_mut(&mut self) -> &mut Self::Target {370 &mut self.collection371 }372}373374impl<T: Config> CollectionHandle<T> {375 /// Checks if the `user` is the owner of the collection.376 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {377 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);378 Ok(())379 }380381 /// Returns **true** if the `user` is the owner or administrator of the collection.382 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {383 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))384 }385386 /// Checks if the `user` is the owner or administrator of the collection.387 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {388 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);389 Ok(())390 }391392 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.393 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {394 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)395 }396397 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.398 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {399 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)400 }401402 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.403 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {404 ensure!(405 <Allowlist<T>>::get((self.id, user)),406 <Error<T>>::AddressNotInAllowlist407 );408 Ok(())409 }410411 /// Changes collection owner to another account412 /// #### Store read/writes413 /// 1 writes414 pub fn change_owner(415 &mut self,416 caller: T::CrossAccountId,417 new_owner: T::CrossAccountId,418 ) -> DispatchResult {419 self.check_is_internal()?;420 self.check_is_owner(&caller)?;421 self.collection.owner = new_owner.as_sub().clone();422423 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(424 self.id,425 new_owner.as_sub().clone(),426 ));427 <PalletEvm<T>>::deposit_log(428 erc::CollectionHelpersEvents::CollectionChanged {429 collection_id: eth::collection_id_to_address(self.id),430 }431 .to_log(T::ContractAddress::get()),432 );433434 self.save()435 }436}437438#[frame_support::pallet]439pub mod pallet {440 use super::*;441 use dispatch::CollectionDispatch;442 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};443 use frame_system::pallet_prelude::*;444 use frame_support::traits::Currency;445 use up_data_structs::{TokenId, mapping::TokenAddressMapping};446 use scale_info::TypeInfo;447 use weights::WeightInfo;448449 #[pallet::config]450 pub trait Config:451 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo452 {453 /// Weight information for functions of this pallet.454 type WeightInfo: WeightInfo;455456 /// Events compatible with [`frame_system::Config::Event`].457 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;458459 /// Handler of accounts and payment.460 type Currency: Currency<Self::AccountId>;461462 /// Set price to create a collection.463 #[pallet::constant]464 type CollectionCreationPrice: Get<465 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,466 >;467468 /// Dispatcher of operations on collections.469 type CollectionDispatch: CollectionDispatch<Self>;470471 /// Account which holds the chain's treasury.472 type TreasuryAccountId: Get<Self::AccountId>;473474 /// Address under which the CollectionHelper contract would be available.475 #[pallet::constant]476 type ContractAddress: Get<H160>;477478 /// Mapper for token addresses to Ethereum addresses.479 type EvmTokenAddressMapping: TokenAddressMapping<H160>;480481 /// Mapper for token addresses to [`CrossAccountId`].482 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;483 }484485 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);486487 #[pallet::pallet]488 #[pallet::storage_version(STORAGE_VERSION)]489 #[pallet::generate_store(pub(super) trait Store)]490 pub struct Pallet<T>(_);491492 #[pallet::extra_constants]493 impl<T: Config> Pallet<T> {494 /// Maximum admins per collection.495 pub fn collection_admins_limit() -> u32 {496 COLLECTION_ADMINS_LIMIT497 }498 }499500 #[pallet::event]501 #[pallet::generate_deposit(pub fn deposit_event)]502 pub enum Event<T: Config> {503 /// New collection was created504 CollectionCreated(505 /// Globally unique identifier of newly created collection.506 CollectionId,507 /// [`CollectionMode`] converted into _u8_.508 u8,509 /// Collection owner.510 T::AccountId,511 ),512513 /// New collection was destroyed514 CollectionDestroyed(515 /// Globally unique identifier of collection.516 CollectionId,517 ),518519 /// New item was created.520 ItemCreated(521 /// Id of the collection where item was created.522 CollectionId,523 /// Id of an item. Unique within the collection.524 TokenId,525 /// Owner of newly created item526 T::CrossAccountId,527 /// Always 1 for NFT528 u128,529 ),530531 /// Collection item was burned.532 ItemDestroyed(533 /// Id of the collection where item was destroyed.534 CollectionId,535 /// Identifier of burned NFT.536 TokenId,537 /// Which user has destroyed its tokens.538 T::CrossAccountId,539 /// Amount of token pieces destroed. Always 1 for NFT.540 u128,541 ),542543 /// Item was transferred544 Transfer(545 /// Id of collection to which item is belong.546 CollectionId,547 /// Id of an item.548 TokenId,549 /// Original owner of item.550 T::CrossAccountId,551 /// New owner of item.552 T::CrossAccountId,553 /// Amount of token pieces transfered. Always 1 for NFT.554 u128,555 ),556557 /// Amount pieces of token owned by `sender` was approved for `spender`.558 Approved(559 /// Id of collection to which item is belong.560 CollectionId,561 /// Id of an item.562 TokenId,563 /// Original owner of item.564 T::CrossAccountId,565 /// Id for which the approval was granted.566 T::CrossAccountId,567 /// Amount of token pieces transfered. Always 1 for NFT.568 u128,569 ),570571 /// A `sender` approves operations on all owned tokens for `spender`.572 ApprovedForAll(573 /// Id of collection to which item is belong.574 CollectionId,575 /// Owner of a wallet.576 T::CrossAccountId,577 /// Id for which operator status was granted or rewoked.578 T::CrossAccountId,579 /// Is operator status granted or revoked?580 bool,581 ),582583 /// The colletion property has been added or edited.584 CollectionPropertySet(585 /// Id of collection to which property has been set.586 CollectionId,587 /// The property that was set.588 PropertyKey,589 ),590591 /// The property has been deleted.592 CollectionPropertyDeleted(593 /// Id of collection to which property has been deleted.594 CollectionId,595 /// The property that was deleted.596 PropertyKey,597 ),598599 /// The token property has been added or edited.600 TokenPropertySet(601 /// Identifier of the collection whose token has the property set.602 CollectionId,603 /// The token for which the property was set.604 TokenId,605 /// The property that was set.606 PropertyKey,607 ),608609 /// The token property has been deleted.610 TokenPropertyDeleted(611 /// Identifier of the collection whose token has the property deleted.612 CollectionId,613 /// The token for which the property was deleted.614 TokenId,615 /// The property that was deleted.616 PropertyKey,617 ),618619 /// The token property permission of a collection has been set.620 PropertyPermissionSet(621 /// ID of collection to which property permission has been set.622 CollectionId,623 /// The property permission that was set.624 PropertyKey,625 ),626627 /// Address was added to the allow list.628 AllowListAddressAdded(629 /// ID of the affected collection.630 CollectionId,631 /// Address of the added account.632 T::CrossAccountId,633 ),634635 /// Address was removed from the allow list.636 AllowListAddressRemoved(637 /// ID of the affected collection.638 CollectionId,639 /// Address of the removed account.640 T::CrossAccountId,641 ),642643 /// Collection admin was added.644 CollectionAdminAdded(645 /// ID of the affected collection.646 CollectionId,647 /// Admin address.648 T::CrossAccountId,649 ),650651 /// Collection admin was removed.652 CollectionAdminRemoved(653 /// ID of the affected collection.654 CollectionId,655 /// Removed admin address.656 T::CrossAccountId,657 ),658659 /// Collection limits were set.660 CollectionLimitSet(661 /// ID of the affected collection.662 CollectionId,663 ),664665 /// Collection owned was changed.666 CollectionOwnerChanged(667 /// ID of the affected collection.668 CollectionId,669 /// New owner address.670 T::AccountId,671 ),672673 /// Collection permissions were set.674 CollectionPermissionSet(675 /// ID of the affected collection.676 CollectionId,677 ),678679 /// Collection sponsor was set.680 CollectionSponsorSet(681 /// ID of the affected collection.682 CollectionId,683 /// New sponsor address.684 T::AccountId,685 ),686687 /// New sponsor was confirm.688 SponsorshipConfirmed(689 /// ID of the affected collection.690 CollectionId,691 /// New sponsor address.692 T::AccountId,693 ),694695 /// Collection sponsor was removed.696 CollectionSponsorRemoved(697 /// ID of the affected collection.698 CollectionId,699 ),700 }701702 #[pallet::error]703 pub enum Error<T> {704 /// This collection does not exist.705 CollectionNotFound,706 /// Sender parameter and item owner must be equal.707 MustBeTokenOwner,708 /// No permission to perform action709 NoPermission,710 /// Destroying only empty collections is allowed711 CantDestroyNotEmptyCollection,712 /// Collection is not in mint mode.713 PublicMintingNotAllowed,714 /// Address is not in allow list.715 AddressNotInAllowlist,716717 /// Collection name can not be longer than 63 char.718 CollectionNameLimitExceeded,719 /// Collection description can not be longer than 255 char.720 CollectionDescriptionLimitExceeded,721 /// Token prefix can not be longer than 15 char.722 CollectionTokenPrefixLimitExceeded,723 /// Total collections bound exceeded.724 TotalCollectionsLimitExceeded,725 /// Exceeded max admin count726 CollectionAdminCountExceeded,727 /// Collection limit bounds per collection exceeded728 CollectionLimitBoundsExceeded,729 /// Tried to enable permissions which are only permitted to be disabled730 OwnerPermissionsCantBeReverted,731 /// Collection settings not allowing items transferring732 TransferNotAllowed,733 /// Account token limit exceeded per collection734 AccountTokenLimitExceeded,735 /// Collection token limit exceeded736 CollectionTokenLimitExceeded,737 /// Metadata flag frozen738 MetadataFlagFrozen,739740 /// Item does not exist741 TokenNotFound,742 /// Item is balance not enough743 TokenValueTooLow,744 /// Requested value is more than the approved745 ApprovedValueTooLow,746 /// Tried to approve more than owned747 CantApproveMoreThanOwned,748749 /// Can't transfer tokens to ethereum zero address750 AddressIsZero,751752 /// The operation is not supported753 UnsupportedOperation,754755 /// Insufficient funds to perform an action756 NotSufficientFounds,757758 /// User does not satisfy the nesting rule759 UserIsNotAllowedToNest,760 /// Only tokens from specific collections may nest tokens under this one761 SourceCollectionIsNotAllowedToNest,762763 /// Tried to store more data than allowed in collection field764 CollectionFieldSizeExceeded,765766 /// Tried to store more property data than allowed767 NoSpaceForProperty,768769 /// Tried to store more property keys than allowed770 PropertyLimitReached,771772 /// Property key is too long773 PropertyKeyIsTooLong,774775 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed776 InvalidCharacterInPropertyKey,777778 /// Empty property keys are forbidden779 EmptyPropertyKey,780781 /// Tried to access an external collection with an internal API782 CollectionIsExternal,783784 /// Tried to access an internal collection with an external API785 CollectionIsInternal,786787 /// This address is not set as sponsor, use setCollectionSponsor first.788 ConfirmSponsorshipFail,789790 /// The user is not an administrator.791 UserIsNotCollectionAdmin,792 }793794 /// Storage of the count of created collections. Essentially contains the last collection ID.795 #[pallet::storage]796 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;797798 /// Storage of the count of deleted collections.799 #[pallet::storage]800 pub type DestroyedCollectionCount<T> =801 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;802803 /// Storage of collection info.804 #[pallet::storage]805 pub type CollectionById<T> = StorageMap<806 Hasher = Blake2_128Concat,807 Key = CollectionId,808 Value = Collection<<T as frame_system::Config>::AccountId>,809 QueryKind = OptionQuery,810 >;811812 /// Storage of collection properties.813 #[pallet::storage]814 #[pallet::getter(fn collection_properties)]815 pub type CollectionProperties<T> = StorageMap<816 Hasher = Blake2_128Concat,817 Key = CollectionId,818 Value = Properties,819 QueryKind = ValueQuery,820 OnEmpty = up_data_structs::CollectionProperties,821 >;822823 /// Storage of token property permissions of a collection.824 #[pallet::storage]825 #[pallet::getter(fn property_permissions)]826 pub type CollectionPropertyPermissions<T> = StorageMap<827 Hasher = Blake2_128Concat,828 Key = CollectionId,829 Value = PropertiesPermissionMap,830 QueryKind = ValueQuery,831 >;832833 /// Storage of the amount of collection admins.834 #[pallet::storage]835 pub type AdminAmount<T> = StorageMap<836 Hasher = Blake2_128Concat,837 Key = CollectionId,838 Value = u32,839 QueryKind = ValueQuery,840 >;841842 /// List of collection admins.843 #[pallet::storage]844 pub type IsAdmin<T: Config> = StorageNMap<845 Key = (846 Key<Blake2_128Concat, CollectionId>,847 Key<Blake2_128Concat, T::CrossAccountId>,848 ),849 Value = bool,850 QueryKind = ValueQuery,851 >;852853 /// Allowlisted collection users.854 #[pallet::storage]855 pub type Allowlist<T: Config> = StorageNMap<856 Key = (857 Key<Blake2_128Concat, CollectionId>,858 Key<Blake2_128Concat, T::CrossAccountId>,859 ),860 Value = bool,861 QueryKind = ValueQuery,862 >;863864 /// Not used by code, exists only to provide some types to metadata.865 #[pallet::storage]866 pub type DummyStorageValue<T: Config> = StorageValue<867 Value = (868 CollectionStats,869 CollectionId,870 TokenId,871 TokenChild,872 PhantomType<(873 TokenData<T::CrossAccountId>,874 RpcCollection<T::AccountId>,875 // RMRK876 RmrkCollectionInfo<T::AccountId>,877 RmrkInstanceInfo<T::AccountId>,878 RmrkResourceInfo,879 RmrkPropertyInfo,880 RmrkBaseInfo<T::AccountId>,881 RmrkPartType,882 RmrkBoundedTheme,883 RmrkNftChild,884 )>,885 ),886 QueryKind = OptionQuery,887 >;888889 #[pallet::hooks]890 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {891 fn on_runtime_upgrade() -> Weight {892 StorageVersion::new(1).put::<Pallet<T>>();893894 Weight::zero()895 }896 }897}898899impl<T: Config> Pallet<T> {900 /// Enshure that receiver address is correct.901 ///902 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.903 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {904 ensure!(905 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,906 <Error<T>>::AddressIsZero907 );908 Ok(())909 }910911 /// Get a vector of collection admins.912 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {913 <IsAdmin<T>>::iter_prefix((collection,))914 .map(|(a, _)| a)915 .collect()916 }917918 /// Get a vector of users allowed to mint tokens.919 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {920 <Allowlist<T>>::iter_prefix((collection,))921 .map(|(a, _)| a)922 .collect()923 }924925 /// Is `user` allowed to mint token in `collection`.926 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {927 <Allowlist<T>>::get((collection, user))928 }929930 /// Get statistics of collections.931 pub fn collection_stats() -> CollectionStats {932 let created = <CreatedCollectionCount<T>>::get();933 let destroyed = <DestroyedCollectionCount<T>>::get();934 CollectionStats {935 created: created.0,936 destroyed: destroyed.0,937 alive: created.0 - destroyed.0,938 }939 }940941 /// Get the effective limits for the collection.942 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {943 let collection = <CollectionById<T>>::get(collection)?;944 let limits = collection.limits;945 let effective_limits = CollectionLimits {946 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),947 sponsored_data_size: Some(limits.sponsored_data_size()),948 sponsored_data_rate_limit: Some(949 limits950 .sponsored_data_rate_limit951 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),952 ),953 token_limit: Some(limits.token_limit()),954 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(955 match collection.mode {956 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,957 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,958 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,959 },960 )),961 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),962 owner_can_transfer: Some(limits.owner_can_transfer()),963 owner_can_destroy: Some(limits.owner_can_destroy()),964 transfers_enabled: Some(limits.transfers_enabled()),965 };966967 Some(effective_limits)968 }969970 /// Returns information about the `collection` adapted for rpc.971 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {972 let Collection {973 name,974 description,975 owner,976 mode,977 token_prefix,978 sponsorship,979 limits,980 permissions,981 flags,982 } = <CollectionById<T>>::get(collection)?;983984 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)985 .into_iter()986 .map(|(key, permission)| PropertyKeyPermission { key, permission })987 .collect();988989 let properties = <CollectionProperties<T>>::get(collection)990 .into_iter()991 .map(|(key, value)| Property { key, value })992 .collect();993994 let permissions = CollectionPermissions {995 access: Some(permissions.access()),996 mint_mode: Some(permissions.mint_mode()),997 nesting: Some(permissions.nesting().clone()),998 };9991000 Some(RpcCollection {1001 name: name.into_inner(),1002 description: description.into_inner(),1003 owner,1004 mode,1005 token_prefix: token_prefix.into_inner(),1006 sponsorship,1007 limits,1008 permissions,1009 token_property_permissions,1010 properties,1011 read_only: flags.external,10121013 flags: RpcCollectionFlags {1014 foreign: flags.foreign,1015 erc721metadata: flags.erc721metadata,1016 },1017 })1018 }1019}10201021macro_rules! limit_default {1022 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1023 $(1024 if let Some($new) = $new.$field {1025 let $old = $old.$field($($arg)?);1026 let _ = $new;1027 let _ = $old;1028 $check1029 } else {1030 $new.$field = $old.$field1031 }1032 )*1033 }};1034}1035macro_rules! limit_default_clone {1036 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1037 $(1038 if let Some($new) = $new.$field.clone() {1039 let $old = $old.$field($($arg)?);1040 let _ = $new;1041 let _ = $old;1042 $check1043 } else {1044 $new.$field = $old.$field.clone()1045 }1046 )*1047 }};1048}10491050impl<T: Config> Pallet<T> {1051 /// Create new collection.1052 ///1053 /// * `owner` - The owner of the collection.1054 /// * `data` - Description of the created collection.1055 /// * `flags` - Extra flags to store.1056 pub fn init_collection(1057 owner: T::CrossAccountId,1058 payer: T::CrossAccountId,1059 data: CreateCollectionData<T::AccountId>,1060 flags: CollectionFlags,1061 ) -> Result<CollectionId, DispatchError> {1062 {1063 ensure!(1064 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1065 Error::<T>::CollectionTokenPrefixLimitExceeded1066 );1067 }10681069 let created_count = <CreatedCollectionCount<T>>::get()1070 .01071 .checked_add(1)1072 .ok_or(ArithmeticError::Overflow)?;1073 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1074 let id = CollectionId(created_count);10751076 // bound Total number of collections1077 ensure!(1078 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1079 <Error<T>>::TotalCollectionsLimitExceeded1080 );10811082 // =========10831084 let collection = Collection {1085 owner: owner.as_sub().clone(),1086 name: data.name,1087 mode: data.mode.clone(),1088 description: data.description,1089 token_prefix: data.token_prefix,1090 sponsorship: data1091 .pending_sponsor1092 .map(SponsorshipState::Unconfirmed)1093 .unwrap_or_default(),1094 limits: data1095 .limits1096 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1097 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1098 permissions: data1099 .permissions1100 .map(|permissions| {1101 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1102 })1103 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1104 flags,1105 };11061107 let mut collection_properties = up_data_structs::CollectionProperties::get();1108 collection_properties1109 .try_set_from_iter(data.properties.into_iter())1110 .map_err(<Error<T>>::from)?;11111112 CollectionProperties::<T>::insert(id, collection_properties);11131114 let mut token_props_permissions = PropertiesPermissionMap::new();1115 token_props_permissions1116 .try_set_from_iter(data.token_property_permissions.into_iter())1117 .map_err(<Error<T>>::from)?;11181119 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11201121 // Take a (non-refundable) deposit of collection creation1122 {1123 let mut imbalance =1124 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1125 imbalance.subsume(1126 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1127 &T::TreasuryAccountId::get(),1128 T::CollectionCreationPrice::get(),1129 ),1130 );1131 <T as Config>::Currency::settle(1132 payer.as_sub(),1133 imbalance,1134 WithdrawReasons::TRANSFER,1135 ExistenceRequirement::KeepAlive,1136 )1137 .map_err(|_| Error::<T>::NotSufficientFounds)?;1138 }11391140 <CreatedCollectionCount<T>>::put(created_count);1141 <Pallet<T>>::deposit_event(Event::CollectionCreated(1142 id,1143 data.mode.id(),1144 owner.as_sub().clone(),1145 ));1146 <PalletEvm<T>>::deposit_log(1147 erc::CollectionHelpersEvents::CollectionCreated {1148 owner: *owner.as_eth(),1149 collection_id: eth::collection_id_to_address(id),1150 }1151 .to_log(T::ContractAddress::get()),1152 );1153 <CollectionById<T>>::insert(id, collection);1154 Ok(id)1155 }11561157 /// Destroy collection.1158 ///1159 /// * `collection` - Collection handler.1160 /// * `sender` - The owner or administrator of the collection.1161 pub fn destroy_collection(1162 collection: CollectionHandle<T>,1163 sender: &T::CrossAccountId,1164 ) -> DispatchResult {1165 ensure!(1166 collection.limits.owner_can_destroy(),1167 <Error<T>>::NoPermission,1168 );1169 collection.check_is_owner(sender)?;11701171 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1172 .01173 .checked_add(1)1174 .ok_or(ArithmeticError::Overflow)?;11751176 // =========11771178 <DestroyedCollectionCount<T>>::put(destroyed_collections);1179 <CollectionById<T>>::remove(collection.id);1180 <AdminAmount<T>>::remove(collection.id);1181 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1182 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1183 <CollectionProperties<T>>::remove(collection.id);11841185 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11861187 <PalletEvm<T>>::deposit_log(1188 erc::CollectionHelpersEvents::CollectionDestroyed {1189 collection_id: eth::collection_id_to_address(collection.id),1190 }1191 .to_log(T::ContractAddress::get()),1192 );1193 Ok(())1194 }11951196 /// Set collection property.1197 ///1198 /// * `collection` - Collection handler.1199 /// * `sender` - The owner or administrator of the collection.1200 /// * `property` - The property to set.1201 pub fn set_collection_property(1202 collection: &CollectionHandle<T>,1203 sender: &T::CrossAccountId,1204 property: Property,1205 ) -> DispatchResult {1206 collection.check_is_owner_or_admin(sender)?;12071208 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1209 let property = property.clone();1210 properties.try_set(property.key, property.value)1211 })1212 .map_err(<Error<T>>::from)?;12131214 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));1215 <PalletEvm<T>>::deposit_log(1216 erc::CollectionHelpersEvents::CollectionChanged {1217 collection_id: eth::collection_id_to_address(collection.id),1218 }1219 .to_log(T::ContractAddress::get()),1220 );12211222 Ok(())1223 }12241225 /// Set scouped collection property.1226 ///1227 /// * `collection_id` - ID of the collection for which the property is being set.1228 /// * `scope` - Property scope.1229 /// * `property` - The property to set.1230 pub fn set_scoped_collection_property(1231 collection_id: CollectionId,1232 scope: PropertyScope,1233 property: Property,1234 ) -> DispatchResult {1235 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1236 properties.try_scoped_set(scope, property.key, property.value)1237 })1238 .map_err(<Error<T>>::from)?;12391240 Ok(())1241 }12421243 /// Set scouped collection properties.1244 ///1245 /// * `collection_id` - ID of the collection for which the properties is being set.1246 /// * `scope` - Property scope.1247 /// * `properties` - The properties to set.1248 pub fn set_scoped_collection_properties(1249 collection_id: CollectionId,1250 scope: PropertyScope,1251 properties: impl Iterator<Item = Property>,1252 ) -> DispatchResult {1253 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1254 stored_properties.try_scoped_set_from_iter(scope, properties)1255 })1256 .map_err(<Error<T>>::from)?;12571258 Ok(())1259 }12601261 /// Set collection properties.1262 ///1263 /// * `collection` - Collection handler.1264 /// * `sender` - The owner or administrator of the collection.1265 /// * `properties` - The properties to set.1266 #[transactional]1267 pub fn set_collection_properties(1268 collection: &CollectionHandle<T>,1269 sender: &T::CrossAccountId,1270 properties: Vec<Property>,1271 ) -> DispatchResult {1272 for property in properties {1273 Self::set_collection_property(collection, sender, property)?;1274 }12751276 Ok(())1277 }12781279 /// Delete collection property.1280 ///1281 /// * `collection` - Collection handler.1282 /// * `sender` - The owner or administrator of the collection.1283 /// * `property` - The property to delete.1284 pub fn delete_collection_property(1285 collection: &CollectionHandle<T>,1286 sender: &T::CrossAccountId,1287 property_key: PropertyKey,1288 ) -> DispatchResult {1289 collection.check_is_owner_or_admin(sender)?;12901291 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1292 properties.remove(&property_key)1293 })1294 .map_err(<Error<T>>::from)?;12951296 Self::deposit_event(Event::CollectionPropertyDeleted(1297 collection.id,1298 property_key,1299 ));1300 <PalletEvm<T>>::deposit_log(1301 erc::CollectionHelpersEvents::CollectionChanged {1302 collection_id: eth::collection_id_to_address(collection.id),1303 }1304 .to_log(T::ContractAddress::get()),1305 );13061307 Ok(())1308 }13091310 /// Delete collection properties.1311 ///1312 /// * `collection` - Collection handler.1313 /// * `sender` - The owner or administrator of the collection.1314 /// * `properties` - The properties to delete.1315 #[transactional]1316 pub fn delete_collection_properties(1317 collection: &CollectionHandle<T>,1318 sender: &T::CrossAccountId,1319 property_keys: Vec<PropertyKey>,1320 ) -> DispatchResult {1321 for key in property_keys {1322 Self::delete_collection_property(collection, sender, key)?;1323 }13241325 Ok(())1326 }13271328 /// Set collection propetry permission without any checks.1329 ///1330 /// Used for migrations.1331 ///1332 /// * `collection` - Collection handler.1333 /// * `property_permissions` - Property permissions.1334 pub fn set_property_permission_unchecked(1335 collection: CollectionId,1336 property_permission: PropertyKeyPermission,1337 ) -> DispatchResult {1338 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1339 permissions.try_set(property_permission.key, property_permission.permission)1340 })1341 .map_err(<Error<T>>::from)?;1342 Ok(())1343 }13441345 /// Set collection property permission.1346 ///1347 /// * `collection` - Collection handler.1348 /// * `sender` - The owner or administrator of the collection.1349 /// * `property_permission` - Property permission.1350 pub fn set_property_permission(1351 collection: &CollectionHandle<T>,1352 sender: &T::CrossAccountId,1353 property_permission: PropertyKeyPermission,1354 ) -> DispatchResult {1355 Self::set_scoped_property_permission(1356 collection,1357 sender,1358 PropertyScope::None,1359 property_permission,1360 )1361 }13621363 /// Set collection property permission with scope.1364 ///1365 /// * `collection` - Collection handler.1366 /// * `sender` - The owner or administrator of the collection.1367 /// * `scope` - Property scope.1368 /// * `property_permission` - Property permission.1369 pub fn set_scoped_property_permission(1370 collection: &CollectionHandle<T>,1371 sender: &T::CrossAccountId,1372 scope: PropertyScope,1373 property_permission: PropertyKeyPermission,1374 ) -> DispatchResult {1375 collection.check_is_owner_or_admin(sender)?;13761377 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1378 let current_permission = all_permissions.get(&property_permission.key);1379 if matches![1380 current_permission,1381 Some(PropertyPermission { mutable: false, .. })1382 ] {1383 return Err(<Error<T>>::NoPermission.into());1384 }13851386 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1387 let property_permission = property_permission.clone();1388 permissions.try_scoped_set(1389 scope,1390 property_permission.key,1391 property_permission.permission,1392 )1393 })1394 .map_err(<Error<T>>::from)?;13951396 Self::deposit_event(Event::PropertyPermissionSet(1397 collection.id,1398 property_permission.key,1399 ));1400 <PalletEvm<T>>::deposit_log(1401 erc::CollectionHelpersEvents::CollectionChanged {1402 collection_id: eth::collection_id_to_address(collection.id),1403 }1404 .to_log(T::ContractAddress::get()),1405 );14061407 Ok(())1408 }14091410 /// Set token property permission.1411 ///1412 /// * `collection` - Collection handler.1413 /// * `sender` - The owner or administrator of the collection.1414 /// * `property_permissions` - Property permissions.1415 #[transactional]1416 pub fn set_token_property_permissions(1417 collection: &CollectionHandle<T>,1418 sender: &T::CrossAccountId,1419 property_permissions: Vec<PropertyKeyPermission>,1420 ) -> DispatchResult {1421 Self::set_scoped_token_property_permissions(1422 collection,1423 sender,1424 PropertyScope::None,1425 property_permissions,1426 )1427 }14281429 /// Set token property permission with scope.1430 ///1431 /// * `collection` - Collection handler.1432 /// * `sender` - The owner or administrator of the collection.1433 /// * `scope` - Property scope.1434 /// * `property_permissions` - Property permissions.1435 #[transactional]1436 pub fn set_scoped_token_property_permissions(1437 collection: &CollectionHandle<T>,1438 sender: &T::CrossAccountId,1439 scope: PropertyScope,1440 property_permissions: Vec<PropertyKeyPermission>,1441 ) -> DispatchResult {1442 for prop_pemission in property_permissions {1443 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1444 }14451446 Ok(())1447 }14481449 /// Get collection property.1450 pub fn get_collection_property(1451 collection_id: CollectionId,1452 key: &PropertyKey,1453 ) -> Option<PropertyValue> {1454 Self::collection_properties(collection_id).get(key).cloned()1455 }14561457 /// Convert byte vector to property key vector.1458 pub fn bytes_keys_to_property_keys(1459 keys: Vec<Vec<u8>>,1460 ) -> Result<Vec<PropertyKey>, DispatchError> {1461 keys.into_iter()1462 .map(|key| -> Result<PropertyKey, DispatchError> {1463 key.try_into()1464 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1465 })1466 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1467 }14681469 /// Get properties according to given keys.1470 pub fn filter_collection_properties(1471 collection_id: CollectionId,1472 keys: Option<Vec<PropertyKey>>,1473 ) -> Result<Vec<Property>, DispatchError> {1474 let properties = Self::collection_properties(collection_id);14751476 let properties = keys1477 .map(|keys| {1478 keys.into_iter()1479 .filter_map(|key| {1480 properties.get(&key).map(|value| Property {1481 key,1482 value: value.clone(),1483 })1484 })1485 .collect()1486 })1487 .unwrap_or_else(|| {1488 properties1489 .into_iter()1490 .map(|(key, value)| Property { key, value })1491 .collect()1492 });14931494 Ok(properties)1495 }14961497 /// Get property permissions according to given keys.1498 pub fn filter_property_permissions(1499 collection_id: CollectionId,1500 keys: Option<Vec<PropertyKey>>,1501 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1502 let permissions = Self::property_permissions(collection_id);15031504 let key_permissions = keys1505 .map(|keys| {1506 keys.into_iter()1507 .filter_map(|key| {1508 permissions1509 .get(&key)1510 .map(|permission| PropertyKeyPermission {1511 key,1512 permission: permission.clone(),1513 })1514 })1515 .collect()1516 })1517 .unwrap_or_else(|| {1518 permissions1519 .into_iter()1520 .map(|(key, permission)| PropertyKeyPermission { key, permission })1521 .collect()1522 });15231524 Ok(key_permissions)1525 }15261527 /// Toggle `user` participation in the `collection`'s allow list.1528 /// #### Store read/writes1529 /// 1 writes1530 pub fn toggle_allowlist(1531 collection: &CollectionHandle<T>,1532 sender: &T::CrossAccountId,1533 user: &T::CrossAccountId,1534 allowed: bool,1535 ) -> DispatchResult {1536 collection.check_is_owner_or_admin(sender)?;15371538 // =========15391540 if allowed {1541 <Allowlist<T>>::insert((collection.id, user), true);1542 Self::deposit_event(Event::<T>::AllowListAddressAdded(1543 collection.id,1544 user.clone(),1545 ));1546 } else {1547 <Allowlist<T>>::remove((collection.id, user));1548 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1549 collection.id,1550 user.clone(),1551 ));1552 }15531554 <PalletEvm<T>>::deposit_log(1555 erc::CollectionHelpersEvents::CollectionChanged {1556 collection_id: eth::collection_id_to_address(collection.id),1557 }1558 .to_log(T::ContractAddress::get()),1559 );15601561 Ok(())1562 }15631564 /// Toggle `user` participation in the `collection`'s admin list.1565 /// #### Store read/writes1566 /// 2 reads, 2 writes1567 pub fn toggle_admin(1568 collection: &CollectionHandle<T>,1569 sender: &T::CrossAccountId,1570 user: &T::CrossAccountId,1571 admin: bool,1572 ) -> DispatchResult {1573 collection.check_is_internal()?;1574 collection.check_is_owner(sender)?;15751576 let is_admin = <IsAdmin<T>>::get((collection.id, user));1577 if is_admin == admin {1578 if admin {1579 return Ok(());1580 } else {1581 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1582 }1583 }1584 let amount = <AdminAmount<T>>::get(collection.id);15851586 // =========15871588 if admin {1589 let amount = amount1590 .checked_add(1)1591 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1592 ensure!(1593 amount <= Self::collection_admins_limit(),1594 <Error<T>>::CollectionAdminCountExceeded,1595 );15961597 <AdminAmount<T>>::insert(collection.id, amount);1598 <IsAdmin<T>>::insert((collection.id, user), true);15991600 Self::deposit_event(Event::<T>::CollectionAdminAdded(1601 collection.id,1602 user.clone(),1603 ));1604 } else {1605 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1606 <IsAdmin<T>>::remove((collection.id, user));16071608 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1609 collection.id,1610 user.clone(),1611 ));1612 }16131614 <PalletEvm<T>>::deposit_log(1615 erc::CollectionHelpersEvents::CollectionChanged {1616 collection_id: eth::collection_id_to_address(collection.id),1617 }1618 .to_log(T::ContractAddress::get()),1619 );16201621 Ok(())1622 }16231624 /// Update collection limits.1625 pub fn update_limits(1626 user: &T::CrossAccountId,1627 collection: &mut CollectionHandle<T>,1628 new_limit: CollectionLimits,1629 ) -> DispatchResult {1630 collection.check_is_internal()?;1631 collection.check_is_owner_or_admin(user)?;16321633 collection.limits =1634 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;16351636 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1637 <PalletEvm<T>>::deposit_log(1638 erc::CollectionHelpersEvents::CollectionChanged {1639 collection_id: eth::collection_id_to_address(collection.id),1640 }1641 .to_log(T::ContractAddress::get()),1642 );16431644 collection.save()1645 }16461647 /// Merge set fields from `new_limit` to `old_limit`.1648 fn clamp_limits(1649 mode: CollectionMode,1650 old_limit: &CollectionLimits,1651 mut new_limit: CollectionLimits,1652 ) -> Result<CollectionLimits, DispatchError> {1653 let limits = old_limit;1654 limit_default!(old_limit, new_limit,1655 account_token_ownership_limit => ensure!(1656 new_limit <= MAX_TOKEN_OWNERSHIP,1657 <Error<T>>::CollectionLimitBoundsExceeded,1658 ),1659 sponsored_data_size => ensure!(1660 new_limit <= CUSTOM_DATA_LIMIT,1661 <Error<T>>::CollectionLimitBoundsExceeded,1662 ),16631664 sponsored_data_rate_limit => {},1665 token_limit => ensure!(1666 old_limit >= new_limit && new_limit > 0,1667 <Error<T>>::CollectionTokenLimitExceeded1668 ),16691670 sponsor_transfer_timeout(match mode {1671 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1672 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1673 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1674 }) => ensure!(1675 new_limit <= MAX_SPONSOR_TIMEOUT,1676 <Error<T>>::CollectionLimitBoundsExceeded,1677 ),1678 sponsor_approve_timeout => {},1679 owner_can_transfer => ensure!(1680 !limits.owner_can_transfer_instaled() ||1681 old_limit || !new_limit,1682 <Error<T>>::OwnerPermissionsCantBeReverted,1683 ),1684 owner_can_destroy => ensure!(1685 old_limit || !new_limit,1686 <Error<T>>::OwnerPermissionsCantBeReverted,1687 ),1688 transfers_enabled => {},1689 );1690 Ok(new_limit)1691 }16921693 /// Update collection permissions.1694 pub fn update_permissions(1695 user: &T::CrossAccountId,1696 collection: &mut CollectionHandle<T>,1697 new_permission: CollectionPermissions,1698 ) -> DispatchResult {1699 collection.check_is_internal()?;1700 collection.check_is_owner_or_admin(user)?;1701 collection.permissions = Self::clamp_permissions(1702 collection.mode.clone(),1703 &collection.permissions,1704 new_permission,1705 )?;17061707 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1708 <PalletEvm<T>>::deposit_log(1709 erc::CollectionHelpersEvents::CollectionChanged {1710 collection_id: eth::collection_id_to_address(collection.id),1711 }1712 .to_log(T::ContractAddress::get()),1713 );17141715 collection.save()1716 }17171718 /// Merge set fields from `new_permission` to `old_permission`.1719 fn clamp_permissions(1720 _mode: CollectionMode,1721 old_permission: &CollectionPermissions,1722 mut new_permission: CollectionPermissions,1723 ) -> Result<CollectionPermissions, DispatchError> {1724 limit_default_clone!(old_permission, new_permission,1725 access => {},1726 mint_mode => {},1727 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1728 );1729 Ok(new_permission)1730 }1731}17321733/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1734#[macro_export]1735macro_rules! unsupported {1736 ($runtime:path) => {1737 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1738 };1739}17401741/// Return weights for various worst-case operations.1742pub trait CommonWeightInfo<CrossAccountId> {1743 /// Weight of item creation.1744 fn create_item() -> Weight;17451746 /// Weight of items creation.1747 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;17481749 /// Weight of items creation.1750 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;17511752 /// The weight of the burning item.1753 fn burn_item() -> Weight;17541755 /// Property setting weight.1756 ///1757 /// * `amount`- The number of properties to set.1758 fn set_collection_properties(amount: u32) -> Weight;17591760 /// Collection property deletion weight.1761 ///1762 /// * `amount`- The number of properties to set.1763 fn delete_collection_properties(amount: u32) -> Weight;17641765 /// Token property setting weight.1766 ///1767 /// * `amount`- The number of properties to set.1768 fn set_token_properties(amount: u32) -> Weight;17691770 /// Token property deletion weight.1771 ///1772 /// * `amount`- The number of properties to delete.1773 fn delete_token_properties(amount: u32) -> Weight;17741775 /// Token property permissions set weight.1776 ///1777 /// * `amount`- The number of property permissions to set.1778 fn set_token_property_permissions(amount: u32) -> Weight;17791780 /// Transfer price of the token or its parts.1781 fn transfer() -> Weight;17821783 /// The price of setting the permission of the operation from another user.1784 fn approve() -> Weight;17851786 /// Transfer price from another user.1787 fn transfer_from() -> Weight;17881789 /// The price of burning a token from another user.1790 fn burn_from() -> Weight;17911792 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1793 /// whole users's balance.1794 ///1795 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1796 fn burn_recursively_self_raw() -> Weight;17971798 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1799 ///1800 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1801 fn burn_recursively_breadth_raw(amount: u32) -> Weight;18021803 /// The price of recursive burning a token.1804 ///1805 /// `max_selfs` - The maximum burning weight of the token itself.1806 /// `max_breadth` - The maximum number of nested tokens to burn.1807 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1808 Self::burn_recursively_self_raw()1809 .saturating_mul(max_selfs.max(1) as u64)1810 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1811 }18121813 /// The price of retrieving token owner1814 fn token_owner() -> Weight;18151816 /// The price of setting approval for all1817 fn set_allowance_for_all() -> Weight;18181819 /// The price of repairing an item.1820 fn repair_item() -> Weight;1821}18221823/// Weight info extension trait for refungible pallet.1824pub trait RefungibleExtensionsWeightInfo {1825 /// Weight of token repartition.1826 fn repartition() -> Weight;1827}18281829/// Common collection operations.1830///1831/// It wraps methods in Fungible, Nonfungible and Refungible pallets1832/// and adds weight info.1833pub trait CommonCollectionOperations<T: Config> {1834 /// Create token.1835 ///1836 /// * `sender` - The user who mint the token and pays for the transaction.1837 /// * `to` - The user who will own the token.1838 /// * `data` - Token data.1839 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1840 fn create_item(1841 &self,1842 sender: T::CrossAccountId,1843 to: T::CrossAccountId,1844 data: CreateItemData,1845 nesting_budget: &dyn Budget,1846 ) -> DispatchResultWithPostInfo;18471848 /// Create multiple tokens.1849 ///1850 /// * `sender` - The user who mint the token and pays for the transaction.1851 /// * `to` - The user who will own the token.1852 /// * `data` - Token data.1853 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1854 fn create_multiple_items(1855 &self,1856 sender: T::CrossAccountId,1857 to: T::CrossAccountId,1858 data: Vec<CreateItemData>,1859 nesting_budget: &dyn Budget,1860 ) -> DispatchResultWithPostInfo;18611862 /// Create multiple tokens.1863 ///1864 /// * `sender` - The user who mint the token and pays for the transaction.1865 /// * `to` - The user who will own the token.1866 /// * `data` - Token data.1867 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1868 fn create_multiple_items_ex(1869 &self,1870 sender: T::CrossAccountId,1871 data: CreateItemExData<T::CrossAccountId>,1872 nesting_budget: &dyn Budget,1873 ) -> DispatchResultWithPostInfo;18741875 /// Burn token.1876 ///1877 /// * `sender` - The user who owns the token.1878 /// * `token` - Token id that will burned.1879 /// * `amount` - The number of parts of the token that will be burned.1880 fn burn_item(1881 &self,1882 sender: T::CrossAccountId,1883 token: TokenId,1884 amount: u128,1885 ) -> DispatchResultWithPostInfo;18861887 /// Burn token and all nested tokens recursievly.1888 ///1889 /// * `sender` - The user who owns the token.1890 /// * `token` - Token id that will burned.1891 /// * `self_budget` - The budget that can be spent on burning tokens.1892 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1893 fn burn_item_recursively(1894 &self,1895 sender: T::CrossAccountId,1896 token: TokenId,1897 self_budget: &dyn Budget,1898 breadth_budget: &dyn Budget,1899 ) -> DispatchResultWithPostInfo;19001901 /// Set collection properties.1902 ///1903 /// * `sender` - Must be either the owner of the collection or its admin.1904 /// * `properties` - Properties to be set.1905 fn set_collection_properties(1906 &self,1907 sender: T::CrossAccountId,1908 properties: Vec<Property>,1909 ) -> DispatchResultWithPostInfo;19101911 /// Delete collection properties.1912 ///1913 /// * `sender` - Must be either the owner of the collection or its admin.1914 /// * `properties` - The properties to be removed.1915 fn delete_collection_properties(1916 &self,1917 sender: &T::CrossAccountId,1918 property_keys: Vec<PropertyKey>,1919 ) -> DispatchResultWithPostInfo;19201921 /// Set token properties.1922 ///1923 /// The appropriate [`PropertyPermission`] for the token property1924 /// must be set with [`Self::set_token_property_permissions`].1925 ///1926 /// * `sender` - Must be either the owner of the token or its admin.1927 /// * `token_id` - The token for which the properties are being set.1928 /// * `properties` - Properties to be set.1929 /// * `budget` - Budget for setting properties.1930 fn set_token_properties(1931 &self,1932 sender: T::CrossAccountId,1933 token_id: TokenId,1934 properties: Vec<Property>,1935 budget: &dyn Budget,1936 ) -> DispatchResultWithPostInfo;19371938 /// Remove token properties.1939 ///1940 /// The appropriate [`PropertyPermission`] for the token property1941 /// must be set with [`Self::set_token_property_permissions`].1942 ///1943 /// * `sender` - Must be either the owner of the token or its admin.1944 /// * `token_id` - The token for which the properties are being remove.1945 /// * `property_keys` - Keys to remove corresponding properties.1946 /// * `budget` - Budget for removing properties.1947 fn delete_token_properties(1948 &self,1949 sender: T::CrossAccountId,1950 token_id: TokenId,1951 property_keys: Vec<PropertyKey>,1952 budget: &dyn Budget,1953 ) -> DispatchResultWithPostInfo;19541955 /// Set token property permissions.1956 ///1957 /// * `sender` - Must be either the owner of the token or its admin.1958 /// * `token_id` - The token for which the properties are being set.1959 /// * `property_permissions` - Property permissions to be set.1960 /// * `budget` - Budget for setting properties.1961 fn set_token_property_permissions(1962 &self,1963 sender: &T::CrossAccountId,1964 property_permissions: Vec<PropertyKeyPermission>,1965 ) -> DispatchResultWithPostInfo;19661967 /// Transfer amount of token pieces.1968 ///1969 /// * `sender` - Donor user.1970 /// * `to` - Recepient user.1971 /// * `token` - The token of which parts are being sent.1972 /// * `amount` - The number of parts of the token that will be transferred.1973 /// * `budget` - The maximum budget that can be spent on the transfer.1974 fn transfer(1975 &self,1976 sender: T::CrossAccountId,1977 to: T::CrossAccountId,1978 token: TokenId,1979 amount: u128,1980 budget: &dyn Budget,1981 ) -> DispatchResultWithPostInfo;19821983 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1984 ///1985 /// * `sender` - The user who grants access to the token.1986 /// * `spender` - The user to whom the rights are granted.1987 /// * `token` - The token to which access is granted.1988 /// * `amount` - The amount of pieces that another user can dispose of.1989 fn approve(1990 &self,1991 sender: T::CrossAccountId,1992 spender: T::CrossAccountId,1993 token: TokenId,1994 amount: u128,1995 ) -> DispatchResultWithPostInfo;19961997 /// Send parts of a token owned by another user.1998 ///1999 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2000 ///2001 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2002 /// * `from` - The user who owns the token.2003 /// * `to` - Recepient user.2004 /// * `token` - The token of which parts are being sent.2005 /// * `amount` - The number of parts of the token that will be transferred.2006 /// * `budget` - The maximum budget that can be spent on the transfer.2007 fn transfer_from(2008 &self,2009 sender: T::CrossAccountId,2010 from: T::CrossAccountId,2011 to: T::CrossAccountId,2012 token: TokenId,2013 amount: u128,2014 budget: &dyn Budget,2015 ) -> DispatchResultWithPostInfo;20162017 /// Burn parts of a token owned by another user.2018 ///2019 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2020 ///2021 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2022 /// * `from` - The user who owns the token.2023 /// * `token` - The token of which parts are being sent.2024 /// * `amount` - The number of parts of the token that will be transferred.2025 /// * `budget` - The maximum budget that can be spent on the burn.2026 fn burn_from(2027 &self,2028 sender: T::CrossAccountId,2029 from: T::CrossAccountId,2030 token: TokenId,2031 amount: u128,2032 budget: &dyn Budget,2033 ) -> DispatchResultWithPostInfo;20342035 /// Check permission to nest token.2036 ///2037 /// * `sender` - The user who initiated the check.2038 /// * `from` - The token that is checked for embedding.2039 /// * `under` - Token under which to check.2040 /// * `budget` - The maximum budget that can be spent on the check.2041 fn check_nesting(2042 &self,2043 sender: T::CrossAccountId,2044 from: (CollectionId, TokenId),2045 under: TokenId,2046 budget: &dyn Budget,2047 ) -> DispatchResult;20482049 /// Nest one token into another.2050 ///2051 /// * `under` - Token holder.2052 /// * `to_nest` - Nested token.2053 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20542055 /// Unnest token.2056 ///2057 /// * `under` - Token holder.2058 /// * `to_nest` - Token to unnest.2059 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20602061 /// Get all user tokens.2062 ///2063 /// * `account` - Account for which you need to get tokens.2064 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;20652066 /// Get all the tokens in the collection.2067 fn collection_tokens(&self) -> Vec<TokenId>;20682069 /// Check if the token exists.2070 ///2071 /// * `token` - Id token to check.2072 fn token_exists(&self, token: TokenId) -> bool;20732074 /// Get the id of the last minted token.2075 fn last_token_id(&self) -> TokenId;20762077 /// Get the owner of the token.2078 ///2079 /// * `token` - The token for which you need to find out the owner.2080 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;20812082 /// Returns 10 tokens owners in no particular order.2083 ///2084 /// * `token` - The token for which you need to find out the owners.2085 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;20862087 /// Get the value of the token property by key.2088 ///2089 /// * `token` - Token with the property to get.2090 /// * `key` - Property name.2091 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;20922093 /// Get a set of token properties by key vector.2094 ///2095 /// * `token` - Token with the property to get.2096 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2097 /// then all properties are returned.2098 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;20992100 /// Amount of unique collection tokens2101 fn total_supply(&self) -> u32;21022103 /// Amount of different tokens account has.2104 ///2105 /// * `account` - The account for which need to get the balance.2106 fn account_balance(&self, account: T::CrossAccountId) -> u32;21072108 /// Amount of specific token account have.2109 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;21102111 /// Amount of token pieces2112 fn total_pieces(&self, token: TokenId) -> Option<u128>;21132114 /// Get the number of parts of the token that a trusted user can manage.2115 ///2116 /// * `sender` - Trusted user.2117 /// * `spender` - Owner of the token.2118 /// * `token` - The token for which to get the value.2119 fn allowance(2120 &self,2121 sender: T::CrossAccountId,2122 spender: T::CrossAccountId,2123 token: TokenId,2124 ) -> u128;21252126 /// Get extension for RFT collection.2127 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;21282129 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2130 /// * `owner` - Token owner2131 /// * `operator` - Operator2132 /// * `approve` - Should operator status be granted or revoked?2133 fn set_allowance_for_all(2134 &self,2135 owner: T::CrossAccountId,2136 operator: T::CrossAccountId,2137 approve: bool,2138 ) -> DispatchResultWithPostInfo;21392140 /// Tells whether the given `owner` approves the `operator`.2141 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;21422143 /// Repairs a possibly broken item.2144 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2145}21462147/// Extension for RFT collection.2148pub trait RefungibleExtensions<T>2149where2150 T: Config,2151{2152 /// Change the number of parts of the token.2153 ///2154 /// When the value changes down, this function is equivalent to burning parts of the token.2155 ///2156 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2157 /// * `token` - The token for which you want to change the number of parts.2158 /// * `amount` - The new value of the parts of the token.2159 fn repartition(2160 &self,2161 sender: &T::CrossAccountId,2162 token: TokenId,2163 amount: u128,2164 ) -> DispatchResultWithPostInfo;2165}21662167/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2168///2169/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2170pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2171 let post_info = PostDispatchInfo {2172 actual_weight: Some(weight),2173 pays_fee: Pays::Yes,2174 };2175 match res {2176 Ok(()) => Ok(post_info),2177 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2178 }2179}21802181impl<T: Config> From<PropertiesError> for Error<T> {2182 fn from(error: PropertiesError) -> Self {2183 match error {2184 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2185 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2186 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2187 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2188 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2189 }2190 }2191}1// 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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63 ensure,64 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65 dispatch::Pays,66 transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70 COLLECTION_NUMBER_LIMIT,71 Collection,72 RpcCollection,73 CollectionFlags,74 RpcCollectionFlags,75 CollectionId,76 CreateItemData,77 MAX_TOKEN_PREFIX_LENGTH,78 COLLECTION_ADMINS_LIMIT,79 TokenId,80 TokenChild,81 CollectionStats,82 MAX_TOKEN_OWNERSHIP,83 CollectionMode,84 NFT_SPONSOR_TRANSFER_TIMEOUT,85 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87 MAX_SPONSOR_TIMEOUT,88 CUSTOM_DATA_LIMIT,89 CollectionLimits,90 CreateCollectionData,91 SponsorshipState,92 CreateItemExData,93 SponsoringRateLimit,94 budget::Budget,95 PhantomType,96 Property,97 Properties,98 PropertiesPermissionMap,99 PropertyKey,100 PropertyValue,101 PropertyPermission,102 PropertiesError,103 PropertyKeyPermission,104 TokenData,105 TrySetProperty,106 PropertyScope,107 // RMRK108 RmrkCollectionInfo,109 RmrkInstanceInfo,110 RmrkResourceInfo,111 RmrkPropertyInfo,112 RmrkBaseInfo,113 RmrkPartType,114 RmrkBoundedTheme,115 RmrkNftChild,116 CollectionPermissions,117};118119pub use pallet::*;120use sp_core::H160;121use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};122#[cfg(feature = "runtime-benchmarks")]123pub mod benchmarking;124pub mod dispatch;125pub mod erc;126pub mod eth;127pub mod weights;128129/// Weight info.130pub type SelfWeightOf<T> = <T as Config>::WeightInfo;131132/// Collection handle contains information about collection data and id.133/// Also provides functionality to count consumed gas.134///135/// CollectionHandle is used as a generic wrapper for collections of all types.136/// It allows to perform common operations and queries on any collection type,137/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].138#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]139pub struct CollectionHandle<T: Config> {140 /// Collection id141 pub id: CollectionId,142 collection: Collection<T::AccountId>,143 /// Substrate recorder for counting consumed gas144 pub recorder: SubstrateRecorder<T>,145}146147impl<T: Config> WithRecorder<T> for CollectionHandle<T> {148 fn recorder(&self) -> &SubstrateRecorder<T> {149 &self.recorder150 }151 fn into_recorder(self) -> SubstrateRecorder<T> {152 self.recorder153 }154}155156impl<T: Config> CollectionHandle<T> {157 /// Same as [CollectionHandle::new] but with an explicit gas limit.158 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {159 <CollectionById<T>>::get(id).map(|collection| Self {160 id,161 collection,162 recorder: SubstrateRecorder::new(gas_limit),163 })164 }165166 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].167 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {168 <CollectionById<T>>::get(id).map(|collection| Self {169 id,170 collection,171 recorder,172 })173 }174175 /// Retrives collection data from storage and creates collection handle with default parameters.176 /// If collection not found return `None`177 pub fn new(id: CollectionId) -> Option<Self> {178 Self::new_with_gas_limit(id, u64::MAX)179 }180181 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.182 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {183 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)184 }185186 /// Consume gas for reading.187 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {188 self.recorder189 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(190 <T as frame_system::Config>::DbWeight::get()191 .read192 .saturating_mul(reads),193 )))194 }195196 /// Consume gas for writing.197 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {198 self.recorder199 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(200 <T as frame_system::Config>::DbWeight::get()201 .write202 .saturating_mul(writes),203 )))204 }205206 /// Consume gas for reading and writing.207 pub fn consume_store_reads_and_writes(208 &self,209 reads: u64,210 writes: u64,211 ) -> evm_coder::execution::Result<()> {212 let weight = <T as frame_system::Config>::DbWeight::get();213 let reads = weight.read.saturating_mul(reads);214 let writes = weight.read.saturating_mul(writes);215 self.recorder216 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(217 reads.saturating_add(writes),218 )))219 }220221 /// Save collection to storage.222 pub fn save(&self) -> DispatchResult {223 <CollectionById<T>>::insert(self.id, &self.collection);224 Ok(())225 }226227 /// Set collection sponsor.228 ///229 /// Unique collections allows sponsoring for certain actions.230 /// This method allows you to set the sponsor of the collection.231 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].232 pub fn set_sponsor(233 &mut self,234 sender: &T::CrossAccountId,235 sponsor: T::AccountId,236 ) -> DispatchResult {237 self.check_is_internal()?;238 self.check_is_owner_or_admin(sender)?;239240 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());241242 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));243 <PalletEvm<T>>::deposit_log(244 erc::CollectionHelpersEvents::CollectionChanged {245 collection_id: eth::collection_id_to_address(self.id),246 }247 .to_log(T::ContractAddress::get()),248 );249250 self.save()251 }252253 /// Force set `sponsor`.254 ///255 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation256 /// from the `sponsor` is not required.257 ///258 /// # Arguments259 ///260 /// * `sender`: Caller's account.261 /// * `sponsor`: ID of the account of the sponsor-to-be.262 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {263 self.check_is_internal()?;264265 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());266267 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));268 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));269 <PalletEvm<T>>::deposit_log(270 erc::CollectionHelpersEvents::CollectionChanged {271 collection_id: eth::collection_id_to_address(self.id),272 }273 .to_log(T::ContractAddress::get()),274 );275276 self.save()277 }278279 /// Confirm sponsorship280 ///281 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.282 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].283 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {284 self.check_is_internal()?;285 ensure!(286 self.collection.sponsorship.pending_sponsor() == Some(sender),287 Error::<T>::ConfirmSponsorshipFail288 );289290 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());291292 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));293 <PalletEvm<T>>::deposit_log(294 erc::CollectionHelpersEvents::CollectionChanged {295 collection_id: eth::collection_id_to_address(self.id),296 }297 .to_log(T::ContractAddress::get()),298 );299300 self.save()301 }302303 /// Remove collection sponsor.304 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {305 self.check_is_internal()?;306 self.check_is_owner_or_admin(sender)?;307308 self.collection.sponsorship = SponsorshipState::Disabled;309310 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));311 <PalletEvm<T>>::deposit_log(312 erc::CollectionHelpersEvents::CollectionChanged {313 collection_id: eth::collection_id_to_address(self.id),314 }315 .to_log(T::ContractAddress::get()),316 );317 self.save()318 }319320 /// Force remove `sponsor`.321 ///322 /// Differs from `remove_sponsor` in that323 /// it doesn't require consent from the `owner` of the collection.324 pub fn force_remove_sponsor(&mut self) -> DispatchResult {325 self.check_is_internal()?;326327 self.collection.sponsorship = SponsorshipState::Disabled;328329 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));330 <PalletEvm<T>>::deposit_log(331 erc::CollectionHelpersEvents::CollectionChanged {332 collection_id: eth::collection_id_to_address(self.id),333 }334 .to_log(T::ContractAddress::get()),335 );336 self.save()337 }338339 /// Checks that the collection was created with, and must be operated upon through **Unique API**.340 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.341 pub fn check_is_internal(&self) -> DispatchResult {342 if self.flags.external {343 return Err(<Error<T>>::CollectionIsExternal)?;344 }345346 Ok(())347 }348349 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.350 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.351 pub fn check_is_external(&self) -> DispatchResult {352 if !self.flags.external {353 return Err(<Error<T>>::CollectionIsInternal)?;354 }355356 Ok(())357 }358}359360impl<T: Config> Deref for CollectionHandle<T> {361 type Target = Collection<T::AccountId>;362363 fn deref(&self) -> &Self::Target {364 &self.collection365 }366}367368impl<T: Config> DerefMut for CollectionHandle<T> {369 fn deref_mut(&mut self) -> &mut Self::Target {370 &mut self.collection371 }372}373374impl<T: Config> CollectionHandle<T> {375 /// Checks if the `user` is the owner of the collection.376 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {377 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);378 Ok(())379 }380381 /// Returns **true** if the `user` is the owner or administrator of the collection.382 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {383 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))384 }385386 /// Checks if the `user` is the owner or administrator of the collection.387 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {388 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);389 Ok(())390 }391392 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.393 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {394 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)395 }396397 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.398 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {399 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)400 }401402 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.403 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {404 ensure!(405 <Allowlist<T>>::get((self.id, user)),406 <Error<T>>::AddressNotInAllowlist407 );408 Ok(())409 }410411 /// Changes collection owner to another account412 /// #### Store read/writes413 /// 1 writes414 pub fn change_owner(415 &mut self,416 caller: T::CrossAccountId,417 new_owner: T::CrossAccountId,418 ) -> DispatchResult {419 self.check_is_internal()?;420 self.check_is_owner(&caller)?;421 self.collection.owner = new_owner.as_sub().clone();422423 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(424 self.id,425 new_owner.as_sub().clone(),426 ));427 <PalletEvm<T>>::deposit_log(428 erc::CollectionHelpersEvents::CollectionChanged {429 collection_id: eth::collection_id_to_address(self.id),430 }431 .to_log(T::ContractAddress::get()),432 );433434 self.save()435 }436}437438#[frame_support::pallet]439pub mod pallet {440 use super::*;441 use dispatch::CollectionDispatch;442 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};443 use frame_system::pallet_prelude::*;444 use frame_support::traits::Currency;445 use up_data_structs::{TokenId, mapping::TokenAddressMapping};446 use scale_info::TypeInfo;447 use weights::WeightInfo;448449 #[pallet::config]450 pub trait Config:451 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo452 {453 /// Weight information for functions of this pallet.454 type WeightInfo: WeightInfo;455456 /// Events compatible with [`frame_system::Config::Event`].457 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;458459 /// Handler of accounts and payment.460 type Currency: Currency<Self::AccountId>;461462 /// Set price to create a collection.463 #[pallet::constant]464 type CollectionCreationPrice: Get<465 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,466 >;467468 /// Dispatcher of operations on collections.469 type CollectionDispatch: CollectionDispatch<Self>;470471 /// Account which holds the chain's treasury.472 type TreasuryAccountId: Get<Self::AccountId>;473474 /// Address under which the CollectionHelper contract would be available.475 #[pallet::constant]476 type ContractAddress: Get<H160>;477478 /// Mapper for token addresses to Ethereum addresses.479 type EvmTokenAddressMapping: TokenAddressMapping<H160>;480481 /// Mapper for token addresses to [`CrossAccountId`].482 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;483 }484485 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);486487 #[pallet::pallet]488 #[pallet::storage_version(STORAGE_VERSION)]489 #[pallet::generate_store(pub(super) trait Store)]490 pub struct Pallet<T>(_);491492 #[pallet::extra_constants]493 impl<T: Config> Pallet<T> {494 /// Maximum admins per collection.495 pub fn collection_admins_limit() -> u32 {496 COLLECTION_ADMINS_LIMIT497 }498 }499500 #[pallet::event]501 #[pallet::generate_deposit(pub fn deposit_event)]502 pub enum Event<T: Config> {503 /// New collection was created504 CollectionCreated(505 /// Globally unique identifier of newly created collection.506 CollectionId,507 /// [`CollectionMode`] converted into _u8_.508 u8,509 /// Collection owner.510 T::AccountId,511 ),512513 /// New collection was destroyed514 CollectionDestroyed(515 /// Globally unique identifier of collection.516 CollectionId,517 ),518519 /// New item was created.520 ItemCreated(521 /// Id of the collection where item was created.522 CollectionId,523 /// Id of an item. Unique within the collection.524 TokenId,525 /// Owner of newly created item526 T::CrossAccountId,527 /// Always 1 for NFT528 u128,529 ),530531 /// Collection item was burned.532 ItemDestroyed(533 /// Id of the collection where item was destroyed.534 CollectionId,535 /// Identifier of burned NFT.536 TokenId,537 /// Which user has destroyed its tokens.538 T::CrossAccountId,539 /// Amount of token pieces destroed. Always 1 for NFT.540 u128,541 ),542543 /// Item was transferred544 Transfer(545 /// Id of collection to which item is belong.546 CollectionId,547 /// Id of an item.548 TokenId,549 /// Original owner of item.550 T::CrossAccountId,551 /// New owner of item.552 T::CrossAccountId,553 /// Amount of token pieces transfered. Always 1 for NFT.554 u128,555 ),556557 /// Amount pieces of token owned by `sender` was approved for `spender`.558 Approved(559 /// Id of collection to which item is belong.560 CollectionId,561 /// Id of an item.562 TokenId,563 /// Original owner of item.564 T::CrossAccountId,565 /// Id for which the approval was granted.566 T::CrossAccountId,567 /// Amount of token pieces transfered. Always 1 for NFT.568 u128,569 ),570571 /// A `sender` approves operations on all owned tokens for `spender`.572 ApprovedForAll(573 /// Id of collection to which item is belong.574 CollectionId,575 /// Owner of a wallet.576 T::CrossAccountId,577 /// Id for which operator status was granted or rewoked.578 T::CrossAccountId,579 /// Is operator status granted or revoked?580 bool,581 ),582583 /// The colletion property has been added or edited.584 CollectionPropertySet(585 /// Id of collection to which property has been set.586 CollectionId,587 /// The property that was set.588 PropertyKey,589 ),590591 /// The property has been deleted.592 CollectionPropertyDeleted(593 /// Id of collection to which property has been deleted.594 CollectionId,595 /// The property that was deleted.596 PropertyKey,597 ),598599 /// The token property has been added or edited.600 TokenPropertySet(601 /// Identifier of the collection whose token has the property set.602 CollectionId,603 /// The token for which the property was set.604 TokenId,605 /// The property that was set.606 PropertyKey,607 ),608609 /// The token property has been deleted.610 TokenPropertyDeleted(611 /// Identifier of the collection whose token has the property deleted.612 CollectionId,613 /// The token for which the property was deleted.614 TokenId,615 /// The property that was deleted.616 PropertyKey,617 ),618619 /// The token property permission of a collection has been set.620 PropertyPermissionSet(621 /// ID of collection to which property permission has been set.622 CollectionId,623 /// The property permission that was set.624 PropertyKey,625 ),626627 /// Address was added to the allow list.628 AllowListAddressAdded(629 /// ID of the affected collection.630 CollectionId,631 /// Address of the added account.632 T::CrossAccountId,633 ),634635 /// Address was removed from the allow list.636 AllowListAddressRemoved(637 /// ID of the affected collection.638 CollectionId,639 /// Address of the removed account.640 T::CrossAccountId,641 ),642643 /// Collection admin was added.644 CollectionAdminAdded(645 /// ID of the affected collection.646 CollectionId,647 /// Admin address.648 T::CrossAccountId,649 ),650651 /// Collection admin was removed.652 CollectionAdminRemoved(653 /// ID of the affected collection.654 CollectionId,655 /// Removed admin address.656 T::CrossAccountId,657 ),658659 /// Collection limits were set.660 CollectionLimitSet(661 /// ID of the affected collection.662 CollectionId,663 ),664665 /// Collection owned was changed.666 CollectionOwnerChanged(667 /// ID of the affected collection.668 CollectionId,669 /// New owner address.670 T::AccountId,671 ),672673 /// Collection permissions were set.674 CollectionPermissionSet(675 /// ID of the affected collection.676 CollectionId,677 ),678679 /// Collection sponsor was set.680 CollectionSponsorSet(681 /// ID of the affected collection.682 CollectionId,683 /// New sponsor address.684 T::AccountId,685 ),686687 /// New sponsor was confirm.688 SponsorshipConfirmed(689 /// ID of the affected collection.690 CollectionId,691 /// New sponsor address.692 T::AccountId,693 ),694695 /// Collection sponsor was removed.696 CollectionSponsorRemoved(697 /// ID of the affected collection.698 CollectionId,699 ),700 }701702 #[pallet::error]703 pub enum Error<T> {704 /// This collection does not exist.705 CollectionNotFound,706 /// Sender parameter and item owner must be equal.707 MustBeTokenOwner,708 /// No permission to perform action709 NoPermission,710 /// Destroying only empty collections is allowed711 CantDestroyNotEmptyCollection,712 /// Collection is not in mint mode.713 PublicMintingNotAllowed,714 /// Address is not in allow list.715 AddressNotInAllowlist,716717 /// Collection name can not be longer than 63 char.718 CollectionNameLimitExceeded,719 /// Collection description can not be longer than 255 char.720 CollectionDescriptionLimitExceeded,721 /// Token prefix can not be longer than 15 char.722 CollectionTokenPrefixLimitExceeded,723 /// Total collections bound exceeded.724 TotalCollectionsLimitExceeded,725 /// Exceeded max admin count726 CollectionAdminCountExceeded,727 /// Collection limit bounds per collection exceeded728 CollectionLimitBoundsExceeded,729 /// Tried to enable permissions which are only permitted to be disabled730 OwnerPermissionsCantBeReverted,731 /// Collection settings not allowing items transferring732 TransferNotAllowed,733 /// Account token limit exceeded per collection734 AccountTokenLimitExceeded,735 /// Collection token limit exceeded736 CollectionTokenLimitExceeded,737 /// Metadata flag frozen738 MetadataFlagFrozen,739740 /// Item does not exist741 TokenNotFound,742 /// Item is balance not enough743 TokenValueTooLow,744 /// Requested value is more than the approved745 ApprovedValueTooLow,746 /// Tried to approve more than owned747 CantApproveMoreThanOwned,748749 /// Can't transfer tokens to ethereum zero address750 AddressIsZero,751752 /// The operation is not supported753 UnsupportedOperation,754755 /// Insufficient funds to perform an action756 NotSufficientFounds,757758 /// User does not satisfy the nesting rule759 UserIsNotAllowedToNest,760 /// Only tokens from specific collections may nest tokens under this one761 SourceCollectionIsNotAllowedToNest,762763 /// Tried to store more data than allowed in collection field764 CollectionFieldSizeExceeded,765766 /// Tried to store more property data than allowed767 NoSpaceForProperty,768769 /// Tried to store more property keys than allowed770 PropertyLimitReached,771772 /// Property key is too long773 PropertyKeyIsTooLong,774775 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed776 InvalidCharacterInPropertyKey,777778 /// Empty property keys are forbidden779 EmptyPropertyKey,780781 /// Tried to access an external collection with an internal API782 CollectionIsExternal,783784 /// Tried to access an internal collection with an external API785 CollectionIsInternal,786787 /// This address is not set as sponsor, use setCollectionSponsor first.788 ConfirmSponsorshipFail,789790 /// The user is not an administrator.791 UserIsNotCollectionAdmin,792 }793794 /// Storage of the count of created collections. Essentially contains the last collection ID.795 #[pallet::storage]796 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;797798 /// Storage of the count of deleted collections.799 #[pallet::storage]800 pub type DestroyedCollectionCount<T> =801 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;802803 /// Storage of collection info.804 #[pallet::storage]805 pub type CollectionById<T> = StorageMap<806 Hasher = Blake2_128Concat,807 Key = CollectionId,808 Value = Collection<<T as frame_system::Config>::AccountId>,809 QueryKind = OptionQuery,810 >;811812 /// Storage of collection properties.813 #[pallet::storage]814 #[pallet::getter(fn collection_properties)]815 pub type CollectionProperties<T> = StorageMap<816 Hasher = Blake2_128Concat,817 Key = CollectionId,818 Value = Properties,819 QueryKind = ValueQuery,820 OnEmpty = up_data_structs::CollectionProperties,821 >;822823 /// Storage of token property permissions of a collection.824 #[pallet::storage]825 #[pallet::getter(fn property_permissions)]826 pub type CollectionPropertyPermissions<T> = StorageMap<827 Hasher = Blake2_128Concat,828 Key = CollectionId,829 Value = PropertiesPermissionMap,830 QueryKind = ValueQuery,831 >;832833 /// Storage of the amount of collection admins.834 #[pallet::storage]835 pub type AdminAmount<T> = StorageMap<836 Hasher = Blake2_128Concat,837 Key = CollectionId,838 Value = u32,839 QueryKind = ValueQuery,840 >;841842 /// List of collection admins.843 #[pallet::storage]844 pub type IsAdmin<T: Config> = StorageNMap<845 Key = (846 Key<Blake2_128Concat, CollectionId>,847 Key<Blake2_128Concat, T::CrossAccountId>,848 ),849 Value = bool,850 QueryKind = ValueQuery,851 >;852853 /// Allowlisted collection users.854 #[pallet::storage]855 pub type Allowlist<T: Config> = StorageNMap<856 Key = (857 Key<Blake2_128Concat, CollectionId>,858 Key<Blake2_128Concat, T::CrossAccountId>,859 ),860 Value = bool,861 QueryKind = ValueQuery,862 >;863864 /// Not used by code, exists only to provide some types to metadata.865 #[pallet::storage]866 pub type DummyStorageValue<T: Config> = StorageValue<867 Value = (868 CollectionStats,869 CollectionId,870 TokenId,871 TokenChild,872 PhantomType<(873 TokenData<T::CrossAccountId>,874 RpcCollection<T::AccountId>,875 // RMRK876 RmrkCollectionInfo<T::AccountId>,877 RmrkInstanceInfo<T::AccountId>,878 RmrkResourceInfo,879 RmrkPropertyInfo,880 RmrkBaseInfo<T::AccountId>,881 RmrkPartType,882 RmrkBoundedTheme,883 RmrkNftChild,884 )>,885 ),886 QueryKind = OptionQuery,887 >;888889 #[pallet::hooks]890 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {891 fn on_runtime_upgrade() -> Weight {892 StorageVersion::new(1).put::<Pallet<T>>();893894 Weight::zero()895 }896 }897}898899impl<T: Config> Pallet<T> {900 /// Enshure that receiver address is correct.901 ///902 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.903 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {904 ensure!(905 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,906 <Error<T>>::AddressIsZero907 );908 Ok(())909 }910911 /// Get a vector of collection admins.912 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {913 <IsAdmin<T>>::iter_prefix((collection,))914 .map(|(a, _)| a)915 .collect()916 }917918 /// Get a vector of users allowed to mint tokens.919 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {920 <Allowlist<T>>::iter_prefix((collection,))921 .map(|(a, _)| a)922 .collect()923 }924925 /// Is `user` allowed to mint token in `collection`.926 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {927 <Allowlist<T>>::get((collection, user))928 }929930 /// Get statistics of collections.931 pub fn collection_stats() -> CollectionStats {932 let created = <CreatedCollectionCount<T>>::get();933 let destroyed = <DestroyedCollectionCount<T>>::get();934 CollectionStats {935 created: created.0,936 destroyed: destroyed.0,937 alive: created.0 - destroyed.0,938 }939 }940941 /// Get the effective limits for the collection.942 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {943 let collection = <CollectionById<T>>::get(collection)?;944 let limits = collection.limits;945 let effective_limits = CollectionLimits {946 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),947 sponsored_data_size: Some(limits.sponsored_data_size()),948 sponsored_data_rate_limit: Some(949 limits950 .sponsored_data_rate_limit951 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),952 ),953 token_limit: Some(limits.token_limit()),954 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(955 match collection.mode {956 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,957 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,958 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,959 },960 )),961 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),962 owner_can_transfer: Some(limits.owner_can_transfer()),963 owner_can_destroy: Some(limits.owner_can_destroy()),964 transfers_enabled: Some(limits.transfers_enabled()),965 };966967 Some(effective_limits)968 }969970 /// Returns information about the `collection` adapted for rpc.971 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {972 let Collection {973 name,974 description,975 owner,976 mode,977 token_prefix,978 sponsorship,979 limits,980 permissions,981 flags,982 } = <CollectionById<T>>::get(collection)?;983984 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)985 .into_iter()986 .map(|(key, permission)| PropertyKeyPermission { key, permission })987 .collect();988989 let properties = <CollectionProperties<T>>::get(collection)990 .into_iter()991 .map(|(key, value)| Property { key, value })992 .collect();993994 let permissions = CollectionPermissions {995 access: Some(permissions.access()),996 mint_mode: Some(permissions.mint_mode()),997 nesting: Some(permissions.nesting().clone()),998 };9991000 Some(RpcCollection {1001 name: name.into_inner(),1002 description: description.into_inner(),1003 owner,1004 mode,1005 token_prefix: token_prefix.into_inner(),1006 sponsorship,1007 limits,1008 permissions,1009 token_property_permissions,1010 properties,1011 read_only: flags.external,10121013 flags: RpcCollectionFlags {1014 foreign: flags.foreign,1015 erc721metadata: flags.erc721metadata,1016 },1017 })1018 }1019}10201021macro_rules! limit_default {1022 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1023 $(1024 if let Some($new) = $new.$field {1025 let $old = $old.$field($($arg)?);1026 let _ = $new;1027 let _ = $old;1028 $check1029 } else {1030 $new.$field = $old.$field1031 }1032 )*1033 }};1034}1035macro_rules! limit_default_clone {1036 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1037 $(1038 if let Some($new) = $new.$field.clone() {1039 let $old = $old.$field($($arg)?);1040 let _ = $new;1041 let _ = $old;1042 $check1043 } else {1044 $new.$field = $old.$field.clone()1045 }1046 )*1047 }};1048}10491050impl<T: Config> Pallet<T> {1051 /// Create new collection.1052 ///1053 /// * `owner` - The owner of the collection.1054 /// * `data` - Description of the created collection.1055 /// * `flags` - Extra flags to store.1056 pub fn init_collection(1057 owner: T::CrossAccountId,1058 payer: T::CrossAccountId,1059 data: CreateCollectionData<T::AccountId>,1060 flags: CollectionFlags,1061 ) -> Result<CollectionId, DispatchError> {1062 {1063 ensure!(1064 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1065 Error::<T>::CollectionTokenPrefixLimitExceeded1066 );1067 }10681069 let created_count = <CreatedCollectionCount<T>>::get()1070 .01071 .checked_add(1)1072 .ok_or(ArithmeticError::Overflow)?;1073 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1074 let id = CollectionId(created_count);10751076 // bound Total number of collections1077 ensure!(1078 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1079 <Error<T>>::TotalCollectionsLimitExceeded1080 );10811082 // =========10831084 let collection = Collection {1085 owner: owner.as_sub().clone(),1086 name: data.name,1087 mode: data.mode.clone(),1088 description: data.description,1089 token_prefix: data.token_prefix,1090 sponsorship: data1091 .pending_sponsor1092 .map(SponsorshipState::Unconfirmed)1093 .unwrap_or_default(),1094 limits: data1095 .limits1096 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1097 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1098 permissions: data1099 .permissions1100 .map(|permissions| {1101 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1102 })1103 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1104 flags,1105 };11061107 let mut collection_properties = up_data_structs::CollectionProperties::get();1108 collection_properties1109 .try_set_from_iter(data.properties.into_iter())1110 .map_err(<Error<T>>::from)?;11111112 CollectionProperties::<T>::insert(id, collection_properties);11131114 let mut token_props_permissions = PropertiesPermissionMap::new();1115 token_props_permissions1116 .try_set_from_iter(data.token_property_permissions.into_iter())1117 .map_err(<Error<T>>::from)?;11181119 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11201121 // Take a (non-refundable) deposit of collection creation1122 {1123 let mut imbalance =1124 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1125 imbalance.subsume(1126 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1127 &T::TreasuryAccountId::get(),1128 T::CollectionCreationPrice::get(),1129 ),1130 );1131 <T as Config>::Currency::settle(1132 payer.as_sub(),1133 imbalance,1134 WithdrawReasons::TRANSFER,1135 ExistenceRequirement::KeepAlive,1136 )1137 .map_err(|_| Error::<T>::NotSufficientFounds)?;1138 }11391140 <CreatedCollectionCount<T>>::put(created_count);1141 <Pallet<T>>::deposit_event(Event::CollectionCreated(1142 id,1143 data.mode.id(),1144 owner.as_sub().clone(),1145 ));1146 <PalletEvm<T>>::deposit_log(1147 erc::CollectionHelpersEvents::CollectionCreated {1148 owner: *owner.as_eth(),1149 collection_id: eth::collection_id_to_address(id),1150 }1151 .to_log(T::ContractAddress::get()),1152 );1153 <CollectionById<T>>::insert(id, collection);1154 Ok(id)1155 }11561157 /// Destroy collection.1158 ///1159 /// * `collection` - Collection handler.1160 /// * `sender` - The owner or administrator of the collection.1161 pub fn destroy_collection(1162 collection: CollectionHandle<T>,1163 sender: &T::CrossAccountId,1164 ) -> DispatchResult {1165 ensure!(1166 collection.limits.owner_can_destroy(),1167 <Error<T>>::NoPermission,1168 );1169 collection.check_is_owner(sender)?;11701171 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1172 .01173 .checked_add(1)1174 .ok_or(ArithmeticError::Overflow)?;11751176 // =========11771178 <DestroyedCollectionCount<T>>::put(destroyed_collections);1179 <CollectionById<T>>::remove(collection.id);1180 <AdminAmount<T>>::remove(collection.id);1181 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1182 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1183 <CollectionProperties<T>>::remove(collection.id);11841185 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11861187 <PalletEvm<T>>::deposit_log(1188 erc::CollectionHelpersEvents::CollectionDestroyed {1189 collection_id: eth::collection_id_to_address(collection.id),1190 }1191 .to_log(T::ContractAddress::get()),1192 );1193 Ok(())1194 }11951196 /// Set collection property.1197 ///1198 /// * `collection` - Collection handler.1199 /// * `sender` - The owner or administrator of the collection.1200 /// * `property` - The property to set.1201 pub fn set_collection_property(1202 collection: &CollectionHandle<T>,1203 sender: &T::CrossAccountId,1204 property: Property,1205 ) -> DispatchResult {1206 collection.check_is_owner_or_admin(sender)?;12071208 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1209 let property = property.clone();1210 properties.try_set(property.key, property.value)1211 })1212 .map_err(<Error<T>>::from)?;12131214 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));1215 <PalletEvm<T>>::deposit_log(1216 erc::CollectionHelpersEvents::CollectionChanged {1217 collection_id: eth::collection_id_to_address(collection.id),1218 }1219 .to_log(T::ContractAddress::get()),1220 );12211222 Ok(())1223 }12241225 /// Set a scoped collection property, where the scope is a special prefix1226 /// prohibiting a user to change the property.1227 ///1228 /// * `collection_id` - ID of the collection for which the property is being set.1229 /// * `scope` - Property scope.1230 /// * `property` - The property to set.1231 pub fn set_scoped_collection_property(1232 collection_id: CollectionId,1233 scope: PropertyScope,1234 property: Property,1235 ) -> DispatchResult {1236 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1237 properties.try_scoped_set(scope, property.key, property.value)1238 })1239 .map_err(<Error<T>>::from)?;12401241 Ok(())1242 }12431244 /// Set scoped collection properties, where the scope is a special prefix1245 /// prohibiting a user to change the properties.1246 ///1247 /// * `collection_id` - ID of the collection for which the properties is being set.1248 /// * `scope` - Property scope.1249 /// * `properties` - The properties to set.1250 pub fn set_scoped_collection_properties(1251 collection_id: CollectionId,1252 scope: PropertyScope,1253 properties: impl Iterator<Item = Property>,1254 ) -> DispatchResult {1255 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1256 stored_properties.try_scoped_set_from_iter(scope, properties)1257 })1258 .map_err(<Error<T>>::from)?;12591260 Ok(())1261 }12621263 /// Set collection properties.1264 ///1265 /// * `collection` - Collection handler.1266 /// * `sender` - The owner or administrator of the collection.1267 /// * `properties` - The properties to set.1268 #[transactional]1269 pub fn set_collection_properties(1270 collection: &CollectionHandle<T>,1271 sender: &T::CrossAccountId,1272 properties: Vec<Property>,1273 ) -> DispatchResult {1274 for property in properties {1275 Self::set_collection_property(collection, sender, property)?;1276 }12771278 Ok(())1279 }12801281 /// Delete collection property.1282 ///1283 /// * `collection` - Collection handler.1284 /// * `sender` - The owner or administrator of the collection.1285 /// * `property` - The property to delete.1286 pub fn delete_collection_property(1287 collection: &CollectionHandle<T>,1288 sender: &T::CrossAccountId,1289 property_key: PropertyKey,1290 ) -> DispatchResult {1291 collection.check_is_owner_or_admin(sender)?;12921293 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1294 properties.remove(&property_key)1295 })1296 .map_err(<Error<T>>::from)?;12971298 Self::deposit_event(Event::CollectionPropertyDeleted(1299 collection.id,1300 property_key,1301 ));1302 <PalletEvm<T>>::deposit_log(1303 erc::CollectionHelpersEvents::CollectionChanged {1304 collection_id: eth::collection_id_to_address(collection.id),1305 }1306 .to_log(T::ContractAddress::get()),1307 );13081309 Ok(())1310 }13111312 /// Delete collection properties.1313 ///1314 /// * `collection` - Collection handler.1315 /// * `sender` - The owner or administrator of the collection.1316 /// * `properties` - The properties to delete.1317 #[transactional]1318 pub fn delete_collection_properties(1319 collection: &CollectionHandle<T>,1320 sender: &T::CrossAccountId,1321 property_keys: Vec<PropertyKey>,1322 ) -> DispatchResult {1323 for key in property_keys {1324 Self::delete_collection_property(collection, sender, key)?;1325 }13261327 Ok(())1328 }13291330 /// Set collection propetry permission without any checks.1331 ///1332 /// Used for migrations.1333 ///1334 /// * `collection` - Collection handler.1335 /// * `property_permissions` - Property permissions.1336 pub fn set_property_permission_unchecked(1337 collection: CollectionId,1338 property_permission: PropertyKeyPermission,1339 ) -> DispatchResult {1340 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1341 permissions.try_set(property_permission.key, property_permission.permission)1342 })1343 .map_err(<Error<T>>::from)?;1344 Ok(())1345 }13461347 /// Set collection property permission.1348 ///1349 /// * `collection` - Collection handler.1350 /// * `sender` - The owner or administrator of the collection.1351 /// * `property_permission` - Property permission.1352 pub fn set_property_permission(1353 collection: &CollectionHandle<T>,1354 sender: &T::CrossAccountId,1355 property_permission: PropertyKeyPermission,1356 ) -> DispatchResult {1357 Self::set_scoped_property_permission(1358 collection,1359 sender,1360 PropertyScope::None,1361 property_permission,1362 )1363 }13641365 /// Set collection property permission with scope.1366 ///1367 /// * `collection` - Collection handler.1368 /// * `sender` - The owner or administrator of the collection.1369 /// * `scope` - Property scope.1370 /// * `property_permission` - Property permission.1371 pub fn set_scoped_property_permission(1372 collection: &CollectionHandle<T>,1373 sender: &T::CrossAccountId,1374 scope: PropertyScope,1375 property_permission: PropertyKeyPermission,1376 ) -> DispatchResult {1377 collection.check_is_owner_or_admin(sender)?;13781379 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1380 let current_permission = all_permissions.get(&property_permission.key);1381 if matches![1382 current_permission,1383 Some(PropertyPermission { mutable: false, .. })1384 ] {1385 return Err(<Error<T>>::NoPermission.into());1386 }13871388 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1389 let property_permission = property_permission.clone();1390 permissions.try_scoped_set(1391 scope,1392 property_permission.key,1393 property_permission.permission,1394 )1395 })1396 .map_err(<Error<T>>::from)?;13971398 Self::deposit_event(Event::PropertyPermissionSet(1399 collection.id,1400 property_permission.key,1401 ));1402 <PalletEvm<T>>::deposit_log(1403 erc::CollectionHelpersEvents::CollectionChanged {1404 collection_id: eth::collection_id_to_address(collection.id),1405 }1406 .to_log(T::ContractAddress::get()),1407 );14081409 Ok(())1410 }14111412 /// Set token property permission.1413 ///1414 /// * `collection` - Collection handler.1415 /// * `sender` - The owner or administrator of the collection.1416 /// * `property_permissions` - Property permissions.1417 #[transactional]1418 pub fn set_token_property_permissions(1419 collection: &CollectionHandle<T>,1420 sender: &T::CrossAccountId,1421 property_permissions: Vec<PropertyKeyPermission>,1422 ) -> DispatchResult {1423 Self::set_scoped_token_property_permissions(1424 collection,1425 sender,1426 PropertyScope::None,1427 property_permissions,1428 )1429 }14301431 /// Set token property permission with scope.1432 ///1433 /// * `collection` - Collection handler.1434 /// * `sender` - The owner or administrator of the collection.1435 /// * `scope` - Property scope.1436 /// * `property_permissions` - Property permissions.1437 #[transactional]1438 pub fn set_scoped_token_property_permissions(1439 collection: &CollectionHandle<T>,1440 sender: &T::CrossAccountId,1441 scope: PropertyScope,1442 property_permissions: Vec<PropertyKeyPermission>,1443 ) -> DispatchResult {1444 for prop_pemission in property_permissions {1445 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1446 }14471448 Ok(())1449 }14501451 /// Get collection property.1452 pub fn get_collection_property(1453 collection_id: CollectionId,1454 key: &PropertyKey,1455 ) -> Option<PropertyValue> {1456 Self::collection_properties(collection_id).get(key).cloned()1457 }14581459 /// Convert byte vector to property key vector.1460 pub fn bytes_keys_to_property_keys(1461 keys: Vec<Vec<u8>>,1462 ) -> Result<Vec<PropertyKey>, DispatchError> {1463 keys.into_iter()1464 .map(|key| -> Result<PropertyKey, DispatchError> {1465 key.try_into()1466 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1467 })1468 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1469 }14701471 /// Get properties according to given keys.1472 pub fn filter_collection_properties(1473 collection_id: CollectionId,1474 keys: Option<Vec<PropertyKey>>,1475 ) -> Result<Vec<Property>, DispatchError> {1476 let properties = Self::collection_properties(collection_id);14771478 let properties = keys1479 .map(|keys| {1480 keys.into_iter()1481 .filter_map(|key| {1482 properties.get(&key).map(|value| Property {1483 key,1484 value: value.clone(),1485 })1486 })1487 .collect()1488 })1489 .unwrap_or_else(|| {1490 properties1491 .into_iter()1492 .map(|(key, value)| Property { key, value })1493 .collect()1494 });14951496 Ok(properties)1497 }14981499 /// Get property permissions according to given keys.1500 pub fn filter_property_permissions(1501 collection_id: CollectionId,1502 keys: Option<Vec<PropertyKey>>,1503 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1504 let permissions = Self::property_permissions(collection_id);15051506 let key_permissions = keys1507 .map(|keys| {1508 keys.into_iter()1509 .filter_map(|key| {1510 permissions1511 .get(&key)1512 .map(|permission| PropertyKeyPermission {1513 key,1514 permission: permission.clone(),1515 })1516 })1517 .collect()1518 })1519 .unwrap_or_else(|| {1520 permissions1521 .into_iter()1522 .map(|(key, permission)| PropertyKeyPermission { key, permission })1523 .collect()1524 });15251526 Ok(key_permissions)1527 }15281529 /// Toggle `user` participation in the `collection`'s allow list.1530 /// #### Store read/writes1531 /// 1 writes1532 pub fn toggle_allowlist(1533 collection: &CollectionHandle<T>,1534 sender: &T::CrossAccountId,1535 user: &T::CrossAccountId,1536 allowed: bool,1537 ) -> DispatchResult {1538 collection.check_is_owner_or_admin(sender)?;15391540 // =========15411542 if allowed {1543 <Allowlist<T>>::insert((collection.id, user), true);1544 Self::deposit_event(Event::<T>::AllowListAddressAdded(1545 collection.id,1546 user.clone(),1547 ));1548 } else {1549 <Allowlist<T>>::remove((collection.id, user));1550 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1551 collection.id,1552 user.clone(),1553 ));1554 }15551556 <PalletEvm<T>>::deposit_log(1557 erc::CollectionHelpersEvents::CollectionChanged {1558 collection_id: eth::collection_id_to_address(collection.id),1559 }1560 .to_log(T::ContractAddress::get()),1561 );15621563 Ok(())1564 }15651566 /// Toggle `user` participation in the `collection`'s admin list.1567 /// #### Store read/writes1568 /// 2 reads, 2 writes1569 pub fn toggle_admin(1570 collection: &CollectionHandle<T>,1571 sender: &T::CrossAccountId,1572 user: &T::CrossAccountId,1573 admin: bool,1574 ) -> DispatchResult {1575 collection.check_is_internal()?;1576 collection.check_is_owner(sender)?;15771578 let is_admin = <IsAdmin<T>>::get((collection.id, user));1579 if is_admin == admin {1580 if admin {1581 return Ok(());1582 } else {1583 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1584 }1585 }1586 let amount = <AdminAmount<T>>::get(collection.id);15871588 // =========15891590 if admin {1591 let amount = amount1592 .checked_add(1)1593 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1594 ensure!(1595 amount <= Self::collection_admins_limit(),1596 <Error<T>>::CollectionAdminCountExceeded,1597 );15981599 <AdminAmount<T>>::insert(collection.id, amount);1600 <IsAdmin<T>>::insert((collection.id, user), true);16011602 Self::deposit_event(Event::<T>::CollectionAdminAdded(1603 collection.id,1604 user.clone(),1605 ));1606 } else {1607 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1608 <IsAdmin<T>>::remove((collection.id, user));16091610 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1611 collection.id,1612 user.clone(),1613 ));1614 }16151616 <PalletEvm<T>>::deposit_log(1617 erc::CollectionHelpersEvents::CollectionChanged {1618 collection_id: eth::collection_id_to_address(collection.id),1619 }1620 .to_log(T::ContractAddress::get()),1621 );16221623 Ok(())1624 }16251626 /// Update collection limits.1627 pub fn update_limits(1628 user: &T::CrossAccountId,1629 collection: &mut CollectionHandle<T>,1630 new_limit: CollectionLimits,1631 ) -> DispatchResult {1632 collection.check_is_internal()?;1633 collection.check_is_owner_or_admin(user)?;16341635 collection.limits =1636 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;16371638 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1639 <PalletEvm<T>>::deposit_log(1640 erc::CollectionHelpersEvents::CollectionChanged {1641 collection_id: eth::collection_id_to_address(collection.id),1642 }1643 .to_log(T::ContractAddress::get()),1644 );16451646 collection.save()1647 }16481649 /// Merge set fields from `new_limit` to `old_limit`.1650 fn clamp_limits(1651 mode: CollectionMode,1652 old_limit: &CollectionLimits,1653 mut new_limit: CollectionLimits,1654 ) -> Result<CollectionLimits, DispatchError> {1655 let limits = old_limit;1656 limit_default!(old_limit, new_limit,1657 account_token_ownership_limit => ensure!(1658 new_limit <= MAX_TOKEN_OWNERSHIP,1659 <Error<T>>::CollectionLimitBoundsExceeded,1660 ),1661 sponsored_data_size => ensure!(1662 new_limit <= CUSTOM_DATA_LIMIT,1663 <Error<T>>::CollectionLimitBoundsExceeded,1664 ),16651666 sponsored_data_rate_limit => {},1667 token_limit => ensure!(1668 old_limit >= new_limit && new_limit > 0,1669 <Error<T>>::CollectionTokenLimitExceeded1670 ),16711672 sponsor_transfer_timeout(match mode {1673 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1674 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1675 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1676 }) => ensure!(1677 new_limit <= MAX_SPONSOR_TIMEOUT,1678 <Error<T>>::CollectionLimitBoundsExceeded,1679 ),1680 sponsor_approve_timeout => {},1681 owner_can_transfer => ensure!(1682 !limits.owner_can_transfer_instaled() ||1683 old_limit || !new_limit,1684 <Error<T>>::OwnerPermissionsCantBeReverted,1685 ),1686 owner_can_destroy => ensure!(1687 old_limit || !new_limit,1688 <Error<T>>::OwnerPermissionsCantBeReverted,1689 ),1690 transfers_enabled => {},1691 );1692 Ok(new_limit)1693 }16941695 /// Update collection permissions.1696 pub fn update_permissions(1697 user: &T::CrossAccountId,1698 collection: &mut CollectionHandle<T>,1699 new_permission: CollectionPermissions,1700 ) -> DispatchResult {1701 collection.check_is_internal()?;1702 collection.check_is_owner_or_admin(user)?;1703 collection.permissions = Self::clamp_permissions(1704 collection.mode.clone(),1705 &collection.permissions,1706 new_permission,1707 )?;17081709 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1710 <PalletEvm<T>>::deposit_log(1711 erc::CollectionHelpersEvents::CollectionChanged {1712 collection_id: eth::collection_id_to_address(collection.id),1713 }1714 .to_log(T::ContractAddress::get()),1715 );17161717 collection.save()1718 }17191720 /// Merge set fields from `new_permission` to `old_permission`.1721 fn clamp_permissions(1722 _mode: CollectionMode,1723 old_permission: &CollectionPermissions,1724 mut new_permission: CollectionPermissions,1725 ) -> Result<CollectionPermissions, DispatchError> {1726 limit_default_clone!(old_permission, new_permission,1727 access => {},1728 mint_mode => {},1729 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1730 );1731 Ok(new_permission)1732 }1733}17341735/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1736#[macro_export]1737macro_rules! unsupported {1738 ($runtime:path) => {1739 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1740 };1741}17421743/// Return weights for various worst-case operations.1744pub trait CommonWeightInfo<CrossAccountId> {1745 /// Weight of item creation.1746 fn create_item() -> Weight;17471748 /// Weight of items creation.1749 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;17501751 /// Weight of items creation.1752 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;17531754 /// The weight of the burning item.1755 fn burn_item() -> Weight;17561757 /// Property setting weight.1758 ///1759 /// * `amount`- The number of properties to set.1760 fn set_collection_properties(amount: u32) -> Weight;17611762 /// Collection property deletion weight.1763 ///1764 /// * `amount`- The number of properties to set.1765 fn delete_collection_properties(amount: u32) -> Weight;17661767 /// Token property setting weight.1768 ///1769 /// * `amount`- The number of properties to set.1770 fn set_token_properties(amount: u32) -> Weight;17711772 /// Token property deletion weight.1773 ///1774 /// * `amount`- The number of properties to delete.1775 fn delete_token_properties(amount: u32) -> Weight;17761777 /// Token property permissions set weight.1778 ///1779 /// * `amount`- The number of property permissions to set.1780 fn set_token_property_permissions(amount: u32) -> Weight;17811782 /// Transfer price of the token or its parts.1783 fn transfer() -> Weight;17841785 /// The price of setting the permission of the operation from another user.1786 fn approve() -> Weight;17871788 /// Transfer price from another user.1789 fn transfer_from() -> Weight;17901791 /// The price of burning a token from another user.1792 fn burn_from() -> Weight;17931794 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1795 /// whole users's balance.1796 ///1797 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1798 fn burn_recursively_self_raw() -> Weight;17991800 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1801 ///1802 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1803 fn burn_recursively_breadth_raw(amount: u32) -> Weight;18041805 /// The price of recursive burning a token.1806 ///1807 /// `max_selfs` - The maximum burning weight of the token itself.1808 /// `max_breadth` - The maximum number of nested tokens to burn.1809 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1810 Self::burn_recursively_self_raw()1811 .saturating_mul(max_selfs.max(1) as u64)1812 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1813 }18141815 /// The price of retrieving token owner1816 fn token_owner() -> Weight;18171818 /// The price of setting approval for all1819 fn set_allowance_for_all() -> Weight;18201821 /// The price of repairing an item.1822 fn repair_item() -> Weight;1823}18241825/// Weight info extension trait for refungible pallet.1826pub trait RefungibleExtensionsWeightInfo {1827 /// Weight of token repartition.1828 fn repartition() -> Weight;1829}18301831/// Common collection operations.1832///1833/// It wraps methods in Fungible, Nonfungible and Refungible pallets1834/// and adds weight info.1835pub trait CommonCollectionOperations<T: Config> {1836 /// Create token.1837 ///1838 /// * `sender` - The user who mint the token and pays for the transaction.1839 /// * `to` - The user who will own the token.1840 /// * `data` - Token data.1841 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1842 fn create_item(1843 &self,1844 sender: T::CrossAccountId,1845 to: T::CrossAccountId,1846 data: CreateItemData,1847 nesting_budget: &dyn Budget,1848 ) -> DispatchResultWithPostInfo;18491850 /// Create multiple tokens.1851 ///1852 /// * `sender` - The user who mint the token and pays for the transaction.1853 /// * `to` - The user who will own the token.1854 /// * `data` - Token data.1855 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1856 fn create_multiple_items(1857 &self,1858 sender: T::CrossAccountId,1859 to: T::CrossAccountId,1860 data: Vec<CreateItemData>,1861 nesting_budget: &dyn Budget,1862 ) -> DispatchResultWithPostInfo;18631864 /// Create multiple tokens.1865 ///1866 /// * `sender` - The user who mint the token and pays for the transaction.1867 /// * `to` - The user who will own the token.1868 /// * `data` - Token data.1869 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1870 fn create_multiple_items_ex(1871 &self,1872 sender: T::CrossAccountId,1873 data: CreateItemExData<T::CrossAccountId>,1874 nesting_budget: &dyn Budget,1875 ) -> DispatchResultWithPostInfo;18761877 /// Burn token.1878 ///1879 /// * `sender` - The user who owns the token.1880 /// * `token` - Token id that will burned.1881 /// * `amount` - The number of parts of the token that will be burned.1882 fn burn_item(1883 &self,1884 sender: T::CrossAccountId,1885 token: TokenId,1886 amount: u128,1887 ) -> DispatchResultWithPostInfo;18881889 /// Burn token and all nested tokens recursievly.1890 ///1891 /// * `sender` - The user who owns the token.1892 /// * `token` - Token id that will burned.1893 /// * `self_budget` - The budget that can be spent on burning tokens.1894 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1895 fn burn_item_recursively(1896 &self,1897 sender: T::CrossAccountId,1898 token: TokenId,1899 self_budget: &dyn Budget,1900 breadth_budget: &dyn Budget,1901 ) -> DispatchResultWithPostInfo;19021903 /// Set collection properties.1904 ///1905 /// * `sender` - Must be either the owner of the collection or its admin.1906 /// * `properties` - Properties to be set.1907 fn set_collection_properties(1908 &self,1909 sender: T::CrossAccountId,1910 properties: Vec<Property>,1911 ) -> DispatchResultWithPostInfo;19121913 /// Delete collection properties.1914 ///1915 /// * `sender` - Must be either the owner of the collection or its admin.1916 /// * `properties` - The properties to be removed.1917 fn delete_collection_properties(1918 &self,1919 sender: &T::CrossAccountId,1920 property_keys: Vec<PropertyKey>,1921 ) -> DispatchResultWithPostInfo;19221923 /// Set token properties.1924 ///1925 /// The appropriate [`PropertyPermission`] for the token property1926 /// must be set with [`Self::set_token_property_permissions`].1927 ///1928 /// * `sender` - Must be either the owner of the token or its admin.1929 /// * `token_id` - The token for which the properties are being set.1930 /// * `properties` - Properties to be set.1931 /// * `budget` - Budget for setting properties.1932 fn set_token_properties(1933 &self,1934 sender: T::CrossAccountId,1935 token_id: TokenId,1936 properties: Vec<Property>,1937 budget: &dyn Budget,1938 ) -> DispatchResultWithPostInfo;19391940 /// Remove token properties.1941 ///1942 /// The appropriate [`PropertyPermission`] for the token property1943 /// must be set with [`Self::set_token_property_permissions`].1944 ///1945 /// * `sender` - Must be either the owner of the token or its admin.1946 /// * `token_id` - The token for which the properties are being remove.1947 /// * `property_keys` - Keys to remove corresponding properties.1948 /// * `budget` - Budget for removing properties.1949 fn delete_token_properties(1950 &self,1951 sender: T::CrossAccountId,1952 token_id: TokenId,1953 property_keys: Vec<PropertyKey>,1954 budget: &dyn Budget,1955 ) -> DispatchResultWithPostInfo;19561957 /// Set token property permissions.1958 ///1959 /// * `sender` - Must be either the owner of the token or its admin.1960 /// * `token_id` - The token for which the properties are being set.1961 /// * `property_permissions` - Property permissions to be set.1962 /// * `budget` - Budget for setting properties.1963 fn set_token_property_permissions(1964 &self,1965 sender: &T::CrossAccountId,1966 property_permissions: Vec<PropertyKeyPermission>,1967 ) -> DispatchResultWithPostInfo;19681969 /// Transfer amount of token pieces.1970 ///1971 /// * `sender` - Donor user.1972 /// * `to` - Recepient user.1973 /// * `token` - The token of which parts are being sent.1974 /// * `amount` - The number of parts of the token that will be transferred.1975 /// * `budget` - The maximum budget that can be spent on the transfer.1976 fn transfer(1977 &self,1978 sender: T::CrossAccountId,1979 to: T::CrossAccountId,1980 token: TokenId,1981 amount: u128,1982 budget: &dyn Budget,1983 ) -> DispatchResultWithPostInfo;19841985 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1986 ///1987 /// * `sender` - The user who grants access to the token.1988 /// * `spender` - The user to whom the rights are granted.1989 /// * `token` - The token to which access is granted.1990 /// * `amount` - The amount of pieces that another user can dispose of.1991 fn approve(1992 &self,1993 sender: T::CrossAccountId,1994 spender: T::CrossAccountId,1995 token: TokenId,1996 amount: u128,1997 ) -> DispatchResultWithPostInfo;19981999 /// Send parts of a token owned by another user.2000 ///2001 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2002 ///2003 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2004 /// * `from` - The user who owns the token.2005 /// * `to` - Recepient user.2006 /// * `token` - The token of which parts are being sent.2007 /// * `amount` - The number of parts of the token that will be transferred.2008 /// * `budget` - The maximum budget that can be spent on the transfer.2009 fn transfer_from(2010 &self,2011 sender: T::CrossAccountId,2012 from: T::CrossAccountId,2013 to: T::CrossAccountId,2014 token: TokenId,2015 amount: u128,2016 budget: &dyn Budget,2017 ) -> DispatchResultWithPostInfo;20182019 /// Burn parts of a token owned by another user.2020 ///2021 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2022 ///2023 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2024 /// * `from` - The user who owns the token.2025 /// * `token` - The token of which parts are being sent.2026 /// * `amount` - The number of parts of the token that will be transferred.2027 /// * `budget` - The maximum budget that can be spent on the burn.2028 fn burn_from(2029 &self,2030 sender: T::CrossAccountId,2031 from: T::CrossAccountId,2032 token: TokenId,2033 amount: u128,2034 budget: &dyn Budget,2035 ) -> DispatchResultWithPostInfo;20362037 /// Check permission to nest token.2038 ///2039 /// * `sender` - The user who initiated the check.2040 /// * `from` - The token that is checked for embedding.2041 /// * `under` - Token under which to check.2042 /// * `budget` - The maximum budget that can be spent on the check.2043 fn check_nesting(2044 &self,2045 sender: T::CrossAccountId,2046 from: (CollectionId, TokenId),2047 under: TokenId,2048 budget: &dyn Budget,2049 ) -> DispatchResult;20502051 /// Nest one token into another.2052 ///2053 /// * `under` - Token holder.2054 /// * `to_nest` - Nested token.2055 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20562057 /// Unnest token.2058 ///2059 /// * `under` - Token holder.2060 /// * `to_nest` - Token to unnest.2061 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20622063 /// Get all user tokens.2064 ///2065 /// * `account` - Account for which you need to get tokens.2066 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;20672068 /// Get all the tokens in the collection.2069 fn collection_tokens(&self) -> Vec<TokenId>;20702071 /// Check if the token exists.2072 ///2073 /// * `token` - Id token to check.2074 fn token_exists(&self, token: TokenId) -> bool;20752076 /// Get the id of the last minted token.2077 fn last_token_id(&self) -> TokenId;20782079 /// Get the owner of the token.2080 ///2081 /// * `token` - The token for which you need to find out the owner.2082 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;20832084 /// Returns 10 tokens owners in no particular order.2085 ///2086 /// * `token` - The token for which you need to find out the owners.2087 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;20882089 /// Get the value of the token property by key.2090 ///2091 /// * `token` - Token with the property to get.2092 /// * `key` - Property name.2093 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;20942095 /// Get a set of token properties by key vector.2096 ///2097 /// * `token` - Token with the property to get.2098 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2099 /// then all properties are returned.2100 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;21012102 /// Amount of unique collection tokens2103 fn total_supply(&self) -> u32;21042105 /// Amount of different tokens account has.2106 ///2107 /// * `account` - The account for which need to get the balance.2108 fn account_balance(&self, account: T::CrossAccountId) -> u32;21092110 /// Amount of specific token account have.2111 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;21122113 /// Amount of token pieces2114 fn total_pieces(&self, token: TokenId) -> Option<u128>;21152116 /// Get the number of parts of the token that a trusted user can manage.2117 ///2118 /// * `sender` - Trusted user.2119 /// * `spender` - Owner of the token.2120 /// * `token` - The token for which to get the value.2121 fn allowance(2122 &self,2123 sender: T::CrossAccountId,2124 spender: T::CrossAccountId,2125 token: TokenId,2126 ) -> u128;21272128 /// Get extension for RFT collection.2129 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;21302131 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2132 /// * `owner` - Token owner2133 /// * `operator` - Operator2134 /// * `approve` - Should operator status be granted or revoked?2135 fn set_allowance_for_all(2136 &self,2137 owner: T::CrossAccountId,2138 operator: T::CrossAccountId,2139 approve: bool,2140 ) -> DispatchResultWithPostInfo;21412142 /// Tells whether the given `owner` approves the `operator`.2143 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;21442145 /// Repairs a possibly broken item.2146 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2147}21482149/// Extension for RFT collection.2150pub trait RefungibleExtensions<T>2151where2152 T: Config,2153{2154 /// Change the number of parts of the token.2155 ///2156 /// When the value changes down, this function is equivalent to burning parts of the token.2157 ///2158 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2159 /// * `token` - The token for which you want to change the number of parts.2160 /// * `amount` - The new value of the parts of the token.2161 fn repartition(2162 &self,2163 sender: &T::CrossAccountId,2164 token: TokenId,2165 amount: u128,2166 ) -> DispatchResultWithPostInfo;2167}21682169/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2170///2171/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2172pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2173 let post_info = PostDispatchInfo {2174 actual_weight: Some(weight),2175 pays_fee: Pays::Yes,2176 };2177 match res {2178 Ok(()) => Ok(post_info),2179 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2180 }2181}21822183impl<T: Config> From<PropertiesError> for Error<T> {2184 fn from(error: PropertiesError) -> Self {2185 match error {2186 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2187 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2188 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2189 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2190 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2191 }2192 }2193}pallets/configuration/src/lib.rsdiffbeforeafterboth--- a/pallets/configuration/src/lib.rs
+++ b/pallets/configuration/src/lib.rs
@@ -52,7 +52,7 @@
type DefaultMinGasPrice: Get<u64>;
#[pallet::constant]
- type MaxOverridedAllowedLocations: Get<u32>;
+ type MaxXcmAllowedLocations: Get<u32>;
#[pallet::constant]
type AppPromotionDailyRate: Get<Perbill>;
#[pallet::constant]
@@ -77,7 +77,7 @@
#[pallet::storage]
pub type XcmAllowedLocationsOverride<T: Config> = StorageValue<
- Value = BoundedVec<MultiLocation, T::MaxOverridedAllowedLocations>,
+ Value = BoundedVec<MultiLocation, T::MaxXcmAllowedLocations>,
QueryKind = OptionQuery,
>;
@@ -118,7 +118,7 @@
#[pallet::weight(T::DbWeight::get().writes(1))]
pub fn set_xcm_allowed_locations(
origin: OriginFor<T>,
- locations: Option<BoundedVec<MultiLocation, T::MaxOverridedAllowedLocations>>,
+ locations: Option<BoundedVec<MultiLocation, T::MaxXcmAllowedLocations>>,
) -> DispatchResult {
ensure_root(origin)?;
<XcmAllowedLocationsOverride<T>>::set(locations);
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -18,7 +18,10 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};
use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData};
-use pallet_common::{CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight};
+use pallet_common::{
+ CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
+ weights::WeightInfo as _,
+};
use pallet_structure::Error as StructureError;
use sp_runtime::ArithmeticError;
use sp_std::{vec::Vec, vec};
@@ -53,14 +56,12 @@
<SelfWeightOf<T>>::burn_item()
}
- fn set_collection_properties(_amount: u32) -> Weight {
- // Error
- Weight::zero()
+ fn set_collection_properties(amount: u32) -> Weight {
+ <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)
}
- fn delete_collection_properties(_amount: u32) -> Weight {
- // Error
- Weight::zero()
+ fn delete_collection_properties(amount: u32) -> Weight {
+ <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)
}
fn set_token_properties(_amount: u32) -> Weight {
@@ -294,18 +295,28 @@
fn set_collection_properties(
&self,
- _sender: T::CrossAccountId,
- _property: Vec<Property>,
+ sender: T::CrossAccountId,
+ properties: Vec<Property>,
) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::SettingPropertiesNotAllowed)
+ let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);
+
+ with_weight(
+ <Pallet<T>>::set_collection_properties(self, &sender, properties),
+ weight,
+ )
}
fn delete_collection_properties(
&self,
- _sender: &T::CrossAccountId,
- _property_keys: Vec<PropertyKey>,
+ sender: &T::CrossAccountId,
+ property_keys: Vec<PropertyKey>,
) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::SettingPropertiesNotAllowed)
+ let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);
+
+ with_weight(
+ <Pallet<T>>::delete_collection_properties(self, sender, property_keys),
+ weight,
+ )
}
fn set_token_properties(
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -80,11 +80,11 @@
use core::ops::Deref;
use evm_coder::ToLog;
-use frame_support::{ensure};
+use frame_support::ensure;
use pallet_evm::account::CrossAccountId;
use up_data_structs::{
AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,
- mapping::TokenAddressMapping, budget::Budget,
+ mapping::TokenAddressMapping, budget::Budget, PropertyKey, Property,
};
use pallet_common::{
Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
@@ -260,7 +260,25 @@
Ok(())
}
- ///Checks if collection has tokens. Return `true` if it has.
+ /// Add properties to the collection.
+ pub fn set_collection_properties(
+ collection: &FungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ properties: Vec<Property>,
+ ) -> DispatchResult {
+ <PalletCommon<T>>::set_collection_properties(collection, sender, properties)
+ }
+
+ /// Delete properties of the collection, associated with the provided keys.
+ pub fn delete_collection_properties(
+ collection: &FungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ property_keys: Vec<PropertyKey>,
+ ) -> DispatchResult {
+ <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)
+ }
+
+ /// Checks if collection has tokens. Return `true` if it has.
fn collection_has_tokens(collection_id: CollectionId) -> bool {
<TotalSupply<T>>::get(collection_id) != 0
}
pallets/nonfungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/nonfungible/CHANGELOG.md
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -4,6 +4,16 @@
<!-- bureaucrate goes here -->
+## [0.1.11] - 2022-12-16
+
+### Added
+
+- The function `tokenPropertyPermissions` and `setTokenPropertyPermissions` to `TokenProperties` interface.
+
+### Changed
+
+- Hide `setTokenPropertyPermission` function in `TokenProperties` interface.
+
## [0.1.10] - 2022-11-18
### Added
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-nonfungible"
-version = "0.1.9"
+version = "0.1.11"
license = "GPLv3"
edition = "2021"
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -34,11 +34,11 @@
CollectionPropertiesVec,
};
use pallet_evm_coder_substrate::dispatch_to_evm;
-use sp_std::vec::Vec;
+use sp_std::{vec::Vec, vec};
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
- eth::EthCrossAccount,
+ eth::{EthCrossAccount, EthTokenPermissions},
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::call;
@@ -60,6 +60,7 @@
/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
/// @param tokenOwner Permission to mutate property by token owner if property is mutable.
#[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]
+ #[solidity(hide)]
fn set_token_property_permission(
&mut self,
caller: caller,
@@ -69,10 +70,10 @@
token_owner: bool,
) -> Result<()> {
let caller = T::CrossAccountId::from_eth(caller);
- <Pallet<T>>::set_property_permission(
+ <Pallet<T>>::set_token_property_permissions(
self,
&caller,
- PropertyKeyPermission {
+ vec![PropertyKeyPermission {
key: <Vec<u8>>::from(key)
.try_into()
.map_err(|_| "too long key")?,
@@ -81,11 +82,78 @@
collection_admin,
token_owner,
},
- },
+ }],
)
.map_err(dispatch_to_evm::<T>)
}
+ /// @notice Set permissions for token property.
+ /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+ /// @param permissions Permissions for keys.
+ #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]
+ fn set_token_property_permissions(
+ &mut self,
+ caller: caller,
+ permissions: Vec<(string, Vec<(EthTokenPermissions, bool)>)>,
+ ) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ const PERMISSIONS_FIELDS_COUNT: usize = 3;
+
+ let mut perms = Vec::new();
+
+ for (key, pp) in permissions {
+ if pp.len() > PERMISSIONS_FIELDS_COUNT {
+ return Err(alloc::format!(
+ "Actual number of fields {} for {}, which exceeds the maximum value of {}",
+ pp.len(),
+ stringify!(EthTokenPermissions),
+ PERMISSIONS_FIELDS_COUNT
+ )
+ .as_str()
+ .into());
+ }
+
+ let mut token_permission = PropertyPermission::default();
+
+ for (perm, value) in pp {
+ match perm {
+ EthTokenPermissions::Mutable => token_permission.mutable = value,
+ EthTokenPermissions::TokenOwner => token_permission.token_owner = value,
+ EthTokenPermissions::CollectionAdmin => {
+ token_permission.collection_admin = value
+ }
+ }
+ }
+
+ perms.push(PropertyKeyPermission {
+ key: key.into_bytes().try_into().map_err(|_| "too long key")?,
+ permission: token_permission,
+ });
+ }
+
+ <Pallet<T>>::set_token_property_permissions(self, &caller, perms)
+ .map_err(dispatch_to_evm::<T>)
+ }
+
+ /// @notice Get permissions for token properties.
+ fn token_property_permissions(
+ &self,
+ ) -> Result<Vec<(string, Vec<(EthTokenPermissions, bool)>)>> {
+ let perms = <Pallet<T>>::token_property_permission(self.id);
+ Ok(perms
+ .into_iter()
+ .map(|(key, pp)| {
+ let key = string::from_utf8(key.into_inner()).expect("Stored key must be valid");
+ let pp = vec![
+ (EthTokenPermissions::Mutable, pp.mutable),
+ (EthTokenPermissions::TokenOwner, pp.token_owner),
+ (EthTokenPermissions::CollectionAdmin, pp.collection_admin),
+ ];
+ (key, pp)
+ })
+ .collect())
+ }
+
/// @notice Set token property value.
/// @dev Throws error if `msg.sender` has no permission to edit the property.
/// @param tokenId ID of the token.
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -103,7 +103,7 @@
AccessMode, CollectionId, CollectionFlags, CustomDataLimit, TokenId, CreateCollectionData,
CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyPermission,
PropertyKey, PropertyValue, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,
- TokenChild, AuxPropertyValue,
+ TokenChild, AuxPropertyValue, PropertiesPermissionMap,
};
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_common::{
@@ -824,15 +824,8 @@
)
}
- /// Set property permissions for the collection.
- ///
- /// Sender should be the owner or admin of the collection.
- pub fn set_property_permission(
- collection: &CollectionHandle<T>,
- sender: &T::CrossAccountId,
- permission: PropertyKeyPermission,
- ) -> DispatchResult {
- <PalletCommon<T>>::set_property_permission(collection, sender, permission)
+ pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {
+ <PalletCommon<T>>::property_permissions(collection_id)
}
pub fn check_token_immediate_ownership(
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -18,30 +18,44 @@
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x91a97a68
+/// @dev the ERC-165 identifier for this interface is 0xde0695c2
contract TokenProperties is Dummy, ERC165 {
+ // /// @notice Set permissions for token property.
+ // /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+ // /// @param key Property key.
+ // /// @param isMutable Permission to mutate property.
+ // /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
+ // /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
+ // /// @dev EVM selector for this function is: 0x222d97fa,
+ // /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
+ // function setTokenPropertyPermission(string memory key, bool isMutable, bool collectionAdmin, bool tokenOwner) public {
+ // require(false, stub_error);
+ // key;
+ // isMutable;
+ // collectionAdmin;
+ // tokenOwner;
+ // dummy = 0;
+ // }
+
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
- /// @param key Property key.
- /// @param isMutable Permission to mutate property.
- /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
- /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
- /// @dev EVM selector for this function is: 0x222d97fa,
- /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
- function setTokenPropertyPermission(
- string memory key,
- bool isMutable,
- bool collectionAdmin,
- bool tokenOwner
- ) public {
+ /// @param permissions Permissions for keys.
+ /// @dev EVM selector for this function is: 0xbd92983a,
+ /// or in textual repr: setTokenPropertyPermissions((string,(uint8,bool)[])[])
+ function setTokenPropertyPermissions(Tuple48[] memory permissions) public {
require(false, stub_error);
- key;
- isMutable;
- collectionAdmin;
- tokenOwner;
+ permissions;
dummy = 0;
}
+ /// @dev EVM selector for this function is: 0xf23d7790,
+ /// or in textual repr: tokenPropertyPermissions()
+ function tokenPropertyPermissions() public view returns (Tuple48[] memory) {
+ require(false, stub_error);
+ dummy;
+ return new Tuple48[](0);
+ }
+
// /// @notice Set token property value.
// /// @dev Throws error if `msg.sender` has no permission to edit the property.
// /// @param tokenId ID of the token.
@@ -118,6 +132,24 @@
bytes value;
}
+enum EthTokenPermissions {
+ Mutable,
+ TokenOwner,
+ CollectionAdmin
+}
+
+/// @dev anonymous struct
+struct Tuple48 {
+ string field_0;
+ Tuple46[] field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple46 {
+ EthTokenPermissions field_0;
+ bool field_1;
+}
+
/// @title A contract that allows you to work with collections.
/// @dev the ERC-165 identifier for this interface is 0xb5e1747f
contract Collection is Dummy, ERC165 {
pallets/refungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/refungible/CHANGELOG.md
+++ b/pallets/refungible/CHANGELOG.md
@@ -4,6 +4,16 @@
<!-- bureaucrate goes here -->
+## [0.2.10] - 2022-12-16
+
+### Added
+
+- The function `tokenPropertyPermissions` and `setTokenPropertyPermissions` to `TokenProperties` interface.
+
+### Changed
+
+- Hide `setTokenPropertyPermission` function in `TokenProperties` interface.
+
## [0.2.9] - 2022-11-18
### Added
pallets/refungible/Cargo.tomldiffbeforeafterboth--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-refungible"
-version = "0.2.8"
+version = "0.2.10"
license = "GPLv3"
edition = "2021"
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -33,7 +33,7 @@
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
erc::{CommonEvmHandler, CollectionCall, static_property::key},
- eth::EthCrossAccount,
+ eth::{EthCrossAccount, EthTokenPermissions},
Error as CommonError,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
@@ -63,6 +63,7 @@
/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
/// @param tokenOwner Permission to mutate property by token owner if property is mutable.
#[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]
+ #[solidity(hide)]
fn set_token_property_permission(
&mut self,
caller: caller,
@@ -89,6 +90,77 @@
.map_err(dispatch_to_evm::<T>)
}
+ /// @notice Set permissions for token property.
+ /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+ /// @param permissions Permissions for keys.
+ #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]
+ fn set_token_property_permissions(
+ &mut self,
+ caller: caller,
+ permissions: Vec<(string, Vec<(EthTokenPermissions, bool)>)>,
+ ) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ const PERMISSIONS_FIELDS_COUNT: usize = 3;
+
+ let mut perms = Vec::new();
+
+ for (key, pp) in permissions {
+ if pp.len() > PERMISSIONS_FIELDS_COUNT {
+ return Err(alloc::format!(
+ "Actual number of fields {} for {}, which exceeds the maximum value of {}",
+ pp.len(),
+ stringify!(EthTokenPermissions),
+ PERMISSIONS_FIELDS_COUNT
+ )
+ .as_str()
+ .into());
+ }
+
+ let mut token_permission = PropertyPermission {
+ mutable: false,
+ collection_admin: false,
+ token_owner: false,
+ };
+
+ for (perm, value) in pp {
+ match perm {
+ EthTokenPermissions::Mutable => token_permission.mutable = value,
+ EthTokenPermissions::TokenOwner => token_permission.token_owner = value,
+ EthTokenPermissions::CollectionAdmin => {
+ token_permission.collection_admin = value
+ }
+ }
+ }
+
+ perms.push(PropertyKeyPermission {
+ key: key.into_bytes().try_into().map_err(|_| "too long key")?,
+ permission: token_permission,
+ });
+ }
+
+ <Pallet<T>>::set_token_property_permissions(self, &caller, perms)
+ .map_err(dispatch_to_evm::<T>)
+ }
+
+ /// @notice Get permissions for token properties.
+ fn token_property_permissions(
+ &self,
+ ) -> Result<Vec<(string, Vec<(EthTokenPermissions, bool)>)>> {
+ let perms = <Pallet<T>>::token_property_permission(self.id);
+ Ok(perms
+ .into_iter()
+ .map(|(key, pp)| {
+ let key = string::from_utf8(key.into_inner()).expect("Stored key must be valid");
+ let pp = vec![
+ (EthTokenPermissions::Mutable, pp.mutable),
+ (EthTokenPermissions::TokenOwner, pp.token_owner),
+ (EthTokenPermissions::CollectionAdmin, pp.collection_admin),
+ ];
+ (key, pp)
+ })
+ .collect())
+ }
+
/// @notice Set token property value.
/// @dev Throws error if `msg.sender` has no permission to edit the property.
/// @param tokenId ID of the token.
pallets/refungible/src/erc_token.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -19,11 +19,6 @@
//! Provides ERC-20 standart support implementation and EVM API for unique extensions for Refungible Pallet.
//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.
-extern crate alloc;
-
-#[cfg(not(feature = "std"))]
-use alloc::format;
-
use core::{
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
@@ -35,7 +30,7 @@
use pallet_common::{
CommonWeightInfo,
erc::{CommonEvmHandler, PrecompileResult},
- eth::collection_id_to_address,
+ eth::{collection_id_to_address, EthCrossAccount},
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};
@@ -199,7 +194,10 @@
}
#[solidity_interface(name = ERC20UniqueExtensions)]
-impl<T: Config> RefungibleTokenHandle<T> {
+impl<T: Config> RefungibleTokenHandle<T>
+where
+ T::AccountId: From<[u8; 32]>,
+{
/// @dev Function that burns an amount of the token of a given account,
/// deducting from the sender's allowance for said account.
/// @param from The account whose tokens will be burnt.
@@ -218,6 +216,51 @@
Ok(true)
}
+ /// @dev Function that burns an amount of the token of a given account,
+ /// deducting from the sender's allowance for said account.
+ /// @param from The account whose tokens will be burnt.
+ /// @param amount The amount that will be burnt.
+ #[weight(<SelfWeightOf<T>>::burn_from())]
+ fn burn_from_cross(
+ &mut self,
+ caller: caller,
+ from: EthCrossAccount,
+ amount: uint256,
+ ) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let from = from.into_sub_cross_account::<T>()?;
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ <Pallet<T>>::burn_from(self, &caller, &from, self.1, amount, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+
+ /// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.
+ /// Beware that changing an allowance with this method brings the risk that someone may use both the old
+ /// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
+ /// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
+ /// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
+ /// @param spender The crossaccount which will spend the funds.
+ /// @param amount The amount of tokens to be spent.
+ #[weight(<SelfWeightOf<T>>::approve())]
+ fn approve_cross(
+ &mut self,
+ caller: caller,
+ spender: EthCrossAccount,
+ amount: uint256,
+ ) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let spender = spender.into_sub_cross_account::<T>()?;
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+
+ <Pallet<T>>::set_allowance(self, &caller, &spender, self.1, amount)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
/// @dev Function that changes total amount of the tokens.
/// Throws if `msg.sender` doesn't owns all of the tokens.
/// @param amount New total amount of the tokens.
@@ -229,6 +272,53 @@
<Pallet<T>>::repartition(self, &caller, self.1, amount).map_err(dispatch_to_evm::<T>)?;
Ok(true)
}
+
+ /// @dev Transfer token for a specified address
+ /// @param to The crossaccount to transfer to.
+ /// @param amount The amount to be transferred.
+ #[weight(<CommonWeights<T>>::transfer())]
+ fn transfer_cross(
+ &mut self,
+ caller: caller,
+ to: EthCrossAccount,
+ amount: uint256,
+ ) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let to = to.into_sub_cross_account::<T>()?;
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ <Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+
+ /// @dev Transfer tokens from one address to another
+ /// @param from The address which you want to send tokens from
+ /// @param to The address which you want to transfer to
+ /// @param amount the amount of tokens to be transferred
+ #[weight(<CommonWeights<T>>::transfer_from())]
+ fn transfer_from_cross(
+ &mut self,
+ caller: caller,
+ from: EthCrossAccount,
+ to: EthCrossAccount,
+ amount: uint256,
+ ) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let from = from.into_sub_cross_account::<T>()?;
+ let to = to.into_sub_cross_account::<T>()?;
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ <Pallet<T>>::transfer_from(self, &caller, &from, &to, self.1, amount, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
}
impl<T: Config> RefungibleTokenHandle<T> {
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -113,7 +113,7 @@
AccessMode, budget::Budget, CollectionId, CollectionFlags, CollectionPropertiesVec,
CreateCollectionData, CustomDataLimit, mapping::TokenAddressMapping, MAX_ITEMS_PER_BATCH,
MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,
- PropertyScope, PropertyValue, TokenId, TrySetProperty,
+ PropertyScope, PropertyValue, TokenId, TrySetProperty, PropertiesPermissionMap,
};
pub use pallet::*;
@@ -1378,6 +1378,10 @@
<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)
}
+ pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {
+ <PalletCommon<T>>::property_permissions(collection_id)
+ }
+
pub fn set_scoped_token_property_permissions(
collection: &RefungibleHandle<T>,
sender: &T::CrossAccountId,
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -18,30 +18,45 @@
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x91a97a68
+/// @dev the ERC-165 identifier for this interface is 0xde0695c2
contract TokenProperties is Dummy, ERC165 {
+ // /// @notice Set permissions for token property.
+ // /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+ // /// @param key Property key.
+ // /// @param isMutable Permission to mutate property.
+ // /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
+ // /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
+ // /// @dev EVM selector for this function is: 0x222d97fa,
+ // /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
+ // function setTokenPropertyPermission(string memory key, bool isMutable, bool collectionAdmin, bool tokenOwner) public {
+ // require(false, stub_error);
+ // key;
+ // isMutable;
+ // collectionAdmin;
+ // tokenOwner;
+ // dummy = 0;
+ // }
+
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
- /// @param key Property key.
- /// @param isMutable Permission to mutate property.
- /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
- /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
- /// @dev EVM selector for this function is: 0x222d97fa,
- /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
- function setTokenPropertyPermission(
- string memory key,
- bool isMutable,
- bool collectionAdmin,
- bool tokenOwner
- ) public {
+ /// @param permissions Permissions for keys.
+ /// @dev EVM selector for this function is: 0xbd92983a,
+ /// or in textual repr: setTokenPropertyPermissions((string,(uint8,bool)[])[])
+ function setTokenPropertyPermissions(Tuple53[] memory permissions) public {
require(false, stub_error);
- key;
- isMutable;
- collectionAdmin;
- tokenOwner;
+ permissions;
dummy = 0;
}
+ /// @notice Get permissions for token properties.
+ /// @dev EVM selector for this function is: 0xf23d7790,
+ /// or in textual repr: tokenPropertyPermissions()
+ function tokenPropertyPermissions() public view returns (Tuple53[] memory) {
+ require(false, stub_error);
+ dummy;
+ return new Tuple53[](0);
+ }
+
// /// @notice Set token property value.
// /// @dev Throws error if `msg.sender` has no permission to edit the property.
// /// @param tokenId ID of the token.
@@ -118,6 +133,24 @@
bytes value;
}
+enum EthTokenPermissions {
+ Mutable,
+ TokenOwner,
+ CollectionAdmin
+}
+
+/// @dev anonymous struct
+struct Tuple53 {
+ string field_0;
+ Tuple51[] field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple51 {
+ EthTokenPermissions field_0;
+ bool field_1;
+}
+
/// @title A contract that allows you to work with collections.
/// @dev the ERC-165 identifier for this interface is 0xb5e1747f
contract Collection is Dummy, ERC165 {
pallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungibleToken.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
@@ -36,7 +36,7 @@
}
}
-/// @dev the ERC-165 identifier for this interface is 0xab8deb37
+/// @dev the ERC-165 identifier for this interface is 0xe17a7d2b
contract ERC20UniqueExtensions is Dummy, ERC165 {
/// @dev Function that burns an amount of the token of a given account,
/// deducting from the sender's allowance for said account.
@@ -52,6 +52,37 @@
return false;
}
+ /// @dev Function that burns an amount of the token of a given account,
+ /// deducting from the sender's allowance for said account.
+ /// @param from The account whose tokens will be burnt.
+ /// @param amount The amount that will be burnt.
+ /// @dev EVM selector for this function is: 0xbb2f5a58,
+ /// or in textual repr: burnFromCross((address,uint256),uint256)
+ function burnFromCross(EthCrossAccount memory from, uint256 amount) public returns (bool) {
+ require(false, stub_error);
+ from;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
+ /// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.
+ /// Beware that changing an allowance with this method brings the risk that someone may use both the old
+ /// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
+ /// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
+ /// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
+ /// @param spender The crossaccount which will spend the funds.
+ /// @param amount The amount of tokens to be spent.
+ /// @dev EVM selector for this function is: 0x0ecd0ab0,
+ /// or in textual repr: approveCross((address,uint256),uint256)
+ function approveCross(EthCrossAccount memory spender, uint256 amount) public returns (bool) {
+ require(false, stub_error);
+ spender;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
/// @dev Function that changes total amount of the tokens.
/// Throws if `msg.sender` doesn't owns all of the tokens.
/// @param amount New total amount of the tokens.
@@ -63,6 +94,44 @@
dummy = 0;
return false;
}
+
+ /// @dev Transfer token for a specified address
+ /// @param to The crossaccount to transfer to.
+ /// @param amount The amount to be transferred.
+ /// @dev EVM selector for this function is: 0x2ada85ff,
+ /// or in textual repr: transferCross((address,uint256),uint256)
+ function transferCross(EthCrossAccount memory to, uint256 amount) public returns (bool) {
+ require(false, stub_error);
+ to;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
+ /// @dev Transfer tokens from one address to another
+ /// @param from The address which you want to send tokens from
+ /// @param to The address which you want to transfer to
+ /// @param amount the amount of tokens to be transferred
+ /// @dev EVM selector for this function is: 0xd5cf430b,
+ /// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
+ function transferFromCross(
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
+ uint256 amount
+ ) public returns (bool) {
+ require(false, stub_error);
+ from;
+ to;
+ amount;
+ dummy = 0;
+ return false;
+ }
+}
+
+/// @dev Cross account struct
+struct EthCrossAccount {
+ address eth;
+ uint256 sub;
}
/// @dev inlined interface
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1010,7 +1010,7 @@
pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;
/// Property permission.
-#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
+#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone, Default)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct PropertyPermission {
/// Permission to change the property and property permission.
runtime/common/config/ethereum.rsdiffbeforeafterboth--- a/runtime/common/config/ethereum.rs
+++ b/runtime/common/config/ethereum.rs
@@ -7,8 +7,10 @@
use sp_runtime::{RuntimeAppPublic, Perbill};
use crate::{
runtime_common::{
- dispatch::CollectionDispatchT, ethereum::sponsoring::EvmSponsorshipHandler,
- config::sponsoring::DefaultSponsoringRateLimit, DealWithFees,
+ config::sponsoring::DefaultSponsoringRateLimit,
+ DealWithFees,
+ dispatch::CollectionDispatchT,
+ ethereum::{precompiles::UniquePrecompiles, sponsoring::EvmSponsorshipHandler},
},
Runtime, Aura, Balances, RuntimeEvent, ChainId,
};
@@ -34,6 +36,7 @@
const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);
parameter_types! {
pub BlockGasLimit: U256 = U256::from((NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightTimePerGas::get()).ref_time());
+ pub PrecompilesValue: UniquePrecompiles<Runtime> = UniquePrecompiles::<_>::new();
}
pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);
@@ -62,8 +65,8 @@
type CallOrigin = EnsureAddressTruncated<Self>;
type WithdrawOrigin = EnsureAddressTruncated<Self>;
type AddressMapping = HashedAddressMapping<Self::Hashing>;
- type PrecompilesType = ();
- type PrecompilesValue = ();
+ type PrecompilesType = UniquePrecompiles<Self>;
+ type PrecompilesValue = PrecompilesValue;
type Currency = Balances;
type RuntimeEvent = RuntimeEvent;
type OnMethodCall = (
runtime/common/config/pallets/mod.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -106,7 +106,7 @@
impl pallet_configuration::Config for Runtime {
type DefaultWeightToFeeCoefficient = ConstU32<{ up_common::constants::WEIGHT_TO_FEE_COEFF }>;
type DefaultMinGasPrice = ConstU64<{ up_common::constants::MIN_GAS_PRICE }>;
- type MaxOverridedAllowedLocations = ConstU32<16>;
+ type MaxXcmAllowedLocations = ConstU32<16>;
type AppPromotionDailyRate = AppPromotionDailyRate;
type DayRelayBlocks = DayRelayBlocks;
}
runtime/common/construct_runtime/mod.rsdiffbeforeafterboth--- a/runtime/common/construct_runtime/mod.rs
+++ b/runtime/common/construct_runtime/mod.rs
@@ -82,7 +82,7 @@
#[runtimes(opal, quartz)]
AppPromotion: pallet_app_promotion::{Pallet, Call, Storage, Event<T>} = 73,
- #[runtimes(opal)]
+ #[runtimes(opal, quartz, unique)]
ForeignAssets: pallet_foreign_assets::{Pallet, Call, Storage, Event<T>} = 80,
// Frontier
runtime/common/ethereum/mod.rsdiffbeforeafterboth--- a/runtime/common/ethereum/mod.rs
+++ b/runtime/common/ethereum/mod.rs
@@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+pub mod precompiles;
pub mod self_contained_call;
pub mod sponsoring;
pub mod transaction_converter;
runtime/common/ethereum/precompiles/mod.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/ethereum/precompiles/mod.rs
@@ -0,0 +1,60 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+use pallet_evm::{Precompile, PrecompileHandle, PrecompileResult, PrecompileSet};
+use sp_core::H160;
+use sp_std::marker::PhantomData;
+
+use pallet_evm_precompile_simple::{ECRecover};
+use sr25519::Sr25519Precompile;
+
+mod sr25519;
+mod utils;
+
+pub struct UniquePrecompiles<R>(PhantomData<R>);
+
+impl<R> UniquePrecompiles<R>
+where
+ R: pallet_evm::Config,
+{
+ pub fn new() -> Self {
+ Self(Default::default())
+ }
+ pub fn used_addresses() -> [H160; 2] {
+ [hash(1), hash(20482)]
+ }
+}
+impl<R> PrecompileSet for UniquePrecompiles<R>
+where
+ R: pallet_evm::Config,
+{
+ fn execute(&self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {
+ match handle.code_address() {
+ a if a == hash(1) => Some(ECRecover::execute(handle)),
+ // Sr25519 0x5002
+ a if a == hash(20482) => Some(Sr25519Precompile::<R>::execute(handle)),
+ _ => None,
+ }
+ }
+
+ fn is_precompile(&self, address: H160) -> bool {
+ Self::used_addresses().contains(&address)
+ }
+}
+
+fn hash(a: u64) -> H160 {
+ H160::from_low_u64_be(a)
+}
runtime/common/ethereum/precompiles/sr25519.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/ethereum/precompiles/sr25519.rs
@@ -0,0 +1,103 @@
+// Copyright 2019-2022 PureStake Inc.
+// Copyright 2022 Stake Technologies
+
+// Astar Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Astar Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Astar Network. If not, see <http://www.gnu.org/licenses/>.
+
+use fp_evm::{Context, ExitSucceed, PrecompileHandle, PrecompileOutput};
+use pallet_evm::Precompile;
+use sp_core::{crypto::UncheckedFrom, sr25519, H256};
+use sp_std::marker::PhantomData;
+use sp_std::prelude::*;
+
+use super::utils::{Bytes, EvmDataReader, EvmDataWriter, EvmResult, FunctionModifier, Gasometer};
+
+#[precompile_utils_macro::generate_function_selector]
+#[derive(Debug, PartialEq)]
+pub enum Action {
+ Verify = "verify(bytes32,bytes,bytes)",
+}
+
+/// A precompile to wrap substrate sr25519 functions.
+pub struct Sr25519Precompile<Runtime>(PhantomData<Runtime>);
+
+impl<Runtime: pallet_evm::Config> Precompile for Sr25519Precompile<Runtime> {
+ fn execute(handle: &mut impl PrecompileHandle) -> EvmResult<PrecompileOutput> {
+ log::trace!(target: "sr25519-precompile", "In sr25519 precompile");
+
+ let gasometer = Gasometer::new();
+
+ let (mut input, selector) = EvmDataReader::new_with_selector(&gasometer, handle.input())?;
+ let input = &mut input;
+
+ gasometer.check_function_modifier(
+ handle.context(),
+ handle.is_static(),
+ FunctionModifier::View,
+ )?;
+
+ match selector {
+ // Dispatchables
+ Action::Verify => Self::verify(input, &gasometer, handle.context()),
+ }
+ }
+}
+
+impl<Runtime: pallet_evm::Config> Sr25519Precompile<Runtime> {
+ fn verify(
+ input: &mut EvmDataReader,
+ gasometer: &Gasometer,
+ _: &Context,
+ ) -> EvmResult<PrecompileOutput> {
+ // Bound check
+ input.expect_arguments(gasometer, 3)?;
+
+ // Parse arguments
+ let public: sr25519::Public =
+ sr25519::Public::unchecked_from(input.read::<H256>(gasometer)?).into();
+ let signature_bytes: Vec<u8> = input.read::<Bytes>(gasometer)?.into();
+ let message: Vec<u8> = input.read::<Bytes>(gasometer)?.into();
+
+ // Parse signature
+ let signature_opt = sr25519::Signature::from_slice(&signature_bytes[..]);
+
+ let signature = if let Some(sig) = signature_opt {
+ sig
+ } else {
+ // Return `false` if signature length is wrong
+ return Ok(PrecompileOutput {
+ exit_status: ExitSucceed::Returned,
+ output: EvmDataWriter::new().write(false).build(),
+ });
+ };
+
+ log::trace!(
+ target: "sr25519-precompile",
+ "Verify signature {:?} for public {:?} and message {:?}",
+ signature, public, message,
+ );
+
+ let is_confirmed = sp_io::crypto::sr25519_verify(&signature, &message[..], &public);
+
+ log::trace!(
+ target: "sr25519-precompile",
+ "Verified signature {:?} is {:?}",
+ signature, is_confirmed,
+ );
+
+ Ok(PrecompileOutput {
+ exit_status: ExitSucceed::Returned,
+ output: EvmDataWriter::new().write(is_confirmed).build(),
+ })
+ }
+}
runtime/common/ethereum/precompiles/utils/data.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/ethereum/precompiles/utils/data.rs
@@ -0,0 +1,486 @@
+// Copyright 2019-2022 PureStake Inc.
+// Copyright 2022 Stake Technologies
+// This file is part of Utils package, originally developed by Purestake Inc.
+// Utils package used in Astar Network in terms of GPLv3.
+//
+// Utils is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Utils is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Utils. If not, see <http://www.gnu.org/licenses/>.
+
+use super::{EvmResult, Gasometer};
+
+use sp_std::borrow::ToOwned;
+use core::{any::type_name, ops::Range};
+use sp_core::{H160, H256, U256};
+use sp_std::{convert::TryInto, vec, vec::Vec};
+
+/// The `address` type of Solidity.
+/// H160 could represent 2 types of data (bytes20 and address) that are not encoded the same way.
+/// To avoid issues writing H160 is thus not supported.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct Address(pub H160);
+
+impl From<H160> for Address {
+ fn from(a: H160) -> Address {
+ Address(a)
+ }
+}
+
+impl From<Address> for H160 {
+ fn from(a: Address) -> H160 {
+ a.0
+ }
+}
+
+/// The `bytes`/`string` type of Solidity.
+/// It is different from `Vec<u8>` which will be serialized with padding for each `u8` element
+/// of the array, while `Bytes` is tightly packed.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct Bytes(pub Vec<u8>);
+
+impl From<&[u8]> for Bytes {
+ fn from(a: &[u8]) -> Self {
+ Self(a.to_owned())
+ }
+}
+
+impl From<&str> for Bytes {
+ fn from(a: &str) -> Self {
+ a.as_bytes().into()
+ }
+}
+
+impl Into<Vec<u8>> for Bytes {
+ fn into(self: Self) -> Vec<u8> {
+ self.0
+ }
+}
+
+/// Wrapper around an EVM input slice, helping to parse it.
+/// Provide functions to parse common types.
+#[derive(Clone, Copy, Debug)]
+pub struct EvmDataReader<'a> {
+ input: &'a [u8],
+ cursor: usize,
+}
+
+impl<'a> EvmDataReader<'a> {
+ /// Create a new input parser.
+ pub fn new(input: &'a [u8]) -> Self {
+ Self { input, cursor: 0 }
+ }
+
+ /// Create a new input parser from a selector-initial input.
+ pub fn new_with_selector<T>(gasometer: &Gasometer, input: &'a [u8]) -> EvmResult<(Self, T)>
+ where
+ T: num_enum::TryFromPrimitive<Primitive = u32>,
+ {
+ if input.len() < 4 {
+ return Err(gasometer.revert("tried to parse selector out of bounds"));
+ }
+
+ let mut buffer = [0u8; 4];
+ buffer.copy_from_slice(&input[0..4]);
+ let selector = T::try_from_primitive(u32::from_be_bytes(buffer)).map_err(|_| {
+ log::trace!(
+ target: "precompile-utils",
+ "Failed to match function selector for {}",
+ type_name::<T>()
+ );
+ gasometer.revert("unknown selector")
+ })?;
+
+ Ok((Self::new(&input[4..]), selector))
+ }
+
+ /// Check the input has at least the correct amount of arguments before the end (32 bytes values).
+ pub fn expect_arguments(&self, gasometer: &Gasometer, args: usize) -> EvmResult {
+ if self.input.len() >= self.cursor + args * 32 {
+ Ok(())
+ } else {
+ Err(gasometer.revert("input doesn't match expected length"))
+ }
+ }
+
+ /// Read data from the input.
+ /// Must be provided a gasometer to generate correct Revert errors.
+ /// TODO : Benchmark and add cost of parsing to gasometer ?
+ pub fn read<T: EvmData>(&mut self, gasometer: &Gasometer) -> EvmResult<T> {
+ T::read(self, gasometer)
+ }
+
+ /// Reads a pointer, returning a reader targetting the pointed location.
+ pub fn read_pointer(&mut self, gasometer: &Gasometer) -> EvmResult<Self> {
+ let offset: usize = self
+ .read::<U256>(gasometer)
+ .map_err(|_| gasometer.revert("tried to parse array offset out of bounds"))?
+ .try_into()
+ .map_err(|_| gasometer.revert("array offset is too large"))?;
+
+ if offset >= self.input.len() {
+ return Err(gasometer.revert("pointer points out of bounds"));
+ }
+
+ Ok(Self {
+ input: &self.input[offset..],
+ cursor: 0,
+ })
+ }
+
+ /// Move the reading cursor with provided length, and return a range from the previous cursor
+ /// location to the new one.
+ /// Checks cursor overflows.
+ fn move_cursor(&mut self, gasometer: &Gasometer, len: usize) -> EvmResult<Range<usize>> {
+ let start = self.cursor;
+ let end = self
+ .cursor
+ .checked_add(len)
+ .ok_or_else(|| gasometer.revert("data reading cursor overflow"))?;
+
+ self.cursor = end;
+
+ Ok(start..end)
+ }
+}
+
+/// Help build an EVM input/output data.
+///
+/// Functions takes `self` to allow chaining all calls like
+/// `EvmDataWriter::new().write(...).write(...).build()`.
+/// While it could be more ergonomic to take &mut self, this would
+/// prevent to have a `build` function that don't clone the output.
+#[derive(Clone, Debug)]
+pub struct EvmDataWriter {
+ pub(crate) data: Vec<u8>,
+ offset_data: Vec<OffsetDatum>,
+ selector: Option<u32>,
+}
+
+#[derive(Clone, Debug)]
+struct OffsetDatum {
+ // Offset location in the container data.
+ offset_position: usize,
+ // Data pointed by the offset that must be inserted at the end of container data.
+ data: Vec<u8>,
+ // Inside of arrays, the offset is not from the start of array data (length), but from the start
+ // of the item. This shift allow to correct this.
+ offset_shift: usize,
+}
+
+impl EvmDataWriter {
+ /// Creates a new empty output builder (without selector).
+ pub fn new() -> Self {
+ Self {
+ data: vec![],
+ offset_data: vec![],
+ selector: None,
+ }
+ }
+
+ /// Return the built data.
+ pub fn build(mut self) -> Vec<u8> {
+ Self::bake_offsets(&mut self.data, self.offset_data);
+
+ if let Some(selector) = self.selector {
+ let mut output = selector.to_be_bytes().to_vec();
+ output.append(&mut self.data);
+ output
+ } else {
+ self.data
+ }
+ }
+
+ /// Add offseted data at the end of this writer's data, updating the offsets.
+ fn bake_offsets(output: &mut Vec<u8>, offsets: Vec<OffsetDatum>) {
+ for mut offset_datum in offsets {
+ let offset_position = offset_datum.offset_position;
+ let offset_position_end = offset_position + 32;
+
+ // The offset is the distance between the start of the data and the
+ // start of the pointed data (start of a struct, length of an array).
+ // Offsets in inner data are relative to the start of their respective "container".
+ // However in arrays the "container" is actually the item itself instead of the whole
+ // array, which is corrected by `offset_shift`.
+ let free_space_offset = output.len() - offset_datum.offset_shift;
+
+ // Override dummy offset to the offset it will be in the final output.
+ U256::from(free_space_offset)
+ .to_big_endian(&mut output[offset_position..offset_position_end]);
+
+ // Append this data at the end of the current output.
+ output.append(&mut offset_datum.data);
+ }
+ }
+
+ /// Write arbitrary bytes.
+ /// Doesn't handle any alignement checks, prefer using `write` instead if possible.
+ fn write_raw_bytes(mut self, value: &[u8]) -> Self {
+ self.data.extend_from_slice(value);
+ self
+ }
+
+ /// Write data of requested type.
+ pub fn write<T: EvmData>(mut self, value: T) -> Self {
+ T::write(&mut self, value);
+ self
+ }
+
+ /// Writes a pointer to given data.
+ /// The data will be appended when calling `build`.
+ /// Initially write a dummy value as offset in this writer's data, which will be replaced by
+ /// the correct offset once the pointed data is appended.
+ ///
+ /// Takes `&mut self` since its goal is to be used inside `EvmData` impl and not in chains.
+ pub fn write_pointer(&mut self, data: Vec<u8>) {
+ let offset_position = self.data.len();
+ H256::write(self, H256::repeat_byte(0xff));
+
+ self.offset_data.push(OffsetDatum {
+ offset_position,
+ data,
+ offset_shift: 0,
+ });
+ }
+}
+
+impl Default for EvmDataWriter {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Data that can be converted from and to EVM data types.
+pub trait EvmData: Sized {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self>;
+ fn write(writer: &mut EvmDataWriter, value: Self);
+}
+
+impl EvmData for H256 {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let range = reader.move_cursor(gasometer, 32)?;
+
+ let data = reader
+ .input
+ .get(range)
+ .ok_or_else(|| gasometer.revert("tried to parse H256 out of bounds"))?;
+
+ Ok(H256::from_slice(data))
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ writer.data.extend_from_slice(value.as_bytes());
+ }
+}
+
+impl EvmData for Address {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let range = reader.move_cursor(gasometer, 32)?;
+
+ let data = reader
+ .input
+ .get(range)
+ .ok_or_else(|| gasometer.revert("tried to parse H160 out of bounds"))?;
+
+ Ok(H160::from_slice(&data[12..32]).into())
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ H256::write(writer, value.0.into());
+ }
+}
+
+impl EvmData for U256 {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let range = reader.move_cursor(gasometer, 32)?;
+
+ let data = reader
+ .input
+ .get(range)
+ .ok_or_else(|| gasometer.revert("tried to parse U256 out of bounds"))?;
+
+ Ok(U256::from_big_endian(data))
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ let mut buffer = [0u8; 32];
+ value.to_big_endian(&mut buffer);
+ writer.data.extend_from_slice(&buffer);
+ }
+}
+
+macro_rules! impl_evmdata_for_uints {
+ ($($uint:ty, )*) => {
+ $(
+ impl EvmData for $uint {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let range = reader.move_cursor(gasometer, 32)?;
+
+ let data = reader
+ .input
+ .get(range)
+ .ok_or_else(|| gasometer.revert(alloc::format!(
+ "tried to parse {} out of bounds", core::any::type_name::<Self>()
+ )))?;
+
+ let mut buffer = [0u8; core::mem::size_of::<Self>()];
+ buffer.copy_from_slice(&data[32 - core::mem::size_of::<Self>()..]);
+ Ok(Self::from_be_bytes(buffer))
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ let mut buffer = [0u8; 32];
+ buffer[32 - core::mem::size_of::<Self>()..].copy_from_slice(&value.to_be_bytes());
+ writer.data.extend_from_slice(&buffer);
+ }
+ }
+ )*
+ };
+}
+
+impl_evmdata_for_uints!(u16, u32, u64, u128,);
+
+// The implementation for u8 is specific, for performance reasons.
+impl EvmData for u8 {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let range = reader.move_cursor(gasometer, 32)?;
+
+ let data = reader
+ .input
+ .get(range)
+ .ok_or_else(|| gasometer.revert("tried to parse u64 out of bounds"))?;
+
+ Ok(data[31])
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ let mut buffer = [0u8; 32];
+ buffer[31] = value;
+
+ writer.data.extend_from_slice(&buffer);
+ }
+}
+
+impl EvmData for bool {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let h256 = H256::read(reader, gasometer)
+ .map_err(|_| gasometer.revert("tried to parse bool out of bounds"))?;
+
+ Ok(!h256.is_zero())
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ let mut buffer = [0u8; 32];
+ if value {
+ buffer[31] = 1;
+ }
+
+ writer.data.extend_from_slice(&buffer);
+ }
+}
+
+impl<T: EvmData> EvmData for Vec<T> {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let mut inner_reader = reader.read_pointer(gasometer)?;
+
+ let array_size: usize = inner_reader
+ .read::<U256>(gasometer)
+ .map_err(|_| gasometer.revert("tried to parse array length out of bounds"))?
+ .try_into()
+ .map_err(|_| gasometer.revert("array length is too large"))?;
+
+ let mut array = vec![];
+
+ let mut item_reader = EvmDataReader {
+ input: inner_reader
+ .input
+ .get(32..)
+ .ok_or_else(|| gasometer.revert("try to read array items out of bound"))?,
+ cursor: 0,
+ };
+
+ for _ in 0..array_size {
+ array.push(item_reader.read(gasometer)?);
+ }
+
+ Ok(array)
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ let mut inner_writer = EvmDataWriter::new().write(U256::from(value.len()));
+
+ for inner in value {
+ // Any offset in items are relative to the start of the item instead of the
+ // start of the array. However if there is offseted data it must but appended after
+ // all items (offsets) are written. We thus need to rely on `compute_offsets` to do
+ // that, and must store a "shift" to correct the offsets.
+ let shift = inner_writer.data.len();
+ let item_writer = EvmDataWriter::new().write(inner);
+
+ inner_writer = inner_writer.write_raw_bytes(&item_writer.data);
+ for mut offset_datum in item_writer.offset_data {
+ offset_datum.offset_shift += 32;
+ offset_datum.offset_position += shift;
+ inner_writer.offset_data.push(offset_datum);
+ }
+ }
+
+ writer.write_pointer(inner_writer.build());
+ }
+}
+
+impl EvmData for Bytes {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let mut inner_reader = reader.read_pointer(gasometer)?;
+
+ // Read bytes/string size.
+ let array_size: usize = inner_reader
+ .read::<U256>(gasometer)
+ .map_err(|_| gasometer.revert("tried to parse bytes/string length out of bounds"))?
+ .try_into()
+ .map_err(|_| gasometer.revert("bytes/string length is too large"))?;
+
+ // Get valid range over the bytes data.
+ let range = inner_reader.move_cursor(gasometer, array_size)?;
+
+ let data = inner_reader
+ .input
+ .get(range)
+ .ok_or_else(|| gasometer.revert("tried to parse bytes/string out of bounds"))?;
+
+ let bytes = Self(data.to_owned());
+
+ Ok(bytes)
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ let length = value.0.len();
+
+ // Pad the data.
+ // Leave it as is if a multiple of 32, otherwise pad to next
+ // multiple or 32.
+ let chunks = length / 32;
+ let padded_size = match length % 32 {
+ 0 => chunks * 32,
+ _ => (chunks + 1) * 32,
+ };
+
+ let mut value = value.0.to_vec();
+ value.resize(padded_size, 0);
+
+ writer.write_pointer(
+ EvmDataWriter::new()
+ .write(U256::from(length))
+ .write_raw_bytes(&value)
+ .build(),
+ );
+ }
+}
runtime/common/ethereum/precompiles/utils/macro/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/runtime/common/ethereum/precompiles/utils/macro/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "precompile-utils-macro"
+authors = [ "StakeTechnologies", "PureStake" ]
+description = ""
+edition = "2018"
+version = "0.1.0"
+
+[lib]
+proc-macro = true
+
+[dependencies]
+num_enum = { version = "0.5.3", default-features = false }
+proc-macro2 = "1.0"
+quote = "1.0"
+sha3 = "0.8"
+syn = { version = "1.0", features = [ "extra-traits", "fold", "full", "visit" ] }
runtime/common/ethereum/precompiles/utils/macro/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/ethereum/precompiles/utils/macro/src/lib.rs
@@ -0,0 +1,115 @@
+// Copyright 2019-2022 PureStake Inc.
+// Copyright 2022 Stake Technologies
+// This file is part of Utils package, originally developed by Purestake Inc.
+// Utils package used in Astar Network in terms of GPLv3.
+//
+// Utils is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Utils is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Utils. If not, see <http://www.gnu.org/licenses/>.
+
+#![crate_type = "proc-macro"]
+extern crate proc_macro;
+
+use proc_macro::TokenStream;
+use proc_macro2::Literal;
+use quote::{quote, quote_spanned};
+use sha3::{Digest, Keccak256};
+use std::convert::TryInto;
+use syn::{parse_macro_input, spanned::Spanned, Expr, ExprLit, Ident, ItemEnum, Lit};
+
+/// This macro allows to associate to each variant of an enumeration a discriminant (of type u32
+/// whose value corresponds to the first 4 bytes of the Hash Keccak256 of the character string
+///indicated by the user of this macro.
+///
+/// Usage:
+///
+/// ```ignore
+/// #[generate_function_selector]
+/// enum Action {
+/// Toto = "toto()",
+/// Tata = "tata()",
+/// }
+/// ```
+///
+/// Extanded to:
+///
+/// ```rust
+/// #[repr(u32)]
+/// enum Action {
+/// Toto = 119097542u32,
+/// Tata = 1414311903u32,
+/// }
+/// ```
+///
+#[proc_macro_attribute]
+pub fn generate_function_selector(_: TokenStream, input: TokenStream) -> TokenStream {
+ let item = parse_macro_input!(input as ItemEnum);
+
+ let ItemEnum {
+ attrs,
+ vis,
+ enum_token,
+ ident,
+ variants,
+ ..
+ } = item;
+
+ let mut ident_expressions: Vec<Ident> = vec![];
+ let mut variant_expressions: Vec<Expr> = vec![];
+ for variant in variants {
+ match variant.discriminant {
+ Some((_, Expr::Lit(ExprLit { lit, .. }))) => {
+ if let Lit::Str(lit_str) = lit {
+ let selector = u32::from_be_bytes(
+ Keccak256::digest(lit_str.value().as_ref())[..4]
+ .try_into()
+ .unwrap(),
+ );
+ ident_expressions.push(variant.ident);
+ variant_expressions.push(Expr::Lit(ExprLit {
+ lit: Lit::Verbatim(Literal::u32_suffixed(selector)),
+ attrs: Default::default(),
+ }));
+ } else {
+ return quote_spanned! {
+ lit.span() => compile_error("Expected literal string");
+ }
+ .into();
+ }
+ }
+ Some((_eg, expr)) => {
+ return quote_spanned! {
+ expr.span() => compile_error("Expected literal");
+ }
+ .into()
+ }
+ None => {
+ return quote_spanned! {
+ variant.span() => compile_error("Each variant must have a discriminant");
+ }
+ .into()
+ }
+ }
+ }
+
+ (quote! {
+ #(#attrs)*
+ #[derive(num_enum::TryFromPrimitive, num_enum::IntoPrimitive)]
+ #[repr(u32)]
+ #vis #enum_token #ident {
+ #(
+ #ident_expressions = #variant_expressions,
+ )*
+ }
+ })
+ .into()
+}
runtime/common/ethereum/precompiles/utils/mod.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/ethereum/precompiles/utils/mod.rs
@@ -0,0 +1,95 @@
+// Copyright 2019-2022 PureStake Inc.
+// Copyright 2022 Stake Technologies
+// This file is part of Utils package, originally developed by Purestake Inc.
+// Utils package used in Astar Network in terms of GPLv3.
+//
+// Utils is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Utils is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Utils. If not, see <http://www.gnu.org/licenses/>.
+
+use sp_std::borrow::ToOwned;
+use fp_evm::{Context, ExitRevert, PrecompileFailure};
+use sp_core::U256;
+use sp_std::marker::PhantomData;
+
+mod data;
+
+pub use data::{Bytes, EvmData, EvmDataReader, EvmDataWriter};
+
+/// Alias for Result returning an EVM precompile error.
+pub type EvmResult<T = ()> = Result<T, PrecompileFailure>;
+
+/// Helper functions requiring a Runtime.
+/// This runtime must of course implement `pallet_evm::Config`.
+#[derive(Clone, Copy, Debug)]
+pub struct RuntimeHelper<Runtime>(PhantomData<Runtime>);
+
+/// Represents modifiers a Solidity function can be annotated with.
+#[derive(Copy, Clone, PartialEq, Eq)]
+pub enum FunctionModifier {
+ /// Function that doesn't modify the state.
+ View,
+ /// Function that modifies the state and accept funds.
+ Payable,
+}
+
+/// Custom Gasometer to record costs in precompiles.
+/// It is advised to record known costs as early as possible to
+/// avoid unecessary computations if there is an Out of Gas.
+///
+/// Provides functions related to reverts, as reverts takes the recorded amount
+/// of gas into account.
+#[derive(Clone, Copy, Debug)]
+pub struct Gasometer();
+
+impl Gasometer {
+ /// Create a new Gasometer with provided gas limit.
+ /// None is no limit.
+ pub fn new() -> Self {
+ Self()
+ }
+
+ /// Revert the execution, making the user pay for the the currently
+ /// recorded cost. It is better to **revert** instead of **error** as
+ /// erroring consumes the entire gas limit, and **revert** returns an error
+ /// message to the calling contract.
+ ///
+ /// TODO : Record cost of the input based on its size and handle Out of Gas ?
+ /// This might be required if we format revert messages using user data.
+ #[must_use]
+ pub fn revert(&self, output: impl AsRef<[u8]>) -> PrecompileFailure {
+ PrecompileFailure::Revert {
+ exit_status: ExitRevert::Reverted,
+ output: output.as_ref().to_owned(),
+ }
+ }
+
+ #[must_use]
+ /// Check that a function call is compatible with the context it is
+ /// called into.
+ pub fn check_function_modifier(
+ &self,
+ context: &Context,
+ is_static: bool,
+ modifier: FunctionModifier,
+ ) -> EvmResult {
+ if is_static && modifier != FunctionModifier::View {
+ return Err(self.revert("can't call non-static function in static context"));
+ }
+
+ if modifier != FunctionModifier::Payable && context.apparent_value > U256::zero() {
+ return Err(self.revert("function is not payable"));
+ }
+
+ Ok(())
+ }
+}
runtime/opal/Cargo.tomldiffbeforeafterboth--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -471,6 +471,7 @@
up-rpc = { path = "../../primitives/rpc", default-features = false }
app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false }
rmrk-rpc = { path = "../../primitives/rmrk-rpc", default-features = false }
+fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
pallet-inflation = { path = '../../pallets/inflation', default-features = false }
pallet-app-promotion = { path = '../../pallets/app-promotion', default-features = false }
@@ -494,10 +495,13 @@
pallet-base-fee = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-rpc = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-self-contained = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
+pallet-evm-precompile-simple = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
up-sponsorship = { default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = 'polkadot-v0.9.33' }
pallet-foreign-assets = { default-features = false, path = "../../pallets/foreign-assets" }
pallet-maintenance = { default-features = false, path = "../../pallets/maintenance" }
+precompile-utils-macro = { path = "../common/ethereum/precompiles/utils/macro" }
+num_enum = { version = "0.5.3", default-features = false }
################################################################################
# Test dependencies
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -25,6 +25,8 @@
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
+extern crate alloc;
+
use frame_support::parameter_types;
use sp_version::RuntimeVersion;
runtime/quartz/Cargo.tomldiffbeforeafterboth--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -169,7 +169,7 @@
"pallet-maintenance/std",
]
limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
-quartz-runtime = ['refungible', 'app-promotion']
+quartz-runtime = ['refungible', 'app-promotion', 'foreign-assets']
refungible = []
scheduler = []
@@ -463,6 +463,7 @@
pallet-unique = { path = '../../pallets/unique', default-features = false }
up-rpc = { path = "../../primitives/rpc", default-features = false }
app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false }
+fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
pallet-inflation = { path = '../../pallets/inflation', default-features = false }
pallet-app-promotion = { path = '../../pallets/app-promotion', default-features = false }
@@ -486,10 +487,13 @@
pallet-base-fee = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-rpc = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-self-contained = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
+pallet-evm-precompile-simple = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
up-sponsorship = { default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = 'polkadot-v0.9.33' }
pallet-foreign-assets = { default-features = false, path = "../../pallets/foreign-assets" }
pallet-maintenance = { default-features = false, path = "../../pallets/maintenance" }
+precompile-utils-macro = { path = "../common/ethereum/precompiles/utils/macro" }
+num_enum = { version = "0.5.3", default-features = false }
################################################################################
# Other Dependencies
runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -25,6 +25,8 @@
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
+extern crate alloc;
+
use frame_support::parameter_types;
use sp_version::RuntimeVersion;
runtime/quartz/src/xcm_barrier.rsdiffbeforeafterboth--- a/runtime/quartz/src/xcm_barrier.rs
+++ b/runtime/quartz/src/xcm_barrier.rs
@@ -52,6 +52,11 @@
parents: 1,
interior: Here,
},
+ // Statemint/Statemint location
+ MultiLocation {
+ parents: 1,
+ interior: X1(Parachain(1000)),
+ },
// Karura/Acala location
MultiLocation {
parents: 1,
runtime/unique/Cargo.tomldiffbeforeafterboth--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -170,7 +170,7 @@
"pallet-maintenance/std",
]
limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
-unique-runtime = []
+unique-runtime = ['foreign-assets']
stubgen = ["evm-coder/stubgen"]
refungible = []
@@ -479,11 +479,15 @@
pallet-base-fee = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-rpc = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-self-contained = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
+fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
+pallet-evm-precompile-simple = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
up-sponsorship = { default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = 'polkadot-v0.9.33' }
pallet-foreign-assets = { default-features = false, path = "../../pallets/foreign-assets" }
pallet-maintenance = { default-features = false, path = "../../pallets/maintenance" }
+precompile-utils-macro = { path = "../common/ethereum/precompiles/utils/macro" }
+num_enum = { version = "0.5.3", default-features = false }
################################################################################
# Other Dependencies
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -25,6 +25,8 @@
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
+extern crate alloc;
+
use frame_support::parameter_types;
use sp_version::RuntimeVersion;
runtime/unique/src/xcm_barrier.rsdiffbeforeafterboth--- a/runtime/unique/src/xcm_barrier.rs
+++ b/runtime/unique/src/xcm_barrier.rs
@@ -52,6 +52,11 @@
parents: 1,
interior: Here,
},
+ // Statemint/Statemint location
+ MultiLocation {
+ parents: 1,
+ interior: X1(Parachain(1000)),
+ },
// Karura/Acala location
MultiLocation {
parents: 1,
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -45,6 +45,7 @@
"testNesting": "mocha --timeout 9999999 -r ts-node/register ./**/nest.test.ts",
"testUnnesting": "mocha --timeout 9999999 -r ts-node/register ./**/unnest.test.ts",
"testProperties": "mocha --timeout 9999999 -r ts-node/register ./**/collectionProperties.test.ts ./**/tokenProperties.test.ts ./**/getPropertiesRpc.test.ts",
+ "testCollectionProperties": "mocha --timeout 9999999 -r ts-node/register ./**/collectionProperties.test.ts",
"testMigration": "mocha --timeout 9999999 -r ts-node/register ./**/nesting/migration-check.test.ts",
"testAddCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/addCollectionAdmin.test.ts",
"testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",
tests/src/eth/abi/nonFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -697,12 +697,29 @@
},
{
"inputs": [
- { "internalType": "string", "name": "key", "type": "string" },
- { "internalType": "bool", "name": "isMutable", "type": "bool" },
- { "internalType": "bool", "name": "collectionAdmin", "type": "bool" },
- { "internalType": "bool", "name": "tokenOwner", "type": "bool" }
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ {
+ "components": [
+ {
+ "internalType": "enum EthTokenPermissions",
+ "name": "field_0",
+ "type": "uint8"
+ },
+ { "internalType": "bool", "name": "field_1", "type": "bool" }
+ ],
+ "internalType": "struct Tuple46[]",
+ "name": "field_1",
+ "type": "tuple[]"
+ }
+ ],
+ "internalType": "struct Tuple48[]",
+ "name": "permissions",
+ "type": "tuple[]"
+ }
],
- "name": "setTokenPropertyPermission",
+ "name": "setTokenPropertyPermissions",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
@@ -743,6 +760,35 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "tokenPropertyPermissions",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ {
+ "components": [
+ {
+ "internalType": "enum EthTokenPermissions",
+ "name": "field_0",
+ "type": "uint8"
+ },
+ { "internalType": "bool", "name": "field_1", "type": "bool" }
+ ],
+ "internalType": "struct Tuple46[]",
+ "name": "field_1",
+ "type": "tuple[]"
+ }
+ ],
+ "internalType": "struct Tuple48[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
],
tests/src/eth/abi/reFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -679,12 +679,29 @@
},
{
"inputs": [
- { "internalType": "string", "name": "key", "type": "string" },
- { "internalType": "bool", "name": "isMutable", "type": "bool" },
- { "internalType": "bool", "name": "collectionAdmin", "type": "bool" },
- { "internalType": "bool", "name": "tokenOwner", "type": "bool" }
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ {
+ "components": [
+ {
+ "internalType": "enum EthTokenPermissions",
+ "name": "field_0",
+ "type": "uint8"
+ },
+ { "internalType": "bool", "name": "field_1", "type": "bool" }
+ ],
+ "internalType": "struct Tuple51[]",
+ "name": "field_1",
+ "type": "tuple[]"
+ }
+ ],
+ "internalType": "struct Tuple53[]",
+ "name": "permissions",
+ "type": "tuple[]"
+ }
],
- "name": "setTokenPropertyPermission",
+ "name": "setTokenPropertyPermissions",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
@@ -734,6 +751,35 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "tokenPropertyPermissions",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ {
+ "components": [
+ {
+ "internalType": "enum EthTokenPermissions",
+ "name": "field_0",
+ "type": "uint8"
+ },
+ { "internalType": "bool", "name": "field_1", "type": "bool" }
+ ],
+ "internalType": "struct Tuple51[]",
+ "name": "field_1",
+ "type": "tuple[]"
+ }
+ ],
+ "internalType": "struct Tuple53[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
],
tests/src/eth/abi/reFungibleToken.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungibleToken.json
+++ b/tests/src/eth/abi/reFungibleToken.json
@@ -71,6 +71,24 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct EthCrossAccount",
+ "name": "spender",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "approveCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "owner", "type": "address" }
],
"name": "balanceOf",
@@ -89,6 +107,24 @@
"type": "function"
},
{
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct EthCrossAccount",
+ "name": "from",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "burnFromCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "decimals",
"outputs": [{ "internalType": "uint8", "name": "", "type": "uint8" }],
@@ -160,6 +196,24 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct EthCrossAccount",
+ "name": "to",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "transferCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "from", "type": "address" },
{ "internalType": "address", "name": "to", "type": "address" },
{ "internalType": "uint256", "name": "amount", "type": "uint256" }
@@ -168,5 +222,32 @@
"outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
"stateMutability": "nonpayable",
"type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct EthCrossAccount",
+ "name": "from",
+ "type": "tuple"
+ },
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct EthCrossAccount",
+ "name": "to",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "transferFromCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
}
]
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -13,22 +13,28 @@
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x91a97a68
+/// @dev the ERC-165 identifier for this interface is 0xde0695c2
interface TokenProperties is Dummy, ERC165 {
+ // /// @notice Set permissions for token property.
+ // /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+ // /// @param key Property key.
+ // /// @param isMutable Permission to mutate property.
+ // /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
+ // /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
+ // /// @dev EVM selector for this function is: 0x222d97fa,
+ // /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
+ // function setTokenPropertyPermission(string memory key, bool isMutable, bool collectionAdmin, bool tokenOwner) external;
+
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
- /// @param key Property key.
- /// @param isMutable Permission to mutate property.
- /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
- /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
- /// @dev EVM selector for this function is: 0x222d97fa,
- /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
- function setTokenPropertyPermission(
- string memory key,
- bool isMutable,
- bool collectionAdmin,
- bool tokenOwner
- ) external;
+ /// @param permissions Permissions for keys.
+ /// @dev EVM selector for this function is: 0xbd92983a,
+ /// or in textual repr: setTokenPropertyPermissions((string,(uint8,bool)[])[])
+ function setTokenPropertyPermissions(Tuple43[] memory permissions) external;
+
+ /// @dev EVM selector for this function is: 0xf23d7790,
+ /// or in textual repr: tokenPropertyPermissions()
+ function tokenPropertyPermissions() external view returns (Tuple43[] memory);
// /// @notice Set token property value.
// /// @dev Throws error if `msg.sender` has no permission to edit the property.
@@ -79,6 +85,24 @@
bytes value;
}
+enum EthTokenPermissions {
+ Mutable,
+ TokenOwner,
+ CollectionAdmin
+}
+
+/// @dev anonymous struct
+struct Tuple43 {
+ string field_0;
+ Tuple41[] field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple41 {
+ EthTokenPermissions field_0;
+ bool field_1;
+}
+
/// @title A contract that allows you to work with collections.
/// @dev the ERC-165 identifier for this interface is 0xb5e1747f
interface Collection is Dummy, ERC165 {
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -13,22 +13,29 @@
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x91a97a68
+/// @dev the ERC-165 identifier for this interface is 0xde0695c2
interface TokenProperties is Dummy, ERC165 {
+ // /// @notice Set permissions for token property.
+ // /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+ // /// @param key Property key.
+ // /// @param isMutable Permission to mutate property.
+ // /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
+ // /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
+ // /// @dev EVM selector for this function is: 0x222d97fa,
+ // /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
+ // function setTokenPropertyPermission(string memory key, bool isMutable, bool collectionAdmin, bool tokenOwner) external;
+
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
- /// @param key Property key.
- /// @param isMutable Permission to mutate property.
- /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
- /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
- /// @dev EVM selector for this function is: 0x222d97fa,
- /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
- function setTokenPropertyPermission(
- string memory key,
- bool isMutable,
- bool collectionAdmin,
- bool tokenOwner
- ) external;
+ /// @param permissions Permissions for keys.
+ /// @dev EVM selector for this function is: 0xbd92983a,
+ /// or in textual repr: setTokenPropertyPermissions((string,(uint8,bool)[])[])
+ function setTokenPropertyPermissions(Tuple47[] memory permissions) external;
+
+ /// @notice Get permissions for token properties.
+ /// @dev EVM selector for this function is: 0xf23d7790,
+ /// or in textual repr: tokenPropertyPermissions()
+ function tokenPropertyPermissions() external view returns (Tuple47[] memory);
// /// @notice Set token property value.
// /// @dev Throws error if `msg.sender` has no permission to edit the property.
@@ -79,6 +86,24 @@
bytes value;
}
+enum EthTokenPermissions {
+ Mutable,
+ TokenOwner,
+ CollectionAdmin
+}
+
+/// @dev anonymous struct
+struct Tuple47 {
+ string field_0;
+ Tuple45[] field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple45 {
+ EthTokenPermissions field_0;
+ bool field_1;
+}
+
/// @title A contract that allows you to work with collections.
/// @dev the ERC-165 identifier for this interface is 0xb5e1747f
interface Collection is Dummy, ERC165 {
tests/src/eth/api/UniqueRefungibleToken.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungibleToken.sol
+++ b/tests/src/eth/api/UniqueRefungibleToken.sol
@@ -23,7 +23,7 @@
function parentTokenId() external view returns (uint256);
}
-/// @dev the ERC-165 identifier for this interface is 0xab8deb37
+/// @dev the ERC-165 identifier for this interface is 0xe17a7d2b
interface ERC20UniqueExtensions is Dummy, ERC165 {
/// @dev Function that burns an amount of the token of a given account,
/// deducting from the sender's allowance for said account.
@@ -33,12 +33,56 @@
/// or in textual repr: burnFrom(address,uint256)
function burnFrom(address from, uint256 amount) external returns (bool);
+ /// @dev Function that burns an amount of the token of a given account,
+ /// deducting from the sender's allowance for said account.
+ /// @param from The account whose tokens will be burnt.
+ /// @param amount The amount that will be burnt.
+ /// @dev EVM selector for this function is: 0xbb2f5a58,
+ /// or in textual repr: burnFromCross((address,uint256),uint256)
+ function burnFromCross(EthCrossAccount memory from, uint256 amount) external returns (bool);
+
+ /// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.
+ /// Beware that changing an allowance with this method brings the risk that someone may use both the old
+ /// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
+ /// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
+ /// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
+ /// @param spender The crossaccount which will spend the funds.
+ /// @param amount The amount of tokens to be spent.
+ /// @dev EVM selector for this function is: 0x0ecd0ab0,
+ /// or in textual repr: approveCross((address,uint256),uint256)
+ function approveCross(EthCrossAccount memory spender, uint256 amount) external returns (bool);
+
/// @dev Function that changes total amount of the tokens.
/// Throws if `msg.sender` doesn't owns all of the tokens.
/// @param amount New total amount of the tokens.
/// @dev EVM selector for this function is: 0xd2418ca7,
/// or in textual repr: repartition(uint256)
function repartition(uint256 amount) external returns (bool);
+
+ /// @dev Transfer token for a specified address
+ /// @param to The crossaccount to transfer to.
+ /// @param amount The amount to be transferred.
+ /// @dev EVM selector for this function is: 0x2ada85ff,
+ /// or in textual repr: transferCross((address,uint256),uint256)
+ function transferCross(EthCrossAccount memory to, uint256 amount) external returns (bool);
+
+ /// @dev Transfer tokens from one address to another
+ /// @param from The address which you want to send tokens from
+ /// @param to The address which you want to transfer to
+ /// @param amount the amount of tokens to be transferred
+ /// @dev EVM selector for this function is: 0xd5cf430b,
+ /// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
+ function transferFromCross(
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
+ uint256 amount
+ ) external returns (bool);
+}
+
+/// @dev Cross account struct
+struct EthCrossAccount {
+ address eth;
+ uint256 sub;
}
/// @dev inlined interface
tests/src/eth/events.test.tsdiffbeforeafterboth--- a/tests/src/eth/events.test.ts
+++ b/tests/src/eth/events.test.ts
@@ -19,7 +19,7 @@
import {EthUniqueHelper, itEth, usingEthPlaygrounds} from './util';
import {IEvent, TCollectionMode} from '../util/playgrounds/types';
import {Pallets, requirePalletsOrSkip} from '../util';
-import {NormalizedEvent} from './util/playgrounds/types';
+import {EthTokenPermissions, NormalizedEvent} from './util/playgrounds/types';
let donor: IKeyringPair;
@@ -119,7 +119,13 @@
ethEvents.push(event);
});
const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['PropertyPermissionSet']}]);
- await collection.methods.setTokenPropertyPermission('testKey', true, true, true).send({from: owner});
+ await collection.methods.setTokenPropertyPermissions([
+ ['A', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ]).send({from: owner});
await helper.wait.newBlocks(1);
expect(ethEvents).to.be.like([
{
@@ -374,7 +380,13 @@
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
const result = await collection.methods.mint(owner).send({from: owner});
const tokenId = result.events.Transfer.returnValues.tokenId;
- await collection.methods.setTokenPropertyPermission('A', true, true, true).send({from: owner});
+ await collection.methods.setTokenPropertyPermissions([
+ ['A', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ]).send({from: owner});
const ethEvents: any = [];
tests/src/eth/precompile.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/precompile.test.ts
@@ -0,0 +1,112 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// 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 {IKeyringPair} from '@polkadot/types/types';
+
+import {expect, itEth, usingEthPlaygrounds} from './util';
+
+describe('Precompiles', () => {
+ let donor: IKeyringPair;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (_, privateKey) => {
+ donor = await privateKey({filename: __filename});
+ });
+ });
+
+ itEth('ecrecover is supported', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const ecrecoverCompiledСontract = await helper.ethContract.compile(
+ 'ECRECOVER',
+ `
+ // SPDX-License-Identifier: MIT
+ pragma solidity ^0.8.17;
+
+ contract ECRECOVER{
+ address addressTest = 0x12Cb274aAD8251C875c0bf6872b67d9983E53fDd;
+ bytes32 msgHash1 = 0xc51dac836bc7841a01c4b631fa620904fc8724d7f9f1d3c420f0e02adf229d50;
+ bytes32 msgHash2 = 0xc51dac836bc7841a01c4b631fa620904fc8724d7f9f1d3c420f0e02adf229d51;
+ uint8 v = 0x1b;
+ bytes32 r = 0x44287513919034a471a7dc2b2ed121f95984ae23b20f9637ba8dff471b6719ef;
+ bytes32 s = 0x7d7dc30309a3baffbfd9342b97d0e804092c0aeb5821319aa732bc09146eafb4;
+
+
+ function verifyValid() public view returns(bool) {
+ // Use ECRECOVER to verify address
+ return ecrecover(msgHash1, v, r, s) == (addressTest);
+ }
+
+ function verifyInvalid() public view returns(bool) {
+ // Use ECRECOVER to verify address
+ return ecrecover(msgHash2, v, r, s) == (addressTest);
+ }
+ }
+ `,
+ );
+
+ const ecrecoverСontract = await helper.ethContract.deployByAbi(owner, ecrecoverCompiledСontract.abi, ecrecoverCompiledСontract.object);
+ expect(await ecrecoverСontract.methods.verifyValid().call({from: owner})).to.be.true;
+ expect(await ecrecoverСontract.methods.verifyInvalid().call({from: owner})).to.be.false;
+ });
+
+ itEth('sr25519 is supported', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sr25519CompiledСontract = await helper.ethContract.compile(
+ 'SR25519Contract',
+ `
+ // SPDX-License-Identifier: MIT
+ pragma solidity ^0.8.17;
+
+ /**
+ * @title SR25519 signature interface.
+ */
+ interface SR25519 {
+ /**
+ * @dev Verify signed message using SR25519 crypto.
+ * @return A boolean confirming whether the public key is signer for the message.
+ */
+ function verify(
+ bytes32 public_key,
+ bytes calldata signature,
+ bytes calldata message
+ ) external view returns (bool);
+ }
+
+ contract SR25519Contract{
+ SR25519 public constant sr25519 = SR25519(0x0000000000000000000000000000000000005002);
+
+ bytes32 public_key = 0x96b2f9237ed0890fbeed891ebb81b91ac0d5d5b6e3afcdbc95df1b68d9f14036;
+ bytes signature = hex"4a5d733d7c568f2e88abf0467fd497f87c1be3e940ed897efdf9da72eaad394ef9918cb574ee99c54485775b17a0deaf46ff7a1f10346cea39fff0e4ede97689";
+ bytes message1 = hex"7372323535313920697320737570706f72746564";
+ bytes message2 = hex"7372323535313920697320737570706f7274656401";
+
+
+ function verifyValid() public view returns(bool) {
+ return sr25519.verify(public_key, signature, message1);
+ }
+
+ function verifyInvalid() public view returns(bool) {
+ return sr25519.verify(public_key, signature, message2);
+ }
+ }
+ `,
+ );
+
+ const sr25519Сontract = await helper.ethContract.deployByAbi(owner, sr25519CompiledСontract.abi, sr25519CompiledСontract.object);
+ expect(await sr25519Сontract.methods.verifyValid().call({from: owner})).to.be.true;
+ expect(await sr25519Сontract.methods.verifyInvalid().call({from: owner})).to.be.false;
+ });
+});
\ No newline at end of file
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -159,7 +159,55 @@
expect(+allowance).to.equal(100);
}
});
+
+ itEth('Can perform approveCross()', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const spender = helper.eth.createAccount();
+ const spenderSub = (await helper.arrange.createAccounts([1n], donor))[0];
+ const spenderCrossEth = helper.ethCrossAccount.fromAddress(spender);
+ const spenderCrossSub = helper.ethCrossAccount.fromKeyringPair(spenderSub);
+
+
+ const collection = await helper.rft.mintCollection(alice);
+ const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});
+
+ const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+ const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
+ {
+ const result = await contract.methods.approveCross(spenderCrossEth, 100).send({from: owner});
+ const event = result.events.Approval;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.owner).to.be.equal(owner);
+ expect(event.returnValues.spender).to.be.equal(spender);
+ expect(event.returnValues.value).to.be.equal('100');
+ }
+
+ {
+ const allowance = await contract.methods.allowance(owner, spender).call();
+ expect(+allowance).to.equal(100);
+ }
+
+
+ {
+ const result = await contract.methods.approveCross(spenderCrossSub, 100).send({from: owner});
+ const event = result.events.Approval;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.owner).to.be.equal(owner);
+ expect(event.returnValues.spender).to.be.equal(helper.address.substrateToEth(spenderSub.address));
+ expect(event.returnValues.value).to.be.equal('100');
+ }
+
+ {
+ const allowance = await collection.getTokenApprovedPieces(tokenId, {Ethereum: owner}, {Substrate: spenderSub.address});
+ expect(allowance).to.equal(100n);
+ }
+
+ {
+ //TO-DO expect with future allowanceCross(owner, spenderCrossEth).call()
+ }
+ });
+
itEth('Can perform transferFrom()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const spender = await helper.eth.createAccountWithBalance(donor);
@@ -197,7 +245,75 @@
expect(+balance).to.equal(151);
}
});
+
+ itEth('Can perform transferFromCross()', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+ const spender = await helper.eth.createAccountWithBalance(donor);
+ const receiver = helper.eth.createAccount();
+ const receiverSub = (await helper.arrange.createAccounts([1n], donor))[0];
+ const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiver);
+ const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(receiverSub);
+
+ const collection = await helper.rft.mintCollection(alice);
+ const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});
+
+ const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+ const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
+
+ await contract.methods.approve(spender, 100).send({from: owner});
+
+ {
+ const result = await contract.methods.transferFromCross(ownerCross, receiverCrossEth, 49).send({from: spender});
+ let event = result.events.Transfer;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.from).to.be.equal(owner);
+ expect(event.returnValues.to).to.be.equal(receiver);
+ expect(event.returnValues.value).to.be.equal('49');
+ event = result.events.Approval;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.owner).to.be.equal(owner);
+ expect(event.returnValues.spender).to.be.equal(spender);
+ expect(event.returnValues.value).to.be.equal('51');
+ }
+
+ {
+ const balance = await contract.methods.balanceOf(receiver).call();
+ expect(+balance).to.equal(49);
+ }
+
+ {
+ const balance = await contract.methods.balanceOf(owner).call();
+ expect(+balance).to.equal(151);
+ }
+
+ {
+ const result = await contract.methods.transferFromCross(ownerCross, receiverCrossSub, 51).send({from: spender});
+ let event = result.events.Transfer;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.from).to.be.equal(owner);
+ expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(receiverSub.address));
+ expect(event.returnValues.value).to.be.equal('51');
+
+ event = result.events.Approval;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.owner).to.be.equal(owner);
+ expect(event.returnValues.spender).to.be.equal(spender);
+ expect(event.returnValues.value).to.be.equal('0');
+ }
+
+ {
+ const balance = await collection.getTokenBalance(tokenId, {Substrate: receiverSub.address});
+ expect(balance).to.equal(51n);
+ }
+
+ {
+ const balance = await contract.methods.balanceOf(owner).call();
+ expect(+balance).to.equal(100);
+ }
+ });
+
itEth('Can perform transfer()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
@@ -226,7 +342,7 @@
expect(+balance).to.equal(50);
}
});
-
+
[
'transfer',
// 'transferCross', // TODO
@@ -267,6 +383,56 @@
expect(await rftReceiver.getTop10Owners()).to.deep.eq([{Ethereum: owner.toLowerCase()}]);
}));
+ itEth('Can perform transferCross()', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const receiver = helper.eth.createAccount();
+ const receiverSub = (await helper.arrange.createAccounts([1n], donor))[0];
+ const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiver);
+ const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(receiverSub);
+ const collection = await helper.rft.mintCollection(alice);
+ const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});
+
+ const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+ const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
+
+ {
+ const result = await contract.methods.transferCross(receiverCrossEth, 50).send({from: owner});
+ const event = result.events.Transfer;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.from).to.be.equal(owner);
+ expect(event.returnValues.to).to.be.equal(receiver);
+ expect(event.returnValues.value).to.be.equal('50');
+ }
+
+ {
+ const balance = await contract.methods.balanceOf(owner).call();
+ expect(+balance).to.equal(150);
+ }
+
+ {
+ const balance = await contract.methods.balanceOf(receiver).call();
+ expect(+balance).to.equal(50);
+ }
+
+ {
+ const result = await contract.methods.transferCross(receiverCrossSub, 50).send({from: owner});
+ const event = result.events.Transfer;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.from).to.be.equal(owner);
+ expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(receiverSub.address));
+ expect(event.returnValues.value).to.be.equal('50');
+ }
+
+ {
+ const balance = await contract.methods.balanceOf(owner).call();
+ expect(+balance).to.equal(100);
+ }
+
+ {
+ const balance = await collection.getTokenBalance(tokenId, {Substrate: receiverSub.address});
+ expect(balance).to.equal(50n);
+ }
+ });
itEth('Can perform repartition()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = await helper.eth.createAccountWithBalance(donor);
@@ -353,6 +519,41 @@
expect(event.returnValues.to).to.be.equal(receiver);
expect(event.returnValues.tokenId).to.be.equal(tokenId);
});
+
+ itEth('Can perform burnFromCross()', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const ownerSub = (await helper.arrange.createAccounts([10n], donor))[0];
+ const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+ const spender = await helper.eth.createAccountWithBalance(donor);
+
+ const spenderCrossEth = helper.ethCrossAccount.fromAddress(spender);
+ const ownerSubCross = helper.ethCrossAccount.fromKeyringPair(ownerSub);
+
+ const collection = await helper.rft.mintCollection(alice);
+ const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});
+
+
+ const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+ const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
+
+ {
+ await contract.methods.approveCross(spenderCrossEth, 100).send({from: owner});
+
+ await expect(contract.methods.burnFromCross(ownerCross, 50).send({from: spender})).to.be.fulfilled;
+ await expect(contract.methods.burnFromCross(ownerCross, 100).send({from: spender})).to.be.rejected;
+ expect(await contract.methods.balanceOf(owner).call({from: owner})).to.be.equal('150');
+ }
+ {
+ const {tokenId} = await collection.mintToken(alice, 200n, {Substrate: ownerSub.address});
+ await collection.approveToken(ownerSub, tokenId, {Ethereum: spender}, 100n);
+ const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+ const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
+
+ await expect(contract.methods.burnFromCross(ownerSubCross, 50).send({from: spender})).to.be.fulfilled;
+ await expect(contract.methods.burnFromCross(ownerSubCross, 100).send({from: spender})).to.be.rejected;
+ expect(await collection.getTokenBalance(tokenId, {Substrate: ownerSub.address})).to.be.equal(150n);
+ }
+ });
});
describe('Refungible: Fees', () => {
tests/src/eth/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -20,6 +20,7 @@
import {ITokenPropertyPermission} from '../util/playgrounds/types';
import {Pallets} from '../util';
import {UniqueNFTCollection, UniqueNFToken, UniqueRFTCollection} from '../util/playgrounds/unique';
+import {EthTokenPermissions} from './util/playgrounds/types';
describe('EVM token properties', () => {
let donor: IKeyringPair;
@@ -32,25 +33,170 @@
});
});
- itEth('Can be reconfigured', async({helper}) => {
- const caller = await helper.eth.createAccountWithBalance(donor);
- for(const [mutable,collectionAdmin, tokenOwner] of cartesian([], [false, true], [false, true], [false, true])) {
- const collection = await helper.nft.mintCollection(alice);
- await collection.addAdmin(alice, {Ethereum: caller});
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Set and get token property permissions`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.ethCrossAccount.createAccountWithBalance(donor);
+ for(const [mutable,collectionAdmin, tokenOwner] of cartesian([], [false, true], [false, true], [false, true])) {
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+ await collection.methods.addCollectionAdminCross(caller).send({from: owner});
+
+ await collection.methods.setTokenPropertyPermissions([
+ ['testKey', [
+ [EthTokenPermissions.Mutable, mutable],
+ [EthTokenPermissions.TokenOwner, tokenOwner],
+ [EthTokenPermissions.CollectionAdmin, collectionAdmin]],
+ ],
+ ]).send({from: caller.eth});
- const address = helper.ethAddress.fromCollectionId(collection.collectionId);
- const contract = helper.ethNativeContract.collection(address, 'nft', caller);
-
- await contract.methods.setTokenPropertyPermission('testKey', mutable, collectionAdmin, tokenOwner).send({from: caller});
-
- expect(await collection.getPropertyPermissions()).to.be.deep.equal([{
- key: 'testKey',
- permission: {mutable, collectionAdmin, tokenOwner},
- }]);
- }
- });
+ expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([{
+ key: 'testKey',
+ permission: {mutable, collectionAdmin, tokenOwner},
+ }]);
+ expect(await collection.methods.tokenPropertyPermissions().call({from: caller.eth})).to.be.like([
+ ['testKey', [
+ [EthTokenPermissions.Mutable.toString(), mutable],
+ [EthTokenPermissions.TokenOwner.toString(), tokenOwner],
+ [EthTokenPermissions.CollectionAdmin.toString(), collectionAdmin]],
+ ],
+ ]);
+ }
+ }));
+
[
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Set and get multiple token property permissions as owner`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+ await collection.methods.setTokenPropertyPermissions([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ['testKey_1', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, false],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ['testKey_2', [
+ [EthTokenPermissions.Mutable, false],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, false]],
+ ],
+ ]).send({from: owner});
+
+ expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([
+ {
+ key: 'testKey_0',
+ permission: {mutable: true, tokenOwner: true, collectionAdmin: true},
+ },
+ {
+ key: 'testKey_1',
+ permission: {mutable: true, tokenOwner: false, collectionAdmin: true},
+ },
+ {
+ key: 'testKey_2',
+ permission: {mutable: false, tokenOwner: true, collectionAdmin: false},
+ },
+ ]);
+
+ expect(await collection.methods.tokenPropertyPermissions().call({from: owner})).to.be.like([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable.toString(), true],
+ [EthTokenPermissions.TokenOwner.toString(), true],
+ [EthTokenPermissions.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_1', [
+ [EthTokenPermissions.Mutable.toString(), true],
+ [EthTokenPermissions.TokenOwner.toString(), false],
+ [EthTokenPermissions.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_2', [
+ [EthTokenPermissions.Mutable.toString(), false],
+ [EthTokenPermissions.TokenOwner.toString(), true],
+ [EthTokenPermissions.CollectionAdmin.toString(), false]],
+ ],
+ ]);
+
+ }));
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Set and get multiple token property permissions as admin`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.ethCrossAccount.createAccountWithBalance(donor);
+
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+ await collection.methods.addCollectionAdminCross(caller).send({from: owner});
+
+ await collection.methods.setTokenPropertyPermissions([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ['testKey_1', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, false],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ['testKey_2', [
+ [EthTokenPermissions.Mutable, false],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, false]],
+ ],
+ ]).send({from: caller.eth});
+
+ expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([
+ {
+ key: 'testKey_0',
+ permission: {mutable: true, tokenOwner: true, collectionAdmin: true},
+ },
+ {
+ key: 'testKey_1',
+ permission: {mutable: true, tokenOwner: false, collectionAdmin: true},
+ },
+ {
+ key: 'testKey_2',
+ permission: {mutable: false, tokenOwner: true, collectionAdmin: false},
+ },
+ ]);
+
+ expect(await collection.methods.tokenPropertyPermissions().call({from: caller.eth})).to.be.like([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable.toString(), true],
+ [EthTokenPermissions.TokenOwner.toString(), true],
+ [EthTokenPermissions.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_1', [
+ [EthTokenPermissions.Mutable.toString(), true],
+ [EthTokenPermissions.TokenOwner.toString(), false],
+ [EthTokenPermissions.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_2', [
+ [EthTokenPermissions.Mutable.toString(), false],
+ [EthTokenPermissions.TokenOwner.toString(), true],
+ [EthTokenPermissions.CollectionAdmin.toString(), false]],
+ ],
+ ]);
+
+ }));
+
+ [
{
method: 'setProperties',
methodParams: [[{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}]],
@@ -301,6 +447,47 @@
const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();
expect(actualProps).to.deep.eq(expectedProps);
}));
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Cant set token property permissions as non owner or admin`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+ await expect(collection.methods.setTokenPropertyPermissions([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ]).call({from: caller})).to.be.rejectedWith('NoPermission');
+ }));
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Cant set token property permissions with invalid character`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+ await expect(collection.methods.setTokenPropertyPermissions([
+ // "Space" is invalid character
+ ['testKey 0', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ]).call({from: owner})).to.be.rejectedWith('InvalidCharacterInPropertyKey');
+ }));
+
});
tests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -20,3 +20,8 @@
export type EthProperty = string[];
+export enum EthTokenPermissions {
+ Mutable,
+ TokenOwner,
+ CollectionAdmin
+}
\ No newline at end of file
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -60,7 +60,7 @@
}
async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {
- const out = JSON.parse(solc.compile(JSON.stringify({
+ const compiled = JSON.parse(solc.compile(JSON.stringify({
language: 'Solidity',
sources: {
[`${name}.sol`]: {
@@ -74,7 +74,18 @@
},
},
},
- }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];
+ }), {import: await this.findImports(imports)}));
+
+ const hasErrors = compiled['errors']
+ && compiled['errors'].length > 0
+ && compiled.errors.some(function(err: any) {
+ return err.severity == 'error';
+ });
+
+ if (hasErrors) {
+ throw compiled.errors;
+ }
+ const out = compiled.contracts[`${name}.sol`][name];
return {
abi: out.abi,
tests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-rpc.ts
+++ b/tests/src/interfaces/augment-api-rpc.ts
@@ -16,7 +16,7 @@
import type { BlockHash } from '@polkadot/types/interfaces/chain';
import type { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
-import type { CodeUploadRequest, CodeUploadResult, ContractCallRequest, ContractExecResult, ContractInstantiateResult, InstantiateRequestV1 } from '@polkadot/types/interfaces/contracts';
+import type { CodeUploadRequest, CodeUploadResult, ContractCallRequest, ContractExecResult, ContractInstantiateResult, InstantiateRequest } from '@polkadot/types/interfaces/contracts';
import type { BlockStats } from '@polkadot/types/interfaces/dev';
import type { CreatedBlock } from '@polkadot/types/interfaces/engine';
import type { EthAccount, EthCallRequest, EthFeeHistory, EthFilter, EthFilterChanges, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth';
@@ -24,7 +24,7 @@
import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import type { MmrLeafBatchProof, MmrLeafProof } from '@polkadot/types/interfaces/mmr';
import type { StorageKind } from '@polkadot/types/interfaces/offchain';
-import type { FeeDetails, RuntimeDispatchInfoV1 } from '@polkadot/types/interfaces/payment';
+import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { RpcMethods } from '@polkadot/types/interfaces/rpc';
import type { AccountId, AccountId32, BlockNumber, H160, H256, H64, Hash, Header, Index, Justification, KeyValue, SignedBlock, StorageData } from '@polkadot/types/interfaces/runtime';
import type { MigrationStatusResult, ReadProof, RuntimeVersion, TraceBlockResponse } from '@polkadot/types/interfaces/state';
@@ -174,7 +174,7 @@
* @deprecated Use the runtime interface `api.call.contractsApi.instantiate` instead
* Instantiate a new contract
**/
- instantiate: AugmentedRpc<(request: InstantiateRequestV1 | { origin?: any; value?: any; gasLimit?: any; code?: any; data?: any; salt?: any } | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<ContractInstantiateResult>>;
+ instantiate: AugmentedRpc<(request: InstantiateRequest | { origin?: any; value?: any; gasLimit?: any; storageDepositLimit?: any; code?: any; data?: any; salt?: any } | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<ContractInstantiateResult>>;
/**
* @deprecated Not available in newer versions of the contracts interfaces
* Returns the projected time a given contract will be able to sustain paying its rent
@@ -426,15 +426,13 @@
};
payment: {
/**
- * @deprecated Use `api.call.transactionPaymentApi.queryFeeDetails` instead
* Query the detailed fee of a given encoded extrinsic
**/
queryFeeDetails: AugmentedRpc<(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<FeeDetails>>;
/**
- * @deprecated Use `api.call.transactionPaymentApi.queryInfo` instead
* Retrieves the fee information for an encoded extrinsic
**/
- queryInfo: AugmentedRpc<(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<RuntimeDispatchInfoV1>>;
+ queryInfo: AugmentedRpc<(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<RuntimeDispatchInfo>>;
};
rmrk: {
/**
tests/src/interfaces/augment-api-runtime.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-runtime.ts
+++ b/tests/src/interfaces/augment-api-runtime.ts
@@ -6,7 +6,7 @@
import '@polkadot/api-base/types/calls';
import type { ApiTypes, AugmentedCall, DecoratedCallBase } from '@polkadot/api-base/types';
-import type { Bytes, Null, Option, Result, U256, Vec, bool, u256, u32, u64 } from '@polkadot/types-codec';
+import type { Bytes, Null, Option, Result, U256, Vec, bool, u256, u64 } from '@polkadot/types-codec';
import type { AnyNumber, ITuple } from '@polkadot/types-codec/types';
import type { CheckInherentsResult, InherentData } from '@polkadot/types/interfaces/blockbuilder';
import type { BlockHash } from '@polkadot/types/interfaces/chain';
@@ -16,7 +16,6 @@
import type { EvmAccount, EvmCallInfo, EvmCreateInfo } from '@polkadot/types/interfaces/evm';
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { OpaqueMetadata } from '@polkadot/types/interfaces/metadata';
-import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { AccountId, Block, H160, H256, Header, Index, KeyTypeId, Permill, SlotDuration } from '@polkadot/types/interfaces/runtime';
import type { RuntimeVersion } from '@polkadot/types/interfaces/state';
import type { ApplyExtrinsicResult, DispatchError } from '@polkadot/types/interfaces/system';
@@ -224,21 +223,6 @@
* Validate the transaction.
**/
validateTransaction: AugmentedCall<ApiType, (source: TransactionSource | 'InBlock' | 'Local' | 'External' | number | Uint8Array, tx: Extrinsic | IExtrinsic | string | Uint8Array, blockHash: BlockHash | string | Uint8Array) => Observable<TransactionValidity>>;
- /**
- * Generic call
- **/
- [key: string]: DecoratedCallBase<ApiType>;
- };
- /** 0x37c8bb1350a9a2a8/2 */
- transactionPaymentApi: {
- /**
- * The transaction fee details
- **/
- queryFeeDetails: AugmentedCall<ApiType, (uxt: Extrinsic | IExtrinsic | string | Uint8Array, len: u32 | AnyNumber | Uint8Array) => Observable<FeeDetails>>;
- /**
- * The transaction info
- **/
- queryInfo: AugmentedCall<ApiType, (uxt: Extrinsic | IExtrinsic | string | Uint8Array, len: u32 | AnyNumber | Uint8Array) => Observable<RuntimeDispatchInfo>>;
/**
* Generic call
**/
tests/src/interfaces/augment-types.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -24,7 +24,7 @@
import type { StatementKind } from '@polkadot/types/interfaces/claims';
import type { CollectiveOrigin, MemberCount, ProposalIndex, Votes, VotesTo230 } from '@polkadot/types/interfaces/collective';
import type { AuthorityId, RawVRFOutput } from '@polkadot/types/interfaces/consensus';
-import type { AliveContractInfo, CodeHash, CodeSource, CodeUploadRequest, CodeUploadResult, CodeUploadResultValue, ContractCallFlags, ContractCallRequest, ContractExecResult, ContractExecResultOk, ContractExecResultResult, ContractExecResultSuccessTo255, ContractExecResultSuccessTo260, ContractExecResultTo255, ContractExecResultTo260, ContractExecResultTo267, ContractExecResultU64, ContractInfo, ContractInstantiateResult, ContractInstantiateResultTo267, ContractInstantiateResultTo299, ContractInstantiateResultU64, ContractReturnFlags, ContractStorageKey, DeletedContract, ExecReturnValue, Gas, HostFnWeights, HostFnWeightsTo264, InstantiateRequest, InstantiateRequestV1, InstantiateRequestV2, InstantiateReturnValue, InstantiateReturnValueOk, InstantiateReturnValueTo267, InstructionWeights, Limits, LimitsTo264, PrefabWasmModule, RentProjection, Schedule, ScheduleTo212, ScheduleTo258, ScheduleTo264, SeedOf, StorageDeposit, TombstoneContractInfo, TrieId } from '@polkadot/types/interfaces/contracts';
+import type { AliveContractInfo, CodeHash, CodeSource, CodeUploadRequest, CodeUploadResult, CodeUploadResultValue, ContractCallFlags, ContractCallRequest, ContractExecResult, ContractExecResultOk, ContractExecResultResult, ContractExecResultSuccessTo255, ContractExecResultSuccessTo260, ContractExecResultTo255, ContractExecResultTo260, ContractExecResultTo267, ContractInfo, ContractInstantiateResult, ContractInstantiateResultTo267, ContractInstantiateResultTo299, ContractReturnFlags, ContractStorageKey, DeletedContract, ExecReturnValue, Gas, HostFnWeights, HostFnWeightsTo264, InstantiateRequest, InstantiateRequestV1, InstantiateRequestV2, InstantiateReturnValue, InstantiateReturnValueOk, InstantiateReturnValueTo267, InstructionWeights, Limits, LimitsTo264, PrefabWasmModule, RentProjection, Schedule, ScheduleTo212, ScheduleTo258, ScheduleTo264, SeedOf, StorageDeposit, TombstoneContractInfo, TrieId } from '@polkadot/types/interfaces/contracts';
import type { ContractConstructorSpecLatest, ContractConstructorSpecV0, ContractConstructorSpecV1, ContractConstructorSpecV2, ContractConstructorSpecV3, ContractContractSpecV0, ContractContractSpecV1, ContractContractSpecV2, ContractContractSpecV3, ContractContractSpecV4, ContractCryptoHasher, ContractDiscriminant, ContractDisplayName, ContractEventParamSpecLatest, ContractEventParamSpecV0, ContractEventParamSpecV2, ContractEventSpecLatest, ContractEventSpecV0, ContractEventSpecV1, ContractEventSpecV2, ContractLayoutArray, ContractLayoutCell, ContractLayoutEnum, ContractLayoutHash, ContractLayoutHashingStrategy, ContractLayoutKey, ContractLayoutStruct, ContractLayoutStructField, ContractMessageParamSpecLatest, ContractMessageParamSpecV0, ContractMessageParamSpecV2, ContractMessageSpecLatest, ContractMessageSpecV0, ContractMessageSpecV1, ContractMessageSpecV2, ContractMetadata, ContractMetadataLatest, ContractMetadataV0, ContractMetadataV1, ContractMetadataV2, ContractMetadataV3, ContractMetadataV4, ContractProject, ContractProjectContract, ContractProjectInfo, ContractProjectSource, ContractProjectV0, ContractSelector, ContractStorageLayout, ContractTypeSpec } from '@polkadot/types/interfaces/contractsAbi';
import type { FundIndex, FundInfo, LastContribution, TrieIndex } from '@polkadot/types/interfaces/crowdloan';
import type { CollationInfo, CollationInfoV1, ConfigData, MessageId, OverweightIndex, PageCounter, PageIndexData } from '@polkadot/types/interfaces/cumulus';
@@ -47,7 +47,7 @@
import type { StorageKind } from '@polkadot/types/interfaces/offchain';
import type { DeferredOffenceOf, Kind, OffenceDetails, Offender, OpaqueTimeSlot, ReportIdOf, Reporter } from '@polkadot/types/interfaces/offences';
import type { AbridgedCandidateReceipt, AbridgedHostConfiguration, AbridgedHrmpChannel, AssignmentId, AssignmentKind, AttestedCandidate, AuctionIndex, AuthorityDiscoveryId, AvailabilityBitfield, AvailabilityBitfieldRecord, BackedCandidate, Bidder, BufferedSessionChange, CandidateCommitments, CandidateDescriptor, CandidateEvent, CandidateHash, CandidateInfo, CandidatePendingAvailability, CandidateReceipt, CollatorId, CollatorSignature, CommittedCandidateReceipt, CoreAssignment, CoreIndex, CoreOccupied, CoreState, DisputeLocation, DisputeResult, DisputeState, DisputeStatement, DisputeStatementSet, DoubleVoteReport, DownwardMessage, ExplicitDisputeStatement, GlobalValidationData, GlobalValidationSchedule, GroupIndex, GroupRotationInfo, HeadData, HostConfiguration, HrmpChannel, HrmpChannelId, HrmpOpenChannelRequest, InboundDownwardMessage, InboundHrmpMessage, InboundHrmpMessages, IncomingParachain, IncomingParachainDeploy, IncomingParachainFixed, InvalidDisputeStatementKind, LeasePeriod, LeasePeriodOf, LocalValidationData, MessageIngestionType, MessageQueueChain, MessagingStateSnapshot, MessagingStateSnapshotEgressEntry, MultiDisputeStatementSet, NewBidder, OccupiedCore, OccupiedCoreAssumption, OldV1SessionInfo, OutboundHrmpMessage, ParaGenesisArgs, ParaId, ParaInfo, ParaLifecycle, ParaPastCodeMeta, ParaScheduling, ParaValidatorIndex, ParachainDispatchOrigin, ParachainInherentData, ParachainProposal, ParachainsInherentData, ParathreadClaim, ParathreadClaimQueue, ParathreadEntry, PersistedValidationData, PvfCheckStatement, QueuedParathread, RegisteredParachainInfo, RelayBlockNumber, RelayChainBlockNumber, RelayChainHash, RelayHash, Remark, ReplacementTimes, Retriable, ScheduledCore, Scheduling, ScrapedOnChainVotes, ServiceQuality, SessionInfo, SessionInfoValidatorGroup, SignedAvailabilityBitfield, SignedAvailabilityBitfields, SigningContext, SlotRange, SlotRange10, Statement, SubId, SystemInherentData, TransientValidationData, UpgradeGoAhead, UpgradeRestriction, UpwardMessage, ValidDisputeStatementKind, ValidationCode, ValidationCodeHash, ValidationData, ValidationDataType, ValidationFunctionParams, ValidatorSignature, ValidityAttestation, VecInboundHrmpMessage, WinnersData, WinnersData10, WinnersDataTuple, WinnersDataTuple10, WinningData, WinningData10, WinningDataEntry } from '@polkadot/types/interfaces/parachains';
-import type { FeeDetails, InclusionFee, RuntimeDispatchInfo, RuntimeDispatchInfoV1, RuntimeDispatchInfoV2 } from '@polkadot/types/interfaces/payment';
+import type { FeeDetails, InclusionFee, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { Approvals } from '@polkadot/types/interfaces/poll';
import type { ProxyAnnouncement, ProxyDefinition, ProxyType } from '@polkadot/types/interfaces/proxy';
import type { AccountStatus, AccountValidity } from '@polkadot/types/interfaces/purchase';
@@ -273,12 +273,10 @@
ContractExecResultTo255: ContractExecResultTo255;
ContractExecResultTo260: ContractExecResultTo260;
ContractExecResultTo267: ContractExecResultTo267;
- ContractExecResultU64: ContractExecResultU64;
ContractInfo: ContractInfo;
ContractInstantiateResult: ContractInstantiateResult;
ContractInstantiateResultTo267: ContractInstantiateResultTo267;
ContractInstantiateResultTo299: ContractInstantiateResultTo299;
- ContractInstantiateResultU64: ContractInstantiateResultU64;
ContractLayoutArray: ContractLayoutArray;
ContractLayoutCell: ContractLayoutCell;
ContractLayoutEnum: ContractLayoutEnum;
@@ -1059,8 +1057,6 @@
RpcMethods: RpcMethods;
RuntimeDbWeight: RuntimeDbWeight;
RuntimeDispatchInfo: RuntimeDispatchInfo;
- RuntimeDispatchInfoV1: RuntimeDispatchInfoV1;
- RuntimeDispatchInfoV2: RuntimeDispatchInfoV2;
RuntimeVersion: RuntimeVersion;
RuntimeVersionApi: RuntimeVersionApi;
RuntimeVersionPartial: RuntimeVersionPartial;
tests/src/nesting/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/collectionProperties.test.ts
+++ b/tests/src/nesting/collectionProperties.test.ts
@@ -15,8 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {itSub, Pallets, usingPlaygrounds, expect} from '../util';
-import {UniqueBaseCollection} from '../util/playgrounds/unique';
+import {itSub, Pallets, usingPlaygrounds, expect, requirePalletsOrSkip} from '../util';
describe('Integration Test: Collection Properties', () => {
let alice: IKeyringPair;
@@ -32,116 +31,98 @@
itSub('Properties are initially empty', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice);
expect(await collection.getProperties()).to.be.empty;
- });
-
- async function testSetsPropertiesForCollection(collection: UniqueBaseCollection) {
- // As owner
- await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;
-
- await collection.addAdmin(alice, {Substrate: bob.address});
-
- // As administrator
- await expect(collection.setProperties(bob, [{key: 'black_hole'}])).to.be.fulfilled;
-
- const properties = await collection.getProperties();
- expect(properties).to.include.deep.members([
- {key: 'electron', value: 'come bond'},
- {key: 'black_hole', value: ''},
- ]);
- }
-
- itSub('Sets properties for a NFT collection', async ({helper}) => {
- await testSetsPropertiesForCollection(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Sets properties for a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
- await testSetsPropertiesForCollection(await helper.rft.mintCollection(alice));
});
-
- async function testCheckValidNames(collection: UniqueBaseCollection) {
- // alpha symbols
- await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;
-
- // numeric symbols
- await expect(collection.setProperties(alice, [{key: '451'}])).to.be.fulfilled;
-
- // underscore symbol
- await expect(collection.setProperties(alice, [{key: 'black_hole'}])).to.be.fulfilled;
-
- // dash symbol
- await expect(collection.setProperties(alice, [{key: '-'}])).to.be.fulfilled;
-
- // dot symbol
- await expect(collection.setProperties(alice, [{key: 'once.in.a.long.long.while...', value: 'you get a little lost'}])).to.be.fulfilled;
-
- const properties = await collection.getProperties();
- expect(properties).to.include.deep.members([
- {key: 'answer', value: ''},
- {key: '451', value: ''},
- {key: 'black_hole', value: ''},
- {key: '-', value: ''},
- {key: 'once.in.a.long.long.while...', value: 'you get a little lost'},
- ]);
- }
-
- itSub('Check valid names for NFT collection properties keys', async ({helper}) => {
- await testCheckValidNames(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Check valid names for ReFungible collection properties keys', [Pallets.ReFungible], async ({helper}) => {
- await testCheckValidNames(await helper.rft.mintCollection(alice));
- });
-
- async function testChangesProperties(collection: UniqueBaseCollection) {
- await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;
-
- // Mutate the properties
- await expect(collection.setProperties(alice, [{key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
-
- const properties = await collection.getProperties();
- expect(properties).to.include.deep.members([
- {key: 'electron', value: 'come bond'},
- {key: 'black_hole', value: 'LIGO'},
- ]);
- }
-
- itSub('Changes properties of a NFT collection', async ({helper}) => {
- await testChangesProperties(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Changes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
- await testChangesProperties(await helper.rft.mintCollection(alice));
- });
-
- async function testDeleteProperties(collection: UniqueBaseCollection) {
- await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
-
- await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;
-
- const properties = await collection.getProperties(['black_hole', 'electron']);
- expect(properties).to.be.deep.equal([
- {key: 'black_hole', value: 'LIGO'},
- ]);
- }
-
- itSub('Deletes properties of a NFT collection', async ({helper}) => {
- await testDeleteProperties(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Deletes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
- await testDeleteProperties(await helper.rft.mintCollection(alice));
- });
[
- // TODO enable properties for FT collection in Substrate (release 040)
- // {mode: 'ft' as const, requiredPallets: []},
{mode: 'nft' as const, requiredPallets: []},
+ {mode: 'ft' as const, requiredPallets: []},
{mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
- ].map(testCase =>
- itSub.ifWithPallets(`Allows modifying a collection property multiple times with the same size (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ ].map(testSuite => describe(`${testSuite.mode.toUpperCase()}`, () => {
+ before(async function() {
+ // eslint-disable-next-line require-await
+ await usingPlaygrounds(async helper => {
+ requirePalletsOrSkip(this, helper, testSuite.requiredPallets);
+ });
+ });
+
+ itSub('Sets properties for a collection', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ // As owner
+ await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;
+
+ await collection.addAdmin(alice, {Substrate: bob.address});
+
+ // As administrator
+ await expect(collection.setProperties(bob, [{key: 'black_hole'}])).to.be.fulfilled;
+
+ const properties = await collection.getProperties();
+ expect(properties).to.include.deep.members([
+ {key: 'electron', value: 'come bond'},
+ {key: 'black_hole', value: ''},
+ ]);
+ });
+
+ itSub('Check valid names for collection properties keys', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ // alpha symbols
+ await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;
+
+ // numeric symbols
+ await expect(collection.setProperties(alice, [{key: '451'}])).to.be.fulfilled;
+
+ // underscore symbol
+ await expect(collection.setProperties(alice, [{key: 'black_hole'}])).to.be.fulfilled;
+
+ // dash symbol
+ await expect(collection.setProperties(alice, [{key: '-'}])).to.be.fulfilled;
+
+ // dot symbol
+ await expect(collection.setProperties(alice, [{key: 'once.in.a.long.long.while...', value: 'you get a little lost'}])).to.be.fulfilled;
+
+ const properties = await collection.getProperties();
+ expect(properties).to.include.deep.members([
+ {key: 'answer', value: ''},
+ {key: '451', value: ''},
+ {key: 'black_hole', value: ''},
+ {key: '-', value: ''},
+ {key: 'once.in.a.long.long.while...', value: 'you get a little lost'},
+ ]);
+ });
+
+ itSub('Changes properties of a collection', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;
+
+ // Mutate the properties
+ await expect(collection.setProperties(alice, [{key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
+
+ const properties = await collection.getProperties();
+ expect(properties).to.include.deep.members([
+ {key: 'electron', value: 'come bond'},
+ {key: 'black_hole', value: 'LIGO'},
+ ]);
+ });
+
+ itSub('Deletes properties of a collection', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
+
+ await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;
+
+ const properties = await collection.getProperties(['black_hole', 'electron']);
+ expect(properties).to.be.deep.equal([
+ {key: 'black_hole', value: 'LIGO'},
+ ]);
+ });
+
+ itSub('Allows modifying a collection property multiple times with the same size', async({helper}) => {
const propKey = 'tok-prop';
- const collection = await helper[testCase.mode].mintCollection(alice);
+ const collection = await helper[testSuite.mode].mintCollection(alice);
const maxCollectionPropertiesSize = 40960;
@@ -166,18 +147,12 @@
const consumedSpace = await collection.getPropertiesConsumedSpace();
expect(consumedSpace).to.be.equal(originalSpace);
}
- }));
+ });
- [
- // TODO enable properties for FT collection in Substrate (release 040)
- // {mode: 'ft' as const, requiredPallets: []},
- {mode: 'nft' as const, requiredPallets: []},
- {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
- ].map(testCase =>
- itSub.ifWithPallets(`Adding then removing a collection property doesn't change the consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ itSub('Adding then removing a collection property doesn\'t change the consumed space', async({helper}) => {
const propKey = 'tok-prop';
- const collection = await helper[testCase.mode].mintCollection(alice);
+ const collection = await helper[testSuite.mode].mintCollection(alice);
const originalSpace = await collection.getPropertiesConsumedSpace();
const propDataSize = 4096;
@@ -190,18 +165,12 @@
await collection.deleteProperties(alice, [propKey]);
consumedSpace = await collection.getPropertiesConsumedSpace();
expect(consumedSpace).to.be.equal(originalSpace);
- }));
+ });
- [
- // TODO enable properties for FT collection in Substrate (release 040)
- // {mode: 'ft' as const, requiredPallets: []},
- {mode: 'nft' as const, requiredPallets: []},
- {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
- ].map(testCase =>
- itSub.ifWithPallets(`Modifying a collection property with different sizes correctly changes the consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ itSub('Modifying a collection property with different sizes correctly changes the consumed space', async({helper}) => {
const propKey = 'tok-prop';
- const collection = await helper[testCase.mode].mintCollection(alice);
+ const collection = await helper[testSuite.mode].mintCollection(alice);
const originalSpace = await collection.getPropertiesConsumedSpace();
const initPropDataSize = 4096;
@@ -229,7 +198,8 @@
consumedSpace = await collection.getPropertiesConsumedSpace();
expectedConsumedSpaceDiff = biggerPropDataSize - smallerPropDataSize;
expect(consumedSpace).to.be.equal(biggerPropDataSize - expectedConsumedSpaceDiff);
- }));
+ });
+ }));
});
describe('Negative Integration Test: Collection Properties', () => {
@@ -242,119 +212,108 @@
[alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
});
});
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'ft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testSuite => describe(`${testSuite.mode.toUpperCase()}`, () => {
+ before(async function() {
+ // eslint-disable-next-line require-await
+ await usingPlaygrounds(async helper => {
+ requirePalletsOrSkip(this, helper, testSuite.requiredPallets);
+ });
+ });
- async function testFailsSetPropertiesIfNotOwnerOrAdmin(collection: UniqueBaseCollection) {
- await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))
- .to.be.rejectedWith(/common\.NoPermission/);
-
- expect(await collection.getProperties()).to.be.empty;
- }
-
- itSub('Fails to set properties in a NFT collection if not its onwer/administrator', async ({helper}) => {
- await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Fails to set properties in a ReFungible collection if not its onwer/administrator', [Pallets.ReFungible], async ({helper}) => {
- await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.rft.mintCollection(alice));
- });
+ itSub('Fails to set properties in a collection if not its onwer/administrator', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))
+ .to.be.rejectedWith(/common\.NoPermission/);
- async function testFailsSetPropertiesThatExeedLimits(collection: UniqueBaseCollection) {
- const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();
+ expect(await collection.getProperties()).to.be.empty;
+ });
- // Mute the general tx parsing error, too many bytes to process
- {
- console.error = () => {};
+ itSub('Fails to set properties that exceed the limits', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();
+
+ // Mute the general tx parsing error, too many bytes to process
+ {
+ console.error = () => {};
+ await expect(collection.setProperties(alice, [
+ {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))},
+ ])).to.be.rejected;
+ }
+
+ expect(await collection.getProperties(['electron'])).to.be.empty;
+
await expect(collection.setProperties(alice, [
- {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))},
- ])).to.be.rejected;
- }
-
- expect(await collection.getProperties(['electron'])).to.be.empty;
-
- await expect(collection.setProperties(alice, [
- {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))},
- {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))},
- ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);
-
- expect(await collection.getProperties(['electron', 'black_hole'])).to.be.empty;
- }
-
- itSub('Fails to set properties that exceed the limits (NFT)', async ({helper}) => {
- await testFailsSetPropertiesThatExeedLimits(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Fails to set properties that exceed the limits (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
- await testFailsSetPropertiesThatExeedLimits(await helper.rft.mintCollection(alice));
- });
+ {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))},
+ {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))},
+ ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);
- async function testFailsSetMorePropertiesThanAllowed(collection: UniqueBaseCollection) {
- const propertiesToBeSet = [];
- for (let i = 0; i < 65; i++) {
- propertiesToBeSet.push({
- key: 'electron_' + i,
- value: Math.random() > 0.5 ? 'high' : 'low',
- });
- }
-
- await expect(collection.setProperties(alice, propertiesToBeSet)).
- to.be.rejectedWith(/common\.PropertyLimitReached/);
-
- expect(await collection.getProperties()).to.be.empty;
- }
-
- itSub('Fails to set more properties than it is allowed (NFT)', async ({helper}) => {
- await testFailsSetMorePropertiesThanAllowed(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Fails to set more properties than it is allowed (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
- await testFailsSetMorePropertiesThanAllowed(await helper.rft.mintCollection(alice));
- });
+ expect(await collection.getProperties(['electron', 'black_hole'])).to.be.empty;
+ });
+
+ itSub('Fails to set more properties than it is allowed', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ const propertiesToBeSet = [];
+ for (let i = 0; i < 65; i++) {
+ propertiesToBeSet.push({
+ key: 'electron_' + i,
+ value: Math.random() > 0.5 ? 'high' : 'low',
+ });
+ }
+
+ await expect(collection.setProperties(alice, propertiesToBeSet)).
+ to.be.rejectedWith(/common\.PropertyLimitReached/);
+
+ expect(await collection.getProperties()).to.be.empty;
+ });
+
+ itSub('Fails to set properties with invalid names', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ const invalidProperties = [
+ [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],
+ [{key: 'Mr/Sandman', value: 'Bring me a gene'}],
+ [{key: 'déjà vu', value: 'hmm...'}],
+ ];
- async function testFailsSetPropertiesWithInvalidNames(collection: UniqueBaseCollection) {
- const invalidProperties = [
- [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],
- [{key: 'Mr/Sandman', value: 'Bring me a gene'}],
- [{key: 'déjà vu', value: 'hmm...'}],
- ];
-
- for (let i = 0; i < invalidProperties.length; i++) {
+ for (let i = 0; i < invalidProperties.length; i++) {
+ await expect(
+ collection.setProperties(alice, invalidProperties[i]),
+ `on rejecting the new badly-named property #${i}`,
+ ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
+ }
+
await expect(
- collection.setProperties(alice, invalidProperties[i]),
- `on rejecting the new badly-named property #${i}`,
- ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
- }
-
- await expect(
- collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]),
- 'on rejecting an unnamed property',
- ).to.be.rejectedWith(/common\.EmptyPropertyKey/);
-
- await expect(
- collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]),
- 'on setting the correctly-but-still-badly-named property',
- ).to.be.fulfilled;
-
- const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');
-
- const properties = await collection.getProperties(keys);
- expect(properties).to.be.deep.equal([
- {key: 'CRISPR-Cas9', value: 'rewriting nature!'},
- ]);
-
- for (let i = 0; i < invalidProperties.length; i++) {
+ collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]),
+ 'on rejecting an unnamed property',
+ ).to.be.rejectedWith(/common\.EmptyPropertyKey/);
+
await expect(
- collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)),
- `on trying to delete the non-existent badly-named property #${i}`,
- ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
- }
- }
-
- itSub('Fails to set properties with invalid names (NFT)', async ({helper}) => {
- await testFailsSetPropertiesWithInvalidNames(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Fails to set properties with invalid names (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
- await testFailsSetPropertiesWithInvalidNames(await helper.rft.mintCollection(alice));
- });
+ collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]),
+ 'on setting the correctly-but-still-badly-named property',
+ ).to.be.fulfilled;
+
+ const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');
+
+ const properties = await collection.getProperties(keys);
+ expect(properties).to.be.deep.equal([
+ {key: 'CRISPR-Cas9', value: 'rewriting nature!'},
+ ]);
+
+ for (let i = 0; i < invalidProperties.length; i++) {
+ await expect(
+ collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)),
+ `on trying to delete the non-existent badly-named property #${i}`,
+ ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
+ }
+ });
+ }));
});
\ No newline at end of file
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -80,6 +80,7 @@
requiredPallets.push(
refungible,
appPromotion,
+ foreignAssets,
);
} else if (chain.eq('UNIQUE')) {
// Insert Unique additional pallets here