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

difftreelog

source

pallets/refungible/src/erc_token.rs11.3 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::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};33use pallet_common::{34	CommonWeightInfo,35	erc::{CommonEvmHandler, PrecompileResult, static_property::key},36	eth::map_eth_to_id,37};38use pallet_evm::{account::CrossAccountId, PrecompileHandle};39use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};40use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};41use sp_core::H160;42use sp_std::vec::Vec;43use up_data_structs::{mapping::TokenAddressMapping, PropertyScope, TokenId};4445use crate::{46	Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,47	TokenProperties, TotalSupply, weights::WeightInfo,48};4950pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);5152#[solidity_interface(name = "ERC1633")]53impl<T: Config> RefungibleTokenHandle<T> {54	fn parent_token(&self) -> Result<address> {55		self.consume_store_reads(2)?;56		let props = <TokenProperties<T>>::get((self.id, self.1));57		let key = key::parent_nft();5859		let key_scoped = PropertyScope::Eth60			.apply(key)61			.expect("property key shouldn't exceed length limit");62		let value = props.get(&key_scoped).ok_or("key not found")?;63		Ok(H160::from_slice(value.as_slice()))64	}6566	fn parent_token_id(&self) -> Result<uint256> {67		self.consume_store_reads(2)?;68		let props = <TokenProperties<T>>::get((self.id, self.1));69		let key = key::parent_nft();7071		let key_scoped = PropertyScope::Eth72			.apply(key)73			.expect("property key shouldn't exceed length limit");74		let value = props.get(&key_scoped).ok_or("key not found")?;75		let nft_token_address = H160::from_slice(value.as_slice());76		let nft_token_account = T::CrossAccountId::from_eth(nft_token_address);77		let (_, token_id) = T::CrossTokenAddressMapping::address_to_token(&nft_token_account)78			.ok_or("parent NFT should contain NFT token address")?;7980		Ok(token_id.into())81	}82}8384#[solidity_interface(name = "ERC1633UniqueExtensions")]85impl<T: Config> RefungibleTokenHandle<T> {86	#[solidity(rename_selector = "setParentNFT")]87	#[weight(<CommonWeights<T>>::token_owner() + <SelfWeightOf<T>>::set_parent_nft_unchecked())]88	fn set_parent_nft(89		&mut self,90		caller: caller,91		collection: address,92		nft_id: uint256,93	) -> Result<bool> {94		self.consume_store_reads(1)?;95		let caller = T::CrossAccountId::from_eth(caller);96		let nft_collection = map_eth_to_id(&collection).ok_or("collection not found")?;97		let nft_token = nft_id.try_into()?;9899		<Pallet<T>>::set_parent_nft(&self.0, self.1, caller, nft_collection, nft_token)100			.map_err(dispatch_to_evm::<T>)?;101102		Ok(true)103	}104}105106#[derive(ToLog)]107pub enum ERC20Events {108	/// @dev This event is emitted when the amount of tokens (value) is sent109	/// from the from address to the to address. In the case of minting new110	/// tokens, the transfer is usually from the 0 address while in the case111	/// of burning tokens the transfer is to 0.112	Transfer {113		#[indexed]114		from: address,115		#[indexed]116		to: address,117		value: uint256,118	},119	/// @dev This event is emitted when the amount of tokens (value) is approved120	/// by the owner to be used by the spender.121	Approval {122		#[indexed]123		owner: address,124		#[indexed]125		spender: address,126		value: uint256,127	},128}129130/// @title Standard ERC20 token131///132/// @dev Implementation of the basic standard token.133/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md134#[solidity_interface(name = "ERC20", events(ERC20Events))]135impl<T: Config> RefungibleTokenHandle<T> {136	/// @return the name of the token.137	fn name(&self) -> Result<string> {138		Ok(decode_utf16(self.name.iter().copied())139			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))140			.collect::<string>())141	}142143	/// @return the symbol of the token.144	fn symbol(&self) -> Result<string> {145		Ok(string::from_utf8_lossy(&self.token_prefix).into())146	}147148	/// @dev Total number of tokens in existence149	fn total_supply(&self) -> Result<uint256> {150		self.consume_store_reads(1)?;151		Ok(<TotalSupply<T>>::get((self.id, self.1)).into())152	}153154	/// @dev Not supported155	fn decimals(&self) -> Result<uint8> {156		// Decimals aren't supported for refungible tokens157		Ok(0)158	}159160	/// @dev Gets the balance of the specified address.161	/// @param owner The address to query the balance of.162	/// @return An uint256 representing the amount owned by the passed address.163	fn balance_of(&self, owner: address) -> Result<uint256> {164		self.consume_store_reads(1)?;165		let owner = T::CrossAccountId::from_eth(owner);166		let balance = <Balance<T>>::get((self.id, self.1, owner));167		Ok(balance.into())168	}169170	/// @dev Transfer token for a specified address171	/// @param to The address to transfer to.172	/// @param amount The amount to be transferred.173	#[weight(<CommonWeights<T>>::transfer())]174	fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {175		let caller = T::CrossAccountId::from_eth(caller);176		let to = T::CrossAccountId::from_eth(to);177		let amount = amount.try_into().map_err(|_| "amount overflow")?;178		let budget = self179			.recorder180			.weight_calls_budget(<StructureWeight<T>>::find_parent());181182		<Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)183			.map_err(|_| "transfer error")?;184		Ok(true)185	}186187	/// @dev Transfer tokens from one address to another188	/// @param from address The address which you want to send tokens from189	/// @param to address The address which you want to transfer to190	/// @param amount uint256 the amount of tokens to be transferred191	#[weight(<CommonWeights<T>>::transfer_from())]192	fn transfer_from(193		&mut self,194		caller: caller,195		from: address,196		to: address,197		amount: uint256,198	) -> Result<bool> {199		let caller = T::CrossAccountId::from_eth(caller);200		let from = T::CrossAccountId::from_eth(from);201		let to = T::CrossAccountId::from_eth(to);202		let amount = amount.try_into().map_err(|_| "amount overflow")?;203		let budget = self204			.recorder205			.weight_calls_budget(<StructureWeight<T>>::find_parent());206207		<Pallet<T>>::transfer_from(self, &caller, &from, &to, self.1, amount, &budget)208			.map_err(dispatch_to_evm::<T>)?;209		Ok(true)210	}211212	/// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.213	/// Beware that changing an allowance with this method brings the risk that someone may use both the old214	/// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this215	/// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:216	/// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729217	/// @param spender The address which will spend the funds.218	/// @param amount The amount of tokens to be spent.219	#[weight(<SelfWeightOf<T>>::approve())]220	fn approve(&mut self, caller: caller, spender: address, amount: uint256) -> Result<bool> {221		let caller = T::CrossAccountId::from_eth(caller);222		let spender = T::CrossAccountId::from_eth(spender);223		let amount = amount.try_into().map_err(|_| "amount overflow")?;224225		<Pallet<T>>::set_allowance(self, &caller, &spender, self.1, amount)226			.map_err(dispatch_to_evm::<T>)?;227		Ok(true)228	}229230	/// @dev Function to check the amount of tokens that an owner allowed to a spender.231	/// @param owner address The address which owns the funds.232	/// @param spender address The address which will spend the funds.233	/// @return A uint256 specifying the amount of tokens still available for the spender.234	fn allowance(&self, owner: address, spender: address) -> Result<uint256> {235		self.consume_store_reads(1)?;236		let owner = T::CrossAccountId::from_eth(owner);237		let spender = T::CrossAccountId::from_eth(spender);238239		Ok(<Allowance<T>>::get((self.id, self.1, owner, spender)).into())240	}241}242243#[solidity_interface(name = "ERC20UniqueExtensions")]244impl<T: Config> RefungibleTokenHandle<T> {245	/// @dev Function that burns an amount of the token of a given account,246	/// deducting from the sender's allowance for said account.247	/// @param from The account whose tokens will be burnt.248	/// @param amount The amount that will be burnt.249	#[weight(<SelfWeightOf<T>>::burn_from())]250	fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {251		let caller = T::CrossAccountId::from_eth(caller);252		let from = T::CrossAccountId::from_eth(from);253		let amount = amount.try_into().map_err(|_| "amount overflow")?;254		let budget = self255			.recorder256			.weight_calls_budget(<StructureWeight<T>>::find_parent());257258		<Pallet<T>>::burn_from(self, &caller, &from, self.1, amount, &budget)259			.map_err(dispatch_to_evm::<T>)?;260		Ok(true)261	}262263	/// @dev Function that changes total amount of the tokens.264	///  Throws if `msg.sender` doesn't owns all of the tokens.265	/// @param amount New total amount of the tokens.266	#[weight(<SelfWeightOf<T>>::repartition_item())]267	fn repartition(&mut self, caller: caller, amount: uint256) -> Result<bool> {268		let caller = T::CrossAccountId::from_eth(caller);269		let amount = amount.try_into().map_err(|_| "amount overflow")?;270271		<Pallet<T>>::repartition(self, &caller, self.1, amount).map_err(dispatch_to_evm::<T>)?;272		Ok(true)273	}274}275276impl<T: Config> RefungibleTokenHandle<T> {277	pub fn into_inner(self) -> RefungibleHandle<T> {278		self.0279	}280	pub fn common_mut(&mut self) -> &mut RefungibleHandle<T> {281		&mut self.0282	}283}284285impl<T: Config> WithRecorder<T> for RefungibleTokenHandle<T> {286	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {287		self.0.recorder()288	}289	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {290		self.0.into_recorder()291	}292}293294impl<T: Config> Deref for RefungibleTokenHandle<T> {295	type Target = RefungibleHandle<T>;296297	fn deref(&self) -> &Self::Target {298		&self.0299	}300}301302#[solidity_interface(303	name = "UniqueRefungibleToken",304	is(ERC20, ERC20UniqueExtensions, ERC1633, ERC1633UniqueExtensions)305)]306impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}307308generate_stubgen!(gen_impl, UniqueRefungibleTokenCall<()>, true);309generate_stubgen!(gen_iface, UniqueRefungibleTokenCall<()>, false);310311impl<T: Config> CommonEvmHandler for RefungibleTokenHandle<T>312where313	T::AccountId: From<[u8; 32]>,314{315	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungibleToken.raw");316317	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {318		call::<T, UniqueRefungibleTokenCall<T>, _, _>(handle, self)319	}320}