git.delta.rocks / unique-network / refs/commits / 905f9b3923e7

difftreelog

refactor fix complex value type support in evm-coder

Yaroslav Bolyukin2023-08-29parent: #1a4aa2d.patch.diff
in: master

14 files changed

modifiedCargo.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",
modifiedCargo.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 }
modifiedpallets/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"]
modifiedpallets/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,
 }
modifiedpallets/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();
 
modifiedpallets/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))),
 			}));
 		}
 
modifiedpallets/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,
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
139 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 collection
143 /// Create a collection143 /// @return address Address of the newly created collection
144 /// @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 };162
163163 let properties: BoundedVec<_, _> = data
164 let properties: BoundedVec<_, _> = data164 .properties
165 .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")?;170
171171 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")?;177
178178 let limits = if !data.limits.is_empty() {
179 let limits = if !data.limits.is_empty() {179 Some(
180 Some(180 data.limits
181 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 None
186 None186 };
187 };187
188188 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>()?;189
190190 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_settings
193 data.nesting_settings193 .restricted
194 .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 None
203 None203 };
204 };204
205205 let admin_list = data
206 let admin_list = data206 .admin_list
207 .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<_>>>()?;210
211211 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 }215
216216 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());243
244244 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>)?;246
247247 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 */
252250
253 /// Create an NFT collection251 /// Create an NFT collection
254 /// @param name Name of the collection252 /// @param name Name of the collection
modifiedprimitives/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"]
modifiedruntime/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};
modifiedruntime/common/ethereum/sponsoring.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -17,7 +17,7 @@
 //! Implements EVM sponsoring logic via TransactionValidityHack
 
 use core::{convert::TryInto, marker::PhantomData};
-use evm_coder::{Call, abi::AbiReader};
+use evm_coder::{Call};
 use pallet_common::{CollectionHandle, eth::map_eth_to_id};
 use pallet_evm::account::CrossAccountId;
 use pallet_evm_transaction_payment::CallContext;
@@ -66,11 +66,11 @@
 		if let Some(collection_id) = map_eth_to_id(&call_context.contract_address) {
 			let collection = <CollectionHandle<T>>::new(collection_id)?;
 			let sponsor = collection.sponsorship.sponsor()?.clone();
-			let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;
+			// let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;
 			Some(T::CrossAccountId::from_sub(match &collection.mode {
 				CollectionMode::NFT => {
 					let collection = NonfungibleHandle::cast(collection);
-					let call = <UniqueNFTCall<T>>::parse(method_id, &mut reader).ok()??;
+					let call = <UniqueNFTCall<T>>::parse_full(&call_context.input).ok()??;
 					match call {
 						UniqueNFTCall::TokenProperties(call) => match call {
 							TokenPropertiesCall::SetProperty {
@@ -161,11 +161,11 @@
 					}
 				}
 				CollectionMode::ReFungible => {
-					let call = <UniqueRefungibleCall<T>>::parse(method_id, &mut reader).ok()??;
+					let call = <UniqueRefungibleCall<T>>::parse_full(&call_context.input).ok()??;
 					refungible::call_sponsor(call, collection, who).map(|()| sponsor)
 				}
 				CollectionMode::Fungible(_) => {
-					let call = <UniqueFungibleCall<T>>::parse(method_id, &mut reader).ok()??;
+					let call = <UniqueFungibleCall<T>>::parse_full(&call_context.input).ok()??;
 					match call {
 						UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {
 							withdraw_transfer::<T>(&collection, who, &TokenId::default())
@@ -196,8 +196,7 @@
 			// Token existance isn't checked at this point and should be checked in `withdraw` method.
 			let token = RefungibleTokenHandle(rft_collection, token_id);
 
-			let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;
-			let call = <UniqueRefungibleTokenCall<T>>::parse(method_id, &mut reader).ok()??;
+			let call = <UniqueRefungibleTokenCall<T>>::parse_full(&call_context.input).ok()??;
 			Some(T::CrossAccountId::from_sub(
 				refungible::token_call_sponsor(call, token, who).map(|()| sponsor)?,
 			))
modifiedtests/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"
modifiedtests/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
+}
modifiedtests/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;