12345678910111213141516171819use 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;28293031const ETH_COLLECTION_PREFIX: [u8; 16] = [32 0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,33];343536pub 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(ð[16..20]);42 Some(CollectionId(u32::from_be_bytes(id_bytes)))43}444546pub fn collection_id_to_address(id: CollectionId) -> Address {47 let mut out = [0; 20];48 out[0..16].copy_from_slice(Ð_COLLECTION_PREFIX);49 out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));50 H160(out)51}525354pub fn is_collection(address: &Address) -> bool {55 address[0..16] == ETH_COLLECTION_PREFIX56}575859pub 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}686970#[derive(Debug, Default, AbiCoder)]71pub struct CrossAddress {72 pub(crate) eth: Address,73 pub(crate) sub: U256,74}7576impl CrossAddress {77 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 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 101 pub fn from_eth(address: Address) -> Self {102 Self {103 eth: address,104 sub: Default::default(),105 }106 }107 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}126127128#[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}158159160#[derive(Debug, Default, Clone, Copy, AbiCoder)]161#[repr(u8)]162pub enum CollectionLimitField {163 164 #[default]165 AccountTokenOwnership,166167 168 SponsoredDataSize,169170 171 SponsoredDataRateLimit,172173 174 TokenLimit,175176 177 SponsorTransferTimeout,178179 180 SponsorApproveTimeout,181182 183 OwnerCanTransfer,184185 186 OwnerCanDestroy,187188 189 TransferEnabled,190}191192193#[derive(Debug, Default, AbiCoder)]194pub struct CollectionLimit {195 field: CollectionLimitField,196 value: Option<U256>,197}198199impl CollectionLimit {200 201 pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {202 Self {203 field,204 value: value.map(|value| value.into()),205 }206 }207 208 pub fn has_value(&self) -> bool {209 self.value.is_some()210 }211}212213impl TryInto<up_data_structs::CollectionLimits> for CollectionLimit {214 type Error = pallet_evm_coder_substrate::execution::Error;215216 fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {217 let value = self218 .value219 .ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;220 let value = Some(value.try_into().map_err(|error| {221 Self::Error::Revert(format!(222 "can't convert value to u32 \"{value}\" because: \"{error}\""223 ))224 })?);225226 let convert_value_to_bool = || match value {227 Some(value) => match value {228 0 => Ok(Some(false)),229 1 => Ok(Some(true)),230 _ => {231 return Err(Self::Error::Revert(format!(232 "can't convert value to boolean \"{value}\""233 )))234 }235 },236 None => Ok(None),237 };238239 let mut limits = up_data_structs::CollectionLimits::default();240 match self.field {241 CollectionLimitField::AccountTokenOwnership => {242 limits.account_token_ownership_limit = value;243 }244 CollectionLimitField::SponsoredDataSize => {245 limits.sponsored_data_size = value;246 }247 CollectionLimitField::SponsoredDataRateLimit => {248 limits.sponsored_data_rate_limit =249 value.map(up_data_structs::SponsoringRateLimit::Blocks);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}273274275#[derive(Default, Debug, Clone, Copy, AbiCoder)]276#[repr(u8)]277pub enum CollectionPermissionField {278 279 #[default]280 TokenOwner,281282 283 CollectionAdmin,284}285286287#[derive(AbiCoder, Copy, Clone, Default, Debug)]288#[repr(u8)]289pub enum TokenPermissionField {290 291 #[default]292 Mutable,293294 295 TokenOwner,296297 298 CollectionAdmin,299}300301302#[derive(Debug, Default, AbiCoder)]303pub struct PropertyPermission {304 305 code: TokenPermissionField,306 307 value: bool,308}309310impl PropertyPermission {311 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 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}343344345#[derive(Debug, Default, AbiCoder)]346pub struct TokenPropertyPermission {347 348 key: evm_coder::types::String,349 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 375 pub fn into_property_key_permissions(376 permissions: Vec<TokenPropertyPermission>,377 ) -> pallet_evm_coder_substrate::execution::Result<Vec<up_data_structs::PropertyKeyPermission>>378 {379 let mut perms = Vec::new();380381 for TokenPropertyPermission { key, permissions } in permissions {382 let token_permission = PropertyPermission::from_vec(permissions);383384 perms.push(up_data_structs::PropertyKeyPermission {385 key: key.into_bytes().try_into().map_err(|_| "too long key")?,386 permission: token_permission,387 });388 }389 Ok(perms)390 }391}392393394#[derive(Debug, AbiCoder)]395pub struct TokenUri {396 397 pub id: U256,398399 400 pub uri: String,401}402403404#[derive(Debug, Default, AbiCoder)]405pub struct CollectionNesting {406 token_owner: bool,407 ids: Vec<U256>,408}409410impl CollectionNesting {411 412 pub fn new(token_owner: bool, ids: Vec<U256>) -> Self {413 Self { token_owner, ids }414 }415}416417418#[derive(Debug, Default, AbiCoder)]419pub struct CollectionNestingPermission {420 field: CollectionPermissionField,421 value: bool,422}423424impl CollectionNestingPermission {425 426 pub fn new(field: CollectionPermissionField, value: bool) -> Self {427 Self { field, value }428 }429}430431432#[derive(AbiCoder, Copy, Clone, Default, Debug)]433#[repr(u8)]434pub enum AccessMode {435 436 #[default]437 Normal,438 439 AllowList,440}441442impl From<up_data_structs::AccessMode> for AccessMode {443 fn from(value: up_data_structs::AccessMode) -> Self {444 match value {445 up_data_structs::AccessMode::Normal => AccessMode::Normal,446 up_data_structs::AccessMode::AllowList => AccessMode::AllowList,447 }448 }449}450451impl From<AccessMode> for up_data_structs::AccessMode {452 fn from(value: AccessMode) -> Self {453 match value {454 AccessMode::Normal => up_data_structs::AccessMode::Normal,455 AccessMode::AllowList => up_data_structs::AccessMode::AllowList,456 }457 }458}