git.delta.rocks / unique-network / refs/commits / d7a4e69fe08d

difftreelog

added erc20 api for refungible tokens

Grigoriy Simonov2022-07-22parent: #5ffdcf0.patch.diff
in: master

7 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6322,11 +6322,14 @@
 name = "pallet-refungible"
 version = "0.1.1"
 dependencies = [
+ "ethereum",
+ "evm-coder",
  "frame-benchmarking",
  "frame-support",
  "frame-system",
  "pallet-common",
  "pallet-evm",
+ "pallet-evm-coder-substrate",
  "pallet-structure",
  "parity-scale-codec 3.1.5",
  "scale-info",
modifiedpallets/refungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -11,36 +11,43 @@
 version = '3.1.2'
 
 [dependencies]
-frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
-frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
-sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
-sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
-sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
-pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.24" }
+evm-coder = { default-features = false, path = '../../crates/evm-coder' }
+pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
 pallet-common = { default-features = false, path = '../common' }
 pallet-structure = { default-features = false, path = '../structure' }
+struct-versioning = { path = "../../crates/struct-versioning" }
 up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
+
+ethereum = { version = "0.12.0", default-features = false }
+scale-info = { version = "2.0.1", default-features = false, features = ["derive",] }
+
 frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
-scale-info = { version = "2.0.1", default-features = false, features = [
-    "derive",
-] }
-struct-versioning = { path = "../../crates/struct-versioning" }
+frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
+frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.24" }
+sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
+sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
+sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
 
 [features]
 default = ["std"]
 std = [
+    "ethereum/std",
+    "evm-coder/std",
+    'frame-benchmarking/std',
     "frame-support/std",
     "frame-system/std",
+    "pallet-common/std",
+    "pallet-evm/std",
+    "pallet-evm-coder-substrate/std",
+    "pallet-structure/std",
     "sp-runtime/std",
     "sp-std/std",
     "up-data-structs/std",
-    "pallet-common/std",
-    "pallet-structure/std",
-    'frame-benchmarking/std',
-    "pallet-evm/std",
 ]
 runtime-benchmarks = [
     'frame-benchmarking',
     'frame-support/runtime-benchmarks',
     'frame-system/runtime-benchmarks',
+    'up-data-structs/runtime-benchmarks',
 ]
deletedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ /dev/null
@@ -1,47 +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 up_data_structs::TokenId;
-use pallet_common::erc::CommonEvmHandler;
-use pallet_evm::PrecompileHandle;
-
-use crate::{Config, RefungibleHandle};
-
-impl<T: Config> CommonEvmHandler for RefungibleHandle<T> {
-	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");
-
-	fn call(
-		self,
-		_handle: &mut impl PrecompileHandle,
-	) -> Option<pallet_common::erc::PrecompileResult> {
-		// TODO: Implement RFT variant of ERC721
-		None
-	}
-}
-
-pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);
-
-impl<T: Config> CommonEvmHandler for RefungibleTokenHandle<T> {
-	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungibleToken.raw");
-
-	fn call(
-		self,
-		_handle: &mut impl PrecompileHandle,
-	) -> Option<pallet_common::erc::PrecompileResult> {
-		// TODO: Implement RFT variant of ERC20
-		None
-	}
-}
addedpallets/refungible/src/erc20.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/refungible/src/erc20.rs
@@ -0,0 +1,204 @@
+// 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/>.
+
+extern crate alloc;
+use core::{
+	char::{REPLACEMENT_CHARACTER, decode_utf16},
+	convert::TryInto,
+	ops::Deref,
+};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
+use pallet_common::{
+	CommonWeightInfo,
+	erc::{CommonEvmHandler, PrecompileResult},
+};
+use pallet_evm::{account::CrossAccountId, PrecompileHandle};
+use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};
+use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
+use sp_std::vec::Vec;
+use up_data_structs::{CollectionMode, TokenId};
+
+use crate::{
+	Allowance, Balance, common::CommonWeights, Config, erc721::UniqueRFTCall, Pallet,
+	RefungibleHandle, SelfWeightOf, weights::WeightInfo, TotalSupply,
+};
+
+pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);
+
+#[derive(ToLog)]
+pub enum ERC20Events {
+	Transfer {
+		#[indexed]
+		from: address,
+		#[indexed]
+		to: address,
+		value: uint256,
+	},
+	Approval {
+		#[indexed]
+		owner: address,
+		#[indexed]
+		spender: address,
+		value: uint256,
+	},
+}
+
+#[solidity_interface(name = "ERC20", events(ERC20Events))]
+impl<T: Config> RefungibleTokenHandle<T> {
+	fn name(&self) -> Result<string> {
+		Ok(decode_utf16(self.name.iter().copied())
+			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
+			.collect::<string>())
+	}
+	fn symbol(&self) -> Result<string> {
+		Ok(string::from_utf8_lossy(&self.token_prefix).into())
+	}
+	fn total_supply(&self) -> Result<uint256> {
+		self.consume_store_reads(1)?;
+		Ok(<TotalSupply<T>>::get((self.id, self.1)).into())
+	}
+
+	fn decimals(&self) -> Result<uint8> {
+		Ok(if let CollectionMode::Fungible(decimals) = &self.mode {
+			*decimals
+		} else {
+			unreachable!()
+		})
+	}
+	fn balance_of(&self, owner: address) -> Result<uint256> {
+		self.consume_store_reads(1)?;
+		let owner = T::CrossAccountId::from_eth(owner);
+		let balance = <Balance<T>>::get((self.id, self.1, owner));
+		Ok(balance.into())
+	}
+	#[weight(<CommonWeights<T>>::transfer())]
+	fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		let to = T::CrossAccountId::from_eth(to);
+		let amount = amount.try_into().map_err(|_| "amount overflow")?;
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+		<Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)
+			.map_err(|_| "transfer error")?;
+		Ok(true)
+	}
+	#[weight(<CommonWeights<T>>::transfer_from())]
+	fn transfer_from(
+		&mut self,
+		caller: caller,
+		from: address,
+		to: address,
+		amount: uint256,
+	) -> Result<bool> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		let from = T::CrossAccountId::from_eth(from);
+		let to = T::CrossAccountId::from_eth(to);
+		let amount = amount.try_into().map_err(|_| "amount overflow")?;
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+		<Pallet<T>>::transfer_from(self, &caller, &from, &to, self.1, amount, &budget)
+			.map_err(dispatch_to_evm::<T>)?;
+		Ok(true)
+	}
+	#[weight(<SelfWeightOf<T>>::approve())]
+	fn approve(&mut self, caller: caller, spender: address, amount: uint256) -> Result<bool> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		let spender = T::CrossAccountId::from_eth(spender);
+		let amount = amount.try_into().map_err(|_| "amount overflow")?;
+
+		<Pallet<T>>::set_allowance(self, &caller, &spender, self.1, amount)
+			.map_err(dispatch_to_evm::<T>)?;
+		Ok(true)
+	}
+	fn allowance(&self, owner: address, spender: address) -> Result<uint256> {
+		self.consume_store_reads(1)?;
+		let owner = T::CrossAccountId::from_eth(owner);
+		let spender = T::CrossAccountId::from_eth(spender);
+
+		Ok(<Allowance<T>>::get((self.id, self.1, owner, spender)).into())
+	}
+}
+
+#[solidity_interface(name = "ERC20UniqueExtensions")]
+impl<T: Config> RefungibleTokenHandle<T> {
+	#[weight(<SelfWeightOf<T>>::burn_from())]
+	fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		let from = T::CrossAccountId::from_eth(from);
+		let amount = amount.try_into().map_err(|_| "amount overflow")?;
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+		<Pallet<T>>::burn_from(self, &caller, &from, self.1, amount, &budget)
+			.map_err(dispatch_to_evm::<T>)?;
+		Ok(true)
+	}
+}
+
+impl<T: Config> RefungibleTokenHandle<T> {
+	pub fn into_inner(self) -> RefungibleHandle<T> {
+		self.0
+	}
+	pub fn common_mut(&mut self) -> &mut RefungibleHandle<T> {
+		&mut self.0
+	}
+}
+
+impl<T: Config> WithRecorder<T> for RefungibleTokenHandle<T> {
+	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {
+		self.0.recorder()
+	}
+	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {
+		self.0.into_recorder()
+	}
+}
+
+impl<T: Config> Deref for RefungibleTokenHandle<T> {
+	type Target = RefungibleHandle<T>;
+
+	fn deref(&self) -> &Self::Target {
+		&self.0
+	}
+}
+
+#[solidity_interface(
+	name = "UniqueRefungibleToken",
+	is(
+		ERC20,
+		ERC20UniqueExtensions,
+		via("RefungibleHandle<T>", common_mut, UniqueRFT)
+	)
+)]
+impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}
+
+generate_stubgen!(gen_impl, UniqueRefungibleTokenCall<()>, true);
+generate_stubgen!(gen_iface, UniqueRefungibleTokenCall<()>, false);
+
+impl<T: Config> CommonEvmHandler for RefungibleTokenHandle<T>
+where
+	T::AccountId: From<[u8; 32]>,
+{
+	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungibleToken.raw");
+
+	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {
+		call::<T, UniqueRefungibleTokenCall<T>, _, _>(handle, self)
+	}
+}
addedpallets/refungible/src/erc721.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/refungible/src/erc721.rs
@@ -0,0 +1,32 @@
+extern crate alloc;
+use evm_coder::{generate_stubgen, solidity_interface, types::*};
+
+use pallet_common::{CollectionHandle, erc::CollectionCall, erc::CommonEvmHandler};
+
+use pallet_evm::PrecompileHandle;
+use pallet_evm_coder_substrate::call;
+
+use crate::{Config, RefungibleHandle};
+
+#[solidity_interface(
+	name = "UniqueRFT",
+	is(via("CollectionHandle<T>", common_mut, Collection),)
+)]
+impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> {}
+
+// Not a tests, but code generators
+generate_stubgen!(gen_impl, UniqueRFTCall<()>, true);
+generate_stubgen!(gen_iface, UniqueRFTCall<()>, false);
+
+impl<T: Config> CommonEvmHandler for RefungibleHandle<T>
+where
+	T::AccountId: From<[u8; 32]>,
+{
+	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");
+	fn call(
+		self,
+		handle: &mut impl PrecompileHandle,
+	) -> Option<pallet_common::erc::PrecompileResult> {
+		call::<T, UniqueRFTCall<T>, _, _>(handle, self)
+	}
+}
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -87,30 +87,31 @@
 
 #![cfg_attr(not(feature = "std"), no_std)]
 
-use frame_support::{ensure, fail, BoundedVec, transactional, storage::with_transaction};
-use up_data_structs::{
-	AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,
-	CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping, budget::Budget,
-	Property, PropertyScope, TrySetProperty, PropertyKey, PropertyValue, PropertyPermission,
-	PropertyKeyPermission,
-};
-use pallet_evm::account::CrossAccountId;
-use pallet_common::{
-	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
-	CommonCollectionOperations as _,
-};
+use crate::erc20::ERC20Events;
+
+use codec::{Encode, Decode, MaxEncodedLen};
+use core::ops::Deref;
+use evm_coder::ToLog;
+use frame_support::{BoundedVec, ensure, fail, storage::with_transaction, transactional};
+use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
+use pallet_evm_coder_substrate::WithRecorder;
+use pallet_common::{CommonCollectionOperations, Error as CommonError, Event as CommonEvent, Pallet as PalletCommon};
 use pallet_structure::Pallet as PalletStructure;
+use scale_info::TypeInfo;
+use sp_core::H160;
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
 use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
-use core::ops::Deref;
-use codec::{Encode, Decode, MaxEncodedLen};
-use scale_info::TypeInfo;
+use up_data_structs::{
+	AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData, CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId,
+	Property, PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue, TrySetProperty
+};
 
 pub use pallet::*;
 #[cfg(feature = "runtime-benchmarks")]
 pub mod benchmarking;
 pub mod common;
-pub mod erc;
+pub mod erc20;
+pub mod erc721;
 pub mod weights;
 pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
 
@@ -271,7 +272,11 @@
 	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {
 		self.0
 	}
+	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {
+		&mut self.0
+	}
 }
+
 impl<T: Config> Deref for RefungibleHandle<T> {
 	type Target = pallet_common::CollectionHandle<T>;
 
@@ -280,6 +285,15 @@
 	}
 }
 
+impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {
+	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {
+		self.0.recorder()
+	}
+	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {
+		self.0.into_recorder()
+	}
+}
+
 impl<T: Config> Pallet<T> {
 	/// Get number of RFT tokens in collection
 	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {
@@ -460,7 +474,18 @@
 			<Balance<T>>::insert((collection.id, token, owner), balance);
 		}
 		<TotalSupply<T>>::insert((collection.id, token), total_supply);
-		// TODO: ERC20 transfer event
+
+		<PalletEvm<T>>::deposit_log(
+			ERC20Events::Transfer {
+				from: *owner.as_eth(),
+				to: H160::default(),
+				value: amount.into(),
+			}
+			.to_log(T::EvmTokenAddressMapping::token_to_address(
+				collection.id,
+				token,
+			)),
+		);
 		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
 			collection.id,
 			token,
@@ -736,7 +761,17 @@
 			}
 		}
 
-		// TODO: ERC20 transfer event
+		<PalletEvm<T>>::deposit_log(
+			ERC20Events::Transfer {
+				from: *from.as_eth(),
+				to: *to.as_eth(),
+				value: amount.into(),
+			}
+			.to_log(T::EvmTokenAddressMapping::token_to_address(
+				collection.id,
+				token,
+			)),
+		);
 		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(
 			collection.id,
 			token,
@@ -889,7 +924,17 @@
 					continue;
 				}
 
-				// TODO: ERC20 transfer event
+				<PalletEvm<T>>::deposit_log(
+					ERC20Events::Transfer {
+						from: H160::default(),
+						to: *user.as_eth(),
+						value: amount.into(),
+					}
+					.to_log(T::EvmTokenAddressMapping::token_to_address(
+						collection.id,
+						TokenId(token_id),
+					)),
+				);
 				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
 					collection.id,
 					TokenId(token_id),
@@ -913,7 +958,18 @@
 		} else {
 			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);
 		}
-		// TODO: ERC20 approval event
+
+		<PalletEvm<T>>::deposit_log(
+			ERC20Events::Approval {
+				owner: *sender.as_eth(),
+				spender: *spender.as_eth(),
+				value: amount.into(),
+			}
+			.to_log(T::EvmTokenAddressMapping::token_to_address(
+				collection.id,
+				token,
+			)),
+		);
 		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(
 			collection.id,
 			token,
modifiedruntime/common/src/dispatch.rsdiffbeforeafterboth
before · runtime/common/src/dispatch.rs
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/>.1617use frame_support::{dispatch::DispatchResult, ensure};18use pallet_evm::{PrecompileHandle, PrecompileResult};19use sp_core::H160;20use sp_std::{borrow::ToOwned, vec::Vec};21use pallet_common::{22	CollectionById, CollectionHandle, CommonCollectionOperations, erc::CommonEvmHandler,23	eth::map_eth_to_id,24};25pub use pallet_common::dispatch::CollectionDispatch;26use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};27use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};28use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle, erc::RefungibleTokenHandle};29use up_data_structs::{30	CollectionMode, CreateCollectionData, MAX_DECIMAL_POINTS, mapping::TokenAddressMapping,31};3233pub enum CollectionDispatchT<T>34where35	T: pallet_fungible::Config + pallet_nonfungible::Config + pallet_refungible::Config,36{37	Fungible(FungibleHandle<T>),38	Nonfungible(NonfungibleHandle<T>),39	Refungible(RefungibleHandle<T>),40}41impl<T> CollectionDispatch<T> for CollectionDispatchT<T>42where43	T: pallet_common::Config44		+ pallet_unique::Config45		+ pallet_fungible::Config46		+ pallet_nonfungible::Config47		+ pallet_refungible::Config,48{49	fn create(50		sender: T::CrossAccountId,51		data: CreateCollectionData<T::AccountId>,52	) -> DispatchResult {53		let _id = match data.mode {54			CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, data, false)?,55			CollectionMode::Fungible(decimal_points) => {56				// check params57				ensure!(58					decimal_points <= MAX_DECIMAL_POINTS,59					pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded60				);61				<PalletFungible<T>>::init_collection(sender, data)?62			}63			CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, data)?,64		};65		Ok(())66	}6768	fn destroy(sender: T::CrossAccountId, collection: CollectionHandle<T>) -> DispatchResult {69		match collection.mode {70			CollectionMode::ReFungible => {71				PalletRefungible::destroy_collection(RefungibleHandle::cast(collection), &sender)?72			}73			CollectionMode::Fungible(_) => {74				PalletFungible::destroy_collection(FungibleHandle::cast(collection), &sender)?75			}76			CollectionMode::NFT => {77				PalletNonfungible::destroy_collection(NonfungibleHandle::cast(collection), &sender)?78			}79		}80		Ok(())81	}8283	fn dispatch(handle: CollectionHandle<T>) -> Self {84		match handle.mode {85			CollectionMode::Fungible(_) => Self::Fungible(FungibleHandle::cast(handle)),86			CollectionMode::NFT => Self::Nonfungible(NonfungibleHandle::cast(handle)),87			CollectionMode::ReFungible => Self::Refungible(RefungibleHandle::cast(handle)),88		}89	}9091	fn into_inner(self) -> CollectionHandle<T> {92		match self {93			Self::Fungible(f) => f.into_inner(),94			Self::Nonfungible(f) => f.into_inner(),95			Self::Refungible(f) => f.into_inner(),96		}97	}9899	fn as_dyn(&self) -> &dyn CommonCollectionOperations<T> {100		match self {101			Self::Fungible(h) => h,102			Self::Nonfungible(h) => h,103			Self::Refungible(h) => h,104		}105	}106}107108impl<T> pallet_evm::OnMethodCall<T> for CollectionDispatchT<T>109where110	T: pallet_common::Config111		+ pallet_unique::Config112		+ pallet_fungible::Config113		+ pallet_nonfungible::Config114		+ pallet_refungible::Config,115	T::AccountId: From<[u8; 32]>,116{117	fn is_reserved(target: &H160) -> bool {118		map_eth_to_id(target).is_some()119	}120	fn is_used(target: &H160) -> bool {121		map_eth_to_id(target)122			.map(<CollectionById<T>>::contains_key)123			.unwrap_or(false)124	}125	fn get_code(target: &H160) -> Option<Vec<u8>> {126		if let Some(collection_id) = map_eth_to_id(target) {127			let collection = <CollectionById<T>>::get(collection_id)?;128			Some(129				match collection.mode {130					CollectionMode::NFT => <NonfungibleHandle<T>>::CODE,131					CollectionMode::Fungible(_) => <FungibleHandle<T>>::CODE,132					CollectionMode::ReFungible => <RefungibleHandle<T>>::CODE,133				}134				.to_owned(),135			)136		} else if let Some((collection_id, _token_id)) =137			<T as pallet_common::Config>::EvmTokenAddressMapping::address_to_token(target)138		{139			let collection = <CollectionById<T>>::get(collection_id)?;140			if collection.mode != CollectionMode::ReFungible {141				return None;142			}143			// TODO: check token existence144			Some(<RefungibleTokenHandle<T>>::CODE.to_owned())145		} else {146			None147		}148	}149	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {150		if let Some(collection_id) = map_eth_to_id(&handle.code_address()) {151			let collection =152				<CollectionHandle<T>>::new_with_gas_limit(collection_id, handle.remaining_gas())?;153			let dispatched = Self::dispatch(collection);154155			match dispatched {156				Self::Fungible(h) => h.call(handle),157				Self::Nonfungible(h) => h.call(handle),158				Self::Refungible(h) => h.call(handle),159			}160		} else if let Some((collection_id, token_id)) =161			<T as pallet_common::Config>::EvmTokenAddressMapping::address_to_token(162				&handle.code_address(),163			) {164			let collection =165				<CollectionHandle<T>>::new_with_gas_limit(collection_id, handle.remaining_gas())?;166			if collection.mode != CollectionMode::ReFungible {167				return None;168			}169170			let h = RefungibleHandle::cast(collection);171			// TODO: check token existence172			RefungibleTokenHandle(h, token_id).call(handle)173		} else {174			None175		}176	}177}
after · runtime/common/src/dispatch.rs
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/>.1617use frame_support::{dispatch::DispatchResult, ensure};18use pallet_evm::{PrecompileHandle, PrecompileResult};19use sp_core::H160;20use sp_std::{borrow::ToOwned, vec::Vec};21use pallet_common::{22	CollectionById, CollectionHandle, CommonCollectionOperations, erc::CommonEvmHandler,23	eth::map_eth_to_id,24};25pub use pallet_common::dispatch::CollectionDispatch;26use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};27use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};28use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle, erc20::RefungibleTokenHandle};29use up_data_structs::{30	CollectionMode, CreateCollectionData, MAX_DECIMAL_POINTS, mapping::TokenAddressMapping,31};3233pub enum CollectionDispatchT<T>34where35	T: pallet_fungible::Config + pallet_nonfungible::Config + pallet_refungible::Config,36{37	Fungible(FungibleHandle<T>),38	Nonfungible(NonfungibleHandle<T>),39	Refungible(RefungibleHandle<T>),40}41impl<T> CollectionDispatch<T> for CollectionDispatchT<T>42where43	T: pallet_common::Config44		+ pallet_unique::Config45		+ pallet_fungible::Config46		+ pallet_nonfungible::Config47		+ pallet_refungible::Config,48{49	fn create(50		sender: T::CrossAccountId,51		data: CreateCollectionData<T::AccountId>,52	) -> DispatchResult {53		let _id = match data.mode {54			CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, data, false)?,55			CollectionMode::Fungible(decimal_points) => {56				// check params57				ensure!(58					decimal_points <= MAX_DECIMAL_POINTS,59					pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded60				);61				<PalletFungible<T>>::init_collection(sender, data)?62			}63			CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, data)?,64		};65		Ok(())66	}6768	fn destroy(sender: T::CrossAccountId, collection: CollectionHandle<T>) -> DispatchResult {69		match collection.mode {70			CollectionMode::ReFungible => {71				PalletRefungible::destroy_collection(RefungibleHandle::cast(collection), &sender)?72			}73			CollectionMode::Fungible(_) => {74				PalletFungible::destroy_collection(FungibleHandle::cast(collection), &sender)?75			}76			CollectionMode::NFT => {77				PalletNonfungible::destroy_collection(NonfungibleHandle::cast(collection), &sender)?78			}79		}80		Ok(())81	}8283	fn dispatch(handle: CollectionHandle<T>) -> Self {84		match handle.mode {85			CollectionMode::Fungible(_) => Self::Fungible(FungibleHandle::cast(handle)),86			CollectionMode::NFT => Self::Nonfungible(NonfungibleHandle::cast(handle)),87			CollectionMode::ReFungible => Self::Refungible(RefungibleHandle::cast(handle)),88		}89	}9091	fn into_inner(self) -> CollectionHandle<T> {92		match self {93			Self::Fungible(f) => f.into_inner(),94			Self::Nonfungible(f) => f.into_inner(),95			Self::Refungible(f) => f.into_inner(),96		}97	}9899	fn as_dyn(&self) -> &dyn CommonCollectionOperations<T> {100		match self {101			Self::Fungible(h) => h,102			Self::Nonfungible(h) => h,103			Self::Refungible(h) => h,104		}105	}106}107108impl<T> pallet_evm::OnMethodCall<T> for CollectionDispatchT<T>109where110	T: pallet_common::Config111		+ pallet_unique::Config112		+ pallet_fungible::Config113		+ pallet_nonfungible::Config114		+ pallet_refungible::Config,115	T::AccountId: From<[u8; 32]>,116{117	fn is_reserved(target: &H160) -> bool {118		map_eth_to_id(target).is_some()119	}120	fn is_used(target: &H160) -> bool {121		map_eth_to_id(target)122			.map(<CollectionById<T>>::contains_key)123			.unwrap_or(false)124	}125	fn get_code(target: &H160) -> Option<Vec<u8>> {126		if let Some(collection_id) = map_eth_to_id(target) {127			let collection = <CollectionById<T>>::get(collection_id)?;128			Some(129				match collection.mode {130					CollectionMode::NFT => <NonfungibleHandle<T>>::CODE,131					CollectionMode::Fungible(_) => <FungibleHandle<T>>::CODE,132					CollectionMode::ReFungible => <RefungibleHandle<T>>::CODE,133				}134				.to_owned(),135			)136		} else if let Some((collection_id, _token_id)) =137			<T as pallet_common::Config>::EvmTokenAddressMapping::address_to_token(target)138		{139			let collection = <CollectionById<T>>::get(collection_id)?;140			if collection.mode != CollectionMode::ReFungible {141				return None;142			}143			// TODO: check token existence144			Some(<RefungibleTokenHandle<T>>::CODE.to_owned())145		} else {146			None147		}148	}149	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {150		if let Some(collection_id) = map_eth_to_id(&handle.code_address()) {151			let collection =152				<CollectionHandle<T>>::new_with_gas_limit(collection_id, handle.remaining_gas())?;153			let dispatched = Self::dispatch(collection);154155			match dispatched {156				Self::Fungible(h) => h.call(handle),157				Self::Nonfungible(h) => h.call(handle),158				Self::Refungible(h) => h.call(handle),159			}160		} else if let Some((collection_id, token_id)) =161			<T as pallet_common::Config>::EvmTokenAddressMapping::address_to_token(162				&handle.code_address(),163			) {164			let collection =165				<CollectionHandle<T>>::new_with_gas_limit(collection_id, handle.remaining_gas())?;166			if collection.mode != CollectionMode::ReFungible {167				return None;168			}169170			let h = RefungibleHandle::cast(collection);171			// TODO: check token existence172			RefungibleTokenHandle(h, token_id).call(handle)173		} else {174			None175		}176	}177}