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

difftreelog

refactor move token address mapping to trait

Yaroslav Bolyukin2022-04-07parent: #3ae92b8.patch.diff
in: master

6 files changed

modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -19,18 +19,12 @@
 
 // 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 1
 // TODO: Unhardcode prefix
-const ETH_ACCOUNT_PREFIX: [u8; 16] = [
+const ETH_COLLECTION_PREFIX: [u8; 16] = [
 	0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
 ];
 
-// 0xf8238ccfff8ed887463fd5e00000000100000002  - collection 1, token 2
-// TODO: Unhardcode prefix
-const ETH_ACCOUNT_TOKEN_PREFIX: [u8; 12] = [
-	0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
-];
-
 pub fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {
-	if eth[0..16] != ETH_ACCOUNT_PREFIX {
+	if eth[0..16] != ETH_COLLECTION_PREFIX {
 		return None;
 	}
 	let mut id_bytes = [0; 4];
@@ -39,28 +33,7 @@
 }
 pub fn collection_id_to_address(id: CollectionId) -> H160 {
 	let mut out = [0; 20];
-	out[0..16].copy_from_slice(&ETH_ACCOUNT_PREFIX);
+	out[0..16].copy_from_slice(&ETH_COLLECTION_PREFIX);
 	out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));
-	H160(out)
-}
-
-pub fn map_eth_to_token_id(eth: &H160) -> Option<(CollectionId, TokenId)> {
-	if eth[0..12] != ETH_ACCOUNT_TOKEN_PREFIX {
-		return None;
-	}
-	let mut id_bytes = [0; 4];
-	let mut token_id_bytes = [0; 4];
-	id_bytes.copy_from_slice(&eth[12..16]);
-	token_id_bytes.copy_from_slice(&eth[16..20]);
-	Some((
-		CollectionId(u32::from_be_bytes(id_bytes)),
-		TokenId(u32::from_be_bytes(token_id_bytes)),
-	))
-}
-pub fn collection_token_id_to_address(id: CollectionId, token: TokenId) -> H160 {
-	let mut out = [0; 20];
-	out[0..12].copy_from_slice(&ETH_ACCOUNT_TOKEN_PREFIX);
-	out[12..16].copy_from_slice(&u32::to_be_bytes(id.0));
-	out[16..20].copy_from_slice(&u32::to_be_bytes(token.0));
 	H160(out)
 }
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -165,8 +165,10 @@
 	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};
 	use pallet_evm::account;
 	use dispatch::CollectionDispatch;
+	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};
+	use frame_system::pallet_prelude::*;
 	use frame_support::traits::Currency;
-	use up_data_structs::TokenId;
+	use up_data_structs::{TokenId, mapping::TokenAddressMapping};
 	use scale_info::TypeInfo;
 	use up_evm_mapping::CrossAccountId;
 
@@ -185,6 +187,9 @@
 		type CollectionDispatch: CollectionDispatch<Self>;
 
 		type TreasuryAccountId: Get<Self::AccountId>;
+
+		type EvmTokenAddressMapping: TokenAddressMapping<H160>;
+		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;
 	}
 
 	#[pallet::pallet]
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
before · primitives/data-structs/src/lib.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#![cfg_attr(not(feature = "std"), no_std)]1819use core::{20	convert::{TryFrom, TryInto},21	fmt,22};23use frame_support::storage::bounded_btree_map::BoundedBTreeMap;24use sp_std::collections::btree_map::BTreeMap;2526#[cfg(feature = "serde")]27pub use serde::{Serialize, Deserialize};2829use sp_core::U256;30use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};31use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};32pub use frame_support::{33	BoundedVec, construct_runtime, decl_event, decl_module, decl_storage, decl_error,34	dispatch::DispatchResult,35	ensure, fail, parameter_types,36	traits::{37		Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,38		Randomness, IsSubType, WithdrawReasons,39	},40	weights::{41		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},42		DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,43		WeightToFeePolynomial, DispatchClass,44	},45	StorageValue, transactional,46	pallet_prelude::ConstU32,47};48use derivative::Derivative;49use scale_info::TypeInfo;5051mod migration;5253pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;54pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;55pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;5657pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {58	100_00059} else {60	1061};62pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {63	100_00064} else {65	1066};67pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {68	204869} else {70	1071};72pub const COLLECTION_ADMINS_LIMIT: u32 = 5;73pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;74pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {75	1_000_00076} else {77	1078};7980// Timeouts for item types in passed blocks81pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;82pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;83pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;8485pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;8687// Schema limits88pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;89pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;90pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;9192pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;93pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;94pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;9596/// How much items can be created per single97/// create_many call98pub const MAX_ITEMS_PER_BATCH: u32 = 200;99100pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;101102#[derive(103	Encode,104	Decode,105	PartialEq,106	Eq,107	PartialOrd,108	Ord,109	Clone,110	Copy,111	Debug,112	Default,113	TypeInfo,114	MaxEncodedLen,115)]116#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]117pub struct CollectionId(pub u32);118impl EncodeLike<u32> for CollectionId {}119impl EncodeLike<CollectionId> for u32 {}120121#[derive(122	Encode,123	Decode,124	PartialEq,125	Eq,126	PartialOrd,127	Ord,128	Clone,129	Copy,130	Debug,131	Default,132	TypeInfo,133	MaxEncodedLen,134)]135#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]136pub struct TokenId(pub u32);137impl EncodeLike<u32> for TokenId {}138impl EncodeLike<TokenId> for u32 {}139140impl TokenId {141	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {142		self.0143			.checked_add(1)144			.ok_or(ArithmeticError::Overflow)145			.map(Self)146	}147}148149impl From<TokenId> for U256 {150	fn from(t: TokenId) -> Self {151		t.0.into()152	}153}154155impl TryFrom<U256> for TokenId {156	type Error = &'static str;157158	fn try_from(value: U256) -> Result<Self, Self::Error> {159		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))160	}161}162163pub struct OverflowError;164impl From<OverflowError> for &'static str {165	fn from(_: OverflowError) -> Self {166		"overflow occured"167	}168}169170pub type DecimalPoints = u8;171172#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]173#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]174pub enum CollectionMode {175	NFT,176	// decimal points177	Fungible(DecimalPoints),178	ReFungible,179}180181impl CollectionMode {182	pub fn id(&self) -> u8 {183		match self {184			CollectionMode::NFT => 1,185			CollectionMode::Fungible(_) => 2,186			CollectionMode::ReFungible => 3,187		}188	}189}190191pub trait SponsoringResolve<AccountId, Call> {192	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;193}194195#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]196#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]197pub enum AccessMode {198	Normal,199	AllowList,200}201impl Default for AccessMode {202	fn default() -> Self {203		Self::Normal204	}205}206207#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]208#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]209pub enum SchemaVersion {210	ImageURL,211	Unique,212}213impl Default for SchemaVersion {214	fn default() -> Self {215		Self::ImageURL216	}217}218219#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]220#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]221pub struct Ownership<AccountId> {222	pub owner: AccountId,223	pub fraction: u128,224}225226#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]227#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]228pub enum SponsorshipState<AccountId> {229	/// The fees are applied to the transaction sender230	Disabled,231	Unconfirmed(AccountId),232	/// Transactions are sponsored by specified account233	Confirmed(AccountId),234}235236impl<AccountId> SponsorshipState<AccountId> {237	pub fn sponsor(&self) -> Option<&AccountId> {238		match self {239			Self::Confirmed(sponsor) => Some(sponsor),240			_ => None,241		}242	}243244	pub fn pending_sponsor(&self) -> Option<&AccountId> {245		match self {246			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),247			_ => None,248		}249	}250251	pub fn confirmed(&self) -> bool {252		matches!(self, Self::Confirmed(_))253	}254}255256impl<T> Default for SponsorshipState<T> {257	fn default() -> Self {258		Self::Disabled259	}260}261262#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]263#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]264pub struct Collection<AccountId> {265	pub owner: AccountId,266	pub mode: CollectionMode,267	pub access: AccessMode,268	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]269	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,270	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]271	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,272	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]273	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,274	pub mint_mode: bool,275	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]276	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,277	pub schema_version: SchemaVersion,278	pub sponsorship: SponsorshipState<AccountId>,279	pub limits: CollectionLimits, // Collection private restrictions280	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]281	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,282	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]283	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,284	pub meta_update_permission: MetaUpdatePermission,285}286287#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]288#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]289#[derivative(Default(bound = ""))]290pub struct CreateCollectionData<AccountId> {291	#[derivative(Default(value = "CollectionMode::NFT"))]292	pub mode: CollectionMode,293	pub access: Option<AccessMode>,294	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]295	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,296	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]297	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,298	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]299	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,300	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]301	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,302	pub schema_version: Option<SchemaVersion>,303	pub pending_sponsor: Option<AccountId>,304	pub limits: Option<CollectionLimits>,305	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]306	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,307	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]308	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,309	pub meta_update_permission: Option<MetaUpdatePermission>,310}311312#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]313#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]314pub struct NftItemType<AccountId> {315	pub owner: AccountId,316	pub const_data: Vec<u8>,317	pub variable_data: Vec<u8>,318}319320#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]321#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]322pub struct FungibleItemType {323	pub value: u128,324}325326#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]327#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]328pub struct ReFungibleItemType<AccountId> {329	pub owner: Vec<Ownership<AccountId>>,330	pub const_data: Vec<u8>,331	pub variable_data: Vec<u8>,332}333334/// All fields are wrapped in `Option`s, where None means chain default335#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]336#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]337pub struct CollectionLimits {338	pub account_token_ownership_limit: Option<u32>,339	pub sponsored_data_size: Option<u32>,340	/// None - setVariableMetadata is not sponsored341	/// Some(v) - setVariableMetadata is sponsored342	///           if there is v block between txs343	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,344	pub token_limit: Option<u32>,345346	// Timeouts for item types in passed blocks347	pub sponsor_transfer_timeout: Option<u32>,348	pub sponsor_approve_timeout: Option<u32>,349	pub owner_can_transfer: Option<bool>,350	pub owner_can_destroy: Option<bool>,351	pub transfers_enabled: Option<bool>,352}353354impl CollectionLimits {355	pub fn account_token_ownership_limit(&self) -> u32 {356		self.account_token_ownership_limit357			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)358			.min(MAX_TOKEN_OWNERSHIP)359	}360	pub fn sponsored_data_size(&self) -> u32 {361		self.sponsored_data_size362			.unwrap_or(CUSTOM_DATA_LIMIT)363			.min(CUSTOM_DATA_LIMIT)364	}365	pub fn token_limit(&self) -> u32 {366		self.token_limit367			.unwrap_or(COLLECTION_TOKEN_LIMIT)368			.min(COLLECTION_TOKEN_LIMIT)369	}370	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {371		self.sponsor_transfer_timeout372			.unwrap_or(default)373			.min(MAX_SPONSOR_TIMEOUT)374	}375	pub fn sponsor_approve_timeout(&self) -> u32 {376		self.sponsor_approve_timeout377			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)378			.min(MAX_SPONSOR_TIMEOUT)379	}380	pub fn owner_can_transfer(&self) -> bool {381		self.owner_can_transfer.unwrap_or(true)382	}383	pub fn owner_can_destroy(&self) -> bool {384		self.owner_can_destroy.unwrap_or(true)385	}386	pub fn transfers_enabled(&self) -> bool {387		self.transfers_enabled.unwrap_or(true)388	}389	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {390		match self391			.sponsored_data_rate_limit392			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)393		{394			SponsoringRateLimit::SponsoringDisabled => None,395			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),396		}397	}398}399400#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]401#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]402pub enum SponsoringRateLimit {403	SponsoringDisabled,404	Blocks(u32),405}406407/// BoundedVec doesn't supports serde408#[cfg(feature = "serde1")]409mod bounded_serde {410	use core::convert::TryFrom;411	use frame_support::{BoundedVec, traits::Get};412	use serde::{413		ser::{self, Serialize},414		de::{self, Deserialize, Error},415	};416	use sp_std::vec::Vec;417418	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>419	where420		D: ser::Serializer,421		V: Serialize,422	{423		(value as &Vec<_>).serialize(serializer)424	}425426	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>427	where428		D: de::Deserializer<'de>,429		V: de::Deserialize<'de>,430		S: Get<u32>,431	{432		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?433		let vec = <Vec<V>>::deserialize(deserializer)?;434		let len = vec.len();435		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))436	}437}438439fn bounded_debug<V, S>(v: &BoundedVec<V, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>440where441	V: fmt::Debug,442{443	use core::fmt::Debug;444	(&v as &Vec<V>).fmt(f)445}446447#[cfg(feature = "serde1")]448#[allow(dead_code)]449mod bounded_map_serde {450	use core::convert::TryFrom;451	use sp_std::collections::btree_map::BTreeMap;452	use frame_support::{traits::Get, storage::bounded_btree_map::BoundedBTreeMap};453	use serde::{454		ser::{self, Serialize},455		de::{self, Deserialize, Error},456	};457	pub fn serialize<D, K, V, S>(458		value: &BoundedBTreeMap<K, V, S>,459		serializer: D,460	) -> Result<D::Ok, D::Error>461	where462		D: ser::Serializer,463		K: Serialize + Ord,464		V: Serialize,465	{466		(value as &BTreeMap<_, _>).serialize(serializer)467	}468469	pub fn deserialize<'de, D, K, V, S>(470		deserializer: D,471	) -> Result<BoundedBTreeMap<K, V, S>, D::Error>472	where473		D: de::Deserializer<'de>,474		K: de::Deserialize<'de> + Ord,475		V: de::Deserialize<'de>,476		S: Get<u32>,477	{478		let map = <BTreeMap<K, V>>::deserialize(deserializer)?;479		let len = map.len();480		TryFrom::try_from(map).map_err(|_| D::Error::invalid_length(len, &"lesser size"))481	}482}483484fn bounded_map_debug<K, V, S>(485	v: &BoundedBTreeMap<K, V, S>,486	f: &mut fmt::Formatter,487) -> Result<(), fmt::Error>488where489	K: fmt::Debug + Ord,490	V: fmt::Debug,491{492	use core::fmt::Debug;493	(&v as &BTreeMap<K, V>).fmt(f)494}495496#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]497#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]498#[derivative(Debug)]499pub struct CreateNftData {500	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]501	#[derivative(Debug(format_with = "bounded_debug"))]502	pub const_data: BoundedVec<u8, CustomDataLimit>,503	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]504	#[derivative(Debug(format_with = "bounded_debug"))]505	pub variable_data: BoundedVec<u8, CustomDataLimit>,506}507508#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]509#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]510pub struct CreateFungibleData {511	pub value: u128,512}513514#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]515#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]516#[derivative(Debug)]517pub struct CreateReFungibleData {518	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]519	#[derivative(Debug(format_with = "bounded_debug"))]520	pub const_data: BoundedVec<u8, CustomDataLimit>,521	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]522	#[derivative(Debug(format_with = "bounded_debug"))]523	pub variable_data: BoundedVec<u8, CustomDataLimit>,524	pub pieces: u128,525}526527#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]528#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]529pub enum MetaUpdatePermission {530	ItemOwner,531	Admin,532	None,533}534535impl Default for MetaUpdatePermission {536	fn default() -> Self {537		Self::ItemOwner538	}539}540541#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]542#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]543pub enum CreateItemData {544	NFT(CreateNftData),545	Fungible(CreateFungibleData),546	ReFungible(CreateReFungibleData),547}548549#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]550#[derivative(Debug)]551pub struct CreateNftExData<CrossAccountId> {552	#[derivative(Debug(format_with = "bounded_debug"))]553	pub const_data: BoundedVec<u8, CustomDataLimit>,554	#[derivative(Debug(format_with = "bounded_debug"))]555	pub variable_data: BoundedVec<u8, CustomDataLimit>,556	pub owner: CrossAccountId,557}558559#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]560#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]561pub struct CreateRefungibleExData<CrossAccountId> {562	#[derivative(Debug(format_with = "bounded_debug"))]563	pub const_data: BoundedVec<u8, CustomDataLimit>,564	#[derivative(Debug(format_with = "bounded_debug"))]565	pub variable_data: BoundedVec<u8, CustomDataLimit>,566	#[derivative(Debug(format_with = "bounded_map_debug"))]567	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,568}569570#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]571#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]572pub enum CreateItemExData<CrossAccountId> {573	NFT(574		#[derivative(Debug(format_with = "bounded_debug"))]575		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,576	),577	Fungible(578		#[derivative(Debug(format_with = "bounded_map_debug"))]579		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,580	),581	/// Many tokens, each may have only one owner582	RefungibleMultipleItems(583		#[derivative(Debug(format_with = "bounded_debug"))]584		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,585	),586	/// Single token, which may have many owners587	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),588}589590impl CreateItemData {591	pub fn data_size(&self) -> usize {592		match self {593			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),594			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),595			_ => 0,596		}597	}598}599600impl From<CreateNftData> for CreateItemData {601	fn from(item: CreateNftData) -> Self {602		CreateItemData::NFT(item)603	}604}605606impl From<CreateReFungibleData> for CreateItemData {607	fn from(item: CreateReFungibleData) -> Self {608		CreateItemData::ReFungible(item)609	}610}611612impl From<CreateFungibleData> for CreateItemData {613	fn from(item: CreateFungibleData) -> Self {614		CreateItemData::Fungible(item)615	}616}617618#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]619#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]620pub struct CollectionStats {621	pub created: u32,622	pub destroyed: u32,623	pub alive: u32,624}
after · primitives/data-structs/src/lib.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#![cfg_attr(not(feature = "std"), no_std)]1819use core::{20	convert::{TryFrom, TryInto},21	fmt,22};23use frame_support::{24	storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},25	traits::ConstU16,26};27use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};2829#[cfg(feature = "serde")]30use serde::{Serialize, Deserialize};3132use sp_core::U256;33use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};34use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};35use frame_support::{BoundedVec, traits::ConstU32};36use derivative::Derivative;37use scale_info::TypeInfo;3839pub mod mapping;40mod migration;4142pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;43pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;44pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;4546pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {47	100_00048} else {49	1050};51pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {52	100_00053} else {54	1055};56pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {57	204858} else {59	1060};61pub const COLLECTION_ADMINS_LIMIT: u32 = 5;62pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;63pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {64	1_000_00065} else {66	1067};6869// Timeouts for item types in passed blocks70pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;71pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;72pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;7374pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;7576// Schema limits77pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;78pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;79pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;8081pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;82pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;83pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;8485/// How much items can be created per single86/// create_many call87pub const MAX_ITEMS_PER_BATCH: u32 = 200;8889pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;9091#[derive(92	Encode,93	Decode,94	PartialEq,95	Eq,96	PartialOrd,97	Ord,98	Clone,99	Copy,100	Debug,101	Default,102	TypeInfo,103	MaxEncodedLen,104)]105#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]106pub struct CollectionId(pub u32);107impl EncodeLike<u32> for CollectionId {}108impl EncodeLike<CollectionId> for u32 {}109110#[derive(111	Encode,112	Decode,113	PartialEq,114	Eq,115	PartialOrd,116	Ord,117	Clone,118	Copy,119	Debug,120	Default,121	TypeInfo,122	MaxEncodedLen,123)]124#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]125pub struct TokenId(pub u32);126impl EncodeLike<u32> for TokenId {}127impl EncodeLike<TokenId> for u32 {}128129impl TokenId {130	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {131		self.0132			.checked_add(1)133			.ok_or(ArithmeticError::Overflow)134			.map(Self)135	}136}137138impl From<TokenId> for U256 {139	fn from(t: TokenId) -> Self {140		t.0.into()141	}142}143144impl TryFrom<U256> for TokenId {145	type Error = &'static str;146147	fn try_from(value: U256) -> Result<Self, Self::Error> {148		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))149	}150}151152pub struct OverflowError;153impl From<OverflowError> for &'static str {154	fn from(_: OverflowError) -> Self {155		"overflow occured"156	}157}158159pub type DecimalPoints = u8;160161#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]162#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]163pub enum CollectionMode {164	NFT,165	// decimal points166	Fungible(DecimalPoints),167	ReFungible,168}169170impl CollectionMode {171	pub fn id(&self) -> u8 {172		match self {173			CollectionMode::NFT => 1,174			CollectionMode::Fungible(_) => 2,175			CollectionMode::ReFungible => 3,176		}177	}178}179180pub trait SponsoringResolve<AccountId, Call> {181	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;182}183184#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]185#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]186pub enum AccessMode {187	Normal,188	AllowList,189}190impl Default for AccessMode {191	fn default() -> Self {192		Self::Normal193	}194}195196#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]197#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]198pub enum SchemaVersion {199	ImageURL,200	Unique,201}202impl Default for SchemaVersion {203	fn default() -> Self {204		Self::ImageURL205	}206}207208#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]209#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]210pub struct Ownership<AccountId> {211	pub owner: AccountId,212	pub fraction: u128,213}214215#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]216#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]217pub enum SponsorshipState<AccountId> {218	/// The fees are applied to the transaction sender219	Disabled,220	Unconfirmed(AccountId),221	/// Transactions are sponsored by specified account222	Confirmed(AccountId),223}224225impl<AccountId> SponsorshipState<AccountId> {226	pub fn sponsor(&self) -> Option<&AccountId> {227		match self {228			Self::Confirmed(sponsor) => Some(sponsor),229			_ => None,230		}231	}232233	pub fn pending_sponsor(&self) -> Option<&AccountId> {234		match self {235			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),236			_ => None,237		}238	}239240	pub fn confirmed(&self) -> bool {241		matches!(self, Self::Confirmed(_))242	}243}244245impl<T> Default for SponsorshipState<T> {246	fn default() -> Self {247		Self::Disabled248	}249}250251#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]252#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]253pub struct Collection<AccountId> {254	pub owner: AccountId,255	pub mode: CollectionMode,256	pub access: AccessMode,257	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]258	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,259	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]260	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,261	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]262	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,263	pub mint_mode: bool,264	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]265	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,266	pub schema_version: SchemaVersion,267	pub sponsorship: SponsorshipState<AccountId>,268	pub limits: CollectionLimits, // Collection private restrictions269	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]270	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,271	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]272	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,273	pub meta_update_permission: MetaUpdatePermission,274}275276#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]277#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]278#[derivative(Default(bound = ""))]279pub struct CreateCollectionData<AccountId> {280	#[derivative(Default(value = "CollectionMode::NFT"))]281	pub mode: CollectionMode,282	pub access: Option<AccessMode>,283	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]284	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,285	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]286	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,287	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]288	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,289	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]290	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,291	pub schema_version: Option<SchemaVersion>,292	pub pending_sponsor: Option<AccountId>,293	pub limits: Option<CollectionLimits>,294	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]295	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,296	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]297	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,298	pub meta_update_permission: Option<MetaUpdatePermission>,299}300301#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]302#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]303pub struct NftItemType<AccountId> {304	pub owner: AccountId,305	pub const_data: Vec<u8>,306	pub variable_data: Vec<u8>,307}308309#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]310#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]311pub struct FungibleItemType {312	pub value: u128,313}314315#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]316#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]317pub struct ReFungibleItemType<AccountId> {318	pub owner: Vec<Ownership<AccountId>>,319	pub const_data: Vec<u8>,320	pub variable_data: Vec<u8>,321}322323/// All fields are wrapped in `Option`s, where None means chain default324#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]325#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]326pub struct CollectionLimits {327	pub account_token_ownership_limit: Option<u32>,328	pub sponsored_data_size: Option<u32>,329	/// None - setVariableMetadata is not sponsored330	/// Some(v) - setVariableMetadata is sponsored331	///           if there is v block between txs332	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,333	pub token_limit: Option<u32>,334335	// Timeouts for item types in passed blocks336	pub sponsor_transfer_timeout: Option<u32>,337	pub sponsor_approve_timeout: Option<u32>,338	pub owner_can_transfer: Option<bool>,339	pub owner_can_destroy: Option<bool>,340	pub transfers_enabled: Option<bool>,341}342343impl CollectionLimits {344	pub fn account_token_ownership_limit(&self) -> u32 {345		self.account_token_ownership_limit346			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)347			.min(MAX_TOKEN_OWNERSHIP)348	}349	pub fn sponsored_data_size(&self) -> u32 {350		self.sponsored_data_size351			.unwrap_or(CUSTOM_DATA_LIMIT)352			.min(CUSTOM_DATA_LIMIT)353	}354	pub fn token_limit(&self) -> u32 {355		self.token_limit356			.unwrap_or(COLLECTION_TOKEN_LIMIT)357			.min(COLLECTION_TOKEN_LIMIT)358	}359	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {360		self.sponsor_transfer_timeout361			.unwrap_or(default)362			.min(MAX_SPONSOR_TIMEOUT)363	}364	pub fn sponsor_approve_timeout(&self) -> u32 {365		self.sponsor_approve_timeout366			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)367			.min(MAX_SPONSOR_TIMEOUT)368	}369	pub fn owner_can_transfer(&self) -> bool {370		self.owner_can_transfer.unwrap_or(true)371	}372	pub fn owner_can_destroy(&self) -> bool {373		self.owner_can_destroy.unwrap_or(true)374	}375	pub fn transfers_enabled(&self) -> bool {376		self.transfers_enabled.unwrap_or(true)377	}378	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {379		match self380			.sponsored_data_rate_limit381			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)382		{383			SponsoringRateLimit::SponsoringDisabled => None,384			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),385		}386	}387}388389#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]390#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]391pub enum SponsoringRateLimit {392	SponsoringDisabled,393	Blocks(u32),394}395396/// BoundedVec doesn't supports serde397#[cfg(feature = "serde1")]398mod bounded_serde {399	use core::convert::TryFrom;400	use frame_support::{BoundedVec, traits::Get};401	use serde::{402		ser::{self, Serialize},403		de::{self, Deserialize, Error},404	};405	use sp_std::vec::Vec;406407	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>408	where409		D: ser::Serializer,410		V: Serialize,411	{412		(value as &Vec<_>).serialize(serializer)413	}414415	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>416	where417		D: de::Deserializer<'de>,418		V: de::Deserialize<'de>,419		S: Get<u32>,420	{421		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?422		let vec = <Vec<V>>::deserialize(deserializer)?;423		let len = vec.len();424		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))425	}426}427428fn bounded_debug<V, S>(v: &BoundedVec<V, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>429where430	V: fmt::Debug,431{432	use core::fmt::Debug;433	(&v as &Vec<V>).fmt(f)434}435436#[cfg(feature = "serde1")]437#[allow(dead_code)]438mod bounded_map_serde {439	use core::convert::TryFrom;440	use sp_std::collections::btree_map::BTreeMap;441	use frame_support::{traits::Get, storage::bounded_btree_map::BoundedBTreeMap};442	use serde::{443		ser::{self, Serialize},444		de::{self, Deserialize, Error},445	};446	pub fn serialize<D, K, V, S>(447		value: &BoundedBTreeMap<K, V, S>,448		serializer: D,449	) -> Result<D::Ok, D::Error>450	where451		D: ser::Serializer,452		K: Serialize + Ord,453		V: Serialize,454	{455		(value as &BTreeMap<_, _>).serialize(serializer)456	}457458	pub fn deserialize<'de, D, K, V, S>(459		deserializer: D,460	) -> Result<BoundedBTreeMap<K, V, S>, D::Error>461	where462		D: de::Deserializer<'de>,463		K: de::Deserialize<'de> + Ord,464		V: de::Deserialize<'de>,465		S: Get<u32>,466	{467		let map = <BTreeMap<K, V>>::deserialize(deserializer)?;468		let len = map.len();469		TryFrom::try_from(map).map_err(|_| D::Error::invalid_length(len, &"lesser size"))470	}471}472473fn bounded_map_debug<K, V, S>(474	v: &BoundedBTreeMap<K, V, S>,475	f: &mut fmt::Formatter,476) -> Result<(), fmt::Error>477where478	K: fmt::Debug + Ord,479	V: fmt::Debug,480{481	use core::fmt::Debug;482	(&v as &BTreeMap<K, V>).fmt(f)483}484485#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]486#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]487#[derivative(Debug)]488pub struct CreateNftData {489	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]490	#[derivative(Debug(format_with = "bounded_debug"))]491	pub const_data: BoundedVec<u8, CustomDataLimit>,492	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]493	#[derivative(Debug(format_with = "bounded_debug"))]494	pub variable_data: BoundedVec<u8, CustomDataLimit>,495}496497#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]498#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]499pub struct CreateFungibleData {500	pub value: u128,501}502503#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]504#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]505#[derivative(Debug)]506pub struct CreateReFungibleData {507	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]508	#[derivative(Debug(format_with = "bounded_debug"))]509	pub const_data: BoundedVec<u8, CustomDataLimit>,510	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]511	#[derivative(Debug(format_with = "bounded_debug"))]512	pub variable_data: BoundedVec<u8, CustomDataLimit>,513	pub pieces: u128,514}515516#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]517#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]518pub enum MetaUpdatePermission {519	ItemOwner,520	Admin,521	None,522}523524impl Default for MetaUpdatePermission {525	fn default() -> Self {526		Self::ItemOwner527	}528}529530#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]531#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]532pub enum CreateItemData {533	NFT(CreateNftData),534	Fungible(CreateFungibleData),535	ReFungible(CreateReFungibleData),536}537538#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]539#[derivative(Debug)]540pub struct CreateNftExData<CrossAccountId> {541	#[derivative(Debug(format_with = "bounded_debug"))]542	pub const_data: BoundedVec<u8, CustomDataLimit>,543	#[derivative(Debug(format_with = "bounded_debug"))]544	pub variable_data: BoundedVec<u8, CustomDataLimit>,545	pub owner: CrossAccountId,546}547548#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]549#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]550pub struct CreateRefungibleExData<CrossAccountId> {551	#[derivative(Debug(format_with = "bounded_debug"))]552	pub const_data: BoundedVec<u8, CustomDataLimit>,553	#[derivative(Debug(format_with = "bounded_debug"))]554	pub variable_data: BoundedVec<u8, CustomDataLimit>,555	#[derivative(Debug(format_with = "bounded_map_debug"))]556	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,557}558559#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]560#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]561pub enum CreateItemExData<CrossAccountId> {562	NFT(563		#[derivative(Debug(format_with = "bounded_debug"))]564		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,565	),566	Fungible(567		#[derivative(Debug(format_with = "bounded_map_debug"))]568		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,569	),570	/// Many tokens, each may have only one owner571	RefungibleMultipleItems(572		#[derivative(Debug(format_with = "bounded_debug"))]573		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,574	),575	/// Single token, which may have many owners576	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),577}578579impl CreateItemData {580	pub fn data_size(&self) -> usize {581		match self {582			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),583			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),584			_ => 0,585		}586	}587}588589impl From<CreateNftData> for CreateItemData {590	fn from(item: CreateNftData) -> Self {591		CreateItemData::NFT(item)592	}593}594595impl From<CreateReFungibleData> for CreateItemData {596	fn from(item: CreateReFungibleData) -> Self {597		CreateItemData::ReFungible(item)598	}599}600601impl From<CreateFungibleData> for CreateItemData {602	fn from(item: CreateFungibleData) -> Self {603		CreateItemData::Fungible(item)604	}605}606607#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]608#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]609pub struct CollectionStats {610	pub created: u32,611	pub destroyed: u32,612	pub alive: u32,613}
addedprimitives/data-structs/src/mapping.rsdiffbeforeafterboth
--- /dev/null
+++ b/primitives/data-structs/src/mapping.rs
@@ -0,0 +1,63 @@
+use core::marker::PhantomData;
+
+use sp_core::H160;
+
+use crate::{CollectionId, TokenId};
+use up_evm_mapping::CrossAccountId;
+
+pub trait TokenAddressMapping<Address> {
+	fn token_to_address(collection: CollectionId, token: TokenId) -> Address;
+	fn address_to_token(address: &Address) -> Option<(CollectionId, TokenId)>;
+	fn is_token_address(address: &Address) -> bool;
+}
+
+pub struct EvmTokenAddressMapping;
+
+/// 0xf8238ccfff8ed887463fd5e00000000100000002  - collection 1, token 2
+const ETH_COLLECTION_TOKEN_PREFIX: [u8; 12] = [
+	0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
+];
+
+impl TokenAddressMapping<H160> for EvmTokenAddressMapping {
+	fn token_to_address(collection: CollectionId, token: TokenId) -> H160 {
+		let mut out = [0; 20];
+		out[0..12].copy_from_slice(&ETH_COLLECTION_TOKEN_PREFIX);
+		out[12..16].copy_from_slice(&u32::to_be_bytes(collection.0));
+		out[16..20].copy_from_slice(&u32::to_be_bytes(token.0));
+		H160(out)
+	}
+
+	fn address_to_token(eth: &H160) -> Option<(CollectionId, TokenId)> {
+		if eth[0..12] != ETH_COLLECTION_TOKEN_PREFIX {
+			return None;
+		}
+		let mut id_bytes = [0; 4];
+		let mut token_id_bytes = [0; 4];
+		id_bytes.copy_from_slice(&eth[12..16]);
+		token_id_bytes.copy_from_slice(&eth[16..20]);
+		Some((
+			CollectionId(u32::from_be_bytes(id_bytes)),
+			TokenId(u32::from_be_bytes(token_id_bytes)),
+		))
+	}
+
+	fn is_token_address(address: &H160) -> bool {
+		address[0..12] == ETH_COLLECTION_TOKEN_PREFIX
+	}
+}
+
+pub struct CrossTokenAddressMapping<A>(PhantomData<A>);
+
+impl<A, C: CrossAccountId<A>> TokenAddressMapping<C> for CrossTokenAddressMapping<A> {
+	fn token_to_address(collection: CollectionId, token: TokenId) -> C {
+		C::from_eth(EvmTokenAddressMapping::token_to_address(collection, token))
+	}
+
+	fn address_to_token(address: &C) -> Option<(CollectionId, TokenId)> {
+		EvmTokenAddressMapping::address_to_token(address.as_eth())
+	}
+
+	fn is_token_address(address: &C) -> bool {
+		EvmTokenAddressMapping::is_token_address(address.as_eth())
+	}
+}
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -66,6 +66,7 @@
 		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
 	},
 };
+use up_data_structs::mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping};
 use up_data_structs::{CollectionId, TokenId, CollectionStats, Collection};
 // use pallet_contracts::weights::WeightInfo;
 // #[cfg(any(feature = "std", test))]
modifiedtests/src/eth/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -56,13 +56,27 @@
   }
 }
 
-export function collectionIdToAddress(address: number): string {
-  if (address >= 0xffffffff || address < 0) throw new Error('id overflow');
+function encodeIntBE(v: number): number[] {
+  if (v >= 0xffffffff || v < 0) throw new Error('id overflow');
+  return [
+    v >> 24,
+    (v >> 16) & 0xff,
+    (v >> 8) & 0xff,
+    v & 0xff,
+  ];
+}
+
+export function collectionIdToAddress(collection: number): string {
   const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
-    address >> 24,
-    (address >> 16) & 0xff,
-    (address >> 8) & 0xff,
-    address & 0xff,
+    ...encodeIntBE(collection),
+  ]);
+  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
+}
+
+export function tokenIdToAddress(collection: number, token: number): string {
+  const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
+    ...encodeIntBE(collection),
+    ...encodeIntBE(token),
   ]);
   return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
 }