difftreelog
refactor fix complex value type support in evm-coder
in: master
14 files changed
Cargo.lockdiffbeforeafterboth265326532654[[package]]2654[[package]]2655name = "evm-coder"2655name = "evm-coder"2656version = "0.3.6"2656version = "0.4.2"2657source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.6#be59ae41a5d2ec9389bae22d54f81122b6ba55a4"2657source = "registry+https://github.com/rust-lang/crates.io-index"2658checksum = "b88ae5a449e7e9dfef59c0dd2df396bc56d81a6f4e297490c0c64aa73f7f7ad4"2658dependencies = [2659dependencies = [2659 "ethereum",2660 "ethereum",2660 "evm-coder-procedural",2661 "evm-coder-procedural",266526662666[[package]]2667[[package]]2667name = "evm-coder-procedural"2668name = "evm-coder-procedural"2668version = "0.3.6"2669version = "0.4.2"2669source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.6#be59ae41a5d2ec9389bae22d54f81122b6ba55a4"2670source = "registry+https://github.com/rust-lang/crates.io-index"2671checksum = "6223c1063c1f53380b4b9aaf2e4d82eba4808c661c61265619b804b09b7a6b1a"2670dependencies = [2672dependencies = [2671 "Inflector",2673 "Inflector",2672 "hex",2674 "hex",Cargo.tomldiffbeforeafterboth27[workspace.dependencies]27[workspace.dependencies]28# Unique28# Unique29app-promotion-rpc = { path = "primitives/app_promotion_rpc", default-features = false }29app-promotion-rpc = { path = "primitives/app_promotion_rpc", default-features = false }30evm-coder = { git = "https://github.com/uniquenetwork/evm-coder", tag = "v0.3.6", default-features = false, features = [30evm-coder = { version = "0.4.2", default-features = false, features = [31 'bondrewd',31 'bondrewd',32] }32] }33pallet-app-promotion = { path = "pallets/app-promotion", default-features = false }33pallet-app-promotion = { path = "pallets/app-promotion", default-features = false }pallets/common/Cargo.tomldiffbeforeafterboth35 "sp-std/std",35 "sp-std/std",36 "up-data-structs/std",36 "up-data-structs/std",37 "up-pov-estimate-rpc/std",37 "up-pov-estimate-rpc/std",38 "evm-coder/std",38]39]39stubgen = ["evm-coder/stubgen"]40stubgen = ["evm-coder/stubgen", "up-data-structs/stubgen"]40tests = []41tests = []41try-runtime = ["frame-support/try-runtime"]42try-runtime = ["frame-support/try-runtime"]4243pallets/common/src/eth.rsdiffbeforeafterboth549/// Collection properties549/// Collection properties550#[derive(Debug, Default, AbiCoder)]550#[derive(Debug, Default, AbiCoder)]551pub struct CreateCollectionData {551pub struct CreateCollectionData {552 /// Collection sponsor553 pub pending_sponsor: CrossAddress,554 /// Collection name552 /// Collection name555 pub name: String,553 pub name: String,556 /// Collection description554 /// Collection description571 pub nesting_settings: CollectionNestingAndPermission,569 pub nesting_settings: CollectionNestingAndPermission,572 /// Collection limits570 /// Collection limits573 pub limits: Vec<CollectionLimitValue>,571 pub limits: Vec<CollectionLimitValue>,572 /// Collection sponsor573 pub pending_sponsor: CrossAddress,574 /// Extra collection flags574 /// Extra collection flags575 pub flags: CollectionFlags,575 pub flags: CollectionFlags,576}576}pallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth26use frame_support::dispatch::Weight;26use frame_support::dispatch::Weight;272728use core::marker::PhantomData;28use core::marker::PhantomData;29use sp_std::cell::RefCell;29use sp_std::{cell::RefCell, vec::Vec};303031use codec::Decode;31use codec::Decode;32use frame_support::pallet_prelude::DispatchError;32use frame_support::pallet_prelude::DispatchError;46pub use spez::spez;46pub use spez::spez;474748use evm_coder::{48use evm_coder::{49 abi::{AbiReader, AbiWrite, AbiWriter},50 types::{Msg, Value},49 types::{Msg, Value},50 AbiEncode,51};51};525253pub use pallet::*;53pub use pallet::*;168 pub fn evm_to_precompile_output(168 pub fn evm_to_precompile_output(169 self,169 self,170 handle: &mut impl PrecompileHandle,170 handle: &mut impl PrecompileHandle,171 result: execution::Result<Option<AbiWriter>>,171 result: execution::Result<Option<Vec<u8>>>,172 ) -> Option<PrecompileResult> {172 ) -> Option<PrecompileResult> {173 use execution::Error;173 use execution::Error;174 // We ignore error here, as it should not occur, as we have our own bookkeeping of gas174 // We ignore error here, as it should not occur, as we have our own bookkeeping of gas175 let _ = handle.record_cost(self.initial_gas - self.gas_left());175 let _ = handle.record_cost(self.initial_gas - self.gas_left());176 Some(match result {176 Some(match result {177 Ok(Some(v)) => Ok(PrecompileOutput {177 Ok(Some(v)) => Ok(PrecompileOutput {178 exit_status: ExitSucceed::Returned,178 exit_status: ExitSucceed::Returned,179 output: v.finish(),179 output: v,180 }),180 }),181 Ok(None) => return None,181 Ok(None) => return None,182 Err(Error::Revert(e)) => {182 Err(Error::Revert(e)) => Err(PrecompileFailure::Revert {183 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));184 (&e as &str).abi_write(&mut writer);185186 Err(PrecompileFailure::Revert {187 exit_status: ExitRevert::Reverted,183 exit_status: ExitRevert::Reverted,188 output: writer.finish(),184 output: (&e as &str,).abi_encode_call(evm_coder::fn_selector!(Error(string))),189 })185 }),190 }191 Err(Error::Fatal(f)) => Err(PrecompileFailure::Fatal { exit_status: f }),186 Err(Error::Fatal(f)) => Err(PrecompileFailure::Fatal { exit_status: f }),192 Err(Error::Error(e)) => Err(e.into()),187 Err(Error::Error(e)) => Err(e.into()),193 })188 })266 C: evm_coder::Call + PreDispatch,261 C: evm_coder::Call + PreDispatch,267 E: evm_coder::Callable<C> + WithRecorder<T>,262 E: evm_coder::Callable<C> + WithRecorder<T>,268 H: PrecompileHandle,263 H: PrecompileHandle,269 execution::ResultWithPostInfo<AbiWriter>: From<ResultWithPostInfoOf<E, AbiWriter>>,264 execution::ResultWithPostInfo<Vec<u8>>: From<ResultWithPostInfoOf<E, Vec<u8>>>,270{265{271 let result = call_internal(266 let result = call_internal(272 handle.context().caller,267 handle.context().caller,282 e: &mut E,277 e: &mut E,283 value: Value,278 value: Value,284 input: &[u8],279 input: &[u8],285) -> execution::Result<Option<AbiWriter>>280) -> execution::Result<Option<Vec<u8>>>286where281where287 T: Config,282 T: Config,288 C: evm_coder::Call + PreDispatch,283 C: evm_coder::Call + PreDispatch,289 E: Contract + evm_coder::Callable<C> + WithRecorder<T>,284 E: Contract + evm_coder::Callable<C> + WithRecorder<T>,290 execution::ResultWithPostInfo<AbiWriter>: From<ResultWithPostInfoOf<E, AbiWriter>>,285 execution::ResultWithPostInfo<Vec<u8>>: From<ResultWithPostInfoOf<E, Vec<u8>>>,291{286{292 let (selector, mut reader) = AbiReader::new_call(input)?;293 let call = C::parse(selector, &mut reader)?;287 let call = C::parse_full(input)?;294 if call.is_none() {288 if call.is_none() {295 let selector = u32::from_be_bytes(selector);296 return Err(format!("unrecognized selector: 0x{selector:0<8x}").into());289 return Err("unrecognized selector".into());297 }290 }298 let call = call.unwrap();291 let call = call.unwrap();299292pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth19extern crate alloc;19extern crate alloc;20use core::marker::PhantomData;20use core::marker::PhantomData;21use evm_coder::{21use evm_coder::{22 abi::{AbiWriter, AbiType},22 abi::{AbiType, AbiEncode},23 generate_stubgen, solidity_interface,23 generate_stubgen, solidity_interface,24 types::*,24 types::*,25 ToLog,25 ToLog,370 {370 {371 return Some(Err(PrecompileFailure::Revert {371 return Some(Err(PrecompileFailure::Revert {372 exit_status: ExitRevert::Reverted,372 exit_status: ExitRevert::Reverted,373 output: {373 output: ("target contract is allowlisted",)374 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));374 .abi_encode_call(evm_coder::fn_selector!(Error(string))),375 writer.string("Target contract is allowlisted");376 writer.finish()377 },378 }));375 }));379 }376 }380377pallets/gov-origins/src/lib.rsdiffbeforeafterboth313132 #[derive(PartialEq, Eq, Clone, MaxEncodedLen, Encode, Decode, TypeInfo, RuntimeDebug)]32 #[derive(PartialEq, Eq, Clone, MaxEncodedLen, Encode, Decode, TypeInfo, RuntimeDebug)]33 #[pallet::origin]33 #[pallet::origin]34 #[non_exhaustive]34 pub enum Origin {35 pub enum Origin {35 /// Origin able to send proposal from fellowship collective to democracy pallet.36 /// Origin able to send proposal from fellowship collective to democracy pallet.36 FellowshipProposition,37 FellowshipProposition,pallets/unique/src/eth/mod.rsdiffbeforeafterboth139 T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,139 T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,140 T::AccountId: From<[u8; 32]>,140 T::AccountId: From<[u8; 32]>,141{141{142 /*142 /// Create a collection143 /// Create a collection143 /// @return address Address of the newly created collection144 /// @return address Address of the newly created collection144 #[weight(<SelfWeightOf<T>>::create_collection())]145 #[weight(<SelfWeightOf<T>>::create_collection())]145 #[solidity(rename_selector = "createCollection")]146 #[solidity(rename_selector = "createCollection")]146 fn create_collection(147 fn create_collection(147 &mut self,148 &mut self,148 caller: Caller,149 caller: Caller,149 value: Value,150 value: Value,150 data: eth::CreateCollectionData,151 data: eth::CreateCollectionData,151 ) -> Result<Address> {152 ) -> Result<Address> {152 let (caller, name, description, token_prefix) =153 let (caller, name, description, token_prefix) =153 convert_data::<T>(caller, data.name, data.description, data.token_prefix)?;154 convert_data::<T>(caller, data.name, data.description, data.token_prefix)?;154 if data.mode != eth::CollectionMode::Fungible && data.decimals != 0 {155 if data.mode != eth::CollectionMode::Fungible && data.decimals != 0 {155 return Err("decimals are only supported for NFT and RFT collections".into());156 return Err("decimals are only supported for NFT and RFT collections".into());156 }157 }157 let mode = match data.mode {158 let mode = match data.mode {158 eth::CollectionMode::Fungible => CollectionMode::Fungible(data.decimals),159 eth::CollectionMode::Fungible => CollectionMode::Fungible(data.decimals),159 eth::CollectionMode::Nonfungible => CollectionMode::NFT,160 eth::CollectionMode::Nonfungible => CollectionMode::NFT,160 eth::CollectionMode::Refungible => CollectionMode::ReFungible,161 eth::CollectionMode::Refungible => CollectionMode::ReFungible,161 };162 };162163163 let properties: BoundedVec<_, _> = data164 let properties: BoundedVec<_, _> = data164 .properties165 .properties165 .into_iter()166 .into_iter()166 .map(eth::Property::try_into)167 .map(eth::Property::try_into)167 .collect::<Result<Vec<_>>>()?168 .collect::<Result<Vec<_>>>()?168 .try_into()169 .try_into()169 .map_err(|_| "too many properties")?;170 .map_err(|_| "too many properties")?;170171171 let token_property_permissions =172 let token_property_permissions =172 eth::TokenPropertyPermission::into_property_key_permissions(173 eth::TokenPropertyPermission::into_property_key_permissions(173 data.token_property_permissions,174 data.token_property_permissions,174 )?175 )?175 .try_into()176 .try_into()176 .map_err(|_| "too many property permissions")?;177 .map_err(|_| "too many property permissions")?;177178178 let limits = if !data.limits.is_empty() {179 let limits = if !data.limits.is_empty() {179 Some(180 Some(180 data.limits181 data.limits181 .into_iter()182 .into_iter()182 .collect::<Result<up_data_structs::CollectionLimits>>()?,183 .collect::<Result<up_data_structs::CollectionLimits>>()?,183 )184 )184 } else {185 } else {185 None186 None186 };187 };187188188 let pending_sponsor = data.pending_sponsor.into_option_sub_cross_account::<T>()?;189 let pending_sponsor = data.pending_sponsor.into_option_sub_cross_account::<T>()?;189190190 let restricted = if !data.nesting_settings.restricted.is_empty() {191 let restricted = if !data.nesting_settings.restricted.is_empty() {191 Some(192 Some(192 data.nesting_settings193 data.nesting_settings193 .restricted194 .restricted194 .iter()195 .iter()195 .map(map_eth_to_id)196 .map(map_eth_to_id)196 .collect::<Option<BTreeSet<_>>>()197 .collect::<Option<BTreeSet<_>>>()197 .ok_or("can't convert address into collection id")?198 .ok_or("can't convert address into collection id")?198 .try_into()199 .try_into()199 .map_err(|_| "too many collections")?,200 .map_err(|_| "too many collections")?,200 )201 )201 } else {202 } else {202 None203 None203 };204 };204205205 let admin_list = data206 let admin_list = data206 .admin_list207 .admin_list207 .into_iter()208 .into_iter()208 .map(|admin| admin.into_sub_cross_account::<T>())209 .map(|admin| admin.into_sub_cross_account::<T>())209 .collect::<Result<Vec<_>>>()?;210 .collect::<Result<Vec<_>>>()?;210211211 let flags = data.flags;212 let flags = data.flags;212 if !flags.is_allowed_for_user() {213 if !flags.is_allowed_for_user() {213 return Err("internal flags were used".into());214 return Err("internal flags were used".into());214 }215 }215216216 let data = CreateCollectionData {217 let data = CreateCollectionData {217 name,218 name,218 mode,219 mode,219 description,220 description,220 token_prefix,221 token_prefix,221 properties,222 properties,222 token_property_permissions,223 token_property_permissions,223 limits,224 limits,224 pending_sponsor,225 pending_sponsor,225 access: None,226 access: None,226 permissions: Some(CollectionPermissions {227 permissions: Some(CollectionPermissions {227 access: None,228 access: None,228 mint_mode: None,229 mint_mode: None,229 nesting: Some(NestingPermissions {230 nesting: Some(NestingPermissions {230 token_owner: data.nesting_settings.token_owner,231 token_owner: data.nesting_settings.token_owner,231 collection_admin: data.nesting_settings.collection_admin,232 collection_admin: data.nesting_settings.collection_admin,232 restricted,233 restricted,233 #[cfg(feature = "runtime-benchmarks")]234 #[cfg(feature = "runtime-benchmarks")]234 permissive: true,235 permissive: true,235 }),236 }),236 }),237 }),237 admin_list,238 admin_list,238 flags,239 flags,239 };240 };240 check_sent_amount_equals_collection_creation_price::<T>(value)?;241 check_sent_amount_equals_collection_creation_price::<T>(value)?;241 let collection_helpers_address =242 let collection_helpers_address =242 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());243 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());243244244 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)245 let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)245 .map_err(dispatch_to_evm::<T>)?;246 .map_err(dispatch_to_evm::<T>)?;246247247 let address = pallet_common::eth::collection_id_to_address(collection_id);248 let address = pallet_common::eth::collection_id_to_address(collection_id);248 Ok(address)249 Ok(address)249 }250 }251 */252250253 /// Create an NFT collection251 /// Create an NFT collection254 /// @param name Name of the collection252 /// @param name Name of the collectionprimitives/data-structs/Cargo.tomldiffbeforeafterboth39 "sp-runtime/std",39 "sp-runtime/std",40 "sp-std/std",40 "sp-std/std",41]41]42stubgen = ["evm-coder/stubgen"]4243runtime/common/config/pallets/mod.rsdiffbeforeafterboth24 weights::CommonWeights,24 weights::CommonWeights,25 RelayChainBlockNumberProvider,25 RelayChainBlockNumberProvider,26 },26 },27 Runtime, RuntimeEvent, RuntimeCall, RuntimeOrigin, RUNTIME_NAME, TOKEN_SYMBOL, DECIMALS,27 Runtime, RuntimeEvent, RuntimeCall, RUNTIME_NAME, TOKEN_SYMBOL, DECIMALS,28 Balances,28 Balances,29};29};30use frame_support::traits::{ConstU32, ConstU64, Currency};30use frame_support::traits::{ConstU32, ConstU64, Currency};runtime/common/ethereum/sponsoring.rsdiffbeforeafterboth17//! Implements EVM sponsoring logic via TransactionValidityHack17//! Implements EVM sponsoring logic via TransactionValidityHack181819use core::{convert::TryInto, marker::PhantomData};19use core::{convert::TryInto, marker::PhantomData};20use evm_coder::{Call, abi::AbiReader};20use evm_coder::{Call};21use pallet_common::{CollectionHandle, eth::map_eth_to_id};21use pallet_common::{CollectionHandle, eth::map_eth_to_id};22use pallet_evm::account::CrossAccountId;22use pallet_evm::account::CrossAccountId;23use pallet_evm_transaction_payment::CallContext;23use pallet_evm_transaction_payment::CallContext;66 if let Some(collection_id) = map_eth_to_id(&call_context.contract_address) {66 if let Some(collection_id) = map_eth_to_id(&call_context.contract_address) {67 let collection = <CollectionHandle<T>>::new(collection_id)?;67 let collection = <CollectionHandle<T>>::new(collection_id)?;68 let sponsor = collection.sponsorship.sponsor()?.clone();68 let sponsor = collection.sponsorship.sponsor()?.clone();69 let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;69 // let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;70 Some(T::CrossAccountId::from_sub(match &collection.mode {70 Some(T::CrossAccountId::from_sub(match &collection.mode {71 CollectionMode::NFT => {71 CollectionMode::NFT => {72 let collection = NonfungibleHandle::cast(collection);72 let collection = NonfungibleHandle::cast(collection);73 let call = <UniqueNFTCall<T>>::parse(method_id, &mut reader).ok()??;73 let call = <UniqueNFTCall<T>>::parse_full(&call_context.input).ok()??;74 match call {74 match call {75 UniqueNFTCall::TokenProperties(call) => match call {75 UniqueNFTCall::TokenProperties(call) => match call {76 TokenPropertiesCall::SetProperty {76 TokenPropertiesCall::SetProperty {161 }161 }162 }162 }163 CollectionMode::ReFungible => {163 CollectionMode::ReFungible => {164 let call = <UniqueRefungibleCall<T>>::parse(method_id, &mut reader).ok()??;164 let call = <UniqueRefungibleCall<T>>::parse_full(&call_context.input).ok()??;165 refungible::call_sponsor(call, collection, who).map(|()| sponsor)165 refungible::call_sponsor(call, collection, who).map(|()| sponsor)166 }166 }167 CollectionMode::Fungible(_) => {167 CollectionMode::Fungible(_) => {168 let call = <UniqueFungibleCall<T>>::parse(method_id, &mut reader).ok()??;168 let call = <UniqueFungibleCall<T>>::parse_full(&call_context.input).ok()??;169 match call {169 match call {170 UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {170 UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {171 withdraw_transfer::<T>(&collection, who, &TokenId::default())171 withdraw_transfer::<T>(&collection, who, &TokenId::default())196 // Token existance isn't checked at this point and should be checked in `withdraw` method.196 // Token existance isn't checked at this point and should be checked in `withdraw` method.197 let token = RefungibleTokenHandle(rft_collection, token_id);197 let token = RefungibleTokenHandle(rft_collection, token_id);198198199 let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;200 let call = <UniqueRefungibleTokenCall<T>>::parse(method_id, &mut reader).ok()??;199 let call = <UniqueRefungibleTokenCall<T>>::parse_full(&call_context.input).ok()??;201 Some(T::CrossAccountId::from_sub(200 Some(T::CrossAccountId::from_sub(202 refungible::token_call_sponsor(call, token, who).map(|()| sponsor)?,201 refungible::token_call_sponsor(call, token, who).map(|()| sponsor)?,203 ))202 ))tests/src/eth/abi/collectionHelpers.jsondiffbeforeafterboth77 "inputs": [77 "inputs": [78 {78 {79 "components": [79 "components": [80 {81 "components": [82 { "internalType": "address", "name": "eth", "type": "address" },83 { "internalType": "uint256", "name": "sub", "type": "uint256" }84 ],85 "internalType": "struct CrossAddress",86 "name": "pending_sponsor",87 "type": "tuple"88 },89 { "internalType": "string", "name": "name", "type": "string" },80 { "internalType": "string", "name": "name", "type": "string" },90 { "internalType": "string", "name": "description", "type": "string" },81 { "internalType": "string", "name": "description", "type": "string" },91 {82 {169 "name": "limits",160 "name": "limits",170 "type": "tuple[]"161 "type": "tuple[]"171 },162 },163 {164 "components": [165 { "internalType": "address", "name": "eth", "type": "address" },166 { "internalType": "uint256", "name": "sub", "type": "uint256" }167 ],168 "internalType": "struct CrossAddress",169 "name": "pending_sponsor",170 "type": "tuple"171 },172 {172 {173 "internalType": "CollectionFlags",173 "internalType": "CollectionFlags",174 "name": "flags",174 "name": "flags",tests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth59}59}606061export enum CollectionMode {61export enum CollectionMode {62 Fungible,63 Nonfungible,62 Nonfungible,63 Fungible,64 Refungible,64 Refungible,65}65}6666tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth216 }216 }217217218 const tx = collectionHelper.methods.createCollection([218 const tx = collectionHelper.methods.createCollection([219 this.data.pendingSponsor,220 this.data.name,219 this.data.name,221 this.data.description,220 this.data.description,222 this.data.tokenPrefix,221 this.data.tokenPrefix,227 this.data.adminList,226 this.data.adminList,228 this.data.nestingSettings,227 this.data.nestingSettings,229 this.data.limits,228 this.data.limits,229 this.data.pendingSponsor,230 this.data.flags,230 this.data.flags,231 ]);231 ]);232 return tx;232 return tx;