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

difftreelog

feat add nesting

Trubnikov Sergey2023-05-05parent: #3293186.patch.diff
in: master

5 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6264,9 +6264,11 @@
  "pallet-evm",
  "pallet-evm-coder-substrate",
  "pallet-evm-transaction-payment",
+ "pallet-structure",
  "parity-scale-codec",
  "scale-info",
  "sp-core",
+ "sp-runtime",
  "sp-std",
  "up-data-structs",
 ]
modifiedpallets/balances-adapter/Cargo.tomldiffbeforeafterboth
--- a/pallets/balances-adapter/Cargo.toml
+++ b/pallets/balances-adapter/Cargo.toml
@@ -9,7 +9,9 @@
 frame-support = { workspace = true }
 frame-system = { workspace = true }
 pallet-balances = { workspace = true }
+pallet-structure = { workspace = true }
 sp-core = { workspace = true }
+sp-runtime = { workspace = true }
 sp-std = { workspace = true }
 
 #Parity
modifiedpallets/balances-adapter/src/common.rsdiffbeforeafterboth
1use alloc::{vec, vec::Vec};1use alloc::{vec, vec::Vec};
2use core::marker::PhantomData;2use core::marker::PhantomData;
3use crate::{Config, NativeFungibleHandle};3use crate::{Config, NativeFungibleHandle, Pallet};
4use frame_support::{4use frame_support::{fail, traits::Currency, weights::Weight};
5 fail,
6 traits::{Currency, ExistenceRequirement},
7 weights::Weight,
8};
9use pallet_balances::{weights::SubstrateWeight as BalancesWeight, WeightInfo};5use pallet_balances::{weights::SubstrateWeight as BalancesWeight, WeightInfo};
10use pallet_common::{erc::CrossAccountId, CommonCollectionOperations, CommonWeightInfo, with_weight};6use pallet_common::{erc::CrossAccountId, CommonCollectionOperations, CommonWeightInfo};
11use up_data_structs::TokenId;7use up_data_structs::TokenId;
128
13pub struct CommonWeights<T: Config>(PhantomData<T>);9pub struct CommonWeights<T: Config>(PhantomData<T>);
188 to: <T>::CrossAccountId,184 to: <T>::CrossAccountId,
189 _token: TokenId,185 _token: TokenId,
190 amount: u128,186 amount: u128,
191 _budget: &dyn up_data_structs::budget::Budget,187 budget: &dyn up_data_structs::budget::Budget,
192 ) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {188 ) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
193 with_weight(
194 <T as Config>::Currency::transfer(189 <Pallet<T>>::transfer(self, &sender, &to, amount, budget)
195 sender.as_sub(),
196 to.as_sub(),
197 amount.into(),
198 ExistenceRequirement::KeepAlive,
199 ),
200 Default::default(),
201 )
202 }190 }
203191
204 fn approve(192 fn approve(
229 to: <T>::CrossAccountId,217 to: <T>::CrossAccountId,
230 _token: TokenId,218 _token: TokenId,
231 amount: u128,219 amount: u128,
232 _budget: &dyn up_data_structs::budget::Budget,220 budget: &dyn up_data_structs::budget::Budget,
233 ) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {221 ) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
234 if sender != from {
235 fail!(<pallet_common::Error<T>>::NoPermission);
236 }
237 with_weight(
238 <T as Config>::Currency::transfer(222 <Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, budget)
239 from.as_sub(),
240 to.as_sub(),
241 amount.into(),
242 ExistenceRequirement::KeepAlive,
243 ),
244 Default::default(),
245 )
246 }223 }
247224
248 fn burn_from(225 fn burn_from(
modifiedpallets/balances-adapter/src/erc.rsdiffbeforeafterboth
--- a/pallets/balances-adapter/src/erc.rs
+++ b/pallets/balances-adapter/src/erc.rs
@@ -1,4 +1,4 @@
-use crate::{Config, NativeFungibleHandle, SelfWeightOf};
+use crate::{Config, NativeFungibleHandle, Pallet, SelfWeightOf};
 use evm_coder::{abi::AbiType, ToLog, generate_stubgen, solidity_interface, types::*};
 use frame_support::traits::{Currency, ExistenceRequirement};
 use pallet_balances::WeightInfo;
@@ -10,8 +10,9 @@
 use pallet_evm_coder_substrate::{
 	call, dispatch_to_evm,
 	execution::{PreDispatch, Result},
-	frontier_contract,
+	frontier_contract, WithRecorder,
 };
+use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
 use sp_core::{U256, Get};
 use sp_std::vec::Vec;
 
@@ -73,18 +74,12 @@
 		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());
+		let budget = self
+			.recorder()
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		// <Pallet<T>>::transfer(self, &caller, &to, amount, &budget).map_err(|_| "transfer error")?;
-		<T as Config>::Currency::transfer(
-			caller.as_sub(),
-			to.as_sub(),
-			amount,
-			ExistenceRequirement::KeepAlive,
-		)
-		.map_err(dispatch_to_evm::<T>)?;
+		<Pallet<T>>::transfer(self, &caller, &to, amount, &budget)
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
 		Ok(true)
 	}
 
@@ -100,23 +95,12 @@
 		let from = T::CrossAccountId::from_eth(from);
 		let to = T::CrossAccountId::from_eth(to);
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
-
-		if from != caller {
-			return Err("no permission".into());
-		}
-		// let budget = self
-		// 	.recorder
-		// 	.weight_calls_budget(<StructureWeight<T>>::find_parent());
+		let budget = self
+			.recorder()
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		// <Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)
-		// 	.map_err(dispatch_to_evm::<T>)?;
-		<T as Config>::Currency::transfer(
-			caller.as_sub(),
-			to.as_sub(),
-			amount,
-			ExistenceRequirement::KeepAlive,
-		)
-		.map_err(dispatch_to_evm::<T>)?;
+		<Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
 		Ok(true)
 	}
 }
modifiedpallets/balances-adapter/src/lib.rsdiffbeforeafterboth
--- a/pallets/balances-adapter/src/lib.rs
+++ b/pallets/balances-adapter/src/lib.rs
@@ -5,14 +5,17 @@
 use core::ops::Deref;
 
 use frame_support::sp_runtime::DispatchResult;
+use pallet_evm_coder_substrate::{WithRecorder, SubstrateRecorder};
 pub use pallet::*;
-use pallet_evm_coder_substrate::{WithRecorder, SubstrateRecorder};
 
 pub mod common;
 pub mod erc;
 
 pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
 
+const NATIVE_FUNGIBLE_COLLECTION_ID: up_data_structs::CollectionId =
+	up_data_structs::CollectionId(0);
+
 /// Handle for native fungible collection
 pub struct NativeFungibleHandle<T: Config>(SubstrateRecorder<T>);
 impl<T: Config> NativeFungibleHandle<T> {
@@ -45,14 +48,27 @@
 }
 #[frame_support::pallet]
 pub mod pallet {
+	use super::*;
 	use alloc::string::String;
-	use frame_support::{traits::Get};
+	use frame_support::{
+		dispatch::PostDispatchInfo,
+		ensure,
+		pallet_prelude::{DispatchResultWithPostInfo, Pays},
+		traits::{Currency, ExistenceRequirement, Get},
+	};
 	use pallet_balances::WeightInfo;
+	use pallet_common::{erc::CrossAccountId, Error as CommonError, Pallet as PalletCommon};
+	use pallet_structure::Pallet as PalletStructure;
 	use sp_core::U256;
+	use sp_runtime::DispatchError;
+	use up_data_structs::{budget::Budget, mapping::TokenAddressMapping, TokenId};
 
 	#[pallet::config]
 	pub trait Config:
-		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_common::Config
+		frame_system::Config
+		+ pallet_evm_coder_substrate::Config
+		+ pallet_common::Config
+		+ pallet_structure::Config
 	{
 		/// Currency from `pallet_balances`
 		type Currency: frame_support::traits::Currency<
@@ -74,4 +90,104 @@
 	}
 	#[pallet::pallet]
 	pub struct Pallet<T>(_);
+
+	impl<T: Config> Pallet<T> {
+		/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.
+		/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.
+		///
+		/// - `collection`: Collection that contains the token.
+		/// - `spender`: CrossAccountId who has the allowance rights.
+		/// - `from`: The owner of the tokens who sets the allowance.
+		/// - `amount`: Amount of tokens by which the allowance sholud be reduced.
+		fn check_allowed(
+			spender: &T::CrossAccountId,
+			from: &T::CrossAccountId,
+			nesting_budget: &dyn Budget,
+		) -> Result<u128, DispatchError> {
+			if spender.conv_eq(from) {
+				return Ok(0);
+			}
+
+			if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
+				ensure!(
+					<PalletStructure<T>>::check_indirectly_owned(
+						spender.clone(),
+						source.0,
+						source.1,
+						None,
+						nesting_budget
+					)?,
+					<CommonError<T>>::ApprovedValueTooLow,
+				);
+			} else if spender != from {
+				return Ok(0);
+			}
+
+			Ok(<T as Config>::Currency::free_balance(from.as_sub()).into())
+		}
+
+		/// Transfers the specified amount of tokens. Will check that
+		/// the transfer is allowed for the token.
+		///
+		/// - `from`: Owner of tokens to transfer.
+		/// - `to`: Recepient of transfered tokens.
+		/// - `amount`: Amount of tokens to transfer.
+		/// - `collection`: Collection that contains the token
+		pub fn transfer(
+			_collection: &NativeFungibleHandle<T>,
+			from: &T::CrossAccountId,
+			to: &T::CrossAccountId,
+			amount: u128,
+			nesting_budget: &dyn Budget,
+		) -> DispatchResultWithPostInfo {
+			<PalletCommon<T>>::ensure_correct_receiver(to)?;
+
+			if from != to && amount != 0 {
+				<T as Config>::Currency::transfer(
+					from.as_sub(),
+					to.as_sub(),
+					amount.into(),
+					ExistenceRequirement::KeepAlive,
+				)?;
+
+				<PalletStructure<T>>::nest_if_sent_to_token(
+					from.clone(),
+					to,
+					NATIVE_FUNGIBLE_COLLECTION_ID,
+					TokenId::default(),
+					nesting_budget,
+				)?;
+
+				let balance_from: u128 =
+					<T as Config>::Currency::free_balance(from.as_sub()).into();
+				if balance_from == 0 {
+					<PalletStructure<T>>::unnest_if_nested(
+						from,
+						NATIVE_FUNGIBLE_COLLECTION_ID,
+						TokenId::default(),
+					);
+				}
+			};
+
+			Ok(PostDispatchInfo {
+				actual_weight: Some(<SelfWeightOf<T>>::transfer()),
+				pays_fee: Pays::Yes,
+			})
+		}
+
+		pub fn transfer_from(
+			collection: &NativeFungibleHandle<T>,
+			spender: &T::CrossAccountId,
+			from: &T::CrossAccountId,
+			to: &T::CrossAccountId,
+			amount: u128,
+			nesting_budget: &dyn Budget,
+		) -> DispatchResultWithPostInfo {
+			let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;
+			if allowance < amount {
+				return Err(<CommonError<T>>::ApprovedValueTooLow.into());
+			}
+			Self::transfer(collection, from, to, amount, nesting_budget)
+		}
+	}
 }