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 Property {135 136 pub fn key(&self) -> &str {137 self.key.as_str()138 }139140 141 pub fn value(&self) -> &[u8] {142 self.value.0.as_slice()143 }144}145146impl TryFrom<up_data_structs::Property> for Property {147 type Error = pallet_evm_coder_substrate::execution::Error;148149 fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {150 let key = evm_coder::types::String::from_utf8(from.key.into())151 .map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {e}")))?;152 let value = evm_coder::types::Bytes(from.value.to_vec());153 Ok(Property { key, value })154 }155}156157impl TryInto<up_data_structs::Property> for Property {158 type Error = pallet_evm_coder_substrate::execution::Error;159160 fn try_into(self) -> Result<up_data_structs::Property, Self::Error> {161 let key = <Vec<u8>>::from(self.key)162 .try_into()163 .map_err(|_| "key too large")?;164165 let value = self.value.0.try_into().map_err(|_| "value too large")?;166167 Ok(up_data_structs::Property { key, value })168 }169}170171172#[derive(Debug, Default, Clone, Copy, AbiCoder)]173#[repr(u8)]174pub enum CollectionLimitField {175 176 #[default]177 AccountTokenOwnership,178179 180 SponsoredDataSize,181182 183 SponsoredDataRateLimit,184185 186 TokenLimit,187188 189 SponsorTransferTimeout,190191 192 SponsorApproveTimeout,193194 195 OwnerCanTransfer,196197 198 OwnerCanDestroy,199200 201 TransferEnabled,202}203204205#[derive(Debug, Default, AbiCoder)]206pub struct CollectionLimit {207 field: CollectionLimitField,208 value: Option<U256>,209}210211impl CollectionLimit {212 213 pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {214 Self {215 field,216 value: value.map(|value| value.into()),217 }218 }219 220 pub fn has_value(&self) -> bool {221 self.value.is_some()222 }223}224225impl TryInto<up_data_structs::CollectionLimits> for CollectionLimit {226 type Error = pallet_evm_coder_substrate::execution::Error;227228 fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {229 let value = self230 .value231 .ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;232 let value = Some(value.try_into().map_err(|error| {233 Self::Error::Revert(format!(234 "can't convert value to u32 \"{value}\" because: \"{error}\""235 ))236 })?);237238 let convert_value_to_bool = || match value {239 Some(value) => match value {240 0 => Ok(Some(false)),241 1 => Ok(Some(true)),242 _ => Err(Self::Error::Revert(format!(243 "can't convert value to boolean \"{value}\""244 ))),245 },246 None => Ok(None),247 };248249 let mut limits = up_data_structs::CollectionLimits::default();250 match self.field {251 CollectionLimitField::AccountTokenOwnership => {252 limits.account_token_ownership_limit = value;253 }254 CollectionLimitField::SponsoredDataSize => {255 limits.sponsored_data_size = value;256 }257 CollectionLimitField::SponsoredDataRateLimit => {258 limits.sponsored_data_rate_limit =259 value.map(up_data_structs::SponsoringRateLimit::Blocks);260 }261 CollectionLimitField::TokenLimit => {262 limits.token_limit = value;263 }264 CollectionLimitField::SponsorTransferTimeout => {265 limits.sponsor_transfer_timeout = value;266 }267 CollectionLimitField::SponsorApproveTimeout => {268 limits.sponsor_approve_timeout = value;269 }270 CollectionLimitField::OwnerCanTransfer => {271 limits.owner_can_transfer = convert_value_to_bool()?;272 }273 CollectionLimitField::OwnerCanDestroy => {274 limits.owner_can_destroy = convert_value_to_bool()?;275 }276 CollectionLimitField::TransferEnabled => {277 limits.transfers_enabled = convert_value_to_bool()?;278 }279 };280 Ok(limits)281 }282}283284285#[derive(Default, Debug, Clone, Copy, AbiCoder)]286#[repr(u8)]287pub enum CollectionPermissionField {288 289 #[default]290 TokenOwner,291292 293 CollectionAdmin,294}295296297#[derive(AbiCoder, Copy, Clone, Default, Debug)]298#[repr(u8)]299pub enum TokenPermissionField {300 301 #[default]302 Mutable,303304 305 TokenOwner,306307 308 CollectionAdmin,309}310311312#[derive(Debug, Default, AbiCoder)]313pub struct PropertyPermission {314 315 code: TokenPermissionField,316 317 value: bool,318}319320impl PropertyPermission {321 322 pub fn into_vec(pp: up_data_structs::PropertyPermission) -> Vec<Self> {323 vec![324 PropertyPermission {325 code: TokenPermissionField::Mutable,326 value: pp.mutable,327 },328 PropertyPermission {329 code: TokenPermissionField::TokenOwner,330 value: pp.token_owner,331 },332 PropertyPermission {333 code: TokenPermissionField::CollectionAdmin,334 value: pp.collection_admin,335 },336 ]337 }338339 340 pub fn from_vec(permission: Vec<Self>) -> up_data_structs::PropertyPermission {341 let mut token_permission = up_data_structs::PropertyPermission::default();342343 for PropertyPermission { code, value } in permission {344 match code {345 TokenPermissionField::Mutable => token_permission.mutable = value,346 TokenPermissionField::TokenOwner => token_permission.token_owner = value,347 TokenPermissionField::CollectionAdmin => token_permission.collection_admin = value,348 }349 }350 token_permission351 }352}353354355#[derive(Debug, Default, AbiCoder)]356pub struct TokenPropertyPermission {357 358 key: evm_coder::types::String,359 360 permissions: Vec<PropertyPermission>,361}362363impl364 From<(365 up_data_structs::PropertyKey,366 up_data_structs::PropertyPermission,367 )> for TokenPropertyPermission368{369 fn from(370 value: (371 up_data_structs::PropertyKey,372 up_data_structs::PropertyPermission,373 ),374 ) -> Self {375 let (key, permission) = value;376 let key = evm_coder::types::String::from_utf8(key.into_inner())377 .expect("Stored key must be valid");378 let permissions = PropertyPermission::into_vec(permission);379 Self { key, permissions }380 }381}382383impl TokenPropertyPermission {384 385 pub fn into_property_key_permissions(386 permissions: Vec<TokenPropertyPermission>,387 ) -> pallet_evm_coder_substrate::execution::Result<Vec<up_data_structs::PropertyKeyPermission>>388 {389 let mut perms = Vec::new();390391 for TokenPropertyPermission { key, permissions } in permissions {392 let token_permission = PropertyPermission::from_vec(permissions);393394 perms.push(up_data_structs::PropertyKeyPermission {395 key: key.into_bytes().try_into().map_err(|_| "too long key")?,396 permission: token_permission,397 });398 }399 Ok(perms)400 }401}402403404#[derive(Debug, AbiCoder)]405pub struct TokenUri {406 407 pub id: U256,408409 410 pub uri: String,411}412413414#[derive(Debug, Default, AbiCoder)]415pub struct CollectionNesting {416 token_owner: bool,417 ids: Vec<U256>,418}419420impl CollectionNesting {421 422 pub fn new(token_owner: bool, ids: Vec<U256>) -> Self {423 Self { token_owner, ids }424 }425}426427428#[derive(Debug, Default, AbiCoder)]429pub struct CollectionNestingPermission {430 field: CollectionPermissionField,431 value: bool,432}433434impl CollectionNestingPermission {435 436 pub fn new(field: CollectionPermissionField, value: bool) -> Self {437 Self { field, value }438 }439}440441442#[derive(AbiCoder, Copy, Clone, Default, Debug)]443#[repr(u8)]444pub enum AccessMode {445 446 #[default]447 Normal,448 449 AllowList,450}451452impl From<up_data_structs::AccessMode> for AccessMode {453 fn from(value: up_data_structs::AccessMode) -> Self {454 match value {455 up_data_structs::AccessMode::Normal => AccessMode::Normal,456 up_data_structs::AccessMode::AllowList => AccessMode::AllowList,457 }458 }459}460461impl From<AccessMode> for up_data_structs::AccessMode {462 fn from(value: AccessMode) -> Self {463 match value {464 AccessMode::Normal => up_data_structs::AccessMode::Normal,465 AccessMode::AllowList => up_data_structs::AccessMode::AllowList,466 }467 }468}