difftreelog
fix dependency versions after rebase
in: master
12 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2484,7 +2484,7 @@
[[package]]
name = "fc-consensus"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18#7c8ce8f83e0c8a5b57655622b721f8655b161903"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
dependencies = [
"async-trait",
"derive_more",
@@ -2511,7 +2511,7 @@
[[package]]
name = "fc-db"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18#7c8ce8f83e0c8a5b57655622b721f8655b161903"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
dependencies = [
"fp-storage",
"kvdb",
@@ -2527,7 +2527,7 @@
[[package]]
name = "fc-mapping-sync"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18#7c8ce8f83e0c8a5b57655622b721f8655b161903"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
dependencies = [
"fc-consensus",
"fc-db",
@@ -2545,7 +2545,7 @@
[[package]]
name = "fc-rpc"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18#7c8ce8f83e0c8a5b57655622b721f8655b161903"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
dependencies = [
"ethereum",
"ethereum-types",
@@ -2591,7 +2591,7 @@
[[package]]
name = "fc-rpc-core"
version = "1.1.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18#7c8ce8f83e0c8a5b57655622b721f8655b161903"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
dependencies = [
"ethereum",
"ethereum-types",
@@ -2725,7 +2725,7 @@
[[package]]
name = "fp-consensus"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18#7c8ce8f83e0c8a5b57655622b721f8655b161903"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
dependencies = [
"ethereum",
"parity-scale-codec",
@@ -2739,7 +2739,7 @@
[[package]]
name = "fp-evm"
version = "3.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18#7c8ce8f83e0c8a5b57655622b721f8655b161903"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
dependencies = [
"evm",
"impl-trait-for-tuples",
@@ -2751,9 +2751,18 @@
]
[[package]]
+name = "fp-evm-mapping"
+version = "0.1.0"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
+dependencies = [
+ "frame-support",
+ "sp-core",
+]
+
+[[package]]
name = "fp-rpc"
version = "3.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18#7c8ce8f83e0c8a5b57655622b721f8655b161903"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
dependencies = [
"ethereum",
"ethereum-types",
@@ -2770,7 +2779,7 @@
[[package]]
name = "fp-self-contained"
version = "1.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18#7c8ce8f83e0c8a5b57655622b721f8655b161903"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
dependencies = [
"ethereum",
"frame-support",
@@ -2787,7 +2796,7 @@
[[package]]
name = "fp-storage"
version = "2.0.0"
-source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18#7c8ce8f83e0c8a5b57655622b721f8655b161903"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
[[package]]
name = "frame-benchmarking"
@@ -5577,6 +5586,7 @@
"cumulus-primitives-timestamp",
"cumulus-primitives-utility",
"derivative",
+ "fp-evm-mapping",
"fp-rpc",
"fp-self-contained",
"frame-benchmarking",
@@ -5636,7 +5646,6 @@
"substrate-wasm-builder",
"unique-runtime-common",
"up-data-structs",
- "up-evm-mapping",
"up-rpc",
"xcm",
"xcm-builder",
@@ -5835,7 +5844,7 @@
[[package]]
name = "pallet-base-fee"
version = "1.0.0"
-source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18#7c8ce8f83e0c8a5b57655622b721f8655b161903"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
dependencies = [
"frame-support",
"frame-system",
@@ -5988,6 +5997,7 @@
version = "0.1.0"
dependencies = [
"evm-coder",
+ "fp-evm-mapping",
"frame-support",
"frame-system",
"pallet-evm",
@@ -5999,7 +6009,6 @@
"sp-runtime",
"sp-std",
"up-data-structs",
- "up-evm-mapping",
]
[[package]]
@@ -6062,13 +6071,14 @@
[[package]]
name = "pallet-ethereum"
version = "4.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18#7c8ce8f83e0c8a5b57655622b721f8655b161903"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
dependencies = [
"ethereum",
"ethereum-types",
"evm",
"fp-consensus",
"fp-evm",
+ "fp-evm-mapping",
"fp-rpc",
"fp-self-contained",
"fp-storage",
@@ -6092,12 +6102,13 @@
[[package]]
name = "pallet-evm"
version = "6.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18#7c8ce8f83e0c8a5b57655622b721f8655b161903"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.18-2#82310d1dd3189f34bd901a9ac894ad33eca5cf89"
dependencies = [
"evm",
"evm-gasometer",
"evm-runtime",
"fp-evm",
+ "fp-evm-mapping",
"frame-benchmarking",
"frame-support",
"frame-system",
@@ -6141,6 +6152,7 @@
version = "0.1.0"
dependencies = [
"evm-coder",
+ "fp-evm-mapping",
"frame-support",
"frame-system",
"log",
@@ -6176,6 +6188,7 @@
version = "0.1.0"
dependencies = [
"fp-evm",
+ "fp-evm-mapping",
"frame-support",
"frame-system",
"pallet-ethereum",
@@ -6186,7 +6199,6 @@
"sp-io",
"sp-runtime",
"sp-std",
- "up-evm-mapping",
"up-sponsorship",
]
@@ -6200,6 +6212,7 @@
"frame-support",
"frame-system",
"pallet-common",
+ "pallet-evm",
"pallet-evm-coder-substrate",
"pallet-structure",
"parity-scale-codec",
@@ -6427,6 +6440,7 @@
"frame-support",
"frame-system",
"pallet-common",
+ "pallet-evm",
"pallet-evm-coder-substrate",
"pallet-structure",
"parity-scale-codec",
@@ -6544,6 +6558,7 @@
"frame-support",
"frame-system",
"pallet-common",
+ "pallet-evm",
"pallet-structure",
"parity-scale-codec",
"scale-info",
@@ -6817,6 +6832,7 @@
"ethereum",
"evm-coder",
"fp-evm",
+ "fp-evm-mapping",
"frame-benchmarking",
"frame-support",
"frame-system",
@@ -6843,7 +6859,6 @@
"sp-runtime",
"sp-std",
"up-data-structs",
- "up-evm-mapping",
"up-sponsorship",
]
@@ -8726,6 +8741,7 @@
"cumulus-primitives-timestamp",
"cumulus-primitives-utility",
"derivative",
+ "fp-evm-mapping",
"fp-rpc",
"fp-self-contained",
"frame-executive",
@@ -8782,7 +8798,6 @@
"substrate-wasm-builder",
"unique-runtime-common",
"up-data-structs",
- "up-evm-mapping",
"up-rpc",
"xcm",
"xcm-builder",
@@ -12380,6 +12395,7 @@
"jsonrpc-core-client",
"jsonrpc-derive",
"pallet-common",
+ "pallet-evm",
"parity-scale-codec",
"sp-api",
"sp-blockchain",
@@ -12591,6 +12607,7 @@
"cumulus-primitives-timestamp",
"cumulus-primitives-utility",
"derivative",
+ "fp-evm-mapping",
"fp-rpc",
"fp-self-contained",
"frame-benchmarking",
@@ -12650,7 +12667,6 @@
"substrate-wasm-builder",
"unique-runtime-common",
"up-data-structs",
- "up-evm-mapping",
"up-rpc",
"xcm",
"xcm-builder",
@@ -12732,6 +12748,7 @@
"derivative",
"frame-support",
"frame-system",
+ "pallet-evm",
"parity-scale-codec",
"scale-info",
"serde",
@@ -12739,17 +12756,6 @@
"sp-runtime",
"sp-std",
"struct-versioning",
- "up-evm-mapping",
-]
-
-[[package]]
-name = "up-evm-mapping"
-version = "0.1.0"
-dependencies = [
- "frame-support",
- "parity-scale-codec",
- "scale-info",
- "sp-core",
]
[[package]]
@@ -12757,6 +12763,7 @@
version = "0.1.0"
dependencies = [
"pallet-common",
+ "pallet-evm",
"parity-scale-codec",
"sp-api",
"sp-core",
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -19,7 +19,7 @@
use codec::Decode;
use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
use jsonrpc_derive::rpc;
-use up_data_structs::{RpcCollection, Collection, CollectionId, CollectionStats, CollectionLimits, TokenId};
+use up_data_structs::{RpcCollection, CollectionId, CollectionStats, CollectionLimits, TokenId};
use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};
use sp_blockchain::HeaderBackend;
use up_rpc::UniqueApi as UniqueRuntimeApi;
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#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::{Deref, DerefMut};20use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};21use sp_std::vec::Vec;22use pallet_evm::account::CrossAccountId;23use frame_support::{24 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},25 ensure, fail,26 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},27 BoundedVec,28 weights::Pays,29};30use pallet_evm::GasWeightMapping;31use up_data_structs::{32 COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,33 COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId, CollectionStats, MAX_TOKEN_OWNERSHIP,34 CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,35 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,36 CustomDataLimit, CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField, PhantomType,37};38pub use pallet::*;39use sp_core::H160;40use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod dispatch;44pub mod erc;45pub mod eth;4647#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]48pub struct CollectionHandle<T: Config> {49 pub id: CollectionId,50 collection: Collection<T::AccountId>,51 pub recorder: SubstrateRecorder<T>,52}53impl<T: Config> WithRecorder<T> for CollectionHandle<T> {54 fn recorder(&self) -> &SubstrateRecorder<T> {55 &self.recorder56 }57 fn into_recorder(self) -> SubstrateRecorder<T> {58 self.recorder59 }60}61impl<T: Config> CollectionHandle<T> {62 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {63 <CollectionById<T>>::get(id).map(|collection| Self {64 id,65 collection,66 recorder: SubstrateRecorder::new(eth::collection_id_to_address(id), gas_limit),67 })68 }69 pub fn new(id: CollectionId) -> Option<Self> {70 Self::new_with_gas_limit(id, u64::MAX)71 }72 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {73 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)74 }75 pub fn log_mirrored(&self, log: impl evm_coder::ToLog) {76 self.recorder.log_mirrored(log)77 }78 pub fn log_direct(&self, log: impl evm_coder::ToLog) {79 self.recorder.log_direct(log)80 }81 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {82 self.recorder83 .consume_gas(T::GasWeightMapping::weight_to_gas(84 <T as frame_system::Config>::DbWeight::get()85 .read86 .saturating_mul(reads),87 ))88 }89 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {90 self.recorder91 .consume_gas(T::GasWeightMapping::weight_to_gas(92 <T as frame_system::Config>::DbWeight::get()93 .write94 .saturating_mul(writes),95 ))96 }97 pub fn submit_logs(self) {98 self.recorder.submit_logs()99 }100 pub fn save(self) -> DispatchResult {101 self.recorder.submit_logs();102 <CollectionById<T>>::insert(self.id, self.collection);103 Ok(())104 }105}106impl<T: Config> Deref for CollectionHandle<T> {107 type Target = Collection<T::AccountId>;108109 fn deref(&self) -> &Self::Target {110 &self.collection111 }112}113114impl<T: Config> DerefMut for CollectionHandle<T> {115 fn deref_mut(&mut self) -> &mut Self::Target {116 &mut self.collection117 }118}119120impl<T: Config> CollectionHandle<T> {121 pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {122 ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);123 Ok(())124 }125 pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {126 *subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))127 }128 pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {129 ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);130 Ok(())131 }132 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {133 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)134 }135 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {136 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)137 }138 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {139 ensure!(140 <Allowlist<T>>::get((self.id, user)),141 <Error<T>>::AddressNotInAllowlist142 );143 Ok(())144 }145146 pub fn check_can_update_meta(147 &self,148 subject: &T::CrossAccountId,149 item_owner: &T::CrossAccountId,150 ) -> DispatchResult {151 match self.meta_update_permission {152 MetaUpdatePermission::ItemOwner => {153 ensure!(subject == item_owner, <Error<T>>::NoPermission);154 Ok(())155 }156 MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),157 MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),158 }159 }160}161162#[frame_support::pallet]163pub mod pallet {164 use super::*;165 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};166 use pallet_evm::account;167 use dispatch::CollectionDispatch;168 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};169 use frame_system::pallet_prelude::*;170 use frame_support::traits::Currency;171 use up_data_structs::{TokenId, mapping::TokenAddressMapping};172 use scale_info::TypeInfo;173 use up_evm_mapping::CrossAccountId;174175 #[pallet::config]176 pub trait Config:177 frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo + account::Config178 {179 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;180181 type Currency: Currency<Self::AccountId>;182183 #[pallet::constant]184 type CollectionCreationPrice: Get<185 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,186 >;187 type CollectionDispatch: CollectionDispatch<Self>;188189 type TreasuryAccountId: Get<Self::AccountId>;190191 type EvmTokenAddressMapping: TokenAddressMapping<H160>;192 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;193 }194195 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);196197 #[pallet::pallet]198 #[pallet::storage_version(STORAGE_VERSION)]199 #[pallet::generate_store(pub(super) trait Store)]200 pub struct Pallet<T>(_);201202 #[pallet::extra_constants]203 impl<T: Config> Pallet<T> {204 pub fn collection_admins_limit() -> u32 {205 COLLECTION_ADMINS_LIMIT206 }207 }208209 #[pallet::event]210 #[pallet::generate_deposit(pub fn deposit_event)]211 pub enum Event<T: Config> {212 /// New collection was created213 ///214 /// # Arguments215 ///216 /// * collection_id: Globally unique identifier of newly created collection.217 ///218 /// * mode: [CollectionMode] converted into u8.219 ///220 /// * account_id: Collection owner.221 CollectionCreated(CollectionId, u8, T::AccountId),222223 /// New collection was destroyed224 ///225 /// # Arguments226 ///227 /// * collection_id: Globally unique identifier of collection.228 CollectionDestroyed(CollectionId),229230 /// New item was created.231 ///232 /// # Arguments233 ///234 /// * collection_id: Id of the collection where item was created.235 ///236 /// * item_id: Id of an item. Unique within the collection.237 ///238 /// * recipient: Owner of newly created item239 ///240 /// * amount: Always 1 for NFT241 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),242243 /// Collection item was burned.244 ///245 /// # Arguments246 ///247 /// * collection_id.248 ///249 /// * item_id: Identifier of burned NFT.250 ///251 /// * owner: which user has destroyed its tokens252 ///253 /// * amount: Always 1 for NFT254 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),255256 /// Item was transferred257 ///258 /// * collection_id: Id of collection to which item is belong259 ///260 /// * item_id: Id of an item261 ///262 /// * sender: Original owner of item263 ///264 /// * recipient: New owner of item265 ///266 /// * amount: Always 1 for NFT267 Transfer(268 CollectionId,269 TokenId,270 T::CrossAccountId,271 T::CrossAccountId,272 u128,273 ),274275 /// * collection_id276 ///277 /// * item_id278 ///279 /// * sender280 ///281 /// * spender282 ///283 /// * amount284 Approved(285 CollectionId,286 TokenId,287 T::CrossAccountId,288 T::CrossAccountId,289 u128,290 ),291 }292293 #[pallet::error]294 pub enum Error<T> {295 /// This collection does not exist.296 CollectionNotFound,297 /// Sender parameter and item owner must be equal.298 MustBeTokenOwner,299 /// No permission to perform action300 NoPermission,301 /// Collection is not in mint mode.302 PublicMintingNotAllowed,303 /// Address is not in allow list.304 AddressNotInAllowlist,305306 /// Collection name can not be longer than 63 char.307 CollectionNameLimitExceeded,308 /// Collection description can not be longer than 255 char.309 CollectionDescriptionLimitExceeded,310 /// Token prefix can not be longer than 15 char.311 CollectionTokenPrefixLimitExceeded,312 /// Total collections bound exceeded.313 TotalCollectionsLimitExceeded,314 /// variable_data exceeded data limit.315 TokenVariableDataLimitExceeded,316 /// Exceeded max admin count317 CollectionAdminCountExceeded,318 /// Collection limit bounds per collection exceeded319 CollectionLimitBoundsExceeded,320 /// Tried to enable permissions which are only permitted to be disabled321 OwnerPermissionsCantBeReverted,322323 /// Collection settings not allowing items transferring324 TransferNotAllowed,325 /// Account token limit exceeded per collection326 AccountTokenLimitExceeded,327 /// Collection token limit exceeded328 CollectionTokenLimitExceeded,329 /// Metadata flag frozen330 MetadataFlagFrozen,331332 /// Item not exists.333 TokenNotFound,334 /// Item balance not enough.335 TokenValueTooLow,336 /// Requested value more than approved.337 ApprovedValueTooLow,338 /// Tried to approve more than owned339 CantApproveMoreThanOwned,340341 /// Can't transfer tokens to ethereum zero address342 AddressIsZero,343 /// Target collection doesn't supports this operation344 UnsupportedOperation,345346 /// Not sufficient founds to perform action347 NotSufficientFounds,348349 /// Collection has nesting disabled350 NestingIsDisabled,351 /// Only owner may nest tokens under this collection352 OnlyOwnerAllowedToNest,353 /// Only tokens from specific collections may nest tokens under this354 SourceCollectionIsNotAllowedToNest,355356 /// Tried to store more data than allowed in collection field357 CollectionFieldSizeExceeded,358 }359360 #[pallet::storage]361 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;362 #[pallet::storage]363 pub type DestroyedCollectionCount<T> =364 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;365366 /// Collection info367 #[pallet::storage]368 pub type CollectionById<T> = StorageMap<369 Hasher = Blake2_128Concat,370 Key = CollectionId,371 Value = Collection<<T as frame_system::Config>::AccountId>,372 QueryKind = OptionQuery,373 >;374375 /// Large variable-size collection fields are extracted here376 #[pallet::storage]377 pub type CollectionData<T> = StorageNMap<378 Key = (379 Key<Twox64Concat, CollectionId>,380 Key<Twox64Concat, CollectionField>,381 ),382 Value = BoundedVec<u8, ConstU32<COLLECTION_FIELD_LIMIT>>,383 QueryKind = ValueQuery,384 >;385386 #[pallet::storage]387 pub type AdminAmount<T> = StorageMap<388 Hasher = Blake2_128Concat,389 Key = CollectionId,390 Value = u32,391 QueryKind = ValueQuery,392 >;393394 /// List of collection admins395 #[pallet::storage]396 pub type IsAdmin<T: Config> = StorageNMap<397 Key = (398 Key<Blake2_128Concat, CollectionId>,399 Key<Blake2_128Concat, T::CrossAccountId>,400 ),401 Value = bool,402 QueryKind = ValueQuery,403 >;404405 /// Allowlisted collection users406 #[pallet::storage]407 pub type Allowlist<T: Config> = StorageNMap<408 Key = (409 Key<Blake2_128Concat, CollectionId>,410 Key<Blake2_128Concat, T::CrossAccountId>,411 ),412 Value = bool,413 QueryKind = ValueQuery,414 >;415416 /// Not used by code, exists only to provide some types to metadata417 #[pallet::storage]418 pub type DummyStorageValue<T: Config> = StorageValue<419 Value = (420 CollectionStats,421 CollectionId,422 TokenId,423 PhantomType<RpcCollection<T::AccountId>>,424 ),425 QueryKind = OptionQuery,426 >;427428 #[pallet::hooks]429 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {430 fn on_runtime_upgrade() -> Weight {431 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {432 use up_data_structs::{CollectionVersion1, CollectionVersion2};433 <CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {434 Self::set_field_raw(435 id,436 CollectionField::OffchainSchema,437 v.offchain_schema.clone().into_inner(),438 )439 .expect("data has lower bounds than field");440 Self::set_field_raw(441 id,442 CollectionField::VariableOnChainSchema,443 v.variable_on_chain_schema.clone().into_inner(),444 )445 .expect("data has lower bounds than field");446 Self::set_field_raw(447 id,448 CollectionField::ConstOnChainSchema,449 v.const_on_chain_schema.clone().into_inner(),450 )451 .expect("data has lower bounds than field");452453 Some(CollectionVersion2::from(v))454 });455 }456457 0458 }459 }460}461462impl<T: Config> Pallet<T> {463 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens464 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {465 ensure!(466 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,467 <Error<T>>::AddressIsZero468 );469 Ok(())470 }471 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {472 <IsAdmin<T>>::iter_prefix((collection,))473 .map(|(a, _)| a)474 .collect()475 }476 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {477 <Allowlist<T>>::iter_prefix((collection,))478 .map(|(a, _)| a)479 .collect()480 }481 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {482 <Allowlist<T>>::get((collection, user))483 }484 pub fn collection_stats() -> CollectionStats {485 let created = <CreatedCollectionCount<T>>::get();486 let destroyed = <DestroyedCollectionCount<T>>::get();487 CollectionStats {488 created: created.0,489 destroyed: destroyed.0,490 alive: created.0 - destroyed.0,491 }492 }493494 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {495 let collection = <CollectionById<T>>::get(collection);496 if collection.is_none() {497 return None;498 }499500 let collection = collection.unwrap();501 let limits = collection.limits;502 let effective_limits = CollectionLimits {503 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),504 sponsored_data_size: Some(limits.sponsored_data_size()),505 sponsored_data_rate_limit: Some(506 limits507 .sponsored_data_rate_limit508 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),509 ),510 token_limit: Some(limits.token_limit()),511 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(512 match collection.mode {513 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,514 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,515 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,516 },517 )),518 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),519 owner_can_transfer: Some(limits.owner_can_transfer()),520 owner_can_destroy: Some(limits.owner_can_destroy()),521 transfers_enabled: Some(limits.transfers_enabled()),522 };523524 Some(effective_limits)525 }526527 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {528 let Collection {529 name,530 description,531 owner,532 mode,533 access,534 token_prefix,535 mint_mode,536 schema_version,537 sponsorship,538 limits,539 meta_update_permission,540 } = <CollectionById<T>>::get(collection)?;541 Some(RpcCollection {542 name: name.into_inner(),543 description: description.into_inner(),544 owner,545 mode,546 access,547 token_prefix: token_prefix.into_inner(),548 mint_mode,549 schema_version,550 sponsorship,551 limits,552 meta_update_permission,553 offchain_schema: <CollectionData<T>>::get((554 collection,555 CollectionField::OffchainSchema,556 ))557 .into_inner(),558 const_on_chain_schema: <CollectionData<T>>::get((559 collection,560 CollectionField::ConstOnChainSchema,561 ))562 .into_inner(),563 variable_on_chain_schema: <CollectionData<T>>::get((564 collection,565 CollectionField::VariableOnChainSchema,566 ))567 .into_inner(),568 })569 }570}571572impl<T: Config> Pallet<T> {573 pub fn init_collection(574 owner: T::AccountId,575 data: CreateCollectionData<T::AccountId>,576 ) -> Result<CollectionId, DispatchError> {577 {578 ensure!(579 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,580 Error::<T>::CollectionTokenPrefixLimitExceeded581 );582 }583584 let created_count = <CreatedCollectionCount<T>>::get()585 .0586 .checked_add(1)587 .ok_or(ArithmeticError::Overflow)?;588 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;589 let id = CollectionId(created_count);590591 // bound Total number of collections592 ensure!(593 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,594 <Error<T>>::TotalCollectionsLimitExceeded595 );596597 // =========598599 let collection = Collection {600 owner: owner.clone(),601 name: data.name,602 mode: data.mode.clone(),603 mint_mode: false,604 access: data.access.unwrap_or_default(),605 description: data.description,606 token_prefix: data.token_prefix,607 schema_version: data.schema_version.unwrap_or_default(),608 sponsorship: data609 .pending_sponsor610 .map(SponsorshipState::Unconfirmed)611 .unwrap_or_default(),612 limits: data613 .limits614 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))615 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,616 meta_update_permission: data.meta_update_permission.unwrap_or_default(),617 };618619 // Take a (non-refundable) deposit of collection creation620 {621 let mut imbalance =622 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();623 imbalance.subsume(624 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(625 &T::TreasuryAccountId::get(),626 T::CollectionCreationPrice::get(),627 ),628 );629 <T as Config>::Currency::settle(630 &owner,631 imbalance,632 WithdrawReasons::TRANSFER,633 ExistenceRequirement::KeepAlive,634 )635 .map_err(|_| Error::<T>::NotSufficientFounds)?;636 }637638 <CreatedCollectionCount<T>>::put(created_count);639 <Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));640 <CollectionById<T>>::insert(id, collection);641 Self::set_field_raw(642 id,643 CollectionField::OffchainSchema,644 data.offchain_schema.into_inner(),645 )646 .expect("data has lower bounds than field");647 Self::set_field_raw(648 id,649 CollectionField::VariableOnChainSchema,650 data.variable_on_chain_schema.into_inner(),651 )652 .expect("data has lower bounds than field");653 Self::set_field_raw(654 id,655 CollectionField::ConstOnChainSchema,656 data.const_on_chain_schema.into_inner(),657 )658 .expect("data has lower bounds than field");659 Ok(id)660 }661662 pub fn destroy_collection(663 collection: CollectionHandle<T>,664 sender: &T::CrossAccountId,665 ) -> DispatchResult {666 ensure!(667 collection.limits.owner_can_destroy(),668 <Error<T>>::NoPermission,669 );670 collection.check_is_owner(sender)?;671672 let destroyed_collections = <DestroyedCollectionCount<T>>::get()673 .0674 .checked_add(1)675 .ok_or(ArithmeticError::Overflow)?;676677 // =========678679 <DestroyedCollectionCount<T>>::put(destroyed_collections);680 <CollectionById<T>>::remove(collection.id);681 <CollectionData<T>>::remove_prefix((collection.id,), None);682 <AdminAmount<T>>::remove(collection.id);683 <IsAdmin<T>>::remove_prefix((collection.id,), None);684 <Allowlist<T>>::remove_prefix((collection.id,), None);685686 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));687 Ok(())688 }689690 fn set_field_raw(691 collection_id: CollectionId,692 field: CollectionField,693 value: Vec<u8>,694 ) -> DispatchResult {695 if !value.is_empty() {696 <CollectionData<T>>::insert(697 (collection_id, field),698 BoundedVec::try_from(value).map_err(|_| <Error<T>>::CollectionFieldSizeExceeded)?,699 )700 } else {701 <CollectionData<T>>::remove((collection_id, field));702 }703 Ok(())704 }705706 pub fn set_field(707 collection: &CollectionHandle<T>,708 sender: &T::CrossAccountId,709 field: CollectionField,710 value: Vec<u8>,711 ) -> DispatchResult {712 collection.check_is_owner_or_admin(sender)?;713714 // =========715716 Self::set_field_raw(collection.id, field, value)717 }718719 pub fn toggle_allowlist(720 collection: &CollectionHandle<T>,721 sender: &T::CrossAccountId,722 user: &T::CrossAccountId,723 allowed: bool,724 ) -> DispatchResult {725 collection.check_is_owner_or_admin(sender)?;726727 // =========728729 if allowed {730 <Allowlist<T>>::insert((collection.id, user), true);731 } else {732 <Allowlist<T>>::remove((collection.id, user));733 }734735 Ok(())736 }737738 pub fn toggle_admin(739 collection: &CollectionHandle<T>,740 sender: &T::CrossAccountId,741 user: &T::CrossAccountId,742 admin: bool,743 ) -> DispatchResult {744 collection.check_is_owner_or_admin(sender)?;745746 let was_admin = <IsAdmin<T>>::get((collection.id, user));747 if was_admin == admin {748 return Ok(());749 }750 let amount = <AdminAmount<T>>::get(collection.id);751752 if admin {753 let amount = amount754 .checked_add(1)755 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;756 ensure!(757 amount <= Self::collection_admins_limit(),758 <Error<T>>::CollectionAdminCountExceeded,759 );760761 // =========762763 <AdminAmount<T>>::insert(collection.id, amount);764 <IsAdmin<T>>::insert((collection.id, user), true);765 } else {766 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));767 <IsAdmin<T>>::remove((collection.id, user));768 }769770 Ok(())771 }772773 pub fn clamp_limits(774 mode: CollectionMode,775 old_limit: &CollectionLimits,776 mut new_limit: CollectionLimits,777 ) -> Result<CollectionLimits, DispatchError> {778 macro_rules! limit_default {779 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{780 $(781 if let Some($new) = $new.$field {782 let $old = $old.$field($($arg)?);783 let _ = $new;784 let _ = $old;785 $check786 } else {787 $new.$field = $old.$field788 }789 )*790 }};791 }792793 limit_default!(old_limit, new_limit,794 account_token_ownership_limit => ensure!(795 new_limit <= MAX_TOKEN_OWNERSHIP,796 <Error<T>>::CollectionLimitBoundsExceeded,797 ),798 sponsor_transfer_timeout(match mode {799 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,800 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,801 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,802 }) => ensure!(803 new_limit <= MAX_SPONSOR_TIMEOUT,804 <Error<T>>::CollectionLimitBoundsExceeded,805 ),806 sponsored_data_size => ensure!(807 new_limit <= CUSTOM_DATA_LIMIT,808 <Error<T>>::CollectionLimitBoundsExceeded,809 ),810 token_limit => ensure!(811 old_limit >= new_limit && new_limit > 0,812 <Error<T>>::CollectionTokenLimitExceeded813 ),814 owner_can_transfer => ensure!(815 old_limit || !new_limit,816 <Error<T>>::OwnerPermissionsCantBeReverted,817 ),818 owner_can_destroy => ensure!(819 old_limit || !new_limit,820 <Error<T>>::OwnerPermissionsCantBeReverted,821 ),822 sponsored_data_rate_limit => {},823 transfers_enabled => {},824 );825 Ok(new_limit)826 }827}828829#[macro_export]830macro_rules! unsupported {831 () => {832 Err(<Error<T>>::UnsupportedOperation.into())833 };834}835836/// Worst cases837pub trait CommonWeightInfo<CrossAccountId> {838 fn create_item() -> Weight;839 fn create_multiple_items(amount: u32) -> Weight;840 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;841 fn burn_item() -> Weight;842 fn transfer() -> Weight;843 fn approve() -> Weight;844 fn transfer_from() -> Weight;845 fn burn_from() -> Weight;846 fn set_variable_metadata(bytes: u32) -> Weight;847}848849pub trait CommonCollectionOperations<T: Config> {850 fn create_item(851 &self,852 sender: T::CrossAccountId,853 to: T::CrossAccountId,854 data: CreateItemData,855 nesting_budget: &dyn Budget,856 ) -> DispatchResultWithPostInfo;857 fn create_multiple_items(858 &self,859 sender: T::CrossAccountId,860 to: T::CrossAccountId,861 data: Vec<CreateItemData>,862 nesting_budget: &dyn Budget,863 ) -> DispatchResultWithPostInfo;864 fn create_multiple_items_ex(865 &self,866 sender: T::CrossAccountId,867 data: CreateItemExData<T::CrossAccountId>,868 nesting_budget: &dyn Budget,869 ) -> DispatchResultWithPostInfo;870 fn burn_item(871 &self,872 sender: T::CrossAccountId,873 token: TokenId,874 amount: u128,875 ) -> DispatchResultWithPostInfo;876877 fn transfer(878 &self,879 sender: T::CrossAccountId,880 to: T::CrossAccountId,881 token: TokenId,882 amount: u128,883 nesting_budget: &dyn Budget,884 ) -> DispatchResultWithPostInfo;885 fn approve(886 &self,887 sender: T::CrossAccountId,888 spender: T::CrossAccountId,889 token: TokenId,890 amount: u128,891 ) -> DispatchResultWithPostInfo;892 fn transfer_from(893 &self,894 sender: T::CrossAccountId,895 from: T::CrossAccountId,896 to: T::CrossAccountId,897 token: TokenId,898 amount: u128,899 nesting_budget: &dyn Budget,900 ) -> DispatchResultWithPostInfo;901 fn burn_from(902 &self,903 sender: T::CrossAccountId,904 from: T::CrossAccountId,905 token: TokenId,906 amount: u128,907 nesting_budget: &dyn Budget,908 ) -> DispatchResultWithPostInfo;909910 fn set_variable_metadata(911 &self,912 sender: T::CrossAccountId,913 token: TokenId,914 data: BoundedVec<u8, CustomDataLimit>,915 ) -> DispatchResultWithPostInfo;916917 fn check_nesting(918 &self,919 sender: T::CrossAccountId,920 from: CollectionId,921 under: TokenId,922 budget: &dyn Budget,923 ) -> DispatchResult;924925 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;926 fn token_exists(&self, token: TokenId) -> bool;927 fn last_token_id(&self) -> TokenId;928929 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;930 fn const_metadata(&self, token: TokenId) -> Vec<u8>;931 fn variable_metadata(&self, token: TokenId) -> Vec<u8>;932933 /// How many tokens collection contains (Applicable to nonfungible/refungible)934 fn collection_tokens(&self) -> u32;935 /// Amount of different tokens account has (Applicable to nonfungible/refungible)936 fn account_balance(&self, account: T::CrossAccountId) -> u32;937 /// Amount of specific token account have (Applicable to fungible/refungible)938 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;939 fn allowance(940 &self,941 sender: T::CrossAccountId,942 spender: T::CrossAccountId,943 token: TokenId,944 ) -> u128;945}946947// Flexible enough for implementing CommonCollectionOperations948pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {949 let post_info = PostDispatchInfo {950 actual_weight: Some(weight),951 pays_fee: Pays::Yes,952 };953 match res {954 Ok(()) => Ok(post_info),955 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),956 }957}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#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::{Deref, DerefMut};20use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};21use sp_std::vec::Vec;22use pallet_evm::account::CrossAccountId;23use frame_support::{24 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},25 ensure, fail,26 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},27 BoundedVec,28 weights::Pays,29};30use pallet_evm::GasWeightMapping;31use up_data_structs::{32 COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionId, CreateItemData,33 MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId,34 CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,35 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,36 CUSTOM_DATA_LIMIT, CollectionLimits, CustomDataLimit, CreateCollectionData, SponsorshipState,37 CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField,38 PhantomType,39};40pub use pallet::*;41use sp_core::H160;42use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};43#[cfg(feature = "runtime-benchmarks")]44pub mod benchmarking;45pub mod dispatch;46pub mod erc;47pub mod eth;4849#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]50pub struct CollectionHandle<T: Config> {51 pub id: CollectionId,52 collection: Collection<T::AccountId>,53 pub recorder: SubstrateRecorder<T>,54}55impl<T: Config> WithRecorder<T> for CollectionHandle<T> {56 fn recorder(&self) -> &SubstrateRecorder<T> {57 &self.recorder58 }59 fn into_recorder(self) -> SubstrateRecorder<T> {60 self.recorder61 }62}63impl<T: Config> CollectionHandle<T> {64 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {65 <CollectionById<T>>::get(id).map(|collection| Self {66 id,67 collection,68 recorder: SubstrateRecorder::new(eth::collection_id_to_address(id), gas_limit),69 })70 }71 pub fn new(id: CollectionId) -> Option<Self> {72 Self::new_with_gas_limit(id, u64::MAX)73 }74 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {75 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)76 }77 pub fn log_mirrored(&self, log: impl evm_coder::ToLog) {78 self.recorder.log_mirrored(log)79 }80 pub fn log_direct(&self, log: impl evm_coder::ToLog) {81 self.recorder.log_direct(log)82 }83 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {84 self.recorder85 .consume_gas(T::GasWeightMapping::weight_to_gas(86 <T as frame_system::Config>::DbWeight::get()87 .read88 .saturating_mul(reads),89 ))90 }91 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {92 self.recorder93 .consume_gas(T::GasWeightMapping::weight_to_gas(94 <T as frame_system::Config>::DbWeight::get()95 .write96 .saturating_mul(writes),97 ))98 }99 pub fn submit_logs(self) {100 self.recorder.submit_logs()101 }102 pub fn save(self) -> DispatchResult {103 self.recorder.submit_logs();104 <CollectionById<T>>::insert(self.id, self.collection);105 Ok(())106 }107}108impl<T: Config> Deref for CollectionHandle<T> {109 type Target = Collection<T::AccountId>;110111 fn deref(&self) -> &Self::Target {112 &self.collection113 }114}115116impl<T: Config> DerefMut for CollectionHandle<T> {117 fn deref_mut(&mut self) -> &mut Self::Target {118 &mut self.collection119 }120}121122impl<T: Config> CollectionHandle<T> {123 pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {124 ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);125 Ok(())126 }127 pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {128 *subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))129 }130 pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {131 ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);132 Ok(())133 }134 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {135 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)136 }137 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {138 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)139 }140 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {141 ensure!(142 <Allowlist<T>>::get((self.id, user)),143 <Error<T>>::AddressNotInAllowlist144 );145 Ok(())146 }147148 pub fn check_can_update_meta(149 &self,150 subject: &T::CrossAccountId,151 item_owner: &T::CrossAccountId,152 ) -> DispatchResult {153 match self.meta_update_permission {154 MetaUpdatePermission::ItemOwner => {155 ensure!(subject == item_owner, <Error<T>>::NoPermission);156 Ok(())157 }158 MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),159 MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),160 }161 }162}163164#[frame_support::pallet]165pub mod pallet {166 use super::*;167 use pallet_evm::account;168 use dispatch::CollectionDispatch;169 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};170 use frame_system::pallet_prelude::*;171 use frame_support::traits::Currency;172 use up_data_structs::{TokenId, mapping::TokenAddressMapping};173 use scale_info::TypeInfo;174175 #[pallet::config]176 pub trait Config:177 frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo + account::Config178 {179 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;180181 type Currency: Currency<Self::AccountId>;182183 #[pallet::constant]184 type CollectionCreationPrice: Get<185 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,186 >;187 type CollectionDispatch: CollectionDispatch<Self>;188189 type TreasuryAccountId: Get<Self::AccountId>;190191 type EvmTokenAddressMapping: TokenAddressMapping<H160>;192 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;193 }194195 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);196197 #[pallet::pallet]198 #[pallet::storage_version(STORAGE_VERSION)]199 #[pallet::generate_store(pub(super) trait Store)]200 pub struct Pallet<T>(_);201202 #[pallet::extra_constants]203 impl<T: Config> Pallet<T> {204 pub fn collection_admins_limit() -> u32 {205 COLLECTION_ADMINS_LIMIT206 }207 }208209 #[pallet::event]210 #[pallet::generate_deposit(pub fn deposit_event)]211 pub enum Event<T: Config> {212 /// New collection was created213 ///214 /// # Arguments215 ///216 /// * collection_id: Globally unique identifier of newly created collection.217 ///218 /// * mode: [CollectionMode] converted into u8.219 ///220 /// * account_id: Collection owner.221 CollectionCreated(CollectionId, u8, T::AccountId),222223 /// New collection was destroyed224 ///225 /// # Arguments226 ///227 /// * collection_id: Globally unique identifier of collection.228 CollectionDestroyed(CollectionId),229230 /// New item was created.231 ///232 /// # Arguments233 ///234 /// * collection_id: Id of the collection where item was created.235 ///236 /// * item_id: Id of an item. Unique within the collection.237 ///238 /// * recipient: Owner of newly created item239 ///240 /// * amount: Always 1 for NFT241 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),242243 /// Collection item was burned.244 ///245 /// # Arguments246 ///247 /// * collection_id.248 ///249 /// * item_id: Identifier of burned NFT.250 ///251 /// * owner: which user has destroyed its tokens252 ///253 /// * amount: Always 1 for NFT254 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),255256 /// Item was transferred257 ///258 /// * collection_id: Id of collection to which item is belong259 ///260 /// * item_id: Id of an item261 ///262 /// * sender: Original owner of item263 ///264 /// * recipient: New owner of item265 ///266 /// * amount: Always 1 for NFT267 Transfer(268 CollectionId,269 TokenId,270 T::CrossAccountId,271 T::CrossAccountId,272 u128,273 ),274275 /// * collection_id276 ///277 /// * item_id278 ///279 /// * sender280 ///281 /// * spender282 ///283 /// * amount284 Approved(285 CollectionId,286 TokenId,287 T::CrossAccountId,288 T::CrossAccountId,289 u128,290 ),291 }292293 #[pallet::error]294 pub enum Error<T> {295 /// This collection does not exist.296 CollectionNotFound,297 /// Sender parameter and item owner must be equal.298 MustBeTokenOwner,299 /// No permission to perform action300 NoPermission,301 /// Collection is not in mint mode.302 PublicMintingNotAllowed,303 /// Address is not in allow list.304 AddressNotInAllowlist,305306 /// Collection name can not be longer than 63 char.307 CollectionNameLimitExceeded,308 /// Collection description can not be longer than 255 char.309 CollectionDescriptionLimitExceeded,310 /// Token prefix can not be longer than 15 char.311 CollectionTokenPrefixLimitExceeded,312 /// Total collections bound exceeded.313 TotalCollectionsLimitExceeded,314 /// variable_data exceeded data limit.315 TokenVariableDataLimitExceeded,316 /// Exceeded max admin count317 CollectionAdminCountExceeded,318 /// Collection limit bounds per collection exceeded319 CollectionLimitBoundsExceeded,320 /// Tried to enable permissions which are only permitted to be disabled321 OwnerPermissionsCantBeReverted,322323 /// Collection settings not allowing items transferring324 TransferNotAllowed,325 /// Account token limit exceeded per collection326 AccountTokenLimitExceeded,327 /// Collection token limit exceeded328 CollectionTokenLimitExceeded,329 /// Metadata flag frozen330 MetadataFlagFrozen,331332 /// Item not exists.333 TokenNotFound,334 /// Item balance not enough.335 TokenValueTooLow,336 /// Requested value more than approved.337 ApprovedValueTooLow,338 /// Tried to approve more than owned339 CantApproveMoreThanOwned,340341 /// Can't transfer tokens to ethereum zero address342 AddressIsZero,343 /// Target collection doesn't supports this operation344 UnsupportedOperation,345346 /// Not sufficient founds to perform action347 NotSufficientFounds,348349 /// Collection has nesting disabled350 NestingIsDisabled,351 /// Only owner may nest tokens under this collection352 OnlyOwnerAllowedToNest,353 /// Only tokens from specific collections may nest tokens under this354 SourceCollectionIsNotAllowedToNest,355356 /// Tried to store more data than allowed in collection field357 CollectionFieldSizeExceeded,358 }359360 #[pallet::storage]361 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;362 #[pallet::storage]363 pub type DestroyedCollectionCount<T> =364 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;365366 /// Collection info367 #[pallet::storage]368 pub type CollectionById<T> = StorageMap<369 Hasher = Blake2_128Concat,370 Key = CollectionId,371 Value = Collection<<T as frame_system::Config>::AccountId>,372 QueryKind = OptionQuery,373 >;374375 /// Large variable-size collection fields are extracted here376 #[pallet::storage]377 pub type CollectionData<T> = StorageNMap<378 Key = (379 Key<Twox64Concat, CollectionId>,380 Key<Twox64Concat, CollectionField>,381 ),382 Value = BoundedVec<u8, ConstU32<COLLECTION_FIELD_LIMIT>>,383 QueryKind = ValueQuery,384 >;385386 #[pallet::storage]387 pub type AdminAmount<T> = StorageMap<388 Hasher = Blake2_128Concat,389 Key = CollectionId,390 Value = u32,391 QueryKind = ValueQuery,392 >;393394 /// List of collection admins395 #[pallet::storage]396 pub type IsAdmin<T: Config> = StorageNMap<397 Key = (398 Key<Blake2_128Concat, CollectionId>,399 Key<Blake2_128Concat, T::CrossAccountId>,400 ),401 Value = bool,402 QueryKind = ValueQuery,403 >;404405 /// Allowlisted collection users406 #[pallet::storage]407 pub type Allowlist<T: Config> = StorageNMap<408 Key = (409 Key<Blake2_128Concat, CollectionId>,410 Key<Blake2_128Concat, T::CrossAccountId>,411 ),412 Value = bool,413 QueryKind = ValueQuery,414 >;415416 /// Not used by code, exists only to provide some types to metadata417 #[pallet::storage]418 pub type DummyStorageValue<T: Config> = StorageValue<419 Value = (420 CollectionStats,421 CollectionId,422 TokenId,423 PhantomType<RpcCollection<T::AccountId>>,424 ),425 QueryKind = OptionQuery,426 >;427428 #[pallet::hooks]429 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {430 fn on_runtime_upgrade() -> Weight {431 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {432 use up_data_structs::{CollectionVersion1, CollectionVersion2};433 <CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {434 Self::set_field_raw(435 id,436 CollectionField::OffchainSchema,437 v.offchain_schema.clone().into_inner(),438 )439 .expect("data has lower bounds than field");440 Self::set_field_raw(441 id,442 CollectionField::VariableOnChainSchema,443 v.variable_on_chain_schema.clone().into_inner(),444 )445 .expect("data has lower bounds than field");446 Self::set_field_raw(447 id,448 CollectionField::ConstOnChainSchema,449 v.const_on_chain_schema.clone().into_inner(),450 )451 .expect("data has lower bounds than field");452453 Some(CollectionVersion2::from(v))454 });455 }456457 0458 }459 }460}461462impl<T: Config> Pallet<T> {463 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens464 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {465 ensure!(466 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,467 <Error<T>>::AddressIsZero468 );469 Ok(())470 }471 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {472 <IsAdmin<T>>::iter_prefix((collection,))473 .map(|(a, _)| a)474 .collect()475 }476 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {477 <Allowlist<T>>::iter_prefix((collection,))478 .map(|(a, _)| a)479 .collect()480 }481 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {482 <Allowlist<T>>::get((collection, user))483 }484 pub fn collection_stats() -> CollectionStats {485 let created = <CreatedCollectionCount<T>>::get();486 let destroyed = <DestroyedCollectionCount<T>>::get();487 CollectionStats {488 created: created.0,489 destroyed: destroyed.0,490 alive: created.0 - destroyed.0,491 }492 }493494 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {495 let collection = <CollectionById<T>>::get(collection);496 if collection.is_none() {497 return None;498 }499500 let collection = collection.unwrap();501 let limits = collection.limits;502 let effective_limits = CollectionLimits {503 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),504 sponsored_data_size: Some(limits.sponsored_data_size()),505 sponsored_data_rate_limit: Some(506 limits507 .sponsored_data_rate_limit508 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),509 ),510 token_limit: Some(limits.token_limit()),511 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(512 match collection.mode {513 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,514 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,515 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,516 },517 )),518 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),519 owner_can_transfer: Some(limits.owner_can_transfer()),520 owner_can_destroy: Some(limits.owner_can_destroy()),521 transfers_enabled: Some(limits.transfers_enabled()),522 nesting_rule: Some(limits.nesting_rule().clone()),523 };524525 Some(effective_limits)526 }527528 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {529 let Collection {530 name,531 description,532 owner,533 mode,534 access,535 token_prefix,536 mint_mode,537 schema_version,538 sponsorship,539 limits,540 meta_update_permission,541 } = <CollectionById<T>>::get(collection)?;542 Some(RpcCollection {543 name: name.into_inner(),544 description: description.into_inner(),545 owner,546 mode,547 access,548 token_prefix: token_prefix.into_inner(),549 mint_mode,550 schema_version,551 sponsorship,552 limits,553 meta_update_permission,554 offchain_schema: <CollectionData<T>>::get((555 collection,556 CollectionField::OffchainSchema,557 ))558 .into_inner(),559 const_on_chain_schema: <CollectionData<T>>::get((560 collection,561 CollectionField::ConstOnChainSchema,562 ))563 .into_inner(),564 variable_on_chain_schema: <CollectionData<T>>::get((565 collection,566 CollectionField::VariableOnChainSchema,567 ))568 .into_inner(),569 })570 }571}572573impl<T: Config> Pallet<T> {574 pub fn init_collection(575 owner: T::AccountId,576 data: CreateCollectionData<T::AccountId>,577 ) -> Result<CollectionId, DispatchError> {578 {579 ensure!(580 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,581 Error::<T>::CollectionTokenPrefixLimitExceeded582 );583 }584585 let created_count = <CreatedCollectionCount<T>>::get()586 .0587 .checked_add(1)588 .ok_or(ArithmeticError::Overflow)?;589 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;590 let id = CollectionId(created_count);591592 // bound Total number of collections593 ensure!(594 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,595 <Error<T>>::TotalCollectionsLimitExceeded596 );597598 // =========599600 let collection = Collection {601 owner: owner.clone(),602 name: data.name,603 mode: data.mode.clone(),604 mint_mode: false,605 access: data.access.unwrap_or_default(),606 description: data.description,607 token_prefix: data.token_prefix,608 schema_version: data.schema_version.unwrap_or_default(),609 sponsorship: data610 .pending_sponsor611 .map(SponsorshipState::Unconfirmed)612 .unwrap_or_default(),613 limits: data614 .limits615 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))616 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,617 meta_update_permission: data.meta_update_permission.unwrap_or_default(),618 };619620 // Take a (non-refundable) deposit of collection creation621 {622 let mut imbalance =623 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();624 imbalance.subsume(625 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(626 &T::TreasuryAccountId::get(),627 T::CollectionCreationPrice::get(),628 ),629 );630 <T as Config>::Currency::settle(631 &owner,632 imbalance,633 WithdrawReasons::TRANSFER,634 ExistenceRequirement::KeepAlive,635 )636 .map_err(|_| Error::<T>::NotSufficientFounds)?;637 }638639 <CreatedCollectionCount<T>>::put(created_count);640 <Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));641 <CollectionById<T>>::insert(id, collection);642 Self::set_field_raw(643 id,644 CollectionField::OffchainSchema,645 data.offchain_schema.into_inner(),646 )647 .expect("data has lower bounds than field");648 Self::set_field_raw(649 id,650 CollectionField::VariableOnChainSchema,651 data.variable_on_chain_schema.into_inner(),652 )653 .expect("data has lower bounds than field");654 Self::set_field_raw(655 id,656 CollectionField::ConstOnChainSchema,657 data.const_on_chain_schema.into_inner(),658 )659 .expect("data has lower bounds than field");660 Ok(id)661 }662663 pub fn destroy_collection(664 collection: CollectionHandle<T>,665 sender: &T::CrossAccountId,666 ) -> DispatchResult {667 ensure!(668 collection.limits.owner_can_destroy(),669 <Error<T>>::NoPermission,670 );671 collection.check_is_owner(sender)?;672673 let destroyed_collections = <DestroyedCollectionCount<T>>::get()674 .0675 .checked_add(1)676 .ok_or(ArithmeticError::Overflow)?;677678 // =========679680 <DestroyedCollectionCount<T>>::put(destroyed_collections);681 <CollectionById<T>>::remove(collection.id);682 <CollectionData<T>>::remove_prefix((collection.id,), None);683 <AdminAmount<T>>::remove(collection.id);684 <IsAdmin<T>>::remove_prefix((collection.id,), None);685 <Allowlist<T>>::remove_prefix((collection.id,), None);686687 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));688 Ok(())689 }690691 fn set_field_raw(692 collection_id: CollectionId,693 field: CollectionField,694 value: Vec<u8>,695 ) -> DispatchResult {696 if !value.is_empty() {697 <CollectionData<T>>::insert(698 (collection_id, field),699 BoundedVec::try_from(value).map_err(|_| <Error<T>>::CollectionFieldSizeExceeded)?,700 )701 } else {702 <CollectionData<T>>::remove((collection_id, field));703 }704 Ok(())705 }706707 pub fn set_field(708 collection: &CollectionHandle<T>,709 sender: &T::CrossAccountId,710 field: CollectionField,711 value: Vec<u8>,712 ) -> DispatchResult {713 collection.check_is_owner_or_admin(sender)?;714715 // =========716717 Self::set_field_raw(collection.id, field, value)718 }719720 pub fn toggle_allowlist(721 collection: &CollectionHandle<T>,722 sender: &T::CrossAccountId,723 user: &T::CrossAccountId,724 allowed: bool,725 ) -> DispatchResult {726 collection.check_is_owner_or_admin(sender)?;727728 // =========729730 if allowed {731 <Allowlist<T>>::insert((collection.id, user), true);732 } else {733 <Allowlist<T>>::remove((collection.id, user));734 }735736 Ok(())737 }738739 pub fn toggle_admin(740 collection: &CollectionHandle<T>,741 sender: &T::CrossAccountId,742 user: &T::CrossAccountId,743 admin: bool,744 ) -> DispatchResult {745 collection.check_is_owner_or_admin(sender)?;746747 let was_admin = <IsAdmin<T>>::get((collection.id, user));748 if was_admin == admin {749 return Ok(());750 }751 let amount = <AdminAmount<T>>::get(collection.id);752753 if admin {754 let amount = amount755 .checked_add(1)756 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;757 ensure!(758 amount <= Self::collection_admins_limit(),759 <Error<T>>::CollectionAdminCountExceeded,760 );761762 // =========763764 <AdminAmount<T>>::insert(collection.id, amount);765 <IsAdmin<T>>::insert((collection.id, user), true);766 } else {767 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));768 <IsAdmin<T>>::remove((collection.id, user));769 }770771 Ok(())772 }773774 pub fn clamp_limits(775 mode: CollectionMode,776 old_limit: &CollectionLimits,777 mut new_limit: CollectionLimits,778 ) -> Result<CollectionLimits, DispatchError> {779 macro_rules! limit_default {780 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{781 $(782 if let Some($new) = $new.$field {783 let $old = $old.$field($($arg)?);784 let _ = $new;785 let _ = $old;786 $check787 } else {788 $new.$field = $old.$field789 }790 )*791 }};792 }793794 limit_default!(old_limit, new_limit,795 account_token_ownership_limit => ensure!(796 new_limit <= MAX_TOKEN_OWNERSHIP,797 <Error<T>>::CollectionLimitBoundsExceeded,798 ),799 sponsor_transfer_timeout(match mode {800 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,801 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,802 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,803 }) => ensure!(804 new_limit <= MAX_SPONSOR_TIMEOUT,805 <Error<T>>::CollectionLimitBoundsExceeded,806 ),807 sponsored_data_size => ensure!(808 new_limit <= CUSTOM_DATA_LIMIT,809 <Error<T>>::CollectionLimitBoundsExceeded,810 ),811 token_limit => ensure!(812 old_limit >= new_limit && new_limit > 0,813 <Error<T>>::CollectionTokenLimitExceeded814 ),815 owner_can_transfer => ensure!(816 old_limit || !new_limit,817 <Error<T>>::OwnerPermissionsCantBeReverted,818 ),819 owner_can_destroy => ensure!(820 old_limit || !new_limit,821 <Error<T>>::OwnerPermissionsCantBeReverted,822 ),823 sponsored_data_rate_limit => {},824 transfers_enabled => {},825 );826 Ok(new_limit)827 }828}829830#[macro_export]831macro_rules! unsupported {832 () => {833 Err(<Error<T>>::UnsupportedOperation.into())834 };835}836837/// Worst cases838pub trait CommonWeightInfo<CrossAccountId> {839 fn create_item() -> Weight;840 fn create_multiple_items(amount: u32) -> Weight;841 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;842 fn burn_item() -> Weight;843 fn transfer() -> Weight;844 fn approve() -> Weight;845 fn transfer_from() -> Weight;846 fn burn_from() -> Weight;847 fn set_variable_metadata(bytes: u32) -> Weight;848}849850pub trait CommonCollectionOperations<T: Config> {851 fn create_item(852 &self,853 sender: T::CrossAccountId,854 to: T::CrossAccountId,855 data: CreateItemData,856 nesting_budget: &dyn Budget,857 ) -> DispatchResultWithPostInfo;858 fn create_multiple_items(859 &self,860 sender: T::CrossAccountId,861 to: T::CrossAccountId,862 data: Vec<CreateItemData>,863 nesting_budget: &dyn Budget,864 ) -> DispatchResultWithPostInfo;865 fn create_multiple_items_ex(866 &self,867 sender: T::CrossAccountId,868 data: CreateItemExData<T::CrossAccountId>,869 nesting_budget: &dyn Budget,870 ) -> DispatchResultWithPostInfo;871 fn burn_item(872 &self,873 sender: T::CrossAccountId,874 token: TokenId,875 amount: u128,876 ) -> DispatchResultWithPostInfo;877878 fn transfer(879 &self,880 sender: T::CrossAccountId,881 to: T::CrossAccountId,882 token: TokenId,883 amount: u128,884 nesting_budget: &dyn Budget,885 ) -> DispatchResultWithPostInfo;886 fn approve(887 &self,888 sender: T::CrossAccountId,889 spender: T::CrossAccountId,890 token: TokenId,891 amount: u128,892 ) -> DispatchResultWithPostInfo;893 fn transfer_from(894 &self,895 sender: T::CrossAccountId,896 from: T::CrossAccountId,897 to: T::CrossAccountId,898 token: TokenId,899 amount: u128,900 nesting_budget: &dyn Budget,901 ) -> DispatchResultWithPostInfo;902 fn burn_from(903 &self,904 sender: T::CrossAccountId,905 from: T::CrossAccountId,906 token: TokenId,907 amount: u128,908 nesting_budget: &dyn Budget,909 ) -> DispatchResultWithPostInfo;910911 fn set_variable_metadata(912 &self,913 sender: T::CrossAccountId,914 token: TokenId,915 data: BoundedVec<u8, CustomDataLimit>,916 ) -> DispatchResultWithPostInfo;917918 fn check_nesting(919 &self,920 sender: T::CrossAccountId,921 from: CollectionId,922 under: TokenId,923 budget: &dyn Budget,924 ) -> DispatchResult;925926 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;927 fn token_exists(&self, token: TokenId) -> bool;928 fn last_token_id(&self) -> TokenId;929930 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;931 fn const_metadata(&self, token: TokenId) -> Vec<u8>;932 fn variable_metadata(&self, token: TokenId) -> Vec<u8>;933934 /// How many tokens collection contains (Applicable to nonfungible/refungible)935 fn collection_tokens(&self) -> u32;936 /// Amount of different tokens account has (Applicable to nonfungible/refungible)937 fn account_balance(&self, account: T::CrossAccountId) -> u32;938 /// Amount of specific token account have (Applicable to fungible/refungible)939 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;940 fn allowance(941 &self,942 sender: T::CrossAccountId,943 spender: T::CrossAccountId,944 token: TokenId,945 ) -> u128;946}947948// Flexible enough for implementing CommonCollectionOperations949pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {950 let post_info = PostDispatchInfo {951 actual_weight: Some(weight),952 pays_fee: Pays::Yes,953 };954 match res {955 Ok(()) => Ok(post_info),956 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),957 }958}pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -24,8 +24,8 @@
budget::Budget,
};
use pallet_common::{
- Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
- CollectionHandle, dispatch::CollectionDispatch,
+ Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, CollectionHandle,
+ dispatch::CollectionDispatch,
};
use pallet_structure::Pallet as PalletStructure;
use pallet_evm_coder_substrate::WithRecorder;
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -24,8 +24,8 @@
};
use pallet_evm::account::CrossAccountId;
use pallet_common::{
- Error as CommonError, Pallet as PalletCommon, Event as CommonEvent,
- CollectionHandle, dispatch::CollectionDispatch,
+ Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
+ dispatch::CollectionDispatch,
};
use pallet_structure::Pallet as PalletStructure;
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -23,8 +23,8 @@
};
use pallet_evm::account::CrossAccountId;
use pallet_common::{
- Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
- CollectionHandle, dispatch::CollectionDispatch,
+ Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, CollectionHandle,
+ dispatch::CollectionDispatch,
};
use pallet_structure::Pallet as PalletStructure;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
pallets/unique/src/eth/sponsoring.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/sponsoring.rs
+++ b/pallets/unique/src/eth/sponsoring.rs
@@ -31,7 +31,6 @@
UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721MintableCall, ERC721Call,
};
use pallet_fungible::erc::{UniqueFungibleCall, ERC20Call};
-use up_data_structs::{TokenId, CreateItemData, CreateNftData};
pub struct UniqueEthSponsorshipHandler<T: Config>(PhantomData<*const T>);
impl<T: Config> SponsorshipHandler<T::CrossAccountId, (H160, Vec<u8>)>
primitives/data-structs/Cargo.tomldiffbeforeafterboth--- a/primitives/data-structs/Cargo.toml
+++ b/primitives/data-structs/Cargo.toml
@@ -25,6 +25,7 @@
sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20" }
derivative = "2.2.0"
struct-versioning = { path = "../../crates/struct-versioning" }
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.18-2" }
[features]
default = ["std"]
@@ -37,6 +38,7 @@
"sp-runtime/std",
"sp-core/std",
"sp-std/std",
+ "pallet-evm/std",
]
serde1 = ["serde"]
limit-testing = []
primitives/data-structs/src/mapping.rsdiffbeforeafterboth--- a/primitives/data-structs/src/mapping.rs
+++ b/primitives/data-structs/src/mapping.rs
@@ -3,7 +3,7 @@
use sp_core::H160;
use crate::{CollectionId, TokenId};
-use up_evm_mapping::CrossAccountId;
+use pallet_evm::account::CrossAccountId;
pub trait TokenAddressMapping<Address> {
fn token_to_address(collection: CollectionId, token: TokenId) -> Address;
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -16,7 +16,7 @@
#![cfg_attr(not(feature = "std"), no_std)]
-use up_data_structs::{CollectionId, TokenId, RpcCollection, Collection, CollectionStats, CollectionLimits};
+use up_data_structs::{CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits};
use sp_std::vec::Vec;
use codec::Decode;
use sp_runtime::DispatchError;
runtime/common/Cargo.tomldiffbeforeafterboth--- a/runtime/common/Cargo.toml
+++ b/runtime/common/Cargo.toml
@@ -93,11 +93,6 @@
default-features = false
path = "../../primitives/data-structs"
-[dependencies.pallet-evm]
-default-features = false
-git = "https://github.com/uniquenetwork/frontier.git"
-branch = "unique-polkadot-v0.9.18"
-
[dependencies.sp-consensus-aura]
default-features = false
git = "https://github.com/paritytech/substrate"
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -67,7 +67,7 @@
},
};
use up_data_structs::mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping};
-use up_data_structs::{CollectionId, TokenId, CollectionStats, RpcCollection};
+use up_data_structs::{CollectionId, TokenId, CollectionStats, CollectionLimits, RpcCollection};
// use pallet_contracts::weights::WeightInfo;
// #[cfg(any(feature = "std", test))]
use frame_system::{