git.delta.rocks / unique-network / refs/commits / 8900b85b9a67

difftreelog

misk: Change OptionCrossAddress to Option<CrossAddress>

Trubnikov Sergey2023-01-10parent: #72d7965.patch.diff
in: master

6 files changed

modifiedpallets/common/src/eth.rsdiffbeforeafterboth
before · pallets/common/src/eth.rs
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//! The module contains a number of functions for converting and checking ethereum identifiers.1819use alloc::format;20use sp_std::{vec, vec::Vec};21use evm_coder::{22	AbiCoder,23	types::{uint256, address},24};25pub use pallet_evm::{Config, account::CrossAccountId};26use sp_core::H160;27use up_data_structs::CollectionId;2829// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 130// TODO: Unhardcode prefix31const ETH_COLLECTION_PREFIX: [u8; 16] = [32	0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,33];3435/// Maps the ethereum address of the collection in substrate.36pub fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {37	if eth[0..16] != ETH_COLLECTION_PREFIX {38		return None;39	}40	let mut id_bytes = [0; 4];41	id_bytes.copy_from_slice(&eth[16..20]);42	Some(CollectionId(u32::from_be_bytes(id_bytes)))43}4445/// Maps the substrate collection id in ethereum.46pub fn collection_id_to_address(id: CollectionId) -> H160 {47	let mut out = [0; 20];48	out[0..16].copy_from_slice(&ETH_COLLECTION_PREFIX);49	out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));50	H160(out)51}5253/// Check if the ethereum address is a collection.54pub fn is_collection(address: &H160) -> bool {55	address[0..16] == ETH_COLLECTION_PREFIX56}5758/// Convert `uint256` to `CrossAccountId`.59pub fn convert_uint256_to_cross_account<T: Config>(from: uint256) -> T::CrossAccountId60where61	T::AccountId: From<[u8; 32]>,62{63	let mut new_admin_arr = [0_u8; 32];64	from.to_big_endian(&mut new_admin_arr);65	let account_id = T::AccountId::from(new_admin_arr);66	T::CrossAccountId::from_sub(account_id)67}6869/// Ethereum representation of Optional value with CrossAddress.70#[derive(Debug, Default, AbiCoder)]71pub struct OptionCrossAddress {72	/// Whether or not this CrossAdress is valid and has meaning.73	pub status: bool,74	/// The underlying CrossAddress value. If the status is false, can be set to whatever.75	pub value: CrossAddress,76}7778/// Cross account struct79#[derive(Debug, Default, AbiCoder)]80pub struct CrossAddress {81	pub(crate) eth: address,82	pub(crate) sub: uint256,83}8485impl CrossAddress {86	/// Converts `CrossAccountId` to [`CrossAddress`] to be correctly usable with Ethereum.87	pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self88	where89		T: pallet_evm::Config,90		T::AccountId: AsRef<[u8; 32]>,91	{92		if cross_account_id.is_canonical_substrate() {93			Self::from_sub::<T>(cross_account_id.as_sub())94		} else {95			Self {96				eth: *cross_account_id.as_eth(),97				sub: Default::default(),98			}99		}100	}101	/// Creates [`CrossAddress`] from Substrate account.102	pub fn from_sub<T>(account_id: &T::AccountId) -> Self103	where104		T: pallet_evm::Config,105		T::AccountId: AsRef<[u8; 32]>,106	{107		Self {108			eth: Default::default(),109			sub: uint256::from_big_endian(account_id.as_ref()),110		}111	}112	/// Converts [`CrossAddress`] to `CrossAccountId`.113	pub fn into_sub_cross_account<T>(&self) -> evm_coder::execution::Result<T::CrossAccountId>114	where115		T: pallet_evm::Config,116		T::AccountId: From<[u8; 32]>,117	{118		if self.eth == Default::default() && self.sub == Default::default() {119			Err("All fields of cross account is zeroed".into())120		} else if self.eth == Default::default() {121			Ok(convert_uint256_to_cross_account::<T>(self.sub))122		} else if self.sub == Default::default() {123			Ok(T::CrossAccountId::from_eth(self.eth))124		} else {125			Err("All fields of cross account is non zeroed".into())126		}127	}128}129130/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).131#[derive(Debug, Default, AbiCoder)]132pub struct Property {133	key: evm_coder::types::string,134	value: evm_coder::types::bytes,135}136137impl TryFrom<up_data_structs::Property> for Property {138	type Error = evm_coder::execution::Error;139140	fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {141		let key = evm_coder::types::string::from_utf8(from.key.into())142			.map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {}", e)))?;143		let value = evm_coder::types::bytes(from.value.to_vec());144		Ok(Property { key, value })145	}146}147148impl TryInto<up_data_structs::Property> for Property {149	type Error = evm_coder::execution::Error;150151	fn try_into(self) -> Result<up_data_structs::Property, Self::Error> {152		let key = <Vec<u8>>::from(self.key)153			.try_into()154			.map_err(|_| "key too large")?;155156		let value = self.value.0.try_into().map_err(|_| "value too large")?;157158		Ok(up_data_structs::Property { key, value })159	}160}161162/// [`CollectionLimits`](up_data_structs::CollectionLimits) fields representation for EVM.163#[derive(Debug, Default, Clone, Copy, AbiCoder)]164#[repr(u8)]165pub enum CollectionLimitField {166	/// How many tokens can a user have on one account.167	#[default]168	AccountTokenOwnership,169170	/// How many bytes of data are available for sponsorship.171	SponsoredDataSize,172173	/// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]174	SponsoredDataRateLimit,175176	/// How many tokens can be mined into this collection.177	TokenLimit,178179	/// Timeouts for transfer sponsoring.180	SponsorTransferTimeout,181182	/// Timeout for sponsoring an approval in passed blocks.183	SponsorApproveTimeout,184185	/// Whether the collection owner of the collection can send tokens (which belong to other users).186	OwnerCanTransfer,187188	/// Can the collection owner burn other people's tokens.189	OwnerCanDestroy,190191	/// Is it possible to send tokens from this collection between users.192	TransferEnabled,193}194195/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.196#[derive(Debug, Default, AbiCoder)]197pub struct CollectionLimit {198	field: CollectionLimitField,199	value: Option<uint256>,200}201202impl CollectionLimit {203	/// Create [`CollectionLimit`] from field and value.204	pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {205		Self {206			field,207			value: match value {208				Some(value) => Some(value.into()),209				None => None,210			},211		}212	}213	/// Whether the field contains a value.214	pub fn has_value(&self) -> bool {215		self.value.is_some()216	}217}218219impl TryInto<up_data_structs::CollectionLimits> for CollectionLimit {220	type Error = evm_coder::execution::Error;221222	fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {223		let value = self224			.value225			.ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;226		let value = Some(value.try_into().map_err(|error| {227			Self::Error::Revert(format!(228				"can't convert value to u32 \"{}\" because: \"{error}\"",229				value230			))231		})?);232233		let convert_value_to_bool = || match value {234			Some(value) => match value {235				0 => Ok(Some(false)),236				1 => Ok(Some(true)),237				_ => {238					return Err(Self::Error::Revert(format!(239						"can't convert value to boolean \"{value}\""240					)))241				}242			},243			None => Ok(None),244		};245246		let mut limits = up_data_structs::CollectionLimits::default();247		match self.field {248			CollectionLimitField::AccountTokenOwnership => {249				limits.account_token_ownership_limit = value;250			}251			CollectionLimitField::SponsoredDataSize => {252				limits.sponsored_data_size = value;253			}254			CollectionLimitField::SponsoredDataRateLimit => {255				limits.sponsored_data_rate_limit = match value {256					Some(value) => Some(up_data_structs::SponsoringRateLimit::Blocks(value)),257					None => None,258				};259			}260			CollectionLimitField::TokenLimit => {261				limits.token_limit = value;262			}263			CollectionLimitField::SponsorTransferTimeout => {264				limits.sponsor_transfer_timeout = value;265			}266			CollectionLimitField::SponsorApproveTimeout => {267				limits.sponsor_approve_timeout = value;268			}269			CollectionLimitField::OwnerCanTransfer => {270				limits.owner_can_transfer = convert_value_to_bool()?;271			}272			CollectionLimitField::OwnerCanDestroy => {273				limits.owner_can_destroy = convert_value_to_bool()?;274			}275			CollectionLimitField::TransferEnabled => {276				limits.transfers_enabled = convert_value_to_bool()?;277			}278		};279		Ok(limits)280	}281}282283/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) fields as an enumeration.284#[derive(Default, Debug, Clone, Copy, AbiCoder)]285#[repr(u8)]286pub enum CollectionPermissionField {287	/// Owner of token can nest tokens under it.288	#[default]289	TokenOwner,290291	/// Admin of token collection can nest tokens under token.292	CollectionAdmin,293}294295/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.296#[derive(AbiCoder, Copy, Clone, Default, Debug)]297#[repr(u8)]298pub enum TokenPermissionField {299	/// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]300	#[default]301	Mutable,302303	/// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]304	TokenOwner,305306	/// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]307	CollectionAdmin,308}309310/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) as an key and value.311#[derive(Debug, Default, AbiCoder)]312pub struct PropertyPermission {313	/// TokenPermission field.314	code: TokenPermissionField,315	/// TokenPermission value.316	value: bool,317}318319impl PropertyPermission {320	/// Make vector of [`PropertyPermission`] from [`up_data_structs::PropertyPermission`].321	pub fn into_vec(pp: up_data_structs::PropertyPermission) -> Vec<Self> {322		vec![323			PropertyPermission {324				code: TokenPermissionField::Mutable,325				value: pp.mutable,326			},327			PropertyPermission {328				code: TokenPermissionField::TokenOwner,329				value: pp.token_owner,330			},331			PropertyPermission {332				code: TokenPermissionField::CollectionAdmin,333				value: pp.collection_admin,334			},335		]336	}337338	/// Make [`up_data_structs::PropertyPermission`] from vector of [`PropertyPermission`].339	pub fn from_vec(permission: Vec<Self>) -> up_data_structs::PropertyPermission {340		let mut token_permission = up_data_structs::PropertyPermission::default();341342		for PropertyPermission { code, value } in permission {343			match code {344				TokenPermissionField::Mutable => token_permission.mutable = value,345				TokenPermissionField::TokenOwner => token_permission.token_owner = value,346				TokenPermissionField::CollectionAdmin => token_permission.collection_admin = value,347			}348		}349		token_permission350	}351}352353/// Ethereum representation of Token Property Permissions.354#[derive(Debug, Default, AbiCoder)]355pub struct TokenPropertyPermission {356	/// Token property key.357	key: evm_coder::types::string,358	/// Token property permissions.359	permissions: Vec<PropertyPermission>,360}361362impl363	From<(364		up_data_structs::PropertyKey,365		up_data_structs::PropertyPermission,366	)> for TokenPropertyPermission367{368	fn from(369		value: (370			up_data_structs::PropertyKey,371			up_data_structs::PropertyPermission,372		),373	) -> Self {374		let (key, permission) = value;375		let key = evm_coder::types::string::from_utf8(key.into_inner())376			.expect("Stored key must be valid");377		let permissions = PropertyPermission::into_vec(permission);378		Self { key, permissions }379	}380}381382impl TokenPropertyPermission {383	/// Convert vector of [`TokenPropertyPermission`] into vector of [`up_data_structs::PropertyKeyPermission`].384	pub fn into_property_key_permissions(385		permissions: Vec<TokenPropertyPermission>,386	) -> evm_coder::execution::Result<Vec<up_data_structs::PropertyKeyPermission>> {387		let mut perms = Vec::new();388389		for TokenPropertyPermission { key, permissions } in permissions {390			let token_permission = PropertyPermission::from_vec(permissions);391392			perms.push(up_data_structs::PropertyKeyPermission {393				key: key.into_bytes().try_into().map_err(|_| "too long key")?,394				permission: token_permission,395			});396		}397		Ok(perms)398	}399}400401/// Nested collections.402#[derive(Debug, Default, AbiCoder)]403pub struct CollectionNesting {404	token_owner: bool,405	ids: Vec<uint256>,406}407408impl CollectionNesting {409	/// Create [`CollectionNesting`].410	pub fn new(token_owner: bool, ids: Vec<uint256>) -> Self {411		Self { token_owner, ids }412	}413}414415/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) field.416#[derive(Debug, Default, AbiCoder)]417pub struct CollectionNestingPermission {418	field: CollectionPermissionField,419	value: bool,420}421422impl CollectionNestingPermission {423	/// Create [`CollectionNestingPermission`].424	pub fn new(field: CollectionPermissionField, value: bool) -> Self {425		Self { field, value }426	}427}
after · pallets/common/src/eth.rs
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//! The module contains a number of functions for converting and checking ethereum identifiers.1819use alloc::format;20use sp_std::{vec, vec::Vec};21use evm_coder::{22	AbiCoder,23	types::{uint256, address},24};25pub use pallet_evm::{Config, account::CrossAccountId};26use sp_core::H160;27use up_data_structs::CollectionId;2829// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 130// TODO: Unhardcode prefix31const ETH_COLLECTION_PREFIX: [u8; 16] = [32	0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,33];3435/// Maps the ethereum address of the collection in substrate.36pub fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {37	if eth[0..16] != ETH_COLLECTION_PREFIX {38		return None;39	}40	let mut id_bytes = [0; 4];41	id_bytes.copy_from_slice(&eth[16..20]);42	Some(CollectionId(u32::from_be_bytes(id_bytes)))43}4445/// Maps the substrate collection id in ethereum.46pub fn collection_id_to_address(id: CollectionId) -> H160 {47	let mut out = [0; 20];48	out[0..16].copy_from_slice(&ETH_COLLECTION_PREFIX);49	out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));50	H160(out)51}5253/// Check if the ethereum address is a collection.54pub fn is_collection(address: &H160) -> bool {55	address[0..16] == ETH_COLLECTION_PREFIX56}5758/// Convert `uint256` to `CrossAccountId`.59pub fn convert_uint256_to_cross_account<T: Config>(from: uint256) -> T::CrossAccountId60where61	T::AccountId: From<[u8; 32]>,62{63	let mut new_admin_arr = [0_u8; 32];64	from.to_big_endian(&mut new_admin_arr);65	let account_id = T::AccountId::from(new_admin_arr);66	T::CrossAccountId::from_sub(account_id)67}6869/// Cross account struct70#[derive(Debug, Default, AbiCoder)]71pub struct CrossAddress {72	pub(crate) eth: address,73	pub(crate) sub: uint256,74}7576impl CrossAddress {77	/// Converts `CrossAccountId` to [`CrossAddress`] to be correctly usable with Ethereum.78	pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self79	where80		T: pallet_evm::Config,81		T::AccountId: AsRef<[u8; 32]>,82	{83		if cross_account_id.is_canonical_substrate() {84			Self::from_sub::<T>(cross_account_id.as_sub())85		} else {86			Self {87				eth: *cross_account_id.as_eth(),88				sub: Default::default(),89			}90		}91	}92	/// Creates [`CrossAddress`] from Substrate account.93	pub fn from_sub<T>(account_id: &T::AccountId) -> Self94	where95		T: pallet_evm::Config,96		T::AccountId: AsRef<[u8; 32]>,97	{98		Self {99			eth: Default::default(),100			sub: uint256::from_big_endian(account_id.as_ref()),101		}102	}103	/// Converts [`CrossAddress`] to `CrossAccountId`.104	pub fn into_sub_cross_account<T>(&self) -> evm_coder::execution::Result<T::CrossAccountId>105	where106		T: pallet_evm::Config,107		T::AccountId: From<[u8; 32]>,108	{109		if self.eth == Default::default() && self.sub == Default::default() {110			Err("All fields of cross account is zeroed".into())111		} else if self.eth == Default::default() {112			Ok(convert_uint256_to_cross_account::<T>(self.sub))113		} else if self.sub == Default::default() {114			Ok(T::CrossAccountId::from_eth(self.eth))115		} else {116			Err("All fields of cross account is non zeroed".into())117		}118	}119}120121/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).122#[derive(Debug, Default, AbiCoder)]123pub struct Property {124	key: evm_coder::types::string,125	value: evm_coder::types::bytes,126}127128impl TryFrom<up_data_structs::Property> for Property {129	type Error = evm_coder::execution::Error;130131	fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {132		let key = evm_coder::types::string::from_utf8(from.key.into())133			.map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {}", e)))?;134		let value = evm_coder::types::bytes(from.value.to_vec());135		Ok(Property { key, value })136	}137}138139impl TryInto<up_data_structs::Property> for Property {140	type Error = evm_coder::execution::Error;141142	fn try_into(self) -> Result<up_data_structs::Property, Self::Error> {143		let key = <Vec<u8>>::from(self.key)144			.try_into()145			.map_err(|_| "key too large")?;146147		let value = self.value.0.try_into().map_err(|_| "value too large")?;148149		Ok(up_data_structs::Property { key, value })150	}151}152153/// [`CollectionLimits`](up_data_structs::CollectionLimits) fields representation for EVM.154#[derive(Debug, Default, Clone, Copy, AbiCoder)]155#[repr(u8)]156pub enum CollectionLimitField {157	/// How many tokens can a user have on one account.158	#[default]159	AccountTokenOwnership,160161	/// How many bytes of data are available for sponsorship.162	SponsoredDataSize,163164	/// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]165	SponsoredDataRateLimit,166167	/// How many tokens can be mined into this collection.168	TokenLimit,169170	/// Timeouts for transfer sponsoring.171	SponsorTransferTimeout,172173	/// Timeout for sponsoring an approval in passed blocks.174	SponsorApproveTimeout,175176	/// Whether the collection owner of the collection can send tokens (which belong to other users).177	OwnerCanTransfer,178179	/// Can the collection owner burn other people's tokens.180	OwnerCanDestroy,181182	/// Is it possible to send tokens from this collection between users.183	TransferEnabled,184}185186/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.187#[derive(Debug, Default, AbiCoder)]188pub struct CollectionLimit {189	field: CollectionLimitField,190	value: Option<uint256>,191}192193impl CollectionLimit {194	/// Create [`CollectionLimit`] from field and value.195	pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {196		Self {197			field,198			value: match value {199				Some(value) => Some(value.into()),200				None => None,201			},202		}203	}204	/// Whether the field contains a value.205	pub fn has_value(&self) -> bool {206		self.value.is_some()207	}208}209210impl TryInto<up_data_structs::CollectionLimits> for CollectionLimit {211	type Error = evm_coder::execution::Error;212213	fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {214		let value = self215			.value216			.ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;217		let value = Some(value.try_into().map_err(|error| {218			Self::Error::Revert(format!(219				"can't convert value to u32 \"{}\" because: \"{error}\"",220				value221			))222		})?);223224		let convert_value_to_bool = || match value {225			Some(value) => match value {226				0 => Ok(Some(false)),227				1 => Ok(Some(true)),228				_ => {229					return Err(Self::Error::Revert(format!(230						"can't convert value to boolean \"{value}\""231					)))232				}233			},234			None => Ok(None),235		};236237		let mut limits = up_data_structs::CollectionLimits::default();238		match self.field {239			CollectionLimitField::AccountTokenOwnership => {240				limits.account_token_ownership_limit = value;241			}242			CollectionLimitField::SponsoredDataSize => {243				limits.sponsored_data_size = value;244			}245			CollectionLimitField::SponsoredDataRateLimit => {246				limits.sponsored_data_rate_limit = match value {247					Some(value) => Some(up_data_structs::SponsoringRateLimit::Blocks(value)),248					None => None,249				};250			}251			CollectionLimitField::TokenLimit => {252				limits.token_limit = value;253			}254			CollectionLimitField::SponsorTransferTimeout => {255				limits.sponsor_transfer_timeout = value;256			}257			CollectionLimitField::SponsorApproveTimeout => {258				limits.sponsor_approve_timeout = value;259			}260			CollectionLimitField::OwnerCanTransfer => {261				limits.owner_can_transfer = convert_value_to_bool()?;262			}263			CollectionLimitField::OwnerCanDestroy => {264				limits.owner_can_destroy = convert_value_to_bool()?;265			}266			CollectionLimitField::TransferEnabled => {267				limits.transfers_enabled = convert_value_to_bool()?;268			}269		};270		Ok(limits)271	}272}273274/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) fields as an enumeration.275#[derive(Default, Debug, Clone, Copy, AbiCoder)]276#[repr(u8)]277pub enum CollectionPermissionField {278	/// Owner of token can nest tokens under it.279	#[default]280	TokenOwner,281282	/// Admin of token collection can nest tokens under token.283	CollectionAdmin,284}285286/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.287#[derive(AbiCoder, Copy, Clone, Default, Debug)]288#[repr(u8)]289pub enum TokenPermissionField {290	/// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]291	#[default]292	Mutable,293294	/// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]295	TokenOwner,296297	/// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]298	CollectionAdmin,299}300301/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) as an key and value.302#[derive(Debug, Default, AbiCoder)]303pub struct PropertyPermission {304	/// TokenPermission field.305	code: TokenPermissionField,306	/// TokenPermission value.307	value: bool,308}309310impl PropertyPermission {311	/// Make vector of [`PropertyPermission`] from [`up_data_structs::PropertyPermission`].312	pub fn into_vec(pp: up_data_structs::PropertyPermission) -> Vec<Self> {313		vec![314			PropertyPermission {315				code: TokenPermissionField::Mutable,316				value: pp.mutable,317			},318			PropertyPermission {319				code: TokenPermissionField::TokenOwner,320				value: pp.token_owner,321			},322			PropertyPermission {323				code: TokenPermissionField::CollectionAdmin,324				value: pp.collection_admin,325			},326		]327	}328329	/// Make [`up_data_structs::PropertyPermission`] from vector of [`PropertyPermission`].330	pub fn from_vec(permission: Vec<Self>) -> up_data_structs::PropertyPermission {331		let mut token_permission = up_data_structs::PropertyPermission::default();332333		for PropertyPermission { code, value } in permission {334			match code {335				TokenPermissionField::Mutable => token_permission.mutable = value,336				TokenPermissionField::TokenOwner => token_permission.token_owner = value,337				TokenPermissionField::CollectionAdmin => token_permission.collection_admin = value,338			}339		}340		token_permission341	}342}343344/// Ethereum representation of Token Property Permissions.345#[derive(Debug, Default, AbiCoder)]346pub struct TokenPropertyPermission {347	/// Token property key.348	key: evm_coder::types::string,349	/// Token property permissions.350	permissions: Vec<PropertyPermission>,351}352353impl354	From<(355		up_data_structs::PropertyKey,356		up_data_structs::PropertyPermission,357	)> for TokenPropertyPermission358{359	fn from(360		value: (361			up_data_structs::PropertyKey,362			up_data_structs::PropertyPermission,363		),364	) -> Self {365		let (key, permission) = value;366		let key = evm_coder::types::string::from_utf8(key.into_inner())367			.expect("Stored key must be valid");368		let permissions = PropertyPermission::into_vec(permission);369		Self { key, permissions }370	}371}372373impl TokenPropertyPermission {374	/// Convert vector of [`TokenPropertyPermission`] into vector of [`up_data_structs::PropertyKeyPermission`].375	pub fn into_property_key_permissions(376		permissions: Vec<TokenPropertyPermission>,377	) -> evm_coder::execution::Result<Vec<up_data_structs::PropertyKeyPermission>> {378		let mut perms = Vec::new();379380		for TokenPropertyPermission { key, permissions } in permissions {381			let token_permission = PropertyPermission::from_vec(permissions);382383			perms.push(up_data_structs::PropertyKeyPermission {384				key: key.into_bytes().try_into().map_err(|_| "too long key")?,385				permission: token_permission,386			});387		}388		Ok(perms)389	}390}391392/// Nested collections.393#[derive(Debug, Default, AbiCoder)]394pub struct CollectionNesting {395	token_owner: bool,396	ids: Vec<uint256>,397}398399impl CollectionNesting {400	/// Create [`CollectionNesting`].401	pub fn new(token_owner: bool, ids: Vec<uint256>) -> Self {402		Self { token_owner, ids }403	}404}405406/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) field.407#[derive(Debug, Default, AbiCoder)]408pub struct CollectionNestingPermission {409	field: CollectionPermissionField,410	value: bool,411}412413impl CollectionNestingPermission {414	/// Create [`CollectionNestingPermission`].415	pub fn new(field: CollectionPermissionField, value: bool) -> Self {416		Self { field, value }417	}418}
modifiedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -175,16 +175,10 @@
 	///
 	/// @param contractAddress The contract for which a sponsor is requested.
 	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
-	fn sponsor(&self, contract_address: address) -> Result<eth::OptionCrossAddress> {
+	fn sponsor(&self, contract_address: address) -> Result<Option<eth::CrossAddress>> {
 		Ok(match Pallet::<T>::get_sponsor(contract_address) {
-			Some(ref value) => eth::OptionCrossAddress {
-				status: true,
-				value: eth::CrossAddress::from_sub_cross_account::<T>(value),
-			},
-			None => eth::OptionCrossAddress {
-				status: false,
-				value: Default::default(),
-			},
+			Some(ref value) => Some(eth::CrossAddress::from_sub_cross_account::<T>(value)),
+			None => None,
 		})
 	}
 
modifiedpallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/evm-contract-helpers/src/stubs/ContractHelpers.soldiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
+++ b/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
@@ -96,11 +96,11 @@
 	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
 	/// @dev EVM selector for this function is: 0x766c4f37,
 	///  or in textual repr: sponsor(address)
-	function sponsor(address contractAddress) public view returns (OptionCrossAddress memory) {
+	function sponsor(address contractAddress) public view returns (Option_CrossAddress memory) {
 		require(false, stub_error);
 		contractAddress;
 		dummy;
-		return OptionCrossAddress(false, CrossAddress(0x0000000000000000000000000000000000000000, 0));
+		return Option_CrossAddress(false, CrossAddress(0x0000000000000000000000000000000000000000, 0));
 	}
 
 	/// Check tat contract has confirmed sponsor.
@@ -281,10 +281,10 @@
 	uint256 sub;
 }
 
-/// Ethereum representation of Optional value with CrossAddress.
-struct OptionCrossAddress {
-	/// Whether or not this CrossAdress is valid and has meaning.
+/// Optional value
+struct Option_CrossAddress {
+	/// Shows the status of accessibility of value
 	bool status;
-	/// The underlying CrossAddress value. If the status is false, can be set to whatever.
+	/// Actual value if `status` is true
 	CrossAddress value;
 }
modifiedtests/src/eth/abi/contractHelpers.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/contractHelpers.json
+++ b/tests/src/eth/abi/contractHelpers.json
@@ -238,7 +238,7 @@
             "type": "tuple"
           }
         ],
-        "internalType": "struct OptionCrossAddress",
+        "internalType": "struct Option_CrossAddress",
         "name": "",
         "type": "tuple"
       }
modifiedtests/src/eth/api/ContractHelpers.soldiffbeforeafterboth
--- a/tests/src/eth/api/ContractHelpers.sol
+++ b/tests/src/eth/api/ContractHelpers.sol
@@ -69,7 +69,7 @@
 	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
 	/// @dev EVM selector for this function is: 0x766c4f37,
 	///  or in textual repr: sponsor(address)
-	function sponsor(address contractAddress) external view returns (OptionCrossAddress memory);
+	function sponsor(address contractAddress) external view returns (Option_CrossAddress memory);
 
 	/// Check tat contract has confirmed sponsor.
 	///
@@ -181,11 +181,11 @@
 	Generous
 }
 
-/// Ethereum representation of Optional value with CrossAddress.
-struct OptionCrossAddress {
-	/// Whether or not this CrossAdress is valid and has meaning.
+/// Optional value
+struct Option_CrossAddress {
+	/// Shows the status of accessibility of value
 	bool status;
-	/// The underlying CrossAddress value. If the status is false, can be set to whatever.
+	/// Actual value if `status` is true
 	CrossAddress value;
 }