difftreelog
feat delegate erc call to other struct
in: master
9 files changed
crates/evm-coder-macros/src/solidity_interface.rsdiffbeforeafterboth--- a/crates/evm-coder-macros/src/solidity_interface.rs
+++ b/crates/evm-coder-macros/src/solidity_interface.rs
@@ -23,6 +23,7 @@
use syn::{
Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,
MetaNameValue, NestedMeta, PatType, Path, PathArguments, ReturnType, Type, spanned::Spanned,
+ parse_str,
};
use crate::{
@@ -35,16 +36,21 @@
name: Ident,
pascal_call_name: Ident,
snake_call_name: Ident,
+ via: Option<(Type, Ident)>,
}
impl Is {
- fn try_from(path: &Path) -> syn::Result<Self> {
+ fn new_via(path: &Path, via: Option<(Type, Ident)>) -> syn::Result<Self> {
let name = parse_ident_from_path(path, false)?.clone();
Ok(Self {
pascal_call_name: pascal_ident_to_call(&name),
snake_call_name: pascal_ident_to_snake_call(&name),
name,
+ via,
})
}
+ fn new(path: &Path) -> syn::Result<Self> {
+ Self::new_via(path, None)
+ }
fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
let name = &self.name;
@@ -85,8 +91,18 @@
) -> proc_macro2::TokenStream {
let name = &self.name;
let pascal_call_name = &self.pascal_call_name;
+ let via_typ = self
+ .via
+ .as_ref()
+ .map(|(t, _)| quote! {#t})
+ .unwrap_or_else(|| quote! {Self});
+ let via_map = self
+ .via
+ .as_ref()
+ .map(|(_, i)| quote! {.#i()})
+ .unwrap_or_default();
quote! {
- #call_name::#name(call) => return <Self as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self, Msg {
+ #call_name::#name(call) => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {
call,
caller: c.caller,
value: c.value,
@@ -126,8 +142,46 @@
let mut out = Vec::new();
for item in items {
match item {
- NestedMeta::Meta(Meta::Path(path)) => out.push(Is::try_from(path)?),
- _ => return Err(syn::Error::new(item.span(), "expected path").into()),
+ NestedMeta::Meta(Meta::Path(path)) => out.push(Is::new(path)?),
+ // TODO: replace meta parsing with manual
+ NestedMeta::Meta(Meta::List(list))
+ if list.path.is_ident("via") && list.nested.len() == 3 =>
+ {
+ let mut data = list.nested.iter();
+ let typ = match data.next().expect("len == 3") {
+ NestedMeta::Lit(Lit::Str(s)) => {
+ let v = s.value();
+ let typ: Type = parse_str(&v)?;
+ typ
+ }
+ _ => {
+ return Err(syn::Error::new(
+ item.span(),
+ "via typ should be type in string",
+ )
+ .into())
+ }
+ };
+ let via = match data.next().expect("len == 3") {
+ NestedMeta::Meta(Meta::Path(path)) => path
+ .get_ident()
+ .ok_or_else(|| syn::Error::new(item.span(), "via should be ident"))?,
+ _ => return Err(syn::Error::new(item.span(), "via should be ident").into()),
+ };
+ let path = match data.next().expect("len == 3") {
+ NestedMeta::Meta(Meta::Path(path)) => path,
+ _ => return Err(syn::Error::new(item.span(), "path should be path").into()),
+ };
+
+ out.push(Is::new_via(path, Some((typ, via.clone())))?)
+ }
+ _ => {
+ return Err(syn::Error::new(
+ item.span(),
+ "expected either Name or via(\"Type\", getter, Name)",
+ )
+ .into())
+ }
}
}
Ok(Self(out))
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -14,9 +14,14 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-pub use pallet_evm::PrecompileOutput;
-pub use pallet_evm::PrecompileResult;
+use evm_coder::{solidity_interface, types::*, execution::Result};
+pub use pallet_evm::{PrecompileOutput, PrecompileResult, account::CrossAccountId};
+use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_core::{H160, U256};
+use sp_std::vec::Vec;
+use up_data_structs::Property;
+
+use crate::{Pallet, CollectionHandle, Config};
/// Does not always represent a full collection, for RFT it is either
/// collection (Implementing ERC721), or specific collection token (Implementing ERC20)
@@ -25,3 +30,27 @@
fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult>;
}
+
+#[solidity_interface(name = "CollectionProperties")]
+impl<T: Config> CollectionHandle<T> {
+ fn set_property(&mut self, caller: caller, key: string, value: string) -> Result<()> {
+ <Pallet<T>>::set_collection_property(
+ self,
+ &T::CrossAccountId::from_eth(caller),
+ Property {
+ key: <Vec<u8>>::from(key)
+ .try_into()
+ .map_err(|_| "key too large")?,
+ value: <Vec<u8>>::from(value)
+ .try_into()
+ .map_err(|_| "value too large")?,
+ },
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
+ fn delete_property(&mut self, caller: caller, key: string) -> Result<()> {
+ self.set_property(caller, key, string::new())
+ }
+}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -595,7 +595,7 @@
.iter()
.map(|(key, value)| Property {
key: key.clone(),
- value: value.clone()
+ value: value.clone(),
})
.collect();
@@ -680,19 +680,20 @@
};
let mut collection_properties = up_data_structs::CollectionProperties::get();
- collection_properties.try_set_from_iter(
- data.properties.into_iter()
- .map(|p| (p.key, p.value))
- ).map_err(|e| -> Error<T> { e.into() })?;
+ collection_properties
+ .try_set_from_iter(data.properties.into_iter().map(|p| (p.key, p.value)))
+ .map_err(|e| -> Error<T> { e.into() })?;
CollectionProperties::<T>::insert(id, collection_properties);
let mut token_props_permissions = PropertiesPermissionMap::new();
- token_props_permissions.try_set_from_iter(
- data.token_property_permissions
- .into_iter()
- .map(|property| (property.key, property.permission))
- ).map_err(|e| -> Error<T> { e.into() })?;
+ token_props_permissions
+ .try_set_from_iter(
+ data.token_property_permissions
+ .into_iter()
+ .map(|property| (property.key, property.permission)),
+ )
+ .map_err(|e| -> Error<T> { e.into() })?;
CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);
@@ -806,7 +807,8 @@
CollectionProperties::<T>::try_mutate(collection.id, |properties| {
properties.remove(&property_key)
- }).map_err(|e| -> Error<T> { e.into() })?;
+ })
+ .map_err(|e| -> Error<T> { e.into() })?;
Self::deposit_event(Event::CollectionPropertyDeleted(
collection.id,
@@ -903,11 +905,10 @@
let properties = keys
.into_iter()
.filter_map(|key| {
- properties.get(&key)
- .map(|value| Property {
- key,
- value: value.clone(),
- })
+ properties.get(&key).map(|value| Property {
+ key,
+ value: value.clone(),
+ })
})
.collect();
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -24,6 +24,7 @@
use pallet_evm::account::CrossAccountId;
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
+use pallet_common::{CollectionHandle, erc::CollectionPropertiesCall};
use crate::{
Allowance, Balance, Config, FungibleHandle, Pallet, SelfWeightOf, TotalSupply,
@@ -144,7 +145,14 @@
}
}
-#[solidity_interface(name = "UniqueFungible", is(ERC20))]
+#[solidity_interface(
+ name = "UniqueFungible",
+ is(
+ ERC20,
+ ERC20UniqueExtensions,
+ via("CollectionHandle<T>", common_mut, CollectionProperties)
+ )
+)]
impl<T: Config> FungibleHandle<T> {}
generate_stubgen!(gen_impl, UniqueFungibleCall<()>, true);
pallets/fungible/src/lib.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/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::Deref;20use frame_support::{ensure};21use pallet_evm::account::CrossAccountId;22use up_data_structs::{23 AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,24 budget::Budget,25};26use pallet_common::{27 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, CollectionHandle,28 dispatch::CollectionDispatch,29};30use pallet_structure::Pallet as PalletStructure;31use pallet_evm_coder_substrate::WithRecorder;32use sp_core::H160;33use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};34use sp_std::collections::btree_map::BTreeMap;3536pub use pallet::*;3738use crate::erc::ERC20Events;39#[cfg(feature = "runtime-benchmarks")]40pub mod benchmarking;41pub mod common;42pub mod erc;43pub mod weights;4445pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);46pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4748#[frame_support::pallet]49pub mod pallet {50 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};51 use up_data_structs::CollectionId;52 use super::weights::WeightInfo;5354 #[pallet::error]55 pub enum Error<T> {56 /// Not Fungible item data used to mint in Fungible collection.57 NotFungibleDataUsedToMintFungibleCollectionToken,58 /// Not default id passed as TokenId argument59 FungibleItemsHaveNoId,60 /// Tried to set data for fungible item61 FungibleItemsDontHaveData,62 /// Fungible token does not support nested63 FungibleDisallowsNesting,64 /// Setting item properties is not allowed65 SettingPropertiesNotAllowed,66 }6768 #[pallet::config]69 pub trait Config:70 frame_system::Config + pallet_common::Config + pallet_structure::Config71 {72 type WeightInfo: WeightInfo;73 }7475 #[pallet::pallet]76 #[pallet::generate_store(pub(super) trait Store)]77 pub struct Pallet<T>(_);7879 #[pallet::storage]80 pub type TotalSupply<T: Config> =81 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;8283 #[pallet::storage]84 pub type Balance<T: Config> = StorageNMap<85 Key = (86 Key<Twox64Concat, CollectionId>,87 Key<Blake2_128Concat, T::CrossAccountId>,88 ),89 Value = u128,90 QueryKind = ValueQuery,91 >;9293 #[pallet::storage]94 pub type Allowance<T: Config> = StorageNMap<95 Key = (96 Key<Twox64Concat, CollectionId>,97 Key<Blake2_128, T::CrossAccountId>,98 Key<Blake2_128Concat, T::CrossAccountId>,99 ),100 Value = u128,101 QueryKind = ValueQuery,102 >;103}104105pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);106impl<T: Config> FungibleHandle<T> {107 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {108 Self(inner)109 }110 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {111 self.0112 }113}114impl<T: Config> WithRecorder<T> for FungibleHandle<T> {115 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {116 self.0.recorder()117 }118 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {119 self.0.into_recorder()120 }121}122impl<T: Config> Deref for FungibleHandle<T> {123 type Target = pallet_common::CollectionHandle<T>;124125 fn deref(&self) -> &Self::Target {126 &self.0127 }128}129130impl<T: Config> Pallet<T> {131 pub fn init_collection(132 owner: T::AccountId,133 data: CreateCollectionData<T::AccountId>,134 ) -> Result<CollectionId, DispatchError> {135 <PalletCommon<T>>::init_collection(owner, data)136 }137 pub fn destroy_collection(138 collection: FungibleHandle<T>,139 sender: &T::CrossAccountId,140 ) -> DispatchResult {141 let id = collection.id;142143 // =========144145 PalletCommon::destroy_collection(collection.0, sender)?;146147 <TotalSupply<T>>::remove(id);148 <Balance<T>>::remove_prefix((id,), None);149 <Allowance<T>>::remove_prefix((id,), None);150 Ok(())151 }152153 pub fn burn(154 collection: &FungibleHandle<T>,155 owner: &T::CrossAccountId,156 amount: u128,157 ) -> DispatchResult {158 let total_supply = <TotalSupply<T>>::get(collection.id)159 .checked_sub(amount)160 .ok_or(<CommonError<T>>::TokenValueTooLow)?;161162 let balance = <Balance<T>>::get((collection.id, owner))163 .checked_sub(amount)164 .ok_or(<CommonError<T>>::TokenValueTooLow)?;165166 if collection.access == AccessMode::AllowList {167 collection.check_allowlist(owner)?;168 }169170 // =========171172 if balance == 0 {173 <Balance<T>>::remove((collection.id, owner));174 } else {175 <Balance<T>>::insert((collection.id, owner), balance);176 }177 <TotalSupply<T>>::insert(collection.id, total_supply);178179 collection.log_mirrored(ERC20Events::Transfer {180 from: *owner.as_eth(),181 to: H160::default(),182 value: amount.into(),183 });184 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(185 collection.id,186 TokenId::default(),187 owner.clone(),188 amount,189 ));190 Ok(())191 }192193 pub fn transfer(194 collection: &FungibleHandle<T>,195 from: &T::CrossAccountId,196 to: &T::CrossAccountId,197 amount: u128,198 nesting_budget: &dyn Budget,199 ) -> DispatchResult {200 ensure!(201 collection.limits.transfers_enabled(),202 <CommonError<T>>::TransferNotAllowed,203 );204205 if collection.access == AccessMode::AllowList {206 collection.check_allowlist(from)?;207 collection.check_allowlist(to)?;208 }209 <PalletCommon<T>>::ensure_correct_receiver(to)?;210211 let balance_from = <Balance<T>>::get((collection.id, from))212 .checked_sub(amount)213 .ok_or(<CommonError<T>>::TokenValueTooLow)?;214 let balance_to = if from != to {215 Some(216 <Balance<T>>::get((collection.id, to))217 .checked_add(amount)218 .ok_or(ArithmeticError::Overflow)?,219 )220 } else {221 None222 };223224 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {225 let handle = <CollectionHandle<T>>::try_get(target.0)?;226 let dispatch = T::CollectionDispatch::dispatch(handle);227 let dispatch = dispatch.as_dyn();228229 dispatch.check_nesting(230 from.clone(),231 (collection.id, TokenId::default()),232 target.1,233 nesting_budget,234 )?;235 }236237 // =========238239 if let Some(balance_to) = balance_to {240 // from != to241 if balance_from == 0 {242 <Balance<T>>::remove((collection.id, from));243 } else {244 <Balance<T>>::insert((collection.id, from), balance_from);245 }246 <Balance<T>>::insert((collection.id, to), balance_to);247 }248249 collection.log_mirrored(ERC20Events::Transfer {250 from: *from.as_eth(),251 to: *to.as_eth(),252 value: amount.into(),253 });254 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(255 collection.id,256 TokenId::default(),257 from.clone(),258 to.clone(),259 amount,260 ));261 Ok(())262 }263264 pub fn create_multiple_items(265 collection: &FungibleHandle<T>,266 sender: &T::CrossAccountId,267 data: BTreeMap<T::CrossAccountId, u128>,268 nesting_budget: &dyn Budget,269 ) -> DispatchResult {270 if !collection.is_owner_or_admin(sender) {271 ensure!(272 collection.mint_mode,273 <CommonError<T>>::PublicMintingNotAllowed274 );275 collection.check_allowlist(sender)?;276277 for (owner, _) in data.iter() {278 collection.check_allowlist(owner)?;279 }280 }281282 let total_supply = data283 .iter()284 .map(|(_, v)| *v)285 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {286 acc.checked_add(v)287 })288 .ok_or(ArithmeticError::Overflow)?;289290 let mut balances = data;291 for (k, v) in balances.iter_mut() {292 *v = <Balance<T>>::get((collection.id, &k))293 .checked_add(*v)294 .ok_or(ArithmeticError::Overflow)?;295 }296297 for (to, _) in balances.iter() {298 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {299 let handle = <CollectionHandle<T>>::try_get(target.0)?;300 let dispatch = T::CollectionDispatch::dispatch(handle);301 let dispatch = dispatch.as_dyn();302303 dispatch.check_nesting(304 sender.clone(),305 (collection.id, TokenId::default()),306 target.1,307 nesting_budget,308 )?;309 }310 }311312 // =========313314 <TotalSupply<T>>::insert(collection.id, total_supply);315 for (user, amount) in balances {316 <Balance<T>>::insert((collection.id, &user), amount);317318 collection.log_mirrored(ERC20Events::Transfer {319 from: H160::default(),320 to: *user.as_eth(),321 value: amount.into(),322 });323 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(324 collection.id,325 TokenId::default(),326 user.clone(),327 amount,328 ));329 }330331 Ok(())332 }333334 fn set_allowance_unchecked(335 collection: &FungibleHandle<T>,336 owner: &T::CrossAccountId,337 spender: &T::CrossAccountId,338 amount: u128,339 ) {340 if amount == 0 {341 <Allowance<T>>::remove((collection.id, owner, spender));342 } else {343 <Allowance<T>>::insert((collection.id, owner, spender), amount);344 }345346 collection.log_mirrored(ERC20Events::Approval {347 owner: *owner.as_eth(),348 spender: *spender.as_eth(),349 value: amount.into(),350 });351 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(352 collection.id,353 TokenId(0),354 owner.clone(),355 spender.clone(),356 amount,357 ));358 }359360 pub fn set_allowance(361 collection: &FungibleHandle<T>,362 owner: &T::CrossAccountId,363 spender: &T::CrossAccountId,364 amount: u128,365 ) -> DispatchResult {366 if collection.access == AccessMode::AllowList {367 collection.check_allowlist(owner)?;368 collection.check_allowlist(spender)?;369 }370371 if <Balance<T>>::get((collection.id, owner)) < amount {372 ensure!(373 collection.ignores_owned_amount(owner),374 <CommonError<T>>::CantApproveMoreThanOwned375 );376 }377378 // =========379380 Self::set_allowance_unchecked(collection, owner, spender, amount);381 Ok(())382 }383384 fn check_allowed(385 collection: &FungibleHandle<T>,386 spender: &T::CrossAccountId,387 from: &T::CrossAccountId,388 amount: u128,389 nesting_budget: &dyn Budget,390 ) -> Result<Option<u128>, DispatchError> {391 if spender.conv_eq(from) {392 return Ok(None);393 }394 if collection.access == AccessMode::AllowList {395 // `from`, `to` checked in [`transfer`]396 collection.check_allowlist(spender)?;397 }398 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {399 // TODO: should collection owner be allowed to perform this transfer?400 ensure!(401 <PalletStructure<T>>::check_indirectly_owned(402 spender.clone(),403 source.0,404 source.1,405 None,406 nesting_budget407 )?,408 <CommonError<T>>::ApprovedValueTooLow,409 );410 return Ok(None);411 }412 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);413 if allowance.is_none() {414 ensure!(415 collection.ignores_allowance(spender),416 <CommonError<T>>::ApprovedValueTooLow417 );418 }419420 Ok(allowance)421 }422423 pub fn transfer_from(424 collection: &FungibleHandle<T>,425 spender: &T::CrossAccountId,426 from: &T::CrossAccountId,427 to: &T::CrossAccountId,428 amount: u128,429 nesting_budget: &dyn Budget,430 ) -> DispatchResult {431 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;432433 // =========434435 Self::transfer(collection, from, to, amount, nesting_budget)?;436 if let Some(allowance) = allowance {437 Self::set_allowance_unchecked(collection, from, spender, allowance);438 }439 Ok(())440 }441442 pub fn burn_from(443 collection: &FungibleHandle<T>,444 spender: &T::CrossAccountId,445 from: &T::CrossAccountId,446 amount: u128,447 nesting_budget: &dyn Budget,448 ) -> DispatchResult {449 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;450451 // =========452453 Self::burn(collection, from, amount)?;454 if let Some(allowance) = allowance {455 Self::set_allowance_unchecked(collection, from, spender, allowance);456 }457 Ok(())458 }459460 /// Delegated to `create_multiple_items`461 pub fn create_item(462 collection: &FungibleHandle<T>,463 sender: &T::CrossAccountId,464 data: CreateItemData<T>,465 nesting_budget: &dyn Budget,466 ) -> DispatchResult {467 Self::create_multiple_items(468 collection,469 sender,470 [(data.0, data.1)].into_iter().collect(),471 nesting_budget,472 )473 }474}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#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::Deref;20use frame_support::{ensure};21use pallet_evm::account::CrossAccountId;22use up_data_structs::{23 AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,24 budget::Budget,25};26use pallet_common::{27 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, CollectionHandle,28 dispatch::CollectionDispatch,29};30use pallet_structure::Pallet as PalletStructure;31use pallet_evm_coder_substrate::WithRecorder;32use sp_core::H160;33use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};34use sp_std::collections::btree_map::BTreeMap;3536pub use pallet::*;3738use crate::erc::ERC20Events;39#[cfg(feature = "runtime-benchmarks")]40pub mod benchmarking;41pub mod common;42pub mod erc;43pub mod weights;4445pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);46pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4748#[frame_support::pallet]49pub mod pallet {50 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};51 use up_data_structs::CollectionId;52 use super::weights::WeightInfo;5354 #[pallet::error]55 pub enum Error<T> {56 /// Not Fungible item data used to mint in Fungible collection.57 NotFungibleDataUsedToMintFungibleCollectionToken,58 /// Not default id passed as TokenId argument59 FungibleItemsHaveNoId,60 /// Tried to set data for fungible item61 FungibleItemsDontHaveData,62 /// Fungible token does not support nested63 FungibleDisallowsNesting,64 /// Setting item properties is not allowed65 SettingPropertiesNotAllowed,66 }6768 #[pallet::config]69 pub trait Config:70 frame_system::Config + pallet_common::Config + pallet_structure::Config71 {72 type WeightInfo: WeightInfo;73 }7475 #[pallet::pallet]76 #[pallet::generate_store(pub(super) trait Store)]77 pub struct Pallet<T>(_);7879 #[pallet::storage]80 pub type TotalSupply<T: Config> =81 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;8283 #[pallet::storage]84 pub type Balance<T: Config> = StorageNMap<85 Key = (86 Key<Twox64Concat, CollectionId>,87 Key<Blake2_128Concat, T::CrossAccountId>,88 ),89 Value = u128,90 QueryKind = ValueQuery,91 >;9293 #[pallet::storage]94 pub type Allowance<T: Config> = StorageNMap<95 Key = (96 Key<Twox64Concat, CollectionId>,97 Key<Blake2_128, T::CrossAccountId>,98 Key<Blake2_128Concat, T::CrossAccountId>,99 ),100 Value = u128,101 QueryKind = ValueQuery,102 >;103}104105pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);106impl<T: Config> FungibleHandle<T> {107 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {108 Self(inner)109 }110 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {111 self.0112 }113 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {114 &mut self.0115 }116}117impl<T: Config> WithRecorder<T> for FungibleHandle<T> {118 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {119 self.0.recorder()120 }121 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {122 self.0.into_recorder()123 }124}125impl<T: Config> Deref for FungibleHandle<T> {126 type Target = pallet_common::CollectionHandle<T>;127128 fn deref(&self) -> &Self::Target {129 &self.0130 }131}132133impl<T: Config> Pallet<T> {134 pub fn init_collection(135 owner: T::AccountId,136 data: CreateCollectionData<T::AccountId>,137 ) -> Result<CollectionId, DispatchError> {138 <PalletCommon<T>>::init_collection(owner, data)139 }140 pub fn destroy_collection(141 collection: FungibleHandle<T>,142 sender: &T::CrossAccountId,143 ) -> DispatchResult {144 let id = collection.id;145146 // =========147148 PalletCommon::destroy_collection(collection.0, sender)?;149150 <TotalSupply<T>>::remove(id);151 <Balance<T>>::remove_prefix((id,), None);152 <Allowance<T>>::remove_prefix((id,), None);153 Ok(())154 }155156 pub fn burn(157 collection: &FungibleHandle<T>,158 owner: &T::CrossAccountId,159 amount: u128,160 ) -> DispatchResult {161 let total_supply = <TotalSupply<T>>::get(collection.id)162 .checked_sub(amount)163 .ok_or(<CommonError<T>>::TokenValueTooLow)?;164165 let balance = <Balance<T>>::get((collection.id, owner))166 .checked_sub(amount)167 .ok_or(<CommonError<T>>::TokenValueTooLow)?;168169 if collection.access == AccessMode::AllowList {170 collection.check_allowlist(owner)?;171 }172173 // =========174175 if balance == 0 {176 <Balance<T>>::remove((collection.id, owner));177 } else {178 <Balance<T>>::insert((collection.id, owner), balance);179 }180 <TotalSupply<T>>::insert(collection.id, total_supply);181182 collection.log_mirrored(ERC20Events::Transfer {183 from: *owner.as_eth(),184 to: H160::default(),185 value: amount.into(),186 });187 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(188 collection.id,189 TokenId::default(),190 owner.clone(),191 amount,192 ));193 Ok(())194 }195196 pub fn transfer(197 collection: &FungibleHandle<T>,198 from: &T::CrossAccountId,199 to: &T::CrossAccountId,200 amount: u128,201 nesting_budget: &dyn Budget,202 ) -> DispatchResult {203 ensure!(204 collection.limits.transfers_enabled(),205 <CommonError<T>>::TransferNotAllowed,206 );207208 if collection.access == AccessMode::AllowList {209 collection.check_allowlist(from)?;210 collection.check_allowlist(to)?;211 }212 <PalletCommon<T>>::ensure_correct_receiver(to)?;213214 let balance_from = <Balance<T>>::get((collection.id, from))215 .checked_sub(amount)216 .ok_or(<CommonError<T>>::TokenValueTooLow)?;217 let balance_to = if from != to {218 Some(219 <Balance<T>>::get((collection.id, to))220 .checked_add(amount)221 .ok_or(ArithmeticError::Overflow)?,222 )223 } else {224 None225 };226227 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {228 let handle = <CollectionHandle<T>>::try_get(target.0)?;229 let dispatch = T::CollectionDispatch::dispatch(handle);230 let dispatch = dispatch.as_dyn();231232 dispatch.check_nesting(233 from.clone(),234 (collection.id, TokenId::default()),235 target.1,236 nesting_budget,237 )?;238 }239240 // =========241242 if let Some(balance_to) = balance_to {243 // from != to244 if balance_from == 0 {245 <Balance<T>>::remove((collection.id, from));246 } else {247 <Balance<T>>::insert((collection.id, from), balance_from);248 }249 <Balance<T>>::insert((collection.id, to), balance_to);250 }251252 collection.log_mirrored(ERC20Events::Transfer {253 from: *from.as_eth(),254 to: *to.as_eth(),255 value: amount.into(),256 });257 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(258 collection.id,259 TokenId::default(),260 from.clone(),261 to.clone(),262 amount,263 ));264 Ok(())265 }266267 pub fn create_multiple_items(268 collection: &FungibleHandle<T>,269 sender: &T::CrossAccountId,270 data: BTreeMap<T::CrossAccountId, u128>,271 nesting_budget: &dyn Budget,272 ) -> DispatchResult {273 if !collection.is_owner_or_admin(sender) {274 ensure!(275 collection.mint_mode,276 <CommonError<T>>::PublicMintingNotAllowed277 );278 collection.check_allowlist(sender)?;279280 for (owner, _) in data.iter() {281 collection.check_allowlist(owner)?;282 }283 }284285 let total_supply = data286 .iter()287 .map(|(_, v)| *v)288 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {289 acc.checked_add(v)290 })291 .ok_or(ArithmeticError::Overflow)?;292293 let mut balances = data;294 for (k, v) in balances.iter_mut() {295 *v = <Balance<T>>::get((collection.id, &k))296 .checked_add(*v)297 .ok_or(ArithmeticError::Overflow)?;298 }299300 for (to, _) in balances.iter() {301 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {302 let handle = <CollectionHandle<T>>::try_get(target.0)?;303 let dispatch = T::CollectionDispatch::dispatch(handle);304 let dispatch = dispatch.as_dyn();305306 dispatch.check_nesting(307 sender.clone(),308 (collection.id, TokenId::default()),309 target.1,310 nesting_budget,311 )?;312 }313 }314315 // =========316317 <TotalSupply<T>>::insert(collection.id, total_supply);318 for (user, amount) in balances {319 <Balance<T>>::insert((collection.id, &user), amount);320321 collection.log_mirrored(ERC20Events::Transfer {322 from: H160::default(),323 to: *user.as_eth(),324 value: amount.into(),325 });326 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(327 collection.id,328 TokenId::default(),329 user.clone(),330 amount,331 ));332 }333334 Ok(())335 }336337 fn set_allowance_unchecked(338 collection: &FungibleHandle<T>,339 owner: &T::CrossAccountId,340 spender: &T::CrossAccountId,341 amount: u128,342 ) {343 if amount == 0 {344 <Allowance<T>>::remove((collection.id, owner, spender));345 } else {346 <Allowance<T>>::insert((collection.id, owner, spender), amount);347 }348349 collection.log_mirrored(ERC20Events::Approval {350 owner: *owner.as_eth(),351 spender: *spender.as_eth(),352 value: amount.into(),353 });354 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(355 collection.id,356 TokenId(0),357 owner.clone(),358 spender.clone(),359 amount,360 ));361 }362363 pub fn set_allowance(364 collection: &FungibleHandle<T>,365 owner: &T::CrossAccountId,366 spender: &T::CrossAccountId,367 amount: u128,368 ) -> DispatchResult {369 if collection.access == AccessMode::AllowList {370 collection.check_allowlist(owner)?;371 collection.check_allowlist(spender)?;372 }373374 if <Balance<T>>::get((collection.id, owner)) < amount {375 ensure!(376 collection.ignores_owned_amount(owner),377 <CommonError<T>>::CantApproveMoreThanOwned378 );379 }380381 // =========382383 Self::set_allowance_unchecked(collection, owner, spender, amount);384 Ok(())385 }386387 fn check_allowed(388 collection: &FungibleHandle<T>,389 spender: &T::CrossAccountId,390 from: &T::CrossAccountId,391 amount: u128,392 nesting_budget: &dyn Budget,393 ) -> Result<Option<u128>, DispatchError> {394 if spender.conv_eq(from) {395 return Ok(None);396 }397 if collection.access == AccessMode::AllowList {398 // `from`, `to` checked in [`transfer`]399 collection.check_allowlist(spender)?;400 }401 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {402 // TODO: should collection owner be allowed to perform this transfer?403 ensure!(404 <PalletStructure<T>>::check_indirectly_owned(405 spender.clone(),406 source.0,407 source.1,408 None,409 nesting_budget410 )?,411 <CommonError<T>>::ApprovedValueTooLow,412 );413 return Ok(None);414 }415 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);416 if allowance.is_none() {417 ensure!(418 collection.ignores_allowance(spender),419 <CommonError<T>>::ApprovedValueTooLow420 );421 }422423 Ok(allowance)424 }425426 pub fn transfer_from(427 collection: &FungibleHandle<T>,428 spender: &T::CrossAccountId,429 from: &T::CrossAccountId,430 to: &T::CrossAccountId,431 amount: u128,432 nesting_budget: &dyn Budget,433 ) -> DispatchResult {434 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;435436 // =========437438 Self::transfer(collection, from, to, amount, nesting_budget)?;439 if let Some(allowance) = allowance {440 Self::set_allowance_unchecked(collection, from, spender, allowance);441 }442 Ok(())443 }444445 pub fn burn_from(446 collection: &FungibleHandle<T>,447 spender: &T::CrossAccountId,448 from: &T::CrossAccountId,449 amount: u128,450 nesting_budget: &dyn Budget,451 ) -> DispatchResult {452 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;453454 // =========455456 Self::burn(collection, from, amount)?;457 if let Some(allowance) = allowance {458 Self::set_allowance_unchecked(collection, from, spender, allowance);459 }460 Ok(())461 }462463 /// Delegated to `create_multiple_items`464 pub fn create_item(465 collection: &FungibleHandle<T>,466 sender: &T::CrossAccountId,467 data: CreateItemData<T>,468 nesting_budget: &dyn Budget,469 ) -> DispatchResult {470 Self::create_multiple_items(471 collection,472 sender,473 [(data.0, data.1)].into_iter().collect(),474 nesting_budget,475 )476 }477}pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -391,11 +391,10 @@
keys.into_iter()
.filter_map(|key| {
- properties.get(&key)
- .map(|value| Property {
- key,
- value: value.clone(),
- })
+ properties.get(&key).map(|value| Property {
+ key,
+ value: value.clone(),
+ })
})
.collect()
}
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -26,7 +26,8 @@
use sp_core::{H160, U256};
use sp_std::{vec::Vec, vec};
use pallet_common::{
- erc::{CommonEvmHandler, PrecompileResult},
+ erc::{CommonEvmHandler, PrecompileResult, CollectionPropertiesCall},
+ CollectionHandle,
};
use pallet_evm::account::CrossAccountId;
use pallet_evm_coder_substrate::call;
@@ -504,6 +505,7 @@
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
+ via("CollectionHandle<T>", common_mut, CollectionProperties)
)
)]
impl<T: Config> NonfungibleHandle<T> {}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -142,6 +142,9 @@
pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {
self.0
}
+ pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {
+ &mut self.0
+ }
}
impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {
fn recorder(&self) -> &SubstrateRecorder<T> {
@@ -302,7 +305,8 @@
<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
properties.remove(&property_key)
- }).map_err(|e| -> CommonError<T> { e.into() })?;
+ })
+ .map_err(|e| -> CommonError<T> { e.into() })?;
<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(
collection.id,
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -699,7 +699,7 @@
fn try_set_from_iter<I>(&mut self, iter: I) -> Result<(), PropertiesError>
where
- I: Iterator<Item=(PropertyKey, Self::Value)>
+ I: Iterator<Item = (PropertyKey, Self::Value)>,
{
for (key, value) in iter {
self.try_set(key, value)?;
@@ -711,7 +711,9 @@
#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]
#[derivative(Default(bound = ""))]
-pub struct PropertiesMap<Value>(BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>);
+pub struct PropertiesMap<Value>(
+ BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,
+);
impl<Value> PropertiesMap<Value> {
pub fn new() -> Self {