git.delta.rocks / unique-network / refs/commits / c43c309b3350

difftreelog

source

pallets/common/src/eth.rs13.7 KiBsourcehistory
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::{Address, String},24};25pub use pallet_evm::{Config, account::CrossAccountId};26use sp_core::{H160, U256};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: &Address) -> 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) -> Address {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: &Address) -> bool {55	address[0..16] == ETH_COLLECTION_PREFIX56}5758/// Convert `U256` to `CrossAccountId`.59pub fn convert_uint256_to_cross_account<T: Config>(from: U256) -> 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: U256,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::from_eth(*cross_account_id.as_eth())87		}88	}89	/// Creates [`CrossAddress`] from Substrate account.90	pub fn from_sub<T>(account_id: &T::AccountId) -> Self91	where92		T: pallet_evm::Config,93		T::AccountId: AsRef<[u8; 32]>,94	{95		Self {96			eth: Default::default(),97			sub: U256::from_big_endian(account_id.as_ref()),98		}99	}100	/// Creates [`CrossAddress`] from Ethereum account.101	pub fn from_eth(address: Address) -> Self {102		Self {103			eth: address,104			sub: Default::default(),105		}106	}107	/// Converts [`CrossAddress`] to `CrossAccountId`.108	pub fn into_sub_cross_account<T>(109		&self,110	) -> pallet_evm_coder_substrate::execution::Result<T::CrossAccountId>111	where112		T: pallet_evm::Config,113		T::AccountId: From<[u8; 32]>,114	{115		if self.eth == Default::default() && self.sub == Default::default() {116			Err("All fields of cross account is zeroed".into())117		} else if self.eth == Default::default() {118			Ok(convert_uint256_to_cross_account::<T>(self.sub))119		} else if self.sub == Default::default() {120			Ok(T::CrossAccountId::from_eth(self.eth))121		} else {122			Err("All fields of cross account is non zeroed".into())123		}124	}125}126127/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).128#[derive(Debug, Default, AbiCoder)]129pub struct Property {130	key: evm_coder::types::String,131	value: evm_coder::types::Bytes,132}133134impl TryFrom<up_data_structs::Property> for Property {135	type Error = pallet_evm_coder_substrate::execution::Error;136137	fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {138		let key = evm_coder::types::String::from_utf8(from.key.into())139			.map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {}", e)))?;140		let value = evm_coder::types::Bytes(from.value.to_vec());141		Ok(Property { key, value })142	}143}144145impl TryInto<up_data_structs::Property> for Property {146	type Error = pallet_evm_coder_substrate::execution::Error;147148	fn try_into(self) -> Result<up_data_structs::Property, Self::Error> {149		let key = <Vec<u8>>::from(self.key)150			.try_into()151			.map_err(|_| "key too large")?;152153		let value = self.value.0.try_into().map_err(|_| "value too large")?;154155		Ok(up_data_structs::Property { key, value })156	}157}158159/// [`CollectionLimits`](up_data_structs::CollectionLimits) fields representation for EVM.160#[derive(Debug, Default, Clone, Copy, AbiCoder)]161#[repr(u8)]162pub enum CollectionLimitField {163	/// How many tokens can a user have on one account.164	#[default]165	AccountTokenOwnership,166167	/// How many bytes of data are available for sponsorship.168	SponsoredDataSize,169170	/// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]171	SponsoredDataRateLimit,172173	/// How many tokens can be mined into this collection.174	TokenLimit,175176	/// Timeouts for transfer sponsoring.177	SponsorTransferTimeout,178179	/// Timeout for sponsoring an approval in passed blocks.180	SponsorApproveTimeout,181182	/// Whether the collection owner of the collection can send tokens (which belong to other users).183	OwnerCanTransfer,184185	/// Can the collection owner burn other people's tokens.186	OwnerCanDestroy,187188	/// Is it possible to send tokens from this collection between users.189	TransferEnabled,190}191192/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.193#[derive(Debug, Default, AbiCoder)]194pub struct CollectionLimit {195	field: CollectionLimitField,196	value: Option<U256>,197}198199impl CollectionLimit {200	/// Create [`CollectionLimit`] from field and value.201	pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {202		Self {203			field,204			value: match value {205				Some(value) => Some(value.into()),206				None => None,207			},208		}209	}210	/// Whether the field contains a value.211	pub fn has_value(&self) -> bool {212		self.value.is_some()213	}214}215216impl TryInto<up_data_structs::CollectionLimits> for CollectionLimit {217	type Error = pallet_evm_coder_substrate::execution::Error;218219	fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {220		let value = self221			.value222			.ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;223		let value = Some(value.try_into().map_err(|error| {224			Self::Error::Revert(format!(225				"can't convert value to u32 \"{}\" because: \"{error}\"",226				value227			))228		})?);229230		let convert_value_to_bool = || match value {231			Some(value) => match value {232				0 => Ok(Some(false)),233				1 => Ok(Some(true)),234				_ => {235					return Err(Self::Error::Revert(format!(236						"can't convert value to boolean \"{value}\""237					)))238				}239			},240			None => Ok(None),241		};242243		let mut limits = up_data_structs::CollectionLimits::default();244		match self.field {245			CollectionLimitField::AccountTokenOwnership => {246				limits.account_token_ownership_limit = value;247			}248			CollectionLimitField::SponsoredDataSize => {249				limits.sponsored_data_size = value;250			}251			CollectionLimitField::SponsoredDataRateLimit => {252				limits.sponsored_data_rate_limit = match value {253					Some(value) => Some(up_data_structs::SponsoringRateLimit::Blocks(value)),254					None => None,255				};256			}257			CollectionLimitField::TokenLimit => {258				limits.token_limit = value;259			}260			CollectionLimitField::SponsorTransferTimeout => {261				limits.sponsor_transfer_timeout = value;262			}263			CollectionLimitField::SponsorApproveTimeout => {264				limits.sponsor_approve_timeout = value;265			}266			CollectionLimitField::OwnerCanTransfer => {267				limits.owner_can_transfer = convert_value_to_bool()?;268			}269			CollectionLimitField::OwnerCanDestroy => {270				limits.owner_can_destroy = convert_value_to_bool()?;271			}272			CollectionLimitField::TransferEnabled => {273				limits.transfers_enabled = convert_value_to_bool()?;274			}275		};276		Ok(limits)277	}278}279280/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) fields as an enumeration.281#[derive(Default, Debug, Clone, Copy, AbiCoder)]282#[repr(u8)]283pub enum CollectionPermissionField {284	/// Owner of token can nest tokens under it.285	#[default]286	TokenOwner,287288	/// Admin of token collection can nest tokens under token.289	CollectionAdmin,290}291292/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.293#[derive(AbiCoder, Copy, Clone, Default, Debug)]294#[repr(u8)]295pub enum TokenPermissionField {296	/// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]297	#[default]298	Mutable,299300	/// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]301	TokenOwner,302303	/// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]304	CollectionAdmin,305}306307/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) as an key and value.308#[derive(Debug, Default, AbiCoder)]309pub struct PropertyPermission {310	/// TokenPermission field.311	code: TokenPermissionField,312	/// TokenPermission value.313	value: bool,314}315316impl PropertyPermission {317	/// Make vector of [`PropertyPermission`] from [`up_data_structs::PropertyPermission`].318	pub fn into_vec(pp: up_data_structs::PropertyPermission) -> Vec<Self> {319		vec![320			PropertyPermission {321				code: TokenPermissionField::Mutable,322				value: pp.mutable,323			},324			PropertyPermission {325				code: TokenPermissionField::TokenOwner,326				value: pp.token_owner,327			},328			PropertyPermission {329				code: TokenPermissionField::CollectionAdmin,330				value: pp.collection_admin,331			},332		]333	}334335	/// Make [`up_data_structs::PropertyPermission`] from vector of [`PropertyPermission`].336	pub fn from_vec(permission: Vec<Self>) -> up_data_structs::PropertyPermission {337		let mut token_permission = up_data_structs::PropertyPermission::default();338339		for PropertyPermission { code, value } in permission {340			match code {341				TokenPermissionField::Mutable => token_permission.mutable = value,342				TokenPermissionField::TokenOwner => token_permission.token_owner = value,343				TokenPermissionField::CollectionAdmin => token_permission.collection_admin = value,344			}345		}346		token_permission347	}348}349350/// Ethereum representation of Token Property Permissions.351#[derive(Debug, Default, AbiCoder)]352pub struct TokenPropertyPermission {353	/// Token property key.354	key: evm_coder::types::String,355	/// Token property permissions.356	permissions: Vec<PropertyPermission>,357}358359impl360	From<(361		up_data_structs::PropertyKey,362		up_data_structs::PropertyPermission,363	)> for TokenPropertyPermission364{365	fn from(366		value: (367			up_data_structs::PropertyKey,368			up_data_structs::PropertyPermission,369		),370	) -> Self {371		let (key, permission) = value;372		let key = evm_coder::types::String::from_utf8(key.into_inner())373			.expect("Stored key must be valid");374		let permissions = PropertyPermission::into_vec(permission);375		Self { key, permissions }376	}377}378379impl TokenPropertyPermission {380	/// Convert vector of [`TokenPropertyPermission`] into vector of [`up_data_structs::PropertyKeyPermission`].381	pub fn into_property_key_permissions(382		permissions: Vec<TokenPropertyPermission>,383	) -> pallet_evm_coder_substrate::execution::Result<Vec<up_data_structs::PropertyKeyPermission>>384	{385		let mut perms = Vec::new();386387		for TokenPropertyPermission { key, permissions } in permissions {388			let token_permission = PropertyPermission::from_vec(permissions);389390			perms.push(up_data_structs::PropertyKeyPermission {391				key: key.into_bytes().try_into().map_err(|_| "too long key")?,392				permission: token_permission,393			});394		}395		Ok(perms)396	}397}398399/// Data for creation token with uri.400#[derive(Debug, AbiCoder)]401pub struct TokenUri {402	/// Id of new token.403	pub id: U256,404405	/// Uri of new token.406	pub uri: String,407}408409/// Nested collections.410#[derive(Debug, Default, AbiCoder)]411pub struct CollectionNesting {412	token_owner: bool,413	ids: Vec<U256>,414}415416impl CollectionNesting {417	/// Create [`CollectionNesting`].418	pub fn new(token_owner: bool, ids: Vec<U256>) -> Self {419		Self { token_owner, ids }420	}421}422423/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) field.424#[derive(Debug, Default, AbiCoder)]425pub struct CollectionNestingPermission {426	field: CollectionPermissionField,427	value: bool,428}429430impl CollectionNestingPermission {431	/// Create [`CollectionNestingPermission`].432	pub fn new(field: CollectionPermissionField, value: bool) -> Self {433		Self { field, value }434	}435}436437/// Ethereum representation of `AccessMode` (see [`up_data_structs::AccessMode`]).438#[derive(AbiCoder, Copy, Clone, Default, Debug)]439#[repr(u8)]440pub enum AccessMode {441	/// Access grant for owner and admins. Used as default.442	#[default]443	Normal,444	/// Like a [`Normal`](AccessMode::Normal) but also users in allow list.445	AllowList,446}447448impl From<up_data_structs::AccessMode> for AccessMode {449	fn from(value: up_data_structs::AccessMode) -> Self {450		match value {451			up_data_structs::AccessMode::Normal => AccessMode::Normal,452			up_data_structs::AccessMode::AllowList => AccessMode::AllowList,453		}454	}455}456457impl Into<up_data_structs::AccessMode> for AccessMode {458	fn into(self) -> up_data_structs::AccessMode {459		match self {460			AccessMode::Normal => up_data_structs::AccessMode::Normal,461			AccessMode::AllowList => up_data_structs::AccessMode::AllowList,462		}463	}464}