difftreelog
CORE-300 Move CrossAccountId to frontier
in: master
27 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2554,7 +2554,7 @@
"fc-db",
"fc-rpc-core",
"fp-consensus",
- "fp-evm",
+ "fp-evm 3.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"fp-rpc",
"fp-storage",
"futures 0.3.21",
@@ -2565,7 +2565,7 @@
"log",
"lru 0.6.6",
"pallet-ethereum",
- "pallet-evm",
+ "pallet-evm 6.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"parity-scale-codec",
"parking_lot 0.11.2",
"rand 0.7.3",
@@ -2757,7 +2757,7 @@
dependencies = [
"ethereum",
"ethereum-types",
- "fp-evm",
+ "fp-evm 3.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"parity-scale-codec",
"scale-info",
"sp-api",
@@ -2853,6 +2853,21 @@
]
[[package]]
+name = "frame-common"
+version = "0.1.0"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=feature/300#0a1dc4086cbe971ddf57edf82a61cfce52c8c20b"
+dependencies = [
+ "frame-system",
+ "pallet-evm 6.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=feature/300)",
+ "parity-scale-codec",
+ "scale-info",
+ "serde",
+ "sp-core",
+ "sp-std",
+ "up-evm-mapping",
+]
+
+[[package]]
name = "frame-election-provider-support"
version = "4.0.0-dev"
source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.18#fc3fd073d3a0acf9933c3994b660ebd7b5833f65"
@@ -5835,7 +5850,7 @@
dependencies = [
"frame-support",
"frame-system",
- "pallet-evm",
+ "pallet-evm 6.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"parity-scale-codec",
"scale-info",
"serde",
@@ -5984,9 +5999,10 @@
version = "0.1.0"
dependencies = [
"evm-coder",
+ "frame-common",
"frame-support",
"frame-system",
- "pallet-evm",
+ "pallet-evm 6.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"pallet-evm-coder-substrate",
"parity-scale-codec",
"scale-info",
@@ -6064,7 +6080,7 @@
"ethereum-types",
"evm",
"fp-consensus",
- "fp-evm",
+ "fp-evm 3.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"fp-rpc",
"fp-self-contained",
"fp-storage",
@@ -6072,7 +6088,7 @@
"frame-system",
"log",
"pallet-balances",
- "pallet-evm",
+ "pallet-evm 6.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"pallet-timestamp",
"parity-scale-codec",
"rlp",
@@ -6093,7 +6109,7 @@
"evm",
"evm-gasometer",
"evm-runtime",
- "fp-evm",
+ "fp-evm 3.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"frame-benchmarking",
"frame-support",
"frame-system",
@@ -6124,7 +6140,7 @@
"frame-support",
"frame-system",
"pallet-ethereum",
- "pallet-evm",
+ "pallet-evm 6.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"parity-scale-codec",
"scale-info",
"sp-core",
@@ -6139,7 +6155,7 @@
"frame-support",
"frame-system",
"log",
- "pallet-evm",
+ "pallet-evm 6.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"pallet-evm-coder-substrate",
"parity-scale-codec",
"scale-info",
@@ -6154,11 +6170,11 @@
name = "pallet-evm-migration"
version = "0.1.0"
dependencies = [
- "fp-evm",
+ "fp-evm 3.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"frame-benchmarking",
"frame-support",
"frame-system",
- "pallet-evm",
+ "pallet-evm 6.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"parity-scale-codec",
"scale-info",
"sp-core",
@@ -6171,11 +6187,11 @@
name = "pallet-evm-transaction-payment"
version = "0.1.0"
dependencies = [
- "fp-evm",
+ "fp-evm 3.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"frame-support",
"frame-system",
"pallet-ethereum",
- "pallet-evm",
+ "pallet-evm 6.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"parity-scale-codec",
"scale-info",
"sp-core",
@@ -6193,6 +6209,7 @@
"ethereum",
"evm-coder",
"frame-benchmarking",
+ "frame-common",
"frame-support",
"frame-system",
"pallet-common",
@@ -6419,6 +6436,7 @@
"ethereum",
"evm-coder",
"frame-benchmarking",
+ "frame-common",
"frame-support",
"frame-system",
"pallet-common",
@@ -6535,6 +6553,7 @@
version = "0.1.0"
dependencies = [
"frame-benchmarking",
+ "frame-common",
"frame-support",
"frame-system",
"pallet-common",
@@ -6795,15 +6814,16 @@
dependencies = [
"ethereum",
"evm-coder",
- "fp-evm",
+ "fp-evm 3.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"frame-benchmarking",
+ "frame-common",
"frame-support",
"frame-system",
"hex-literal",
"pallet-balances",
"pallet-common",
"pallet-ethereum",
- "pallet-evm",
+ "pallet-evm 6.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"pallet-evm-coder-substrate",
"pallet-fungible",
"pallet-nonfungible",
@@ -12186,7 +12206,7 @@
"chrono",
"lazy_static",
"matchers",
- "parking_lot 0.11.2",
+ "parking_lot 0.10.2",
"regex",
"serde",
"serde_json",
@@ -12333,6 +12353,7 @@
name = "uc-rpc"
version = "0.1.0"
dependencies = [
+ "frame-common",
"jsonrpc-core",
"jsonrpc-core-client",
"jsonrpc-derive",
@@ -12549,6 +12570,7 @@
"fp-rpc",
"fp-self-contained",
"frame-benchmarking",
+ "frame-common",
"frame-executive",
"frame-support",
"frame-system",
@@ -12561,7 +12583,7 @@
"pallet-base-fee",
"pallet-common",
"pallet-ethereum",
- "pallet-evm",
+ "pallet-evm 6.0.0-dev (git+https://github.com/uniquenetwork/frontier.git?branch=unique-polkadot-v0.9.17)",
"pallet-evm-coder-substrate",
"pallet-evm-contract-helpers",
"pallet-evm-migration",
@@ -12688,6 +12710,7 @@
[[package]]
name = "up-evm-mapping"
version = "0.1.0"
+source = "git+https://github.com/uniquenetwork/frontier.git?branch=feature/300#0a1dc4086cbe971ddf57edf82a61cfce52c8c20b"
dependencies = [
"frame-support",
"sp-core",
@@ -12697,6 +12720,7 @@
name = "up-rpc"
version = "0.1.0"
dependencies = [
+ "frame-common",
"pallet-common",
"parity-scale-codec",
"sp-api",
client/rpc/Cargo.tomldiffbeforeafterboth--- a/client/rpc/Cargo.toml
+++ b/client/rpc/Cargo.toml
@@ -18,3 +18,4 @@
sp-core = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" }
sp-rpc = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" }
sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" }
+frame-common = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "feature/300" }
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -201,7 +201,7 @@
AccountId: Decode,
C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
C::Api: UniqueRuntimeApi<Block, CrossAccountId, AccountId>,
- CrossAccountId: pallet_common::account::CrossAccountId<AccountId>,
+ CrossAccountId: frame_common::account::CrossAccountId<AccountId>,
{
pass_method!(account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>);
pass_method!(token_exists(collection: CollectionId, token: TokenId) -> bool);
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -16,11 +16,12 @@
sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.18' }
sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.18' }
sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.18' }
-up-evm-mapping = { default-features = false, path = '../../primitives/evm-mapping' }
up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.18" }
+frame-common = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "feature/300" }
+up-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "feature/300" }
serde = { version = "1.0.130", default-features = false }
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
pallets/common/src/account.rsdiffbeforeafterboth--- a/pallets/common/src/account.rs
+++ /dev/null
@@ -1,195 +0,0 @@
-// 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 crate::Config;
-use codec::{Encode, EncodeLike, Decode, MaxEncodedLen};
-use sp_core::H160;
-use scale_info::{Type, TypeInfo};
-use core::cmp::Ordering;
-use serde::{Serialize, Deserialize};
-use pallet_evm::AddressMapping;
-use sp_std::vec::Vec;
-use sp_std::clone::Clone;
-
-pub use up_evm_mapping::EvmBackwardsAddressMapping;
-
-pub trait CrossAccountId<AccountId>:
- Encode + EncodeLike + Decode + TypeInfo + MaxEncodedLen + Clone + PartialEq + Ord + core::fmt::Debug
-// +
-// Serialize + Deserialize<'static>
-{
- fn as_sub(&self) -> &AccountId;
- fn as_eth(&self) -> &H160;
-
- fn from_sub(account: AccountId) -> Self;
- fn from_eth(account: H160) -> Self;
-
- fn conv_eq(&self, other: &Self) -> bool;
-}
-
-#[derive(Encode, Decode, Serialize, Deserialize, TypeInfo, MaxEncodedLen)]
-#[serde(rename_all = "camelCase")]
-enum BasicCrossAccountIdRepr<AccountId> {
- Substrate(AccountId),
- Ethereum(H160),
-}
-
-#[derive(PartialEq, Eq)]
-pub struct BasicCrossAccountId<T: Config> {
- /// If true - then ethereum is canonical encoding
- from_ethereum: bool,
- substrate: T::AccountId,
- ethereum: H160,
-}
-
-impl<T: Config> MaxEncodedLen for BasicCrossAccountId<T> {
- fn max_encoded_len() -> usize {
- <BasicCrossAccountIdRepr<T::AccountId>>::max_encoded_len()
- }
-}
-
-impl<T: Config> TypeInfo for BasicCrossAccountId<T> {
- type Identity = Self;
-
- fn type_info() -> Type {
- <BasicCrossAccountIdRepr<T::AccountId>>::type_info()
- }
-}
-
-impl<T: Config> core::fmt::Debug for BasicCrossAccountId<T> {
- fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
- if self.from_ethereum {
- fmt.debug_tuple("CrossAccountId::Ethereum")
- .field(&self.ethereum)
- .finish()
- } else {
- fmt.debug_tuple("CrossAccountId::Substrate")
- .field(&self.substrate)
- .finish()
- }
- }
-}
-
-impl<T: Config> PartialOrd for BasicCrossAccountId<T> {
- fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
- Some(self.substrate.cmp(&other.substrate))
- }
-}
-
-impl<T: Config> Ord for BasicCrossAccountId<T> {
- fn cmp(&self, other: &Self) -> Ordering {
- self.partial_cmp(other)
- .expect("substrate account is total ordered")
- }
-}
-
-impl<T: Config> Clone for BasicCrossAccountId<T> {
- fn clone(&self) -> Self {
- Self {
- from_ethereum: self.from_ethereum,
- substrate: self.substrate.clone(),
- ethereum: self.ethereum,
- }
- }
-}
-impl<T: Config> Encode for BasicCrossAccountId<T> {
- fn encode(&self) -> Vec<u8> {
- BasicCrossAccountIdRepr::from(self.clone()).encode()
- }
-}
-impl<T: Config> EncodeLike for BasicCrossAccountId<T> {}
-impl<T: Config> Decode for BasicCrossAccountId<T> {
- fn decode<I>(input: &mut I) -> Result<Self, codec::Error>
- where
- I: codec::Input,
- {
- Ok(BasicCrossAccountIdRepr::decode(input)?.into())
- }
-}
-impl<T> Serialize for BasicCrossAccountId<T>
-where
- T: Config,
- T::AccountId: Serialize,
-{
- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where
- S: serde::Serializer,
- {
- let repr = BasicCrossAccountIdRepr::from(self.clone());
- (&repr).serialize(serializer)
- }
-}
-impl<'de, T> Deserialize<'de> for BasicCrossAccountId<T>
-where
- T: Config,
- T::AccountId: Deserialize<'de>,
-{
- fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where
- D: serde::Deserializer<'de>,
- {
- Ok(BasicCrossAccountIdRepr::deserialize(deserializer)?.into())
- }
-}
-impl<T: Config> CrossAccountId<T::AccountId> for BasicCrossAccountId<T> {
- fn as_sub(&self) -> &T::AccountId {
- &self.substrate
- }
- fn as_eth(&self) -> &H160 {
- &self.ethereum
- }
- fn from_sub(substrate: T::AccountId) -> Self {
- Self {
- ethereum: T::EvmBackwardsAddressMapping::from_account_id(substrate.clone()),
- substrate,
- from_ethereum: false,
- }
- }
- fn from_eth(ethereum: H160) -> Self {
- Self {
- ethereum,
- substrate: T::EvmAddressMapping::into_account_id(ethereum),
- from_ethereum: true,
- }
- }
- fn conv_eq(&self, other: &Self) -> bool {
- if self.from_ethereum == other.from_ethereum {
- self.substrate == other.substrate && self.ethereum == other.ethereum
- } else if self.from_ethereum {
- // ethereum is canonical encoding, but we need to compare derived address
- self.substrate == other.substrate
- } else {
- self.ethereum == other.ethereum
- }
- }
-}
-impl<T: Config> From<BasicCrossAccountIdRepr<T::AccountId>> for BasicCrossAccountId<T> {
- fn from(repr: BasicCrossAccountIdRepr<T::AccountId>) -> Self {
- match repr {
- BasicCrossAccountIdRepr::Substrate(s) => Self::from_sub(s),
- BasicCrossAccountIdRepr::Ethereum(e) => Self::from_eth(e),
- }
- }
-}
-impl<T: Config> From<BasicCrossAccountId<T>> for BasicCrossAccountIdRepr<T::AccountId> {
- fn from(v: BasicCrossAccountId<T>) -> Self {
- if v.from_ethereum {
- BasicCrossAccountIdRepr::Ethereum(*v.as_eth())
- } else {
- BasicCrossAccountIdRepr::Substrate(v.as_sub().clone())
- }
- }
-}
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 account::CrossAccountId;23use frame_support::{24 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo},25 ensure, fail,26 traits::{Imbalance, Get, Currency},27 BoundedVec,28};29use pallet_evm::GasWeightMapping;30use up_data_structs::{31 COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,32 MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo,33 TokenId, Weight, WithdrawReasons, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode,34 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,37};38pub use pallet::*;39use sp_core::H160;40use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};41pub mod account;42#[cfg(feature = "runtime-benchmarks")]43pub mod benchmarking;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 account::CrossAccountId;167 use frame_support::traits::Currency;168 use up_data_structs::TokenId;169 use scale_info::TypeInfo;170171 #[pallet::config]172 pub trait Config: frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo {173 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;174175 type CrossAccountId: CrossAccountId<Self::AccountId>;176177 type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;178 type EvmBackwardsAddressMapping: up_evm_mapping::EvmBackwardsAddressMapping<Self::AccountId>;179180 type Currency: Currency<Self::AccountId>;181182 #[pallet::constant]183 type CollectionCreationPrice: Get<184 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,185 >;186187 type TreasuryAccountId: Get<Self::AccountId>;188 }189190 #[pallet::pallet]191 #[pallet::generate_store(pub(super) trait Store)]192 pub struct Pallet<T>(_);193194 #[pallet::extra_constants]195 impl<T: Config> Pallet<T> {196 pub fn collection_admins_limit() -> u32 {197 COLLECTION_ADMINS_LIMIT198 }199 }200201 #[pallet::event]202 #[pallet::generate_deposit(pub fn deposit_event)]203 pub enum Event<T: Config> {204 /// New collection was created205 ///206 /// # Arguments207 ///208 /// * collection_id: Globally unique identifier of newly created collection.209 ///210 /// * mode: [CollectionMode] converted into u8.211 ///212 /// * account_id: Collection owner.213 CollectionCreated(CollectionId, u8, T::AccountId),214215 /// New collection was destroyed216 ///217 /// # Arguments218 ///219 /// * collection_id: Globally unique identifier of collection.220 CollectionDestroyed(CollectionId),221222 /// New item was created.223 ///224 /// # Arguments225 ///226 /// * collection_id: Id of the collection where item was created.227 ///228 /// * item_id: Id of an item. Unique within the collection.229 ///230 /// * recipient: Owner of newly created item231 ///232 /// * amount: Always 1 for NFT233 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),234235 /// Collection item was burned.236 ///237 /// # Arguments238 ///239 /// * collection_id.240 ///241 /// * item_id: Identifier of burned NFT.242 ///243 /// * owner: which user has destroyed its tokens244 ///245 /// * amount: Always 1 for NFT246 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),247248 /// Item was transferred249 ///250 /// * collection_id: Id of collection to which item is belong251 ///252 /// * item_id: Id of an item253 ///254 /// * sender: Original owner of item255 ///256 /// * recipient: New owner of item257 ///258 /// * amount: Always 1 for NFT259 Transfer(260 CollectionId,261 TokenId,262 T::CrossAccountId,263 T::CrossAccountId,264 u128,265 ),266267 /// * collection_id268 ///269 /// * item_id270 ///271 /// * sender272 ///273 /// * spender274 ///275 /// * amount276 Approved(277 CollectionId,278 TokenId,279 T::CrossAccountId,280 T::CrossAccountId,281 u128,282 ),283 }284285 #[pallet::error]286 pub enum Error<T> {287 /// This collection does not exist.288 CollectionNotFound,289 /// Sender parameter and item owner must be equal.290 MustBeTokenOwner,291 /// No permission to perform action292 NoPermission,293 /// Collection is not in mint mode.294 PublicMintingNotAllowed,295 /// Address is not in allow list.296 AddressNotInAllowlist,297298 /// Collection name can not be longer than 63 char.299 CollectionNameLimitExceeded,300 /// Collection description can not be longer than 255 char.301 CollectionDescriptionLimitExceeded,302 /// Token prefix can not be longer than 15 char.303 CollectionTokenPrefixLimitExceeded,304 /// Total collections bound exceeded.305 TotalCollectionsLimitExceeded,306 /// variable_data exceeded data limit.307 TokenVariableDataLimitExceeded,308 /// Exceeded max admin count309 CollectionAdminCountExceeded,310 /// Collection limit bounds per collection exceeded311 CollectionLimitBoundsExceeded,312 /// Tried to enable permissions which are only permitted to be disabled313 OwnerPermissionsCantBeReverted,314315 /// Collection settings not allowing items transferring316 TransferNotAllowed,317 /// Account token limit exceeded per collection318 AccountTokenLimitExceeded,319 /// Collection token limit exceeded320 CollectionTokenLimitExceeded,321 /// Metadata flag frozen322 MetadataFlagFrozen,323324 /// Item not exists.325 TokenNotFound,326 /// Item balance not enough.327 TokenValueTooLow,328 /// Requested value more than approved.329 ApprovedValueTooLow,330 /// Tried to approve more than owned331 CantApproveMoreThanOwned,332333 /// Can't transfer tokens to ethereum zero address334 AddressIsZero,335 /// Target collection doesn't supports this operation336 UnsupportedOperation,337338 /// Not sufficient founds to perform action339 NotSufficientFounds,340 }341342 #[pallet::storage]343 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;344 #[pallet::storage]345 pub type DestroyedCollectionCount<T> =346 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;347348 /// Collection info349 #[pallet::storage]350 pub type CollectionById<T> = StorageMap<351 Hasher = Blake2_128Concat,352 Key = CollectionId,353 Value = Collection<<T as frame_system::Config>::AccountId>,354 QueryKind = OptionQuery,355 >;356357 #[pallet::storage]358 pub type AdminAmount<T> = StorageMap<359 Hasher = Blake2_128Concat,360 Key = CollectionId,361 Value = u32,362 QueryKind = ValueQuery,363 >;364365 /// List of collection admins366 #[pallet::storage]367 pub type IsAdmin<T: Config> = StorageNMap<368 Key = (369 Key<Blake2_128Concat, CollectionId>,370 Key<Blake2_128Concat, T::CrossAccountId>,371 ),372 Value = bool,373 QueryKind = ValueQuery,374 >;375376 /// Allowlisted collection users377 #[pallet::storage]378 pub type Allowlist<T: Config> = StorageNMap<379 Key = (380 Key<Blake2_128Concat, CollectionId>,381 Key<Blake2_128Concat, T::CrossAccountId>,382 ),383 Value = bool,384 QueryKind = ValueQuery,385 >;386387 /// Not used by code, exists only to provide some types to metadata388 #[pallet::storage]389 pub type DummyStorageValue<T> =390 StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;391}392393impl<T: Config> Pallet<T> {394 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens395 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {396 ensure!(397 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,398 <Error<T>>::AddressIsZero399 );400 Ok(())401 }402 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {403 <IsAdmin<T>>::iter_prefix((collection,))404 .map(|(a, _)| a)405 .collect()406 }407 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {408 <Allowlist<T>>::iter_prefix((collection,))409 .map(|(a, _)| a)410 .collect()411 }412 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {413 <Allowlist<T>>::get((collection, user))414 }415 pub fn collection_stats() -> CollectionStats {416 let created = <CreatedCollectionCount<T>>::get();417 let destroyed = <DestroyedCollectionCount<T>>::get();418 CollectionStats {419 created: created.0,420 destroyed: destroyed.0,421 alive: created.0 - destroyed.0,422 }423 }424}425426impl<T: Config> Pallet<T> {427 pub fn init_collection(428 owner: T::AccountId,429 data: CreateCollectionData<T::AccountId>,430 ) -> Result<CollectionId, DispatchError> {431 {432 ensure!(433 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,434 Error::<T>::CollectionTokenPrefixLimitExceeded435 );436 }437438 let created_count = <CreatedCollectionCount<T>>::get()439 .0440 .checked_add(1)441 .ok_or(ArithmeticError::Overflow)?;442 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;443 let id = CollectionId(created_count);444445 // bound Total number of collections446 ensure!(447 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,448 <Error<T>>::TotalCollectionsLimitExceeded449 );450451 // =========452453 let collection = Collection {454 owner: owner.clone(),455 name: data.name,456 mode: data.mode.clone(),457 mint_mode: false,458 access: data.access.unwrap_or_default(),459 description: data.description,460 token_prefix: data.token_prefix,461 offchain_schema: data.offchain_schema,462 schema_version: data.schema_version.unwrap_or_default(),463 sponsorship: data464 .pending_sponsor465 .map(SponsorshipState::Unconfirmed)466 .unwrap_or_default(),467 variable_on_chain_schema: data.variable_on_chain_schema,468 const_on_chain_schema: data.const_on_chain_schema,469 limits: data470 .limits471 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))472 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,473 meta_update_permission: data.meta_update_permission.unwrap_or_default(),474 };475476 // Take a (non-refundable) deposit of collection creation477 {478 let mut imbalance =479 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();480 imbalance.subsume(481 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(482 &T::TreasuryAccountId::get(),483 T::CollectionCreationPrice::get(),484 ),485 );486 <T as Config>::Currency::settle(487 &owner,488 imbalance,489 WithdrawReasons::TRANSFER,490 ExistenceRequirement::KeepAlive,491 )492 .map_err(|_| Error::<T>::NotSufficientFounds)?;493 }494495 <CreatedCollectionCount<T>>::put(created_count);496 <Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));497 <CollectionById<T>>::insert(id, collection);498 Ok(id)499 }500501 pub fn destroy_collection(502 collection: CollectionHandle<T>,503 sender: &T::CrossAccountId,504 ) -> DispatchResult {505 ensure!(506 collection.limits.owner_can_destroy(),507 <Error<T>>::NoPermission,508 );509 collection.check_is_owner(sender)?;510511 let destroyed_collections = <DestroyedCollectionCount<T>>::get()512 .0513 .checked_add(1)514 .ok_or(ArithmeticError::Overflow)?;515516 // =========517518 <DestroyedCollectionCount<T>>::put(destroyed_collections);519 <CollectionById<T>>::remove(collection.id);520 <AdminAmount<T>>::remove(collection.id);521 <IsAdmin<T>>::remove_prefix((collection.id,), None);522 <Allowlist<T>>::remove_prefix((collection.id,), None);523524 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));525 Ok(())526 }527528 pub fn toggle_allowlist(529 collection: &CollectionHandle<T>,530 sender: &T::CrossAccountId,531 user: &T::CrossAccountId,532 allowed: bool,533 ) -> DispatchResult {534 collection.check_is_owner_or_admin(sender)?;535536 // =========537538 if allowed {539 <Allowlist<T>>::insert((collection.id, user), true);540 } else {541 <Allowlist<T>>::remove((collection.id, user));542 }543544 Ok(())545 }546547 pub fn toggle_admin(548 collection: &CollectionHandle<T>,549 sender: &T::CrossAccountId,550 user: &T::CrossAccountId,551 admin: bool,552 ) -> DispatchResult {553 collection.check_is_owner_or_admin(sender)?;554555 let was_admin = <IsAdmin<T>>::get((collection.id, user));556 if was_admin == admin {557 return Ok(());558 }559 let amount = <AdminAmount<T>>::get(collection.id);560561 if admin {562 let amount = amount563 .checked_add(1)564 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;565 ensure!(566 amount <= Self::collection_admins_limit(),567 <Error<T>>::CollectionAdminCountExceeded,568 );569570 // =========571572 <AdminAmount<T>>::insert(collection.id, amount);573 <IsAdmin<T>>::insert((collection.id, user), true);574 } else {575 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));576 <IsAdmin<T>>::remove((collection.id, user));577 }578579 Ok(())580 }581582 pub fn clamp_limits(583 mode: CollectionMode,584 old_limit: &CollectionLimits,585 mut new_limit: CollectionLimits,586 ) -> Result<CollectionLimits, DispatchError> {587 macro_rules! limit_default {588 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{589 $(590 if let Some($new) = $new.$field {591 let $old = $old.$field($($arg)?);592 let _ = $new;593 let _ = $old;594 $check595 } else {596 $new.$field = $old.$field597 }598 )*599 }};600 }601602 limit_default!(old_limit, new_limit,603 account_token_ownership_limit => ensure!(604 new_limit <= MAX_TOKEN_OWNERSHIP,605 <Error<T>>::CollectionLimitBoundsExceeded,606 ),607 sponsor_transfer_timeout(match mode {608 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,609 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,610 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,611 }) => ensure!(612 new_limit <= MAX_SPONSOR_TIMEOUT,613 <Error<T>>::CollectionLimitBoundsExceeded,614 ),615 sponsored_data_size => ensure!(616 new_limit <= CUSTOM_DATA_LIMIT,617 <Error<T>>::CollectionLimitBoundsExceeded,618 ),619 token_limit => ensure!(620 old_limit >= new_limit && new_limit > 0,621 <Error<T>>::CollectionTokenLimitExceeded622 ),623 owner_can_transfer => ensure!(624 old_limit || !new_limit,625 <Error<T>>::OwnerPermissionsCantBeReverted,626 ),627 owner_can_destroy => ensure!(628 old_limit || !new_limit,629 <Error<T>>::OwnerPermissionsCantBeReverted,630 ),631 sponsored_data_rate_limit => {},632 transfers_enabled => {},633 );634 Ok(new_limit)635 }636}637638#[macro_export]639macro_rules! unsupported {640 () => {641 Err(<Error<T>>::UnsupportedOperation.into())642 };643}644645/// Worst cases646pub trait CommonWeightInfo<CrossAccountId> {647 fn create_item() -> Weight;648 fn create_multiple_items(amount: u32) -> Weight;649 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;650 fn burn_item() -> Weight;651 fn transfer() -> Weight;652 fn approve() -> Weight;653 fn transfer_from() -> Weight;654 fn burn_from() -> Weight;655 fn set_variable_metadata(bytes: u32) -> Weight;656}657658pub trait CommonCollectionOperations<T: Config> {659 fn create_item(660 &self,661 sender: T::CrossAccountId,662 to: T::CrossAccountId,663 data: CreateItemData,664 ) -> DispatchResultWithPostInfo;665 fn create_multiple_items(666 &self,667 sender: T::CrossAccountId,668 to: T::CrossAccountId,669 data: Vec<CreateItemData>,670 ) -> DispatchResultWithPostInfo;671 fn create_multiple_items_ex(672 &self,673 sender: T::CrossAccountId,674 data: CreateItemExData<T::CrossAccountId>,675 ) -> DispatchResultWithPostInfo;676 fn burn_item(677 &self,678 sender: T::CrossAccountId,679 token: TokenId,680 amount: u128,681 ) -> DispatchResultWithPostInfo;682683 fn transfer(684 &self,685 sender: T::CrossAccountId,686 to: T::CrossAccountId,687 token: TokenId,688 amount: u128,689 ) -> DispatchResultWithPostInfo;690 fn approve(691 &self,692 sender: T::CrossAccountId,693 spender: T::CrossAccountId,694 token: TokenId,695 amount: u128,696 ) -> DispatchResultWithPostInfo;697 fn transfer_from(698 &self,699 sender: T::CrossAccountId,700 from: T::CrossAccountId,701 to: T::CrossAccountId,702 token: TokenId,703 amount: u128,704 ) -> DispatchResultWithPostInfo;705 fn burn_from(706 &self,707 sender: T::CrossAccountId,708 from: T::CrossAccountId,709 token: TokenId,710 amount: u128,711 ) -> DispatchResultWithPostInfo;712713 fn set_variable_metadata(714 &self,715 sender: T::CrossAccountId,716 token: TokenId,717 data: BoundedVec<u8, CustomDataLimit>,718 ) -> DispatchResultWithPostInfo;719720 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;721 fn token_exists(&self, token: TokenId) -> bool;722 fn last_token_id(&self) -> TokenId;723724 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;725 fn const_metadata(&self, token: TokenId) -> Vec<u8>;726 fn variable_metadata(&self, token: TokenId) -> Vec<u8>;727728 /// How many tokens collection contains (Applicable to nonfungible/refungible)729 fn collection_tokens(&self) -> u32;730 /// Amount of different tokens account has (Applicable to nonfungible/refungible)731 fn account_balance(&self, account: T::CrossAccountId) -> u32;732 /// Amount of specific token account have (Applicable to fungible/refungible)733 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;734 fn allowance(735 &self,736 sender: T::CrossAccountId,737 spender: T::CrossAccountId,738 token: TokenId,739 ) -> u128;740}741742// Flexible enough for implementing CommonCollectionOperations743pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {744 let post_info = PostDispatchInfo {745 actual_weight: Some(weight),746 pays_fee: Pays::Yes,747 };748 match res {749 Ok(()) => Ok(post_info),750 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),751 }752}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 frame_common::account::CrossAccountId;23use frame_support::{24 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo},25 ensure, fail,26 traits::{Imbalance, Get, Currency},27 BoundedVec,28};29use pallet_evm::GasWeightMapping;30use up_data_structs::{31 COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,32 MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo,33 TokenId, Weight, WithdrawReasons, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode,34 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,37};38pub use pallet::*;39use sp_core::H160;40use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod erc;44pub mod eth;4546#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]47pub struct CollectionHandle<T: Config> {48 pub id: CollectionId,49 collection: Collection<T::AccountId>,50 pub recorder: SubstrateRecorder<T>,51}52impl<T: Config> WithRecorder<T> for CollectionHandle<T> {53 fn recorder(&self) -> &SubstrateRecorder<T> {54 &self.recorder55 }56 fn into_recorder(self) -> SubstrateRecorder<T> {57 self.recorder58 }59}60impl<T: Config> CollectionHandle<T> {61 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {62 <CollectionById<T>>::get(id).map(|collection| Self {63 id,64 collection,65 recorder: SubstrateRecorder::new(eth::collection_id_to_address(id), gas_limit),66 })67 }68 pub fn new(id: CollectionId) -> Option<Self> {69 Self::new_with_gas_limit(id, u64::MAX)70 }71 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {72 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)73 }74 pub fn log_mirrored(&self, log: impl evm_coder::ToLog) {75 self.recorder.log_mirrored(log)76 }77 pub fn log_direct(&self, log: impl evm_coder::ToLog) {78 self.recorder.log_direct(log)79 }80 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {81 self.recorder82 .consume_gas(T::GasWeightMapping::weight_to_gas(83 <T as frame_system::Config>::DbWeight::get()84 .read85 .saturating_mul(reads),86 ))87 }88 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {89 self.recorder90 .consume_gas(T::GasWeightMapping::weight_to_gas(91 <T as frame_system::Config>::DbWeight::get()92 .write93 .saturating_mul(writes),94 ))95 }96 pub fn submit_logs(self) {97 self.recorder.submit_logs()98 }99 pub fn save(self) -> DispatchResult {100 self.recorder.submit_logs();101 <CollectionById<T>>::insert(self.id, self.collection);102 Ok(())103 }104}105impl<T: Config> Deref for CollectionHandle<T> {106 type Target = Collection<T::AccountId>;107108 fn deref(&self) -> &Self::Target {109 &self.collection110 }111}112113impl<T: Config> DerefMut for CollectionHandle<T> {114 fn deref_mut(&mut self) -> &mut Self::Target {115 &mut self.collection116 }117}118119impl<T: Config> CollectionHandle<T> {120 pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {121 ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);122 Ok(())123 }124 pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {125 *subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))126 }127 pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {128 ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);129 Ok(())130 }131 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {132 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)133 }134 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {135 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)136 }137 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {138 ensure!(139 <Allowlist<T>>::get((self.id, user)),140 <Error<T>>::AddressNotInAllowlist141 );142 Ok(())143 }144145 pub fn check_can_update_meta(146 &self,147 subject: &T::CrossAccountId,148 item_owner: &T::CrossAccountId,149 ) -> DispatchResult {150 match self.meta_update_permission {151 MetaUpdatePermission::ItemOwner => {152 ensure!(subject == item_owner, <Error<T>>::NoPermission);153 Ok(())154 }155 MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),156 MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),157 }158 }159}160161#[frame_support::pallet]162pub mod pallet {163 use super::*;164 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};165 use frame_common::account::CrossAccountId;166 use frame_support::traits::Currency;167 use up_data_structs::TokenId;168 use scale_info::TypeInfo;169170 #[pallet::config]171 pub trait Config: frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo {172 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;173174 type CrossAccountId: CrossAccountId<Self::AccountId>;175176 type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;177 type EvmBackwardsAddressMapping: up_evm_mapping::EvmBackwardsAddressMapping<Self::AccountId>;178179 type Currency: Currency<Self::AccountId>;180181 #[pallet::constant]182 type CollectionCreationPrice: Get<183 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,184 >;185186 type TreasuryAccountId: Get<Self::AccountId>;187 }188189 #[pallet::pallet]190 #[pallet::generate_store(pub(super) trait Store)]191 pub struct Pallet<T>(_);192193 #[pallet::extra_constants]194 impl<T: Config> Pallet<T> {195 pub fn collection_admins_limit() -> u32 {196 COLLECTION_ADMINS_LIMIT197 }198 }199200 #[pallet::event]201 #[pallet::generate_deposit(pub fn deposit_event)]202 pub enum Event<T: Config> {203 /// New collection was created204 ///205 /// # Arguments206 ///207 /// * collection_id: Globally unique identifier of newly created collection.208 ///209 /// * mode: [CollectionMode] converted into u8.210 ///211 /// * account_id: Collection owner.212 CollectionCreated(CollectionId, u8, T::AccountId),213214 /// New collection was destroyed215 ///216 /// # Arguments217 ///218 /// * collection_id: Globally unique identifier of collection.219 CollectionDestroyed(CollectionId),220221 /// New item was created.222 ///223 /// # Arguments224 ///225 /// * collection_id: Id of the collection where item was created.226 ///227 /// * item_id: Id of an item. Unique within the collection.228 ///229 /// * recipient: Owner of newly created item230 ///231 /// * amount: Always 1 for NFT232 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),233234 /// Collection item was burned.235 ///236 /// # Arguments237 ///238 /// * collection_id.239 ///240 /// * item_id: Identifier of burned NFT.241 ///242 /// * owner: which user has destroyed its tokens243 ///244 /// * amount: Always 1 for NFT245 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),246247 /// Item was transferred248 ///249 /// * collection_id: Id of collection to which item is belong250 ///251 /// * item_id: Id of an item252 ///253 /// * sender: Original owner of item254 ///255 /// * recipient: New owner of item256 ///257 /// * amount: Always 1 for NFT258 Transfer(259 CollectionId,260 TokenId,261 T::CrossAccountId,262 T::CrossAccountId,263 u128,264 ),265266 /// * collection_id267 ///268 /// * item_id269 ///270 /// * sender271 ///272 /// * spender273 ///274 /// * amount275 Approved(276 CollectionId,277 TokenId,278 T::CrossAccountId,279 T::CrossAccountId,280 u128,281 ),282 }283284 #[pallet::error]285 pub enum Error<T> {286 /// This collection does not exist.287 CollectionNotFound,288 /// Sender parameter and item owner must be equal.289 MustBeTokenOwner,290 /// No permission to perform action291 NoPermission,292 /// Collection is not in mint mode.293 PublicMintingNotAllowed,294 /// Address is not in allow list.295 AddressNotInAllowlist,296297 /// Collection name can not be longer than 63 char.298 CollectionNameLimitExceeded,299 /// Collection description can not be longer than 255 char.300 CollectionDescriptionLimitExceeded,301 /// Token prefix can not be longer than 15 char.302 CollectionTokenPrefixLimitExceeded,303 /// Total collections bound exceeded.304 TotalCollectionsLimitExceeded,305 /// variable_data exceeded data limit.306 TokenVariableDataLimitExceeded,307 /// Exceeded max admin count308 CollectionAdminCountExceeded,309 /// Collection limit bounds per collection exceeded310 CollectionLimitBoundsExceeded,311 /// Tried to enable permissions which are only permitted to be disabled312 OwnerPermissionsCantBeReverted,313314 /// Collection settings not allowing items transferring315 TransferNotAllowed,316 /// Account token limit exceeded per collection317 AccountTokenLimitExceeded,318 /// Collection token limit exceeded319 CollectionTokenLimitExceeded,320 /// Metadata flag frozen321 MetadataFlagFrozen,322323 /// Item not exists.324 TokenNotFound,325 /// Item balance not enough.326 TokenValueTooLow,327 /// Requested value more than approved.328 ApprovedValueTooLow,329 /// Tried to approve more than owned330 CantApproveMoreThanOwned,331332 /// Can't transfer tokens to ethereum zero address333 AddressIsZero,334 /// Target collection doesn't supports this operation335 UnsupportedOperation,336337 /// Not sufficient founds to perform action338 NotSufficientFounds,339 }340341 #[pallet::storage]342 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;343 #[pallet::storage]344 pub type DestroyedCollectionCount<T> =345 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;346347 /// Collection info348 #[pallet::storage]349 pub type CollectionById<T> = StorageMap<350 Hasher = Blake2_128Concat,351 Key = CollectionId,352 Value = Collection<<T as frame_system::Config>::AccountId>,353 QueryKind = OptionQuery,354 >;355356 #[pallet::storage]357 pub type AdminAmount<T> = StorageMap<358 Hasher = Blake2_128Concat,359 Key = CollectionId,360 Value = u32,361 QueryKind = ValueQuery,362 >;363364 /// List of collection admins365 #[pallet::storage]366 pub type IsAdmin<T: Config> = StorageNMap<367 Key = (368 Key<Blake2_128Concat, CollectionId>,369 Key<Blake2_128Concat, T::CrossAccountId>,370 ),371 Value = bool,372 QueryKind = ValueQuery,373 >;374375 /// Allowlisted collection users376 #[pallet::storage]377 pub type Allowlist<T: Config> = StorageNMap<378 Key = (379 Key<Blake2_128Concat, CollectionId>,380 Key<Blake2_128Concat, T::CrossAccountId>,381 ),382 Value = bool,383 QueryKind = ValueQuery,384 >;385386 /// Not used by code, exists only to provide some types to metadata387 #[pallet::storage]388 pub type DummyStorageValue<T> =389 StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;390}391392impl<T: Config> Pallet<T> {393 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens394 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {395 ensure!(396 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,397 <Error<T>>::AddressIsZero398 );399 Ok(())400 }401 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {402 <IsAdmin<T>>::iter_prefix((collection,))403 .map(|(a, _)| a)404 .collect()405 }406 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {407 <Allowlist<T>>::iter_prefix((collection,))408 .map(|(a, _)| a)409 .collect()410 }411 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {412 <Allowlist<T>>::get((collection, user))413 }414 pub fn collection_stats() -> CollectionStats {415 let created = <CreatedCollectionCount<T>>::get();416 let destroyed = <DestroyedCollectionCount<T>>::get();417 CollectionStats {418 created: created.0,419 destroyed: destroyed.0,420 alive: created.0 - destroyed.0,421 }422 }423}424425impl<T: Config> Pallet<T> {426 pub fn init_collection(427 owner: T::AccountId,428 data: CreateCollectionData<T::AccountId>,429 ) -> Result<CollectionId, DispatchError> {430 {431 ensure!(432 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,433 Error::<T>::CollectionTokenPrefixLimitExceeded434 );435 }436437 let created_count = <CreatedCollectionCount<T>>::get()438 .0439 .checked_add(1)440 .ok_or(ArithmeticError::Overflow)?;441 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;442 let id = CollectionId(created_count);443444 // bound Total number of collections445 ensure!(446 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,447 <Error<T>>::TotalCollectionsLimitExceeded448 );449450 // =========451452 let collection = Collection {453 owner: owner.clone(),454 name: data.name,455 mode: data.mode.clone(),456 mint_mode: false,457 access: data.access.unwrap_or_default(),458 description: data.description,459 token_prefix: data.token_prefix,460 offchain_schema: data.offchain_schema,461 schema_version: data.schema_version.unwrap_or_default(),462 sponsorship: data463 .pending_sponsor464 .map(SponsorshipState::Unconfirmed)465 .unwrap_or_default(),466 variable_on_chain_schema: data.variable_on_chain_schema,467 const_on_chain_schema: data.const_on_chain_schema,468 limits: data469 .limits470 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))471 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,472 meta_update_permission: data.meta_update_permission.unwrap_or_default(),473 };474475 // Take a (non-refundable) deposit of collection creation476 {477 let mut imbalance =478 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();479 imbalance.subsume(480 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(481 &T::TreasuryAccountId::get(),482 T::CollectionCreationPrice::get(),483 ),484 );485 <T as Config>::Currency::settle(486 &owner,487 imbalance,488 WithdrawReasons::TRANSFER,489 ExistenceRequirement::KeepAlive,490 )491 .map_err(|_| Error::<T>::NotSufficientFounds)?;492 }493494 <CreatedCollectionCount<T>>::put(created_count);495 <Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));496 <CollectionById<T>>::insert(id, collection);497 Ok(id)498 }499500 pub fn destroy_collection(501 collection: CollectionHandle<T>,502 sender: &T::CrossAccountId,503 ) -> DispatchResult {504 ensure!(505 collection.limits.owner_can_destroy(),506 <Error<T>>::NoPermission,507 );508 collection.check_is_owner(sender)?;509510 let destroyed_collections = <DestroyedCollectionCount<T>>::get()511 .0512 .checked_add(1)513 .ok_or(ArithmeticError::Overflow)?;514515 // =========516517 <DestroyedCollectionCount<T>>::put(destroyed_collections);518 <CollectionById<T>>::remove(collection.id);519 <AdminAmount<T>>::remove(collection.id);520 <IsAdmin<T>>::remove_prefix((collection.id,), None);521 <Allowlist<T>>::remove_prefix((collection.id,), None);522523 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));524 Ok(())525 }526527 pub fn toggle_allowlist(528 collection: &CollectionHandle<T>,529 sender: &T::CrossAccountId,530 user: &T::CrossAccountId,531 allowed: bool,532 ) -> DispatchResult {533 collection.check_is_owner_or_admin(sender)?;534535 // =========536537 if allowed {538 <Allowlist<T>>::insert((collection.id, user), true);539 } else {540 <Allowlist<T>>::remove((collection.id, user));541 }542543 Ok(())544 }545546 pub fn toggle_admin(547 collection: &CollectionHandle<T>,548 sender: &T::CrossAccountId,549 user: &T::CrossAccountId,550 admin: bool,551 ) -> DispatchResult {552 collection.check_is_owner_or_admin(sender)?;553554 let was_admin = <IsAdmin<T>>::get((collection.id, user));555 if was_admin == admin {556 return Ok(());557 }558 let amount = <AdminAmount<T>>::get(collection.id);559560 if admin {561 let amount = amount562 .checked_add(1)563 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;564 ensure!(565 amount <= Self::collection_admins_limit(),566 <Error<T>>::CollectionAdminCountExceeded,567 );568569 // =========570571 <AdminAmount<T>>::insert(collection.id, amount);572 <IsAdmin<T>>::insert((collection.id, user), true);573 } else {574 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));575 <IsAdmin<T>>::remove((collection.id, user));576 }577578 Ok(())579 }580581 pub fn clamp_limits(582 mode: CollectionMode,583 old_limit: &CollectionLimits,584 mut new_limit: CollectionLimits,585 ) -> Result<CollectionLimits, DispatchError> {586 macro_rules! limit_default {587 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{588 $(589 if let Some($new) = $new.$field {590 let $old = $old.$field($($arg)?);591 let _ = $new;592 let _ = $old;593 $check594 } else {595 $new.$field = $old.$field596 }597 )*598 }};599 }600601 limit_default!(old_limit, new_limit,602 account_token_ownership_limit => ensure!(603 new_limit <= MAX_TOKEN_OWNERSHIP,604 <Error<T>>::CollectionLimitBoundsExceeded,605 ),606 sponsor_transfer_timeout(match mode {607 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,608 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,609 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,610 }) => ensure!(611 new_limit <= MAX_SPONSOR_TIMEOUT,612 <Error<T>>::CollectionLimitBoundsExceeded,613 ),614 sponsored_data_size => ensure!(615 new_limit <= CUSTOM_DATA_LIMIT,616 <Error<T>>::CollectionLimitBoundsExceeded,617 ),618 token_limit => ensure!(619 old_limit >= new_limit && new_limit > 0,620 <Error<T>>::CollectionTokenLimitExceeded621 ),622 owner_can_transfer => ensure!(623 old_limit || !new_limit,624 <Error<T>>::OwnerPermissionsCantBeReverted,625 ),626 owner_can_destroy => ensure!(627 old_limit || !new_limit,628 <Error<T>>::OwnerPermissionsCantBeReverted,629 ),630 sponsored_data_rate_limit => {},631 transfers_enabled => {},632 );633 Ok(new_limit)634 }635}636637#[macro_export]638macro_rules! unsupported {639 () => {640 Err(<Error<T>>::UnsupportedOperation.into())641 };642}643644/// Worst cases645pub trait CommonWeightInfo<CrossAccountId> {646 fn create_item() -> Weight;647 fn create_multiple_items(amount: u32) -> Weight;648 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;649 fn burn_item() -> Weight;650 fn transfer() -> Weight;651 fn approve() -> Weight;652 fn transfer_from() -> Weight;653 fn burn_from() -> Weight;654 fn set_variable_metadata(bytes: u32) -> Weight;655}656657pub trait CommonCollectionOperations<T: Config> {658 fn create_item(659 &self,660 sender: T::CrossAccountId,661 to: T::CrossAccountId,662 data: CreateItemData,663 ) -> DispatchResultWithPostInfo;664 fn create_multiple_items(665 &self,666 sender: T::CrossAccountId,667 to: T::CrossAccountId,668 data: Vec<CreateItemData>,669 ) -> DispatchResultWithPostInfo;670 fn create_multiple_items_ex(671 &self,672 sender: T::CrossAccountId,673 data: CreateItemExData<T::CrossAccountId>,674 ) -> DispatchResultWithPostInfo;675 fn burn_item(676 &self,677 sender: T::CrossAccountId,678 token: TokenId,679 amount: u128,680 ) -> DispatchResultWithPostInfo;681682 fn transfer(683 &self,684 sender: T::CrossAccountId,685 to: T::CrossAccountId,686 token: TokenId,687 amount: u128,688 ) -> DispatchResultWithPostInfo;689 fn approve(690 &self,691 sender: T::CrossAccountId,692 spender: T::CrossAccountId,693 token: TokenId,694 amount: u128,695 ) -> DispatchResultWithPostInfo;696 fn transfer_from(697 &self,698 sender: T::CrossAccountId,699 from: T::CrossAccountId,700 to: T::CrossAccountId,701 token: TokenId,702 amount: u128,703 ) -> DispatchResultWithPostInfo;704 fn burn_from(705 &self,706 sender: T::CrossAccountId,707 from: T::CrossAccountId,708 token: TokenId,709 amount: u128,710 ) -> DispatchResultWithPostInfo;711712 fn set_variable_metadata(713 &self,714 sender: T::CrossAccountId,715 token: TokenId,716 data: BoundedVec<u8, CustomDataLimit>,717 ) -> DispatchResultWithPostInfo;718719 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;720 fn token_exists(&self, token: TokenId) -> bool;721 fn last_token_id(&self) -> TokenId;722723 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;724 fn const_metadata(&self, token: TokenId) -> Vec<u8>;725 fn variable_metadata(&self, token: TokenId) -> Vec<u8>;726727 /// How many tokens collection contains (Applicable to nonfungible/refungible)728 fn collection_tokens(&self) -> u32;729 /// Amount of different tokens account has (Applicable to nonfungible/refungible)730 fn account_balance(&self, account: T::CrossAccountId) -> u32;731 /// Amount of specific token account have (Applicable to fungible/refungible)732 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;733 fn allowance(734 &self,735 sender: T::CrossAccountId,736 spender: T::CrossAccountId,737 token: TokenId,738 ) -> u128;739}740741// Flexible enough for implementing CommonCollectionOperations742pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {743 let post_info = PostDispatchInfo {744 actual_weight: Some(weight),745 pays_fee: Pays::Yes,746 };747 match res {748 Ok(()) => Ok(post_info),749 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),750 }751}pallets/evm-contract-helpers/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-contract-helpers/Cargo.toml
+++ b/pallets/evm-contract-helpers/Cargo.toml
@@ -17,7 +17,7 @@
pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.18" }
up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring", branch = 'polkadot-v0.9.18' }
-up-evm-mapping = { default-features = false, path = "../../primitives/evm-mapping" }
+up-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "feature/300" }
log = "0.4.14"
[dependencies.codec]
pallets/evm-transaction-payment/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-transaction-payment/Cargo.toml
+++ b/pallets/evm-transaction-payment/Cargo.toml
@@ -18,7 +18,7 @@
fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.18" }
pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.18" }
up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring", branch = 'polkadot-v0.9.18' }
-up-evm-mapping = { default-features = false, path = "../../primitives/evm-mapping" }
+up-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "feature/300" }
[dependencies.codec]
default-features = false
pallets/fungible/Cargo.tomldiffbeforeafterboth--- a/pallets/fungible/Cargo.toml
+++ b/pallets/fungible/Cargo.toml
@@ -25,6 +25,7 @@
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
+frame-common = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "feature/300" }
[features]
default = ["std"]
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -21,7 +21,7 @@
use pallet_common::erc::{CommonEvmHandler, PrecompileResult};
use sp_core::{H160, U256};
use sp_std::vec::Vec;
-use pallet_common::account::CrossAccountId;
+use frame_common::account::CrossAccountId;
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
use crate::{
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -20,8 +20,9 @@
use frame_support::{ensure};
use up_data_structs::{AccessMode, CollectionId, TokenId, CreateCollectionData};
use pallet_common::{
- Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
+ Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
};
+use frame_common::account::CrossAccountId;
use pallet_evm_coder_substrate::WithRecorder;
use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -25,6 +25,7 @@
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
+frame-common = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "feature/300" }
[features]
default = ["std"]
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -25,9 +25,9 @@
use sp_core::{H160, U256};
use sp_std::{vec::Vec, vec};
use pallet_common::{
- account::CrossAccountId,
erc::{CommonEvmHandler, PrecompileResult},
};
+use frame_common::account::CrossAccountId;
use pallet_evm_coder_substrate::call;
use crate::{
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -22,8 +22,9 @@
AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
};
use pallet_common::{
- Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,
+ Error as CommonError, Pallet as PalletCommon, Event as CommonEvent,
};
+use frame_common::account::CrossAccountId;
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
pallets/refungible/Cargo.tomldiffbeforeafterboth--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -22,6 +22,7 @@
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
+frame-common = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "feature/300" }
[features]
default = ["std"]
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -22,8 +22,9 @@
CreateCollectionData, CreateRefungibleExData,
};
use pallet_common::{
- Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
+ Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
};
+use frame_common::account::CrossAccountId;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
use core::ops::Deref;
pallets/unique/Cargo.tomldiffbeforeafterboth--- a/pallets/unique/Cargo.toml
+++ b/pallets/unique/Cargo.toml
@@ -132,7 +132,8 @@
sp-api = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" }
up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring", branch = 'polkadot-v0.9.18' }
-up-evm-mapping = { default-features = false, path = "../../primitives/evm-mapping" }
+up-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "feature/300" }
+frame-common = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "feature/300" }
evm-coder = { default-features = false, path = "../../crates/evm-coder" }
pallet-evm-coder-substrate = { default-features = false, path = "../../pallets/evm-coder-substrate" }
primitive-types = { version = "0.11.1", default-features = false, features = [
pallets/unique/src/eth/sponsoring.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/sponsoring.rs
+++ b/pallets/unique/src/eth/sponsoring.rs
@@ -25,8 +25,7 @@
use core::marker::PhantomData;
use core::convert::TryInto;
use up_data_structs::TokenId;
-use up_evm_mapping::EvmBackwardsAddressMapping;
-use pallet_common::account::CrossAccountId;
+use frame_common::account::CrossAccountId;
use pallet_nonfungible::erc::{UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721Call};
use pallet_fungible::erc::{UniqueFungibleCall, ERC20Call};
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -54,9 +54,10 @@
CreateCollectionData, CustomDataLimit, CreateItemExData,
};
use pallet_common::{
- account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
+ CollectionHandle, Pallet as PalletCommon, Error as CommonError,
CommonWeightInfo,
};
+use frame_common::account::CrossAccountId;
use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};
use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};
pallets/unique/src/mock.rsdiffbeforeafterboth--- a/pallets/unique/src/mock.rs
+++ b/pallets/unique/src/mock.rs
@@ -26,7 +26,8 @@
use pallet_transaction_payment::{CurrencyAdapter};
use frame_system as system;
use pallet_evm::{AddressMapping, runner::stack::MaybeMirroredLog};
-use pallet_common::account::{EvmBackwardsAddressMapping, CrossAccountId};
+use up_evm_mapping::EvmBackwardsAddressMapping;
+use frame_common::account::CrossAccountId;
use codec::{Encode, Decode, MaxEncodedLen};
use scale_info::TypeInfo;
use up_data_structs::ConstU32;
pallets/unique/src/sponsorship.rsdiffbeforeafterboth--- a/pallets/unique/src/sponsorship.rs
+++ b/pallets/unique/src/sponsorship.rs
@@ -30,7 +30,7 @@
NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, TokenId,
};
use pallet_common::{CollectionHandle};
-use pallet_common::account::CrossAccountId;
+use frame_common::account::CrossAccountId;
pub fn withdraw_transfer<T: Config>(
collection: &CollectionHandle<T>,
primitives/evm-mapping/Cargo.tomldiffbeforeafterboth--- a/primitives/evm-mapping/Cargo.toml
+++ /dev/null
@@ -1,13 +0,0 @@
-[package]
-name = "up-evm-mapping"
-version = "0.1.0"
-license = "GPLv3"
-edition = "2021"
-
-[dependencies]
-sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.18' }
-frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.18' }
-
-[features]
-default = ["std"]
-std = ["sp-core/std", "frame-support/std"]
primitives/evm-mapping/src/lib.rsdiffbeforeafterboth--- a/primitives/evm-mapping/src/lib.rs
+++ /dev/null
@@ -1,39 +0,0 @@
-// 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/>.
-
-#![cfg_attr(not(feature = "std"), no_std)]
-
-use frame_support::sp_runtime::AccountId32;
-use sp_core::H160;
-
-/// Transforms substrate addresses to ethereum (Reverse of `EvmAddressMapping`)
-/// pallet_evm doesn't have this, as it only checks if eth address
-/// is owned by substrate via `EnsureAddressOrigin` trait
-///
-/// This trait implementations shouldn't conflict with used `EnsureAddressOrigin`
-pub trait EvmBackwardsAddressMapping<AccountId> {
- fn from_account_id(account_id: AccountId) -> H160;
-}
-
-/// Should have same mapping as EnsureAddressTruncated
-pub struct MapBackwardsAddressTruncated;
-impl EvmBackwardsAddressMapping<AccountId32> for MapBackwardsAddressTruncated {
- fn from_account_id(account_id: AccountId32) -> H160 {
- let mut out = [0; 20];
- out.copy_from_slice(&(account_id.as_ref() as &[u8])[0..20]);
- H160(out)
- }
-}
primitives/rpc/Cargo.tomldiffbeforeafterboth--- a/primitives/rpc/Cargo.toml
+++ b/primitives/rpc/Cargo.toml
@@ -14,6 +14,7 @@
sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.18' }
sp-api = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.18' }
sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.18' }
+frame-common = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "feature/300" }
[features]
default = ["std"]
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -28,7 +28,7 @@
#[api_version(2)]
pub trait UniqueApi<CrossAccountId, AccountId> where
AccountId: Decode,
- CrossAccountId: pallet_common::account::CrossAccountId<AccountId>,
+ CrossAccountId: frame_common::account::CrossAccountId<AccountId>,
{
#[changed_in(2)]
fn token_owner(collection: CollectionId, token: TokenId) -> Result<CrossAccountId>;
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -116,11 +116,10 @@
pub const RUNTIME_NAME: &str = "Opal";
-type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;
+type CrossAccountId = frame_common::account::BasicCrossAccountId<Runtime>;
impl RuntimeInstance for Runtime {
type CrossAccountId = self::CrossAccountId;
-
type TransactionConverter = self::TransactionConverter;
fn get_transaction_converter() -> TransactionConverter {
@@ -286,6 +285,11 @@
type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;
}
+impl frame_common::account::Config for Runtime {
+ type EvmAddressMapping = pallet_evm::HashedAddressMapping<Self::Hashing>;
+ type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;
+}
+
pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);
impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {
fn find_author<'a, I>(digests: I) -> Option<H160>
@@ -846,7 +850,7 @@
type Event = Event;
type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;
type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;
- type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;
+ type CrossAccountId = frame_common::account::BasicCrossAccountId<Self>;
type Currency = Balances;
type CollectionCreationPrice = CollectionCreationPrice;
runtime/unique/Cargo.tomldiffbeforeafterboth--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -382,7 +382,6 @@
derivative = "2.2.0"
pallet-unique = { path = '../../pallets/unique', default-features = false }
up-rpc = { path = "../../primitives/rpc", default-features = false }
-up-evm-mapping = { path = "../../primitives/evm-mapping", default-features = false }
pallet-inflation = { path = '../../pallets/inflation', default-features = false }
up-data-structs = { path = '../../primitives/data-structs', default-features = false }
pallet-common = { default-features = false, path = "../../pallets/common" }
@@ -401,6 +400,8 @@
pallet-base-fee = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.18" }
fp-rpc = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.18" }
fp-self-contained = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.18" }
+up-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "feature/300" }
+frame-common = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "feature/300" }
################################################################################
# Build Dependencies