difftreelog
refactor fix complex value type support in evm-coder
in: master
14 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2653,8 +2653,9 @@
[[package]]
name = "evm-coder"
-version = "0.3.6"
-source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.6#be59ae41a5d2ec9389bae22d54f81122b6ba55a4"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b88ae5a449e7e9dfef59c0dd2df396bc56d81a6f4e297490c0c64aa73f7f7ad4"
dependencies = [
"ethereum",
"evm-coder-procedural",
@@ -2665,8 +2666,9 @@
[[package]]
name = "evm-coder-procedural"
-version = "0.3.6"
-source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.6#be59ae41a5d2ec9389bae22d54f81122b6ba55a4"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6223c1063c1f53380b4b9aaf2e4d82eba4808c661c61265619b804b09b7a6b1a"
dependencies = [
"Inflector",
"hex",
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -27,7 +27,7 @@
[workspace.dependencies]
# Unique
app-promotion-rpc = { path = "primitives/app_promotion_rpc", default-features = false }
-evm-coder = { git = "https://github.com/uniquenetwork/evm-coder", tag = "v0.3.6", default-features = false, features = [
+evm-coder = { version = "0.4.2", default-features = false, features = [
'bondrewd',
] }
pallet-app-promotion = { path = "pallets/app-promotion", default-features = false }
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -35,7 +35,8 @@
"sp-std/std",
"up-data-structs/std",
"up-pov-estimate-rpc/std",
+ "evm-coder/std",
]
-stubgen = ["evm-coder/stubgen"]
+stubgen = ["evm-coder/stubgen", "up-data-structs/stubgen"]
tests = []
try-runtime = ["frame-support/try-runtime"]
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -549,8 +549,6 @@
/// Collection properties
#[derive(Debug, Default, AbiCoder)]
pub struct CreateCollectionData {
- /// Collection sponsor
- pub pending_sponsor: CrossAddress,
/// Collection name
pub name: String,
/// Collection description
@@ -571,6 +569,8 @@
pub nesting_settings: CollectionNestingAndPermission,
/// Collection limits
pub limits: Vec<CollectionLimitValue>,
+ /// Collection sponsor
+ pub pending_sponsor: CrossAddress,
/// Extra collection flags
pub flags: CollectionFlags,
}
pallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -26,7 +26,7 @@
use frame_support::dispatch::Weight;
use core::marker::PhantomData;
-use sp_std::cell::RefCell;
+use sp_std::{cell::RefCell, vec::Vec};
use codec::Decode;
use frame_support::pallet_prelude::DispatchError;
@@ -46,8 +46,8 @@
pub use spez::spez;
use evm_coder::{
- abi::{AbiReader, AbiWrite, AbiWriter},
types::{Msg, Value},
+ AbiEncode,
};
pub use pallet::*;
@@ -168,7 +168,7 @@
pub fn evm_to_precompile_output(
self,
handle: &mut impl PrecompileHandle,
- result: execution::Result<Option<AbiWriter>>,
+ result: execution::Result<Option<Vec<u8>>>,
) -> Option<PrecompileResult> {
use execution::Error;
// We ignore error here, as it should not occur, as we have our own bookkeeping of gas
@@ -176,18 +176,13 @@
Some(match result {
Ok(Some(v)) => Ok(PrecompileOutput {
exit_status: ExitSucceed::Returned,
- output: v.finish(),
+ output: v,
}),
Ok(None) => return None,
- Err(Error::Revert(e)) => {
- let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));
- (&e as &str).abi_write(&mut writer);
-
- Err(PrecompileFailure::Revert {
- exit_status: ExitRevert::Reverted,
- output: writer.finish(),
- })
- }
+ Err(Error::Revert(e)) => Err(PrecompileFailure::Revert {
+ exit_status: ExitRevert::Reverted,
+ output: (&e as &str,).abi_encode_call(evm_coder::fn_selector!(Error(string))),
+ }),
Err(Error::Fatal(f)) => Err(PrecompileFailure::Fatal { exit_status: f }),
Err(Error::Error(e)) => Err(e.into()),
})
@@ -266,7 +261,7 @@
C: evm_coder::Call + PreDispatch,
E: evm_coder::Callable<C> + WithRecorder<T>,
H: PrecompileHandle,
- execution::ResultWithPostInfo<AbiWriter>: From<ResultWithPostInfoOf<E, AbiWriter>>,
+ execution::ResultWithPostInfo<Vec<u8>>: From<ResultWithPostInfoOf<E, Vec<u8>>>,
{
let result = call_internal(
handle.context().caller,
@@ -282,18 +277,16 @@
e: &mut E,
value: Value,
input: &[u8],
-) -> execution::Result<Option<AbiWriter>>
+) -> execution::Result<Option<Vec<u8>>>
where
T: Config,
C: evm_coder::Call + PreDispatch,
E: Contract + evm_coder::Callable<C> + WithRecorder<T>,
- execution::ResultWithPostInfo<AbiWriter>: From<ResultWithPostInfoOf<E, AbiWriter>>,
+ execution::ResultWithPostInfo<Vec<u8>>: From<ResultWithPostInfoOf<E, Vec<u8>>>,
{
- let (selector, mut reader) = AbiReader::new_call(input)?;
- let call = C::parse(selector, &mut reader)?;
+ let call = C::parse_full(input)?;
if call.is_none() {
- let selector = u32::from_be_bytes(selector);
- return Err(format!("unrecognized selector: 0x{selector:0<8x}").into());
+ return Err("unrecognized selector".into());
}
let call = call.unwrap();
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -19,7 +19,7 @@
extern crate alloc;
use core::marker::PhantomData;
use evm_coder::{
- abi::{AbiWriter, AbiType},
+ abi::{AbiType, AbiEncode},
generate_stubgen, solidity_interface,
types::*,
ToLog,
@@ -370,11 +370,8 @@
{
return Some(Err(PrecompileFailure::Revert {
exit_status: ExitRevert::Reverted,
- output: {
- let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));
- writer.string("Target contract is allowlisted");
- writer.finish()
- },
+ output: ("target contract is allowlisted",)
+ .abi_encode_call(evm_coder::fn_selector!(Error(string))),
}));
}
pallets/gov-origins/src/lib.rsdiffbeforeafterboth--- a/pallets/gov-origins/src/lib.rs
+++ b/pallets/gov-origins/src/lib.rs
@@ -31,6 +31,7 @@
#[derive(PartialEq, Eq, Clone, MaxEncodedLen, Encode, Decode, TypeInfo, RuntimeDebug)]
#[pallet::origin]
+ #[non_exhaustive]
pub enum Origin {
/// Origin able to send proposal from fellowship collective to democracy pallet.
FellowshipProposition,
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -139,116 +139,114 @@
T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,
T::AccountId: From<[u8; 32]>,
{
- /*
- /// Create a collection
- /// @return address Address of the newly created collection
- #[weight(<SelfWeightOf<T>>::create_collection())]
- #[solidity(rename_selector = "createCollection")]
- fn create_collection(
- &mut self,
- caller: Caller,
- value: Value,
- data: eth::CreateCollectionData,
- ) -> Result<Address> {
- let (caller, name, description, token_prefix) =
- convert_data::<T>(caller, data.name, data.description, data.token_prefix)?;
- if data.mode != eth::CollectionMode::Fungible && data.decimals != 0 {
- return Err("decimals are only supported for NFT and RFT collections".into());
- }
- let mode = match data.mode {
- eth::CollectionMode::Fungible => CollectionMode::Fungible(data.decimals),
- eth::CollectionMode::Nonfungible => CollectionMode::NFT,
- eth::CollectionMode::Refungible => CollectionMode::ReFungible,
- };
+ /// Create a collection
+ /// @return address Address of the newly created collection
+ #[weight(<SelfWeightOf<T>>::create_collection())]
+ #[solidity(rename_selector = "createCollection")]
+ fn create_collection(
+ &mut self,
+ caller: Caller,
+ value: Value,
+ data: eth::CreateCollectionData,
+ ) -> Result<Address> {
+ let (caller, name, description, token_prefix) =
+ convert_data::<T>(caller, data.name, data.description, data.token_prefix)?;
+ if data.mode != eth::CollectionMode::Fungible && data.decimals != 0 {
+ return Err("decimals are only supported for NFT and RFT collections".into());
+ }
+ let mode = match data.mode {
+ eth::CollectionMode::Fungible => CollectionMode::Fungible(data.decimals),
+ eth::CollectionMode::Nonfungible => CollectionMode::NFT,
+ eth::CollectionMode::Refungible => CollectionMode::ReFungible,
+ };
- let properties: BoundedVec<_, _> = data
- .properties
- .into_iter()
- .map(eth::Property::try_into)
- .collect::<Result<Vec<_>>>()?
- .try_into()
- .map_err(|_| "too many properties")?;
+ let properties: BoundedVec<_, _> = data
+ .properties
+ .into_iter()
+ .map(eth::Property::try_into)
+ .collect::<Result<Vec<_>>>()?
+ .try_into()
+ .map_err(|_| "too many properties")?;
- let token_property_permissions =
- eth::TokenPropertyPermission::into_property_key_permissions(
- data.token_property_permissions,
- )?
- .try_into()
- .map_err(|_| "too many property permissions")?;
+ let token_property_permissions =
+ eth::TokenPropertyPermission::into_property_key_permissions(
+ data.token_property_permissions,
+ )?
+ .try_into()
+ .map_err(|_| "too many property permissions")?;
- let limits = if !data.limits.is_empty() {
- Some(
- data.limits
- .into_iter()
- .collect::<Result<up_data_structs::CollectionLimits>>()?,
- )
- } else {
- None
- };
+ let limits = if !data.limits.is_empty() {
+ Some(
+ data.limits
+ .into_iter()
+ .collect::<Result<up_data_structs::CollectionLimits>>()?,
+ )
+ } else {
+ None
+ };
- let pending_sponsor = data.pending_sponsor.into_option_sub_cross_account::<T>()?;
+ let pending_sponsor = data.pending_sponsor.into_option_sub_cross_account::<T>()?;
- let restricted = if !data.nesting_settings.restricted.is_empty() {
- Some(
- data.nesting_settings
- .restricted
- .iter()
- .map(map_eth_to_id)
- .collect::<Option<BTreeSet<_>>>()
- .ok_or("can't convert address into collection id")?
- .try_into()
- .map_err(|_| "too many collections")?,
- )
- } else {
- None
- };
+ let restricted = if !data.nesting_settings.restricted.is_empty() {
+ Some(
+ data.nesting_settings
+ .restricted
+ .iter()
+ .map(map_eth_to_id)
+ .collect::<Option<BTreeSet<_>>>()
+ .ok_or("can't convert address into collection id")?
+ .try_into()
+ .map_err(|_| "too many collections")?,
+ )
+ } else {
+ None
+ };
- let admin_list = data
- .admin_list
- .into_iter()
- .map(|admin| admin.into_sub_cross_account::<T>())
- .collect::<Result<Vec<_>>>()?;
+ let admin_list = data
+ .admin_list
+ .into_iter()
+ .map(|admin| admin.into_sub_cross_account::<T>())
+ .collect::<Result<Vec<_>>>()?;
- let flags = data.flags;
- if !flags.is_allowed_for_user() {
- return Err("internal flags were used".into());
- }
+ let flags = data.flags;
+ if !flags.is_allowed_for_user() {
+ return Err("internal flags were used".into());
+ }
- let data = CreateCollectionData {
- name,
- mode,
- description,
- token_prefix,
- properties,
- token_property_permissions,
- limits,
- pending_sponsor,
+ let data = CreateCollectionData {
+ name,
+ mode,
+ description,
+ token_prefix,
+ properties,
+ token_property_permissions,
+ limits,
+ pending_sponsor,
+ access: None,
+ permissions: Some(CollectionPermissions {
access: None,
- permissions: Some(CollectionPermissions {
- access: None,
- mint_mode: None,
- nesting: Some(NestingPermissions {
- token_owner: data.nesting_settings.token_owner,
- collection_admin: data.nesting_settings.collection_admin,
- restricted,
- #[cfg(feature = "runtime-benchmarks")]
- permissive: true,
- }),
+ mint_mode: None,
+ nesting: Some(NestingPermissions {
+ token_owner: data.nesting_settings.token_owner,
+ collection_admin: data.nesting_settings.collection_admin,
+ restricted,
+ #[cfg(feature = "runtime-benchmarks")]
+ permissive: true,
}),
- admin_list,
- flags,
- };
- check_sent_amount_equals_collection_creation_price::<T>(value)?;
- let collection_helpers_address =
- T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
+ }),
+ admin_list,
+ flags,
+ };
+ check_sent_amount_equals_collection_creation_price::<T>(value)?;
+ let collection_helpers_address =
+ T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
- .map_err(dispatch_to_evm::<T>)?;
+ let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
+ .map_err(dispatch_to_evm::<T>)?;
- let address = pallet_common::eth::collection_id_to_address(collection_id);
- Ok(address)
- }
- */
+ let address = pallet_common::eth::collection_id_to_address(collection_id);
+ Ok(address)
+ }
/// Create an NFT collection
/// @param name Name of the collection
primitives/data-structs/Cargo.tomldiffbeforeafterboth--- a/primitives/data-structs/Cargo.toml
+++ b/primitives/data-structs/Cargo.toml
@@ -39,3 +39,4 @@
"sp-runtime/std",
"sp-std/std",
]
+stubgen = ["evm-coder/stubgen"]
runtime/common/config/pallets/mod.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -24,7 +24,7 @@
weights::CommonWeights,
RelayChainBlockNumberProvider,
},
- Runtime, RuntimeEvent, RuntimeCall, RuntimeOrigin, RUNTIME_NAME, TOKEN_SYMBOL, DECIMALS,
+ Runtime, RuntimeEvent, RuntimeCall, RUNTIME_NAME, TOKEN_SYMBOL, DECIMALS,
Balances,
};
use frame_support::traits::{ConstU32, ConstU64, Currency};
runtime/common/ethereum/sponsoring.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//! Implements EVM sponsoring logic via TransactionValidityHack1819use core::{convert::TryInto, marker::PhantomData};20use evm_coder::{Call, abi::AbiReader};21use pallet_common::{CollectionHandle, eth::map_eth_to_id};22use pallet_evm::account::CrossAccountId;23use pallet_evm_transaction_payment::CallContext;24use pallet_nonfungible::{25 Config as NonfungibleConfig, Pallet as NonfungiblePallet, NonfungibleHandle,26 erc::{27 UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721UniqueMintableCall, ERC721Call,28 TokenPropertiesCall,29 },30};31use pallet_fungible::{32 Config as FungibleConfig,33 erc::{UniqueFungibleCall, ERC20Call},34};35use pallet_refungible::{36 Config as RefungibleConfig,37 erc::UniqueRefungibleCall,38 erc_token::{RefungibleTokenHandle, UniqueRefungibleTokenCall},39 RefungibleHandle,40};41use pallet_unique::Config as UniqueConfig;42use sp_std::prelude::*;43use up_data_structs::{44 CollectionMode, CreateItemData, CreateNftData, mapping::TokenAddressMapping, TokenId,45};46use up_sponsorship::SponsorshipHandler;47use crate::{Runtime, runtime_common::sponsoring::*};4849mod refungible;5051pub type EvmSponsorshipHandler = (52 UniqueEthSponsorshipHandler<Runtime>,53 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,54);5556pub struct UniqueEthSponsorshipHandler<T: UniqueConfig>(PhantomData<*const T>);57impl<T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig>58 SponsorshipHandler<T::CrossAccountId, CallContext> for UniqueEthSponsorshipHandler<T>59where60 T::AccountId: From<[u8; 32]>,61{62 fn get_sponsor(63 who: &T::CrossAccountId,64 call_context: &CallContext,65 ) -> Option<T::CrossAccountId> {66 if let Some(collection_id) = map_eth_to_id(&call_context.contract_address) {67 let collection = <CollectionHandle<T>>::new(collection_id)?;68 let sponsor = collection.sponsorship.sponsor()?.clone();69 let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;70 Some(T::CrossAccountId::from_sub(match &collection.mode {71 CollectionMode::NFT => {72 let collection = NonfungibleHandle::cast(collection);73 let call = <UniqueNFTCall<T>>::parse(method_id, &mut reader).ok()??;74 match call {75 UniqueNFTCall::TokenProperties(call) => match call {76 TokenPropertiesCall::SetProperty {77 token_id,78 key,79 value,80 ..81 } => {82 let token_id: TokenId = token_id.try_into().ok()?;83 withdraw_set_existing_token_property::<T>(84 &collection,85 who,86 &token_id,87 key.len() + value.len(),88 )89 .map(|()| sponsor)90 }91 TokenPropertiesCall::SetProperties {92 token_id,93 properties,94 ..95 } => {96 let token_id: TokenId = token_id.try_into().ok()?;97 let data_size = properties98 .into_iter()99 .map(|p| p.key().len() + p.value().len())100 .sum();101102 withdraw_set_existing_token_property::<T>(103 &collection,104 who,105 &token_id,106 data_size,107 )108 .map(|()| sponsor)109 }110 _ => None,111 },112 UniqueNFTCall::ERC721UniqueExtensions(call) => match call {113 ERC721UniqueExtensionsCall::Transfer { token_id, .. } => {114 let token_id: TokenId = token_id.try_into().ok()?;115 withdraw_transfer::<T>(&collection, who, &token_id)116 .map(|()| sponsor)117 }118 ERC721UniqueExtensionsCall::MintCross { properties, .. } => {119 withdraw_create_item::<T>(120 &collection,121 who,122 &CreateItemData::NFT(CreateNftData::default()),123 )?;124125 let token_id =126 <NonfungiblePallet<T>>::next_token_id(&collection).ok()?;127 let data_size: usize = properties128 .into_iter()129 .map(|p| p.key().len() + p.value().len())130 .sum();131132 withdraw_set_token_property::<T>(&collection, &token_id, data_size)133 .map(|()| sponsor)134 }135 _ => None,136 },137 UniqueNFTCall::ERC721UniqueMintable(138 ERC721UniqueMintableCall::Mint { .. }139 | ERC721UniqueMintableCall::MintCheckId { .. }140 | ERC721UniqueMintableCall::MintWithTokenUri { .. }141 | ERC721UniqueMintableCall::MintWithTokenUriCheckId { .. },142 ) => withdraw_create_item::<T>(143 &collection,144 who,145 &CreateItemData::NFT(CreateNftData::default()),146 )147 .map(|()| sponsor),148 UniqueNFTCall::ERC721(ERC721Call::TransferFrom {149 token_id, from, ..150 }) => {151 let token_id: TokenId = token_id.try_into().ok()?;152 let from = T::CrossAccountId::from_eth(from);153 withdraw_transfer::<T>(&collection, &from, &token_id).map(|()| sponsor)154 }155 UniqueNFTCall::ERC721(ERC721Call::Approve { token_id, .. }) => {156 let token_id: TokenId = token_id.try_into().ok()?;157 withdraw_approve::<T>(&collection, who.as_sub(), &token_id)158 .map(|()| sponsor)159 }160 _ => None,161 }162 }163 CollectionMode::ReFungible => {164 let call = <UniqueRefungibleCall<T>>::parse(method_id, &mut reader).ok()??;165 refungible::call_sponsor(call, collection, who).map(|()| sponsor)166 }167 CollectionMode::Fungible(_) => {168 let call = <UniqueFungibleCall<T>>::parse(method_id, &mut reader).ok()??;169 match call {170 UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {171 withdraw_transfer::<T>(&collection, who, &TokenId::default())172 .map(|()| sponsor)173 }174 UniqueFungibleCall::ERC20(ERC20Call::TransferFrom { from, .. }) => {175 let from = T::CrossAccountId::from_eth(from);176 withdraw_transfer::<T>(&collection, &from, &TokenId::default())177 .map(|()| sponsor)178 }179 UniqueFungibleCall::ERC20(ERC20Call::Approve { .. }) => {180 withdraw_approve::<T>(&collection, who.as_sub(), &TokenId::default())181 .map(|()| sponsor)182 }183 _ => None,184 }185 }186 }?))187 } else {188 let (collection_id, token_id) =189 T::EvmTokenAddressMapping::address_to_token(&call_context.contract_address)?;190 let collection = <CollectionHandle<T>>::new(collection_id)?;191 if collection.mode != CollectionMode::ReFungible {192 return None;193 }194 let sponsor = collection.sponsorship.sponsor()?.clone();195 let rft_collection = RefungibleHandle::cast(collection);196 // Token existance isn't checked at this point and should be checked in `withdraw` method.197 let token = RefungibleTokenHandle(rft_collection, token_id);198199 let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;200 let call = <UniqueRefungibleTokenCall<T>>::parse(method_id, &mut reader).ok()??;201 Some(T::CrossAccountId::from_sub(202 refungible::token_call_sponsor(call, token, who).map(|()| sponsor)?,203 ))204 }205 }206}207208mod common {209 use super::*;210211 use pallet_common::erc::{CollectionCall};212213 pub fn collection_call_sponsor<T>(214 call: CollectionCall<T>,215 _collection: CollectionHandle<T>,216 _who: &T::CrossAccountId,217 ) -> Option<()>218 where219 T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,220 {221 use CollectionCall::*;222223 match call {224 // Readonly225 ERC165Call(_, _)226 | CollectionProperty { .. }227 | CollectionProperties { .. }228 | HasCollectionPendingSponsor229 | CollectionSponsor230 | ContractAddress231 | AllowlistedCross { .. }232 | IsOwnerOrAdminEth { .. }233 | IsOwnerOrAdminCross { .. }234 | CollectionOwner235 | CollectionAdmins236 | CollectionLimits237 | CollectionNesting238 | CollectionNestingRestrictedIds239 | CollectionNestingPermissions240 | UniqueCollectionType => None,241242 // Not sponsored243 AddToCollectionAllowList { .. }244 | AddToCollectionAllowListCross { .. }245 | RemoveFromCollectionAllowList { .. }246 | RemoveFromCollectionAllowListCross { .. }247 | AddCollectionAdminCross { .. }248 | RemoveCollectionAdminCross { .. }249 | AddCollectionAdmin { .. }250 | RemoveCollectionAdmin { .. }251 | SetNestingBool { .. }252 | SetNesting { .. }253 | SetNestingCollectionIds { .. }254 | SetCollectionAccess { .. }255 | SetCollectionMintMode { .. }256 | SetOwner { .. }257 | ChangeCollectionOwnerCross { .. }258 | SetCollectionProperty { .. }259 | SetCollectionProperties { .. }260 | DeleteCollectionProperty { .. }261 | DeleteCollectionProperties { .. }262 | SetCollectionSponsor { .. }263 | SetCollectionSponsorCross { .. }264 | SetCollectionLimit { .. }265 | ConfirmCollectionSponsorship266 | RemoveCollectionSponsor => None,267 }268 }269}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//! Implements EVM sponsoring logic via TransactionValidityHack1819use core::{convert::TryInto, marker::PhantomData};20use evm_coder::{Call};21use pallet_common::{CollectionHandle, eth::map_eth_to_id};22use pallet_evm::account::CrossAccountId;23use pallet_evm_transaction_payment::CallContext;24use pallet_nonfungible::{25 Config as NonfungibleConfig, Pallet as NonfungiblePallet, NonfungibleHandle,26 erc::{27 UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721UniqueMintableCall, ERC721Call,28 TokenPropertiesCall,29 },30};31use pallet_fungible::{32 Config as FungibleConfig,33 erc::{UniqueFungibleCall, ERC20Call},34};35use pallet_refungible::{36 Config as RefungibleConfig,37 erc::UniqueRefungibleCall,38 erc_token::{RefungibleTokenHandle, UniqueRefungibleTokenCall},39 RefungibleHandle,40};41use pallet_unique::Config as UniqueConfig;42use sp_std::prelude::*;43use up_data_structs::{44 CollectionMode, CreateItemData, CreateNftData, mapping::TokenAddressMapping, TokenId,45};46use up_sponsorship::SponsorshipHandler;47use crate::{Runtime, runtime_common::sponsoring::*};4849mod refungible;5051pub type EvmSponsorshipHandler = (52 UniqueEthSponsorshipHandler<Runtime>,53 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,54);5556pub struct UniqueEthSponsorshipHandler<T: UniqueConfig>(PhantomData<*const T>);57impl<T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig>58 SponsorshipHandler<T::CrossAccountId, CallContext> for UniqueEthSponsorshipHandler<T>59where60 T::AccountId: From<[u8; 32]>,61{62 fn get_sponsor(63 who: &T::CrossAccountId,64 call_context: &CallContext,65 ) -> Option<T::CrossAccountId> {66 if let Some(collection_id) = map_eth_to_id(&call_context.contract_address) {67 let collection = <CollectionHandle<T>>::new(collection_id)?;68 let sponsor = collection.sponsorship.sponsor()?.clone();69 // let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;70 Some(T::CrossAccountId::from_sub(match &collection.mode {71 CollectionMode::NFT => {72 let collection = NonfungibleHandle::cast(collection);73 let call = <UniqueNFTCall<T>>::parse_full(&call_context.input).ok()??;74 match call {75 UniqueNFTCall::TokenProperties(call) => match call {76 TokenPropertiesCall::SetProperty {77 token_id,78 key,79 value,80 ..81 } => {82 let token_id: TokenId = token_id.try_into().ok()?;83 withdraw_set_existing_token_property::<T>(84 &collection,85 who,86 &token_id,87 key.len() + value.len(),88 )89 .map(|()| sponsor)90 }91 TokenPropertiesCall::SetProperties {92 token_id,93 properties,94 ..95 } => {96 let token_id: TokenId = token_id.try_into().ok()?;97 let data_size = properties98 .into_iter()99 .map(|p| p.key().len() + p.value().len())100 .sum();101102 withdraw_set_existing_token_property::<T>(103 &collection,104 who,105 &token_id,106 data_size,107 )108 .map(|()| sponsor)109 }110 _ => None,111 },112 UniqueNFTCall::ERC721UniqueExtensions(call) => match call {113 ERC721UniqueExtensionsCall::Transfer { token_id, .. } => {114 let token_id: TokenId = token_id.try_into().ok()?;115 withdraw_transfer::<T>(&collection, who, &token_id)116 .map(|()| sponsor)117 }118 ERC721UniqueExtensionsCall::MintCross { properties, .. } => {119 withdraw_create_item::<T>(120 &collection,121 who,122 &CreateItemData::NFT(CreateNftData::default()),123 )?;124125 let token_id =126 <NonfungiblePallet<T>>::next_token_id(&collection).ok()?;127 let data_size: usize = properties128 .into_iter()129 .map(|p| p.key().len() + p.value().len())130 .sum();131132 withdraw_set_token_property::<T>(&collection, &token_id, data_size)133 .map(|()| sponsor)134 }135 _ => None,136 },137 UniqueNFTCall::ERC721UniqueMintable(138 ERC721UniqueMintableCall::Mint { .. }139 | ERC721UniqueMintableCall::MintCheckId { .. }140 | ERC721UniqueMintableCall::MintWithTokenUri { .. }141 | ERC721UniqueMintableCall::MintWithTokenUriCheckId { .. },142 ) => withdraw_create_item::<T>(143 &collection,144 who,145 &CreateItemData::NFT(CreateNftData::default()),146 )147 .map(|()| sponsor),148 UniqueNFTCall::ERC721(ERC721Call::TransferFrom {149 token_id, from, ..150 }) => {151 let token_id: TokenId = token_id.try_into().ok()?;152 let from = T::CrossAccountId::from_eth(from);153 withdraw_transfer::<T>(&collection, &from, &token_id).map(|()| sponsor)154 }155 UniqueNFTCall::ERC721(ERC721Call::Approve { token_id, .. }) => {156 let token_id: TokenId = token_id.try_into().ok()?;157 withdraw_approve::<T>(&collection, who.as_sub(), &token_id)158 .map(|()| sponsor)159 }160 _ => None,161 }162 }163 CollectionMode::ReFungible => {164 let call = <UniqueRefungibleCall<T>>::parse_full(&call_context.input).ok()??;165 refungible::call_sponsor(call, collection, who).map(|()| sponsor)166 }167 CollectionMode::Fungible(_) => {168 let call = <UniqueFungibleCall<T>>::parse_full(&call_context.input).ok()??;169 match call {170 UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {171 withdraw_transfer::<T>(&collection, who, &TokenId::default())172 .map(|()| sponsor)173 }174 UniqueFungibleCall::ERC20(ERC20Call::TransferFrom { from, .. }) => {175 let from = T::CrossAccountId::from_eth(from);176 withdraw_transfer::<T>(&collection, &from, &TokenId::default())177 .map(|()| sponsor)178 }179 UniqueFungibleCall::ERC20(ERC20Call::Approve { .. }) => {180 withdraw_approve::<T>(&collection, who.as_sub(), &TokenId::default())181 .map(|()| sponsor)182 }183 _ => None,184 }185 }186 }?))187 } else {188 let (collection_id, token_id) =189 T::EvmTokenAddressMapping::address_to_token(&call_context.contract_address)?;190 let collection = <CollectionHandle<T>>::new(collection_id)?;191 if collection.mode != CollectionMode::ReFungible {192 return None;193 }194 let sponsor = collection.sponsorship.sponsor()?.clone();195 let rft_collection = RefungibleHandle::cast(collection);196 // Token existance isn't checked at this point and should be checked in `withdraw` method.197 let token = RefungibleTokenHandle(rft_collection, token_id);198199 let call = <UniqueRefungibleTokenCall<T>>::parse_full(&call_context.input).ok()??;200 Some(T::CrossAccountId::from_sub(201 refungible::token_call_sponsor(call, token, who).map(|()| sponsor)?,202 ))203 }204 }205}206207mod common {208 use super::*;209210 use pallet_common::erc::{CollectionCall};211212 pub fn collection_call_sponsor<T>(213 call: CollectionCall<T>,214 _collection: CollectionHandle<T>,215 _who: &T::CrossAccountId,216 ) -> Option<()>217 where218 T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,219 {220 use CollectionCall::*;221222 match call {223 // Readonly224 ERC165Call(_, _)225 | CollectionProperty { .. }226 | CollectionProperties { .. }227 | HasCollectionPendingSponsor228 | CollectionSponsor229 | ContractAddress230 | AllowlistedCross { .. }231 | IsOwnerOrAdminEth { .. }232 | IsOwnerOrAdminCross { .. }233 | CollectionOwner234 | CollectionAdmins235 | CollectionLimits236 | CollectionNesting237 | CollectionNestingRestrictedIds238 | CollectionNestingPermissions239 | UniqueCollectionType => None,240241 // Not sponsored242 AddToCollectionAllowList { .. }243 | AddToCollectionAllowListCross { .. }244 | RemoveFromCollectionAllowList { .. }245 | RemoveFromCollectionAllowListCross { .. }246 | AddCollectionAdminCross { .. }247 | RemoveCollectionAdminCross { .. }248 | AddCollectionAdmin { .. }249 | RemoveCollectionAdmin { .. }250 | SetNestingBool { .. }251 | SetNesting { .. }252 | SetNestingCollectionIds { .. }253 | SetCollectionAccess { .. }254 | SetCollectionMintMode { .. }255 | SetOwner { .. }256 | ChangeCollectionOwnerCross { .. }257 | SetCollectionProperty { .. }258 | SetCollectionProperties { .. }259 | DeleteCollectionProperty { .. }260 | DeleteCollectionProperties { .. }261 | SetCollectionSponsor { .. }262 | SetCollectionSponsorCross { .. }263 | SetCollectionLimit { .. }264 | ConfirmCollectionSponsorship265 | RemoveCollectionSponsor => None,266 }267 }268}tests/src/eth/abi/collectionHelpers.jsondiffbeforeafterboth--- a/tests/src/eth/abi/collectionHelpers.json
+++ b/tests/src/eth/abi/collectionHelpers.json
@@ -77,15 +77,6 @@
"inputs": [
{
"components": [
- {
- "components": [
- { "internalType": "address", "name": "eth", "type": "address" },
- { "internalType": "uint256", "name": "sub", "type": "uint256" }
- ],
- "internalType": "struct CrossAddress",
- "name": "pending_sponsor",
- "type": "tuple"
- },
{ "internalType": "string", "name": "name", "type": "string" },
{ "internalType": "string", "name": "description", "type": "string" },
{
@@ -170,6 +161,15 @@
"type": "tuple[]"
},
{
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct CrossAddress",
+ "name": "pending_sponsor",
+ "type": "tuple"
+ },
+ {
"internalType": "CollectionFlags",
"name": "flags",
"type": "uint8"
tests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -59,8 +59,8 @@
}
export enum CollectionMode {
+ Nonfungible,
Fungible,
- Nonfungible,
Refungible,
}
@@ -129,4 +129,4 @@
else
this.decimals = 0;
}
-}
\ No newline at end of file
+}
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -216,7 +216,6 @@
}
const tx = collectionHelper.methods.createCollection([
- this.data.pendingSponsor,
this.data.name,
this.data.description,
this.data.tokenPrefix,
@@ -227,6 +226,7 @@
this.data.adminList,
this.data.nestingSettings,
this.data.limits,
+ this.data.pendingSponsor,
this.data.flags,
]);
return tx;