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

difftreelog

source

pallets/refungible/src/erc_token.rs14.2 KiBsourcehistory
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.2122use core::{23	char::{REPLACEMENT_CHARACTER, decode_utf16},24	convert::TryInto,25	ops::Deref,26};27use evm_coder::{abi::AbiType, ToLog, generate_stubgen, solidity_interface, types::*};28use pallet_common::{29	erc::{CommonEvmHandler, PrecompileResult},30	eth::{collection_id_to_address, CrossAddress},31	CommonWeightInfo,32};33use pallet_evm::{account::CrossAccountId, PrecompileHandle};34use pallet_evm_coder_substrate::{35	call, dispatch_to_evm, WithRecorder, frontier_contract,36	execution::{Result, PreDispatch},37};38use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};39use sp_std::vec::Vec;40use sp_core::U256;41use up_data_structs::TokenId;4243use crate::{44	Allowance, Balance, Config, Pallet, RefungibleHandle, TotalSupply, common::CommonWeights,45	SelfWeightOf, weights::WeightInfo,46};4748/// Refungible token handle contains information about token's collection and id49///50/// RefungibleTokenHandle doesn't check token's existance upon creation51pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);5253frontier_contract! {54	macro_rules! RefungibleTokenHandle_result {...}55	impl<T: Config> Contract for RefungibleTokenHandle<T> {...}56}5758#[solidity_interface(name = ERC1633, enum(derive(PreDispatch)), enum_attr(weight))]59impl<T: Config> RefungibleTokenHandle<T> {60	fn parent_token(&self) -> Address {61		collection_id_to_address(self.id)62	}6364	fn parent_token_id(&self) -> U256 {65		self.1.into()66	}67}6869#[derive(ToLog)]70pub enum ERC20Events {71	/// @dev This event is emitted when the amount of tokens (value) is sent72	/// from the from address to the to address. In the case of minting new73	/// tokens, the transfer is usually from the 0 address while in the case74	/// of burning tokens the transfer is to 0.75	Transfer {76		#[indexed]77		from: Address,78		#[indexed]79		to: Address,80		value: U256,81	},82	/// @dev This event is emitted when the amount of tokens (value) is approved83	/// by the owner to be used by the spender.84	Approval {85		#[indexed]86		owner: Address,87		#[indexed]88		spender: Address,89		value: U256,90	},91}9293/// @title Standard ERC20 token94///95/// @dev Implementation of the basic standard token.96/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md97#[solidity_interface(name = ERC20, events(ERC20Events), enum(derive(PreDispatch)), enum_attr(weight))]98impl<T: Config> RefungibleTokenHandle<T> {99	/// @return the name of the token.100	fn name(&self) -> String {101		decode_utf16(self.name.iter().copied())102			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))103			.collect::<String>()104	}105106	/// @return the symbol of the token.107	fn symbol(&self) -> String {108		String::from_utf8_lossy(&self.token_prefix).into()109	}110111	/// @dev Total number of tokens in existence112	fn total_supply(&self) -> Result<U256> {113		self.consume_store_reads(1)?;114		Ok(<TotalSupply<T>>::get((self.id, self.1)).into())115	}116117	/// @dev Not supported118	fn decimals(&self) -> Result<u8> {119		// Decimals aren't supported for refungible tokens120		Ok(0)121	}122123	/// @dev Gets the balance of the specified address.124	/// @param owner The address to query the balance of.125	/// @return An uint256 representing the amount owned by the passed address.126	fn balance_of(&self, owner: Address) -> Result<U256> {127		self.consume_store_reads(1)?;128		let owner = T::CrossAccountId::from_eth(owner);129		let balance = <Balance<T>>::get((self.id, self.1, owner));130		Ok(balance.into())131	}132133	/// @dev Transfer token for a specified address134	/// @param to The address to transfer to.135	/// @param amount The amount to be transferred.136	#[weight(<CommonWeights<T>>::transfer())]137	fn transfer(&mut self, caller: Caller, to: Address, amount: U256) -> Result<bool> {138		let caller = T::CrossAccountId::from_eth(caller);139		let to = T::CrossAccountId::from_eth(to);140		let amount = amount.try_into().map_err(|_| "amount overflow")?;141		let budget = self142			.recorder143			.weight_calls_budget(<StructureWeight<T>>::find_parent());144145		<Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)146			.map_err(dispatch_to_evm::<T>)?;147		Ok(true)148	}149150	/// @dev Transfer tokens from one address to another151	/// @param from address The address which you want to send tokens from152	/// @param to address The address which you want to transfer to153	/// @param amount uint256 the amount of tokens to be transferred154	#[weight(<CommonWeights<T>>::transfer_from())]155	fn transfer_from(156		&mut self,157		caller: Caller,158		from: Address,159		to: Address,160		amount: U256,161	) -> Result<bool> {162		let caller = T::CrossAccountId::from_eth(caller);163		let from = T::CrossAccountId::from_eth(from);164		let to = T::CrossAccountId::from_eth(to);165		let amount = amount.try_into().map_err(|_| "amount overflow")?;166		let budget = self167			.recorder168			.weight_calls_budget(<StructureWeight<T>>::find_parent());169170		<Pallet<T>>::transfer_from(self, &caller, &from, &to, self.1, amount, &budget)171			.map_err(dispatch_to_evm::<T>)?;172		Ok(true)173	}174175	/// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.176	/// Beware that changing an allowance with this method brings the risk that someone may use both the old177	/// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this178	/// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:179	/// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729180	/// @param spender The address which will spend the funds.181	/// @param amount The amount of tokens to be spent.182	#[weight(<SelfWeightOf<T>>::approve())]183	fn approve(&mut self, caller: Caller, spender: Address, amount: U256) -> Result<bool> {184		let caller = T::CrossAccountId::from_eth(caller);185		let spender = T::CrossAccountId::from_eth(spender);186		let amount = amount.try_into().map_err(|_| "amount overflow")?;187188		<Pallet<T>>::set_allowance(self, &caller, &spender, self.1, amount)189			.map_err(dispatch_to_evm::<T>)?;190		Ok(true)191	}192193	/// @dev Function to check the amount of tokens that an owner allowed to a spender.194	/// @param owner address The address which owns the funds.195	/// @param spender address The address which will spend the funds.196	/// @return A uint256 specifying the amount of tokens still available for the spender.197	fn allowance(&self, owner: Address, spender: Address) -> Result<U256> {198		self.consume_store_reads(1)?;199		let owner = T::CrossAccountId::from_eth(owner);200		let spender = T::CrossAccountId::from_eth(spender);201202		Ok(<Allowance<T>>::get((self.id, self.1, owner, spender)).into())203	}204}205206#[solidity_interface(name = ERC20UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]207impl<T: Config> RefungibleTokenHandle<T>208where209	T::AccountId: From<[u8; 32]>,210{211	/// @dev Function to check the amount of tokens that an owner allowed to a spender.212	/// @param owner crossAddress The address which owns the funds.213	/// @param spender crossAddress The address which will spend the funds.214	/// @return A uint256 specifying the amount of tokens still available for the spender.215	fn allowance_cross(&self, owner: CrossAddress, spender: CrossAddress) -> Result<U256> {216		let owner = owner.into_sub_cross_account::<T>()?;217		let spender = spender.into_sub_cross_account::<T>()?;218219		Ok(<Allowance<T>>::get((self.id, self.1, owner, spender)).into())220	}221222	/// @dev Function that burns an amount of the token of a given account,223	/// deducting from the sender's allowance for said account.224	/// @param from The account whose tokens will be burnt.225	/// @param amount The amount that will be burnt.226	#[weight(<SelfWeightOf<T>>::burn_from())]227	#[solidity(hide)]228	fn burn_from(&mut self, caller: Caller, from: Address, amount: U256) -> Result<bool> {229		let caller = T::CrossAccountId::from_eth(caller);230		let from = T::CrossAccountId::from_eth(from);231		let amount = amount.try_into().map_err(|_| "amount overflow")?;232		let budget = self233			.recorder234			.weight_calls_budget(<StructureWeight<T>>::find_parent());235236		<Pallet<T>>::burn_from(self, &caller, &from, self.1, amount, &budget)237			.map_err(dispatch_to_evm::<T>)?;238		Ok(true)239	}240241	/// @dev Function that burns an amount of the token of a given account,242	/// deducting from the sender's allowance for said account.243	/// @param from The account whose tokens will be burnt.244	/// @param amount The amount that will be burnt.245	#[weight(<SelfWeightOf<T>>::burn_from())]246	fn burn_from_cross(247		&mut self,248		caller: Caller,249		from: CrossAddress,250		amount: U256,251	) -> Result<bool> {252		let caller = T::CrossAccountId::from_eth(caller);253		let from = from.into_sub_cross_account::<T>()?;254		let amount = amount.try_into().map_err(|_| "amount overflow")?;255		let budget = self256			.recorder257			.weight_calls_budget(<StructureWeight<T>>::find_parent());258259		<Pallet<T>>::burn_from(self, &caller, &from, self.1, amount, &budget)260			.map_err(dispatch_to_evm::<T>)?;261		Ok(true)262	}263264	/// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.265	/// Beware that changing an allowance with this method brings the risk that someone may use both the old266	/// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this267	/// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:268	/// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729269	/// @param spender The crossaccount which will spend the funds.270	/// @param amount The amount of tokens to be spent.271	#[weight(<SelfWeightOf<T>>::approve())]272	fn approve_cross(273		&mut self,274		caller: Caller,275		spender: CrossAddress,276		amount: U256,277	) -> Result<bool> {278		let caller = T::CrossAccountId::from_eth(caller);279		let spender = spender.into_sub_cross_account::<T>()?;280		let amount = amount.try_into().map_err(|_| "amount overflow")?;281282		<Pallet<T>>::set_allowance(self, &caller, &spender, self.1, amount)283			.map_err(dispatch_to_evm::<T>)?;284		Ok(true)285	}286287	/// @notice Balance of account288	/// @param owner An cross address for whom to query the balance289	/// @return The number of fingibles owned by `owner`, possibly zero290	fn balance_of_cross(&self, owner: CrossAddress) -> Result<U256> {291		self.consume_store_reads(1)?;292		let balance = <Balance<T>>::get((self.id, self.1, owner.into_sub_cross_account::<T>()?));293		Ok(balance.into())294	}295296	/// @dev Function that changes total amount of the tokens.297	///  Throws if `msg.sender` doesn't owns all of the tokens.298	/// @param amount New total amount of the tokens.299	#[weight(<SelfWeightOf<T>>::repartition_item())]300	fn repartition(&mut self, caller: Caller, amount: U256) -> Result<bool> {301		let caller = T::CrossAccountId::from_eth(caller);302		let amount = amount.try_into().map_err(|_| "amount overflow")?;303304		<Pallet<T>>::repartition(self, &caller, self.1, amount).map_err(dispatch_to_evm::<T>)?;305		Ok(true)306	}307308	/// @dev Transfer token for a specified address309	/// @param to The crossaccount to transfer to.310	/// @param amount The amount to be transferred.311	#[weight(<CommonWeights<T>>::transfer())]312	fn transfer_cross(&mut self, caller: Caller, to: CrossAddress, amount: U256) -> Result<bool> {313		let caller = T::CrossAccountId::from_eth(caller);314		let to = to.into_sub_cross_account::<T>()?;315		let amount = amount.try_into().map_err(|_| "amount overflow")?;316		let budget = self317			.recorder318			.weight_calls_budget(<StructureWeight<T>>::find_parent());319320		<Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)321			.map_err(dispatch_to_evm::<T>)?;322		Ok(true)323	}324325	/// @dev Transfer tokens from one address to another326	/// @param from The address which you want to send tokens from327	/// @param to The address which you want to transfer to328	/// @param amount the amount of tokens to be transferred329	#[weight(<CommonWeights<T>>::transfer_from())]330	fn transfer_from_cross(331		&mut self,332		caller: Caller,333		from: CrossAddress,334		to: CrossAddress,335		amount: U256,336	) -> Result<bool> {337		let caller = T::CrossAccountId::from_eth(caller);338		let from = from.into_sub_cross_account::<T>()?;339		let to = to.into_sub_cross_account::<T>()?;340		let amount = amount.try_into().map_err(|_| "amount overflow")?;341		let budget = self342			.recorder343			.weight_calls_budget(<StructureWeight<T>>::find_parent());344345		<Pallet<T>>::transfer_from(self, &caller, &from, &to, self.1, amount, &budget)346			.map_err(dispatch_to_evm::<T>)?;347		Ok(true)348	}349}350351impl<T: Config> RefungibleTokenHandle<T> {352	pub fn into_inner(self) -> RefungibleHandle<T> {353		self.0354	}355	pub fn common_mut(&mut self) -> &mut RefungibleHandle<T> {356		&mut self.0357	}358}359360impl<T: Config> WithRecorder<T> for RefungibleTokenHandle<T> {361	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {362		self.0.recorder()363	}364	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {365		self.0.into_recorder()366	}367}368369impl<T: Config> Deref for RefungibleTokenHandle<T> {370	type Target = RefungibleHandle<T>;371372	fn deref(&self) -> &Self::Target {373		&self.0374	}375}376377#[solidity_interface(378	name = UniqueRefungibleToken,379	is(ERC20, ERC20UniqueExtensions, ERC1633),380	enum(derive(PreDispatch)),381)]382impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}383384generate_stubgen!(gen_impl, UniqueRefungibleTokenCall<()>, true);385generate_stubgen!(gen_iface, UniqueRefungibleTokenCall<()>, false);386387impl<T: Config> CommonEvmHandler for RefungibleTokenHandle<T>388where389	T::AccountId: From<[u8; 32]>,390{391	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungibleToken.raw");392393	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {394		call::<T, UniqueRefungibleTokenCall<T>, _, _>(handle, self)395	}396}