difftreelog
doc(refungible-pallet): add documentation for ERC20 EVM API
in: master
4 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6320,7 +6320,7 @@
[[package]]
name = "pallet-refungible"
-version = "0.1.1"
+version = "0.1.2"
dependencies = [
"ethereum",
"evm-coder",
pallets/refungible/CHANGELOG.mddiffbeforeafterboth--- /dev/null
+++ b/pallets/refungible/CHANGELOG.md
@@ -0,0 +1,6 @@
+## v0.1.2 - 2022-07
+
+### Refungible Pallet
+
+feat(refungible-pallet): add ERC-20 EVM API for RFT token pieces ([#413](https://github.com/UniqueNetwork/unique-chain/pull/413))
+test(refungible-pallet): add tests for ERC-20 EVM API for RFT token pieces ([#413](https://github.com/UniqueNetwork/unique-chain/pull/413))
\ No newline at end of file
pallets/refungible/Cargo.tomldiffbeforeafterboth--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-refungible"
-version = "0.1.1"
+version = "0.1.2"
license = "GPLv3"
edition = "2021"
pallets/refungible/src/erc_token.rsdiffbeforeafterboth1// 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/>.1617extern crate alloc;18use core::{19 char::{REPLACEMENT_CHARACTER, decode_utf16},20 convert::TryInto,21 ops::Deref,22};23use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};24use pallet_common::{25 CommonWeightInfo,26 erc::{CommonEvmHandler, PrecompileResult},27};28use pallet_evm::{account::CrossAccountId, PrecompileHandle};29use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};30use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};31use sp_std::vec::Vec;32use up_data_structs::TokenId;3334use crate::{35 Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,36 weights::WeightInfo, TotalSupply,37};3839pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);4041#[derive(ToLog)]42pub enum ERC20Events {43 Transfer {44 #[indexed]45 from: address,46 #[indexed]47 to: address,48 value: uint256,49 },50 Approval {51 #[indexed]52 owner: address,53 #[indexed]54 spender: address,55 value: uint256,56 },57}5859#[solidity_interface(name = "ERC20", events(ERC20Events))]60impl<T: Config> RefungibleTokenHandle<T> {61 fn name(&self) -> Result<string> {62 Ok(decode_utf16(self.name.iter().copied())63 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))64 .collect::<string>())65 }66 fn symbol(&self) -> Result<string> {67 Ok(string::from_utf8_lossy(&self.token_prefix).into())68 }69 fn total_supply(&self) -> Result<uint256> {70 self.consume_store_reads(1)?;71 Ok(<TotalSupply<T>>::get((self.id, self.1)).into())72 }7374 fn decimals(&self) -> Result<uint8> {75 // Decimals aren't supported for refungible tokens76 Ok(0)77 }7879 fn balance_of(&self, owner: address) -> Result<uint256> {80 self.consume_store_reads(1)?;81 let owner = T::CrossAccountId::from_eth(owner);82 let balance = <Balance<T>>::get((self.id, self.1, owner));83 Ok(balance.into())84 }85 #[weight(<CommonWeights<T>>::transfer())]86 fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {87 let caller = T::CrossAccountId::from_eth(caller);88 let to = T::CrossAccountId::from_eth(to);89 let amount = amount.try_into().map_err(|_| "amount overflow")?;90 let budget = self91 .recorder92 .weight_calls_budget(<StructureWeight<T>>::find_parent());9394 <Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)95 .map_err(|_| "transfer error")?;96 Ok(true)97 }98 #[weight(<CommonWeights<T>>::transfer_from())]99 fn transfer_from(100 &mut self,101 caller: caller,102 from: address,103 to: address,104 amount: uint256,105 ) -> Result<bool> {106 let caller = T::CrossAccountId::from_eth(caller);107 let from = T::CrossAccountId::from_eth(from);108 let to = T::CrossAccountId::from_eth(to);109 let amount = amount.try_into().map_err(|_| "amount overflow")?;110 let budget = self111 .recorder112 .weight_calls_budget(<StructureWeight<T>>::find_parent());113114 <Pallet<T>>::transfer_from(self, &caller, &from, &to, self.1, amount, &budget)115 .map_err(dispatch_to_evm::<T>)?;116 Ok(true)117 }118 #[weight(<SelfWeightOf<T>>::approve())]119 fn approve(&mut self, caller: caller, spender: address, amount: uint256) -> Result<bool> {120 let caller = T::CrossAccountId::from_eth(caller);121 let spender = T::CrossAccountId::from_eth(spender);122 let amount = amount.try_into().map_err(|_| "amount overflow")?;123124 <Pallet<T>>::set_allowance(self, &caller, &spender, self.1, amount)125 .map_err(dispatch_to_evm::<T>)?;126 Ok(true)127 }128 fn allowance(&self, owner: address, spender: address) -> Result<uint256> {129 self.consume_store_reads(1)?;130 let owner = T::CrossAccountId::from_eth(owner);131 let spender = T::CrossAccountId::from_eth(spender);132133 Ok(<Allowance<T>>::get((self.id, self.1, owner, spender)).into())134 }135}136137#[solidity_interface(name = "ERC20UniqueExtensions")]138impl<T: Config> RefungibleTokenHandle<T> {139 #[weight(<SelfWeightOf<T>>::burn_from())]140 fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {141 let caller = T::CrossAccountId::from_eth(caller);142 let from = T::CrossAccountId::from_eth(from);143 let amount = amount.try_into().map_err(|_| "amount overflow")?;144 let budget = self145 .recorder146 .weight_calls_budget(<StructureWeight<T>>::find_parent());147148 <Pallet<T>>::burn_from(self, &caller, &from, self.1, amount, &budget)149 .map_err(dispatch_to_evm::<T>)?;150 Ok(true)151 }152153 #[weight(<SelfWeightOf<T>>::repartition_item())]154 fn repartition(&mut self, caller: caller, amount: uint256) -> Result<bool> {155 let caller = T::CrossAccountId::from_eth(caller);156 let amount = amount.try_into().map_err(|_| "amount overflow")?;157158 <Pallet<T>>::repartition(self, &caller, self.1, amount).map_err(dispatch_to_evm::<T>)?;159 Ok(true)160 }161}162163impl<T: Config> RefungibleTokenHandle<T> {164 pub fn into_inner(self) -> RefungibleHandle<T> {165 self.0166 }167 pub fn common_mut(&mut self) -> &mut RefungibleHandle<T> {168 &mut self.0169 }170}171172impl<T: Config> WithRecorder<T> for RefungibleTokenHandle<T> {173 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {174 self.0.recorder()175 }176 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {177 self.0.into_recorder()178 }179}180181impl<T: Config> Deref for RefungibleTokenHandle<T> {182 type Target = RefungibleHandle<T>;183184 fn deref(&self) -> &Self::Target {185 &self.0186 }187}188189#[solidity_interface(name = "UniqueRefungibleToken", is(ERC20, ERC20UniqueExtensions,))]190impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}191192generate_stubgen!(gen_impl, UniqueRefungibleTokenCall<()>, true);193generate_stubgen!(gen_iface, UniqueRefungibleTokenCall<()>, false);194195impl<T: Config> CommonEvmHandler for RefungibleTokenHandle<T>196where197 T::AccountId: From<[u8; 32]>,198{199 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungibleToken.raw");200201 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {202 call::<T, UniqueRefungibleTokenCall<T>, _, _>(handle, self)203 }204}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 new 50 /// 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}