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

difftreelog

source

pallets/refungible/src/erc_token.rs12.9 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::{28	abi::AbiType, ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight,29};30use pallet_common::{31	CommonWeightInfo,32	erc::{CommonEvmHandler, PrecompileResult},33	eth::{collection_id_to_address, EthCrossAccount},34};35use pallet_evm::{account::CrossAccountId, PrecompileHandle};36use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};37use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};38use sp_std::vec::Vec;39use up_data_structs::TokenId;4041use crate::{42	Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,43	TotalSupply, weights::WeightInfo,44};4546pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);4748#[solidity_interface(name = ERC1633)]49impl<T: Config> RefungibleTokenHandle<T> {50	fn parent_token(&self) -> Result<address> {51		Ok(collection_id_to_address(self.id))52	}5354	fn parent_token_id(&self) -> Result<uint256> {55		Ok(self.1.into())56	}57}5859#[derive(ToLog)]60pub enum ERC20Events {61	/// @dev This event is emitted when the amount of tokens (value) is sent62	/// from the from address to the to address. In the case of minting new63	/// tokens, the transfer is usually from the 0 address while in the case64	/// of burning tokens the transfer is to 0.65	Transfer {66		#[indexed]67		from: address,68		#[indexed]69		to: address,70		value: uint256,71	},72	/// @dev This event is emitted when the amount of tokens (value) is approved73	/// by the owner to be used by the spender.74	Approval {75		#[indexed]76		owner: address,77		#[indexed]78		spender: address,79		value: uint256,80	},81}8283/// @title Standard ERC20 token84///85/// @dev Implementation of the basic standard token.86/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md87#[solidity_interface(name = ERC20, events(ERC20Events))]88impl<T: Config> RefungibleTokenHandle<T> {89	/// @return the name of the token.90	fn name(&self) -> Result<string> {91		Ok(decode_utf16(self.name.iter().copied())92			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))93			.collect::<string>())94	}9596	/// @return the symbol of the token.97	fn symbol(&self) -> Result<string> {98		Ok(string::from_utf8_lossy(&self.token_prefix).into())99	}100101	/// @dev Total number of tokens in existence102	fn total_supply(&self) -> Result<uint256> {103		self.consume_store_reads(1)?;104		Ok(<TotalSupply<T>>::get((self.id, self.1)).into())105	}106107	/// @dev Not supported108	fn decimals(&self) -> Result<uint8> {109		// Decimals aren't supported for refungible tokens110		Ok(0)111	}112113	/// @dev Gets the balance of the specified address.114	/// @param owner The address to query the balance of.115	/// @return An uint256 representing the amount owned by the passed address.116	fn balance_of(&self, owner: address) -> Result<uint256> {117		self.consume_store_reads(1)?;118		let owner = T::CrossAccountId::from_eth(owner);119		let balance = <Balance<T>>::get((self.id, self.1, owner));120		Ok(balance.into())121	}122123	/// @dev Transfer token for a specified address124	/// @param to The address to transfer to.125	/// @param amount The amount to be transferred.126	#[weight(<CommonWeights<T>>::transfer())]127	fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {128		let caller = T::CrossAccountId::from_eth(caller);129		let to = T::CrossAccountId::from_eth(to);130		let amount = amount.try_into().map_err(|_| "amount overflow")?;131		let budget = self132			.recorder133			.weight_calls_budget(<StructureWeight<T>>::find_parent());134135		<Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)136			.map_err(dispatch_to_evm::<T>)?;137		Ok(true)138	}139140	/// @dev Transfer tokens from one address to another141	/// @param from address The address which you want to send tokens from142	/// @param to address The address which you want to transfer to143	/// @param amount uint256 the amount of tokens to be transferred144	#[weight(<CommonWeights<T>>::transfer_from())]145	fn transfer_from(146		&mut self,147		caller: caller,148		from: address,149		to: address,150		amount: uint256,151	) -> Result<bool> {152		let caller = T::CrossAccountId::from_eth(caller);153		let from = T::CrossAccountId::from_eth(from);154		let to = T::CrossAccountId::from_eth(to);155		let amount = amount.try_into().map_err(|_| "amount overflow")?;156		let budget = self157			.recorder158			.weight_calls_budget(<StructureWeight<T>>::find_parent());159160		<Pallet<T>>::transfer_from(self, &caller, &from, &to, self.1, amount, &budget)161			.map_err(dispatch_to_evm::<T>)?;162		Ok(true)163	}164165	/// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.166	/// Beware that changing an allowance with this method brings the risk that someone may use both the old167	/// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this168	/// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:169	/// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729170	/// @param spender The address which will spend the funds.171	/// @param amount The amount of tokens to be spent.172	#[weight(<SelfWeightOf<T>>::approve())]173	fn approve(&mut self, caller: caller, spender: address, amount: uint256) -> Result<bool> {174		let caller = T::CrossAccountId::from_eth(caller);175		let spender = T::CrossAccountId::from_eth(spender);176		let amount = amount.try_into().map_err(|_| "amount overflow")?;177178		<Pallet<T>>::set_allowance(self, &caller, &spender, self.1, amount)179			.map_err(dispatch_to_evm::<T>)?;180		Ok(true)181	}182183	/// @dev Function to check the amount of tokens that an owner allowed to a spender.184	/// @param owner address The address which owns the funds.185	/// @param spender address The address which will spend the funds.186	/// @return A uint256 specifying the amount of tokens still available for the spender.187	fn allowance(&self, owner: address, spender: address) -> Result<uint256> {188		self.consume_store_reads(1)?;189		let owner = T::CrossAccountId::from_eth(owner);190		let spender = T::CrossAccountId::from_eth(spender);191192		Ok(<Allowance<T>>::get((self.id, self.1, owner, spender)).into())193	}194}195196#[solidity_interface(name = ERC20UniqueExtensions)]197impl<T: Config> RefungibleTokenHandle<T>198where199	T::AccountId: From<[u8; 32]>,200{201	/// @dev Function that burns an amount of the token of a given account,202	/// deducting from the sender's allowance for said account.203	/// @param from The account whose tokens will be burnt.204	/// @param amount The amount that will be burnt.205	#[weight(<SelfWeightOf<T>>::burn_from())]206	fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {207		let caller = T::CrossAccountId::from_eth(caller);208		let from = T::CrossAccountId::from_eth(from);209		let amount = amount.try_into().map_err(|_| "amount overflow")?;210		let budget = self211			.recorder212			.weight_calls_budget(<StructureWeight<T>>::find_parent());213214		<Pallet<T>>::burn_from(self, &caller, &from, self.1, amount, &budget)215			.map_err(dispatch_to_evm::<T>)?;216		Ok(true)217	}218219	/// @dev Function that burns an amount of the token of a given account,220	/// deducting from the sender's allowance for said account.221	/// @param from The account whose tokens will be burnt.222	/// @param amount The amount that will be burnt.223	#[weight(<SelfWeightOf<T>>::burn_from())]224	fn burn_from_cross(225		&mut self,226		caller: caller,227		from: EthCrossAccount,228		amount: uint256,229	) -> Result<bool> {230		let caller = T::CrossAccountId::from_eth(caller);231		let from = from.into_sub_cross_account::<T>()?;232		let amount = amount.try_into().map_err(|_| "amount overflow")?;233		let budget = self234			.recorder235			.weight_calls_budget(<StructureWeight<T>>::find_parent());236237		<Pallet<T>>::burn_from(self, &caller, &from, self.1, amount, &budget)238			.map_err(dispatch_to_evm::<T>)?;239		Ok(true)240	}241242	/// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.243	/// Beware that changing an allowance with this method brings the risk that someone may use both the old244	/// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this245	/// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:246	/// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729247	/// @param spender The crossaccount which will spend the funds.248	/// @param amount The amount of tokens to be spent.249	#[weight(<SelfWeightOf<T>>::approve())]250	fn approve_cross(251		&mut self,252		caller: caller,253		spender: EthCrossAccount,254		amount: uint256,255	) -> Result<bool> {256		let caller = T::CrossAccountId::from_eth(caller);257		let spender = spender.into_sub_cross_account::<T>()?;258		let amount = amount.try_into().map_err(|_| "amount overflow")?;259260		<Pallet<T>>::set_allowance(self, &caller, &spender, self.1, amount)261			.map_err(dispatch_to_evm::<T>)?;262		Ok(true)263	}264	/// @dev Function that changes total amount of the tokens.265	///  Throws if `msg.sender` doesn't owns all of the tokens.266	/// @param amount New total amount of the tokens.267	#[weight(<SelfWeightOf<T>>::repartition_item())]268	fn repartition(&mut self, caller: caller, amount: uint256) -> Result<bool> {269		let caller = T::CrossAccountId::from_eth(caller);270		let amount = amount.try_into().map_err(|_| "amount overflow")?;271272		<Pallet<T>>::repartition(self, &caller, self.1, amount).map_err(dispatch_to_evm::<T>)?;273		Ok(true)274	}275276	/// @dev Transfer token for a specified address277	/// @param to The crossaccount to transfer to.278	/// @param amount The amount to be transferred.279	#[weight(<CommonWeights<T>>::transfer())]280	fn transfer_cross(281		&mut self,282		caller: caller,283		to: EthCrossAccount,284		amount: uint256,285	) -> Result<bool> {286		let caller = T::CrossAccountId::from_eth(caller);287		let to = to.into_sub_cross_account::<T>()?;288		let amount = amount.try_into().map_err(|_| "amount overflow")?;289		let budget = self290			.recorder291			.weight_calls_budget(<StructureWeight<T>>::find_parent());292293		<Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)294			.map_err(dispatch_to_evm::<T>)?;295		Ok(true)296	}297298	/// @dev Transfer tokens from one address to another299	/// @param from The address which you want to send tokens from300	/// @param to The address which you want to transfer to301	/// @param amount the amount of tokens to be transferred302	#[weight(<CommonWeights<T>>::transfer_from())]303	fn transfer_from_cross(304		&mut self,305		caller: caller,306		from: EthCrossAccount,307		to: EthCrossAccount,308		amount: uint256,309	) -> Result<bool> {310		let caller = T::CrossAccountId::from_eth(caller);311		let from = from.into_sub_cross_account::<T>()?;312		let to = to.into_sub_cross_account::<T>()?;313		let amount = amount.try_into().map_err(|_| "amount overflow")?;314		let budget = self315			.recorder316			.weight_calls_budget(<StructureWeight<T>>::find_parent());317318		<Pallet<T>>::transfer_from(self, &caller, &from, &to, self.1, amount, &budget)319			.map_err(dispatch_to_evm::<T>)?;320		Ok(true)321	}322}323324impl<T: Config> RefungibleTokenHandle<T> {325	pub fn into_inner(self) -> RefungibleHandle<T> {326		self.0327	}328	pub fn common_mut(&mut self) -> &mut RefungibleHandle<T> {329		&mut self.0330	}331}332333impl<T: Config> WithRecorder<T> for RefungibleTokenHandle<T> {334	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {335		self.0.recorder()336	}337	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {338		self.0.into_recorder()339	}340}341342impl<T: Config> Deref for RefungibleTokenHandle<T> {343	type Target = RefungibleHandle<T>;344345	fn deref(&self) -> &Self::Target {346		&self.0347	}348}349350#[solidity_interface(351	name = UniqueRefungibleToken,352	is(ERC20, ERC20UniqueExtensions, ERC1633)353)]354impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}355356generate_stubgen!(gen_impl, UniqueRefungibleTokenCall<()>, true);357generate_stubgen!(gen_iface, UniqueRefungibleTokenCall<()>, false);358359impl<T: Config> CommonEvmHandler for RefungibleTokenHandle<T>360where361	T::AccountId: From<[u8; 32]>,362{363	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungibleToken.raw");364365	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {366		call::<T, UniqueRefungibleTokenCall<T>, _, _>(handle, self)367	}368}