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

difftreelog

chore fix cargo fmt

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

2 files changed

modifiedpallets/refungible/src/erc_token.rsdiffbeforeafterboth
after · pallets/refungible/src/erc_token.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/>.1617//! # Refungible Pallet EVM API for token pieces18//!19//! Provides ERC-20 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;23use core::{24	char::{REPLACEMENT_CHARACTER, decode_utf16},25	convert::TryInto,26	ops::Deref,27};28use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};29use pallet_common::{30	CommonWeightInfo,31	erc::{CommonEvmHandler, PrecompileResult},32};33use pallet_evm::{account::CrossAccountId, PrecompileHandle};34use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};35use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};36use sp_std::vec::Vec;37use up_data_structs::TokenId;3839use crate::{40	Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,41	weights::WeightInfo, TotalSupply,42};4344pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);4546#[derive(ToLog)]47pub enum ERC20Events {48	/// @dev This event is emitted when the amount of tokens (value) is sent49	/// from the from address to the to address. In the case of minting new50	/// tokens, the transfer is usually from the 0 address while in the case51	/// of burning tokens the transfer is to 0.52	Transfer {53		#[indexed]54		from: address,55		#[indexed]56		to: address,57		value: uint256,58	},59	/// @dev This event is emitted when the amount of tokens (value) is approved60	/// by the owner to be used by the spender.61	Approval {62		#[indexed]63		owner: address,64		#[indexed]65		spender: address,66		value: uint256,67	},68}6970/// @title Standard ERC20 token71///72/// @dev Implementation of the basic standard token.73/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md74#[solidity_interface(name = "ERC20", events(ERC20Events))]75impl<T: Config> RefungibleTokenHandle<T> {76	/// @return the name of the token.77	fn name(&self) -> Result<string> {78		Ok(decode_utf16(self.name.iter().copied())79			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))80			.collect::<string>())81	}8283	/// @return the symbol of the token.84	fn symbol(&self) -> Result<string> {85		Ok(string::from_utf8_lossy(&self.token_prefix).into())86	}8788	/// @dev Total number of tokens in existence89	fn total_supply(&self) -> Result<uint256> {90		self.consume_store_reads(1)?;91		Ok(<TotalSupply<T>>::get((self.id, self.1)).into())92	}9394	/// @dev Not supported95	fn decimals(&self) -> Result<uint8> {96		// Decimals aren't supported for refungible tokens97		Ok(0)98	}99100	/// @dev Gets the balance of the specified address.101	/// @param owner The address to query the balance of.102	/// @return An uint256 representing the amount owned by the passed address.103	fn balance_of(&self, owner: address) -> Result<uint256> {104		self.consume_store_reads(1)?;105		let owner = T::CrossAccountId::from_eth(owner);106		let balance = <Balance<T>>::get((self.id, self.1, owner));107		Ok(balance.into())108	}109110	/// @dev Transfer token for a specified address111	/// @param to The address to transfer to.112	/// @param amount The amount to be transferred.113	#[weight(<CommonWeights<T>>::transfer())]114	fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {115		let caller = T::CrossAccountId::from_eth(caller);116		let to = T::CrossAccountId::from_eth(to);117		let amount = amount.try_into().map_err(|_| "amount overflow")?;118		let budget = self119			.recorder120			.weight_calls_budget(<StructureWeight<T>>::find_parent());121122		<Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)123			.map_err(|_| "transfer error")?;124		Ok(true)125	}126127	/// @dev Transfer tokens from one address to another128	/// @param from address The address which you want to send tokens from129	/// @param to address The address which you want to transfer to130	/// @param amount uint256 the amount of tokens to be transferred131	#[weight(<CommonWeights<T>>::transfer_from())]132	fn transfer_from(133		&mut self,134		caller: caller,135		from: address,136		to: address,137		amount: uint256,138	) -> Result<bool> {139		let caller = T::CrossAccountId::from_eth(caller);140		let from = T::CrossAccountId::from_eth(from);141		let to = T::CrossAccountId::from_eth(to);142		let amount = amount.try_into().map_err(|_| "amount overflow")?;143		let budget = self144			.recorder145			.weight_calls_budget(<StructureWeight<T>>::find_parent());146147		<Pallet<T>>::transfer_from(self, &caller, &from, &to, self.1, amount, &budget)148			.map_err(dispatch_to_evm::<T>)?;149		Ok(true)150	}151152	/// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.153	/// Beware that changing an allowance with this method brings the risk that someone may use both the old154	/// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this155	/// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:156	/// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729157	/// @param spender The address which will spend the funds.158	/// @param amount The amount of tokens to be spent.159	#[weight(<SelfWeightOf<T>>::approve())]160	fn approve(&mut self, caller: caller, spender: address, amount: uint256) -> Result<bool> {161		let caller = T::CrossAccountId::from_eth(caller);162		let spender = T::CrossAccountId::from_eth(spender);163		let amount = amount.try_into().map_err(|_| "amount overflow")?;164165		<Pallet<T>>::set_allowance(self, &caller, &spender, self.1, amount)166			.map_err(dispatch_to_evm::<T>)?;167		Ok(true)168	}169170	/// @dev Function to check the amount of tokens that an owner allowed to a spender.171	/// @param owner address The address which owns the funds.172	/// @param spender address The address which will spend the funds.173	/// @return A uint256 specifying the amount of tokens still available for the spender.174	fn allowance(&self, owner: address, spender: address) -> Result<uint256> {175		self.consume_store_reads(1)?;176		let owner = T::CrossAccountId::from_eth(owner);177		let spender = T::CrossAccountId::from_eth(spender);178179		Ok(<Allowance<T>>::get((self.id, self.1, owner, spender)).into())180	}181}182183#[solidity_interface(name = "ERC20UniqueExtensions")]184impl<T: Config> RefungibleTokenHandle<T> {185	/// @dev Function that burns an amount of the token of a given account,186	/// deducting from the sender's allowance for said account.187	/// @param from The account whose tokens will be burnt.188	/// @param amount The amount that will be burnt.189	#[weight(<SelfWeightOf<T>>::burn_from())]190	fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {191		let caller = T::CrossAccountId::from_eth(caller);192		let from = T::CrossAccountId::from_eth(from);193		let amount = amount.try_into().map_err(|_| "amount overflow")?;194		let budget = self195			.recorder196			.weight_calls_budget(<StructureWeight<T>>::find_parent());197198		<Pallet<T>>::burn_from(self, &caller, &from, self.1, amount, &budget)199			.map_err(dispatch_to_evm::<T>)?;200		Ok(true)201	}202203	/// @dev Function that changes total amount of the tokens.204	///  Throws if `msg.sender` doesn't owns all of the tokens.205	/// @param amount New total amount of the tokens.206	#[weight(<SelfWeightOf<T>>::repartition_item())]207	fn repartition(&mut self, caller: caller, amount: uint256) -> Result<bool> {208		let caller = T::CrossAccountId::from_eth(caller);209		let amount = amount.try_into().map_err(|_| "amount overflow")?;210211		<Pallet<T>>::repartition(self, &caller, self.1, amount).map_err(dispatch_to_evm::<T>)?;212		Ok(true)213	}214}215216impl<T: Config> RefungibleTokenHandle<T> {217	pub fn into_inner(self) -> RefungibleHandle<T> {218		self.0219	}220	pub fn common_mut(&mut self) -> &mut RefungibleHandle<T> {221		&mut self.0222	}223}224225impl<T: Config> WithRecorder<T> for RefungibleTokenHandle<T> {226	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {227		self.0.recorder()228	}229	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {230		self.0.into_recorder()231	}232}233234impl<T: Config> Deref for RefungibleTokenHandle<T> {235	type Target = RefungibleHandle<T>;236237	fn deref(&self) -> &Self::Target {238		&self.0239	}240}241242#[solidity_interface(name = "UniqueRefungibleToken", is(ERC20, ERC20UniqueExtensions,))]243impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}244245generate_stubgen!(gen_impl, UniqueRefungibleTokenCall<()>, true);246generate_stubgen!(gen_iface, UniqueRefungibleTokenCall<()>, false);247248impl<T: Config> CommonEvmHandler for RefungibleTokenHandle<T>249where250	T::AccountId: From<[u8; 32]>,251{252	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungibleToken.raw");253254	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {255		call::<T, UniqueRefungibleTokenCall<T>, _, _>(handle, self)256	}257}
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -95,15 +95,19 @@
 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_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 up_data_structs::{
-	AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData, CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId,
-	Property, PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue, TrySetProperty
+	AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData,
+	CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId, Property,
+	PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,
+	TrySetProperty,
 };
 
 pub use pallet::*;