git.delta.rocks / unique-network / refs/commits / 465cfefa64e5

difftreelog

source

pallets/refungible/src/erc_token.rs9.6 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.2122extern crate alloc;2324#[cfg(not(feature = "std"))]25use alloc::format;2627use core::{28	char::{REPLACEMENT_CHARACTER, decode_utf16},29	convert::TryInto,30	ops::Deref,31};32use evm_coder::{33	abi::AbiType, ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight,34};35use pallet_common::{36	CommonWeightInfo,37	erc::{CommonEvmHandler, PrecompileResult},38	eth::collection_id_to_address,39};40use pallet_evm::{account::CrossAccountId, PrecompileHandle};41use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};42use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};43use sp_std::vec::Vec;44use up_data_structs::TokenId;4546use crate::{47	Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,48	TotalSupply, weights::WeightInfo,49};5051pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);5253#[solidity_interface(name = ERC1633)]54impl<T: Config> RefungibleTokenHandle<T> {55	fn parent_token(&self) -> Result<address> {56		Ok(collection_id_to_address(self.id))57	}5859	fn parent_token_id(&self) -> Result<uint256> {60		Ok(self.1.into())61	}62}6364#[derive(ToLog)]65pub enum ERC20Events {66	/// @dev This event is emitted when the amount of tokens (value) is sent67	/// from the from address to the to address. In the case of minting new68	/// tokens, the transfer is usually from the 0 address while in the case69	/// of burning tokens the transfer is to 0.70	Transfer {71		#[indexed]72		from: address,73		#[indexed]74		to: address,75		value: uint256,76	},77	/// @dev This event is emitted when the amount of tokens (value) is approved78	/// by the owner to be used by the spender.79	Approval {80		#[indexed]81		owner: address,82		#[indexed]83		spender: address,84		value: uint256,85	},86}8788/// @title Standard ERC20 token89///90/// @dev Implementation of the basic standard token.91/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md92#[solidity_interface(name = ERC20, events(ERC20Events))]93impl<T: Config> RefungibleTokenHandle<T> {94	/// @return the name of the token.95	fn name(&self) -> Result<string> {96		Ok(decode_utf16(self.name.iter().copied())97			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))98			.collect::<string>())99	}100101	/// @return the symbol of the token.102	fn symbol(&self) -> Result<string> {103		Ok(string::from_utf8_lossy(&self.token_prefix).into())104	}105106	/// @dev Total number of tokens in existence107	fn total_supply(&self) -> Result<uint256> {108		self.consume_store_reads(1)?;109		Ok(<TotalSupply<T>>::get((self.id, self.1)).into())110	}111112	/// @dev Not supported113	fn decimals(&self) -> Result<uint8> {114		// Decimals aren't supported for refungible tokens115		Ok(0)116	}117118	/// @dev Gets the balance of the specified address.119	/// @param owner The address to query the balance of.120	/// @return An uint256 representing the amount owned by the passed address.121	fn balance_of(&self, owner: address) -> Result<uint256> {122		self.consume_store_reads(1)?;123		let owner = T::CrossAccountId::from_eth(owner);124		let balance = <Balance<T>>::get((self.id, self.1, owner));125		Ok(balance.into())126	}127128	/// @dev Transfer token for a specified address129	/// @param to The address to transfer to.130	/// @param amount The amount to be transferred.131	#[weight(<CommonWeights<T>>::transfer())]132	fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {133		let caller = T::CrossAccountId::from_eth(caller);134		let to = T::CrossAccountId::from_eth(to);135		let amount = amount.try_into().map_err(|_| "amount overflow")?;136		let budget = self137			.recorder138			.weight_calls_budget(<StructureWeight<T>>::find_parent());139140		<Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)141			.map_err(dispatch_to_evm::<T>)?;142		Ok(true)143	}144145	/// @dev Transfer tokens from one address to another146	/// @param from address The address which you want to send tokens from147	/// @param to address The address which you want to transfer to148	/// @param amount uint256 the amount of tokens to be transferred149	#[weight(<CommonWeights<T>>::transfer_from())]150	fn transfer_from(151		&mut self,152		caller: caller,153		from: address,154		to: address,155		amount: uint256,156	) -> Result<bool> {157		let caller = T::CrossAccountId::from_eth(caller);158		let from = T::CrossAccountId::from_eth(from);159		let to = T::CrossAccountId::from_eth(to);160		let amount = amount.try_into().map_err(|_| "amount overflow")?;161		let budget = self162			.recorder163			.weight_calls_budget(<StructureWeight<T>>::find_parent());164165		<Pallet<T>>::transfer_from(self, &caller, &from, &to, self.1, amount, &budget)166			.map_err(dispatch_to_evm::<T>)?;167		Ok(true)168	}169170	/// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.171	/// Beware that changing an allowance with this method brings the risk that someone may use both the old172	/// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this173	/// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:174	/// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729175	/// @param spender The address which will spend the funds.176	/// @param amount The amount of tokens to be spent.177	#[weight(<SelfWeightOf<T>>::approve())]178	fn approve(&mut self, caller: caller, spender: address, amount: uint256) -> Result<bool> {179		let caller = T::CrossAccountId::from_eth(caller);180		let spender = T::CrossAccountId::from_eth(spender);181		let amount = amount.try_into().map_err(|_| "amount overflow")?;182183		<Pallet<T>>::set_allowance(self, &caller, &spender, self.1, amount)184			.map_err(dispatch_to_evm::<T>)?;185		Ok(true)186	}187188	/// @dev Function to check the amount of tokens that an owner allowed to a spender.189	/// @param owner address The address which owns the funds.190	/// @param spender address The address which will spend the funds.191	/// @return A uint256 specifying the amount of tokens still available for the spender.192	fn allowance(&self, owner: address, spender: address) -> Result<uint256> {193		self.consume_store_reads(1)?;194		let owner = T::CrossAccountId::from_eth(owner);195		let spender = T::CrossAccountId::from_eth(spender);196197		Ok(<Allowance<T>>::get((self.id, self.1, owner, spender)).into())198	}199}200201#[solidity_interface(name = ERC20UniqueExtensions)]202impl<T: Config> RefungibleTokenHandle<T> {203	/// @dev Function that burns an amount of the token of a given account,204	/// deducting from the sender's allowance for said account.205	/// @param from The account whose tokens will be burnt.206	/// @param amount The amount that will be burnt.207	#[weight(<SelfWeightOf<T>>::burn_from())]208	fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {209		let caller = T::CrossAccountId::from_eth(caller);210		let from = T::CrossAccountId::from_eth(from);211		let amount = amount.try_into().map_err(|_| "amount overflow")?;212		let budget = self213			.recorder214			.weight_calls_budget(<StructureWeight<T>>::find_parent());215216		<Pallet<T>>::burn_from(self, &caller, &from, self.1, amount, &budget)217			.map_err(dispatch_to_evm::<T>)?;218		Ok(true)219	}220221	/// @dev Function that changes total amount of the tokens.222	///  Throws if `msg.sender` doesn't owns all of the tokens.223	/// @param amount New total amount of the tokens.224	#[weight(<SelfWeightOf<T>>::repartition_item())]225	fn repartition(&mut self, caller: caller, amount: uint256) -> Result<bool> {226		let caller = T::CrossAccountId::from_eth(caller);227		let amount = amount.try_into().map_err(|_| "amount overflow")?;228229		<Pallet<T>>::repartition(self, &caller, self.1, amount).map_err(dispatch_to_evm::<T>)?;230		Ok(true)231	}232}233234impl<T: Config> RefungibleTokenHandle<T> {235	pub fn into_inner(self) -> RefungibleHandle<T> {236		self.0237	}238	pub fn common_mut(&mut self) -> &mut RefungibleHandle<T> {239		&mut self.0240	}241}242243impl<T: Config> WithRecorder<T> for RefungibleTokenHandle<T> {244	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {245		self.0.recorder()246	}247	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {248		self.0.into_recorder()249	}250}251252impl<T: Config> Deref for RefungibleTokenHandle<T> {253	type Target = RefungibleHandle<T>;254255	fn deref(&self) -> &Self::Target {256		&self.0257	}258}259260#[solidity_interface(261	name = UniqueRefungibleToken,262	is(ERC20, ERC20UniqueExtensions, ERC1633)263)]264impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}265266generate_stubgen!(gen_impl, UniqueRefungibleTokenCall<()>, true);267generate_stubgen!(gen_iface, UniqueRefungibleTokenCall<()>, false);268269impl<T: Config> CommonEvmHandler for RefungibleTokenHandle<T>270where271	T::AccountId: From<[u8; 32]>,272{273	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungibleToken.raw");274275	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {276		call::<T, UniqueRefungibleTokenCall<T>, _, _>(handle, self)277	}278}