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>(&self) -> evm_coder::execution::Result<T::CrossAccountId>109 where110 T: pallet_evm::Config,111 T::AccountId: From<[u8; 32]>,112 {113 if self.eth == Default::default() && self.sub == Default::default() {114 Err("All fields of cross account is zeroed".into())115 } else if self.eth == Default::default() {116 Ok(convert_uint256_to_cross_account::<T>(self.sub))117 } else if self.sub == Default::default() {118 Ok(T::CrossAccountId::from_eth(self.eth))119 } else {120 Err("All fields of cross account is non zeroed".into())121 }122 }123}124125126#[derive(Debug, Default, AbiCoder)]127pub struct Property {128 key: evm_coder::types::String,129 value: evm_coder::types::Bytes,130}131132impl TryFrom<up_data_structs::Property> for Property {133 type Error = evm_coder::execution::Error;134135 fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {136 let key = evm_coder::types::String::from_utf8(from.key.into())137 .map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {}", e)))?;138 let value = evm_coder::types::Bytes(from.value.to_vec());139 Ok(Property { key, value })140 }141}142143impl TryInto<up_data_structs::Property> for Property {144 type Error = evm_coder::execution::Error;145146 fn try_into(self) -> Result<up_data_structs::Property, Self::Error> {147 let key = <Vec<u8>>::from(self.key)148 .try_into()149 .map_err(|_| "key too large")?;150151 let value = self.value.0.try_into().map_err(|_| "value too large")?;152153 Ok(up_data_structs::Property { key, value })154 }155}156157158#[derive(Debug, Default, Clone, Copy, AbiCoder)]159#[repr(u8)]160pub enum CollectionLimitField {161 162 #[default]163 AccountTokenOwnership,164165 166 SponsoredDataSize,167168 169 SponsoredDataRateLimit,170171 172 TokenLimit,173174 175 SponsorTransferTimeout,176177 178 SponsorApproveTimeout,179180 181 OwnerCanTransfer,182183 184 OwnerCanDestroy,185186 187 TransferEnabled,188}189190191#[derive(Debug, Default, AbiCoder)]192pub struct CollectionLimit {193 field: CollectionLimitField,194 value: Option<U256>,195}196197impl CollectionLimit {198 199 pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {200 Self {201 field,202 value: match value {203 Some(value) => Some(value.into()),204 None => None,205 },206 }207 }208 209 pub fn has_value(&self) -> bool {210 self.value.is_some()211 }212}213214impl TryInto<up_data_structs::CollectionLimits> for CollectionLimit {215 type Error = evm_coder::execution::Error;216217 fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {218 let value = self219 .value220 .ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;221 let value = Some(value.try_into().map_err(|error| {222 Self::Error::Revert(format!(223 "can't convert value to u32 \"{}\" because: \"{error}\"",224 value225 ))226 })?);227228 let convert_value_to_bool = || match value {229 Some(value) => match value {230 0 => Ok(Some(false)),231 1 => Ok(Some(true)),232 _ => {233 return Err(Self::Error::Revert(format!(234 "can't convert value to boolean \"{value}\""235 )))236 }237 },238 None => Ok(None),239 };240241 let mut limits = up_data_structs::CollectionLimits::default();242 match self.field {243 CollectionLimitField::AccountTokenOwnership => {244 limits.account_token_ownership_limit = value;245 }246 CollectionLimitField::SponsoredDataSize => {247 limits.sponsored_data_size = value;248 }249 CollectionLimitField::SponsoredDataRateLimit => {250 limits.sponsored_data_rate_limit = match value {251 Some(value) => Some(up_data_structs::SponsoringRateLimit::Blocks(value)),252 None => None,253 };254 }255 CollectionLimitField::TokenLimit => {256 limits.token_limit = value;257 }258 CollectionLimitField::SponsorTransferTimeout => {259 limits.sponsor_transfer_timeout = value;260 }261 CollectionLimitField::SponsorApproveTimeout => {262 limits.sponsor_approve_timeout = value;263 }264 CollectionLimitField::OwnerCanTransfer => {265 limits.owner_can_transfer = convert_value_to_bool()?;266 }267 CollectionLimitField::OwnerCanDestroy => {268 limits.owner_can_destroy = convert_value_to_bool()?;269 }270 CollectionLimitField::TransferEnabled => {271 limits.transfers_enabled = convert_value_to_bool()?;272 }273 };274 Ok(limits)275 }276}277278279#[derive(Default, Debug, Clone, Copy, AbiCoder)]280#[repr(u8)]281pub enum CollectionPermissionField {282 283 #[default]284 TokenOwner,285286 287 CollectionAdmin,288}289290291#[derive(AbiCoder, Copy, Clone, Default, Debug)]292#[repr(u8)]293pub enum TokenPermissionField {294 295 #[default]296 Mutable,297298 299 TokenOwner,300301 302 CollectionAdmin,303}304305306#[derive(Debug, Default, AbiCoder)]307pub struct PropertyPermission {308 309 code: TokenPermissionField,310 311 value: bool,312}313314impl PropertyPermission {315 316 pub fn into_vec(pp: up_data_structs::PropertyPermission) -> Vec<Self> {317 vec![318 PropertyPermission {319 code: TokenPermissionField::Mutable,320 value: pp.mutable,321 },322 PropertyPermission {323 code: TokenPermissionField::TokenOwner,324 value: pp.token_owner,325 },326 PropertyPermission {327 code: TokenPermissionField::CollectionAdmin,328 value: pp.collection_admin,329 },330 ]331 }332333 334 pub fn from_vec(permission: Vec<Self>) -> up_data_structs::PropertyPermission {335 let mut token_permission = up_data_structs::PropertyPermission::default();336337 for PropertyPermission { code, value } in permission {338 match code {339 TokenPermissionField::Mutable => token_permission.mutable = value,340 TokenPermissionField::TokenOwner => token_permission.token_owner = value,341 TokenPermissionField::CollectionAdmin => token_permission.collection_admin = value,342 }343 }344 token_permission345 }346}347348349#[derive(Debug, Default, AbiCoder)]350pub struct TokenPropertyPermission {351 352 key: evm_coder::types::String,353 354 permissions: Vec<PropertyPermission>,355}356357impl358 From<(359 up_data_structs::PropertyKey,360 up_data_structs::PropertyPermission,361 )> for TokenPropertyPermission362{363 fn from(364 value: (365 up_data_structs::PropertyKey,366 up_data_structs::PropertyPermission,367 ),368 ) -> Self {369 let (key, permission) = value;370 let key = evm_coder::types::String::from_utf8(key.into_inner())371 .expect("Stored key must be valid");372 let permissions = PropertyPermission::into_vec(permission);373 Self { key, permissions }374 }375}376377impl TokenPropertyPermission {378 379 pub fn into_property_key_permissions(380 permissions: Vec<TokenPropertyPermission>,381 ) -> evm_coder::execution::Result<Vec<up_data_structs::PropertyKeyPermission>> {382 let mut perms = Vec::new();383384 for TokenPropertyPermission { key, permissions } in permissions {385 let token_permission = PropertyPermission::from_vec(permissions);386387 perms.push(up_data_structs::PropertyKeyPermission {388 key: key.into_bytes().try_into().map_err(|_| "too long key")?,389 permission: token_permission,390 });391 }392 Ok(perms)393 }394}395396397#[derive(Debug, AbiCoder)]398pub struct TokenUri {399 400 pub id: U256,401402 403 pub uri: String,404}405406407#[derive(Debug, Default, AbiCoder)]408pub struct CollectionNesting {409 token_owner: bool,410 ids: Vec<U256>,411}412413impl CollectionNesting {414 415 pub fn new(token_owner: bool, ids: Vec<U256>) -> Self {416 Self { token_owner, ids }417 }418}419420421#[derive(Debug, Default, AbiCoder)]422pub struct CollectionNestingPermission {423 field: CollectionPermissionField,424 value: bool,425}426427impl CollectionNestingPermission {428 429 pub fn new(field: CollectionPermissionField, value: bool) -> Self {430 Self { field, value }431 }432}433434435#[derive(AbiCoder, Copy, Clone, Default, Debug)]436#[repr(u8)]437pub enum AccessMode {438 439 #[default]440 Normal,441 442 AllowList,443}444445impl From<up_data_structs::AccessMode> for AccessMode {446 fn from(value: up_data_structs::AccessMode) -> Self {447 match value {448 up_data_structs::AccessMode::Normal => AccessMode::Normal,449 up_data_structs::AccessMode::AllowList => AccessMode::AllowList,450 }451 }452}453454impl Into<up_data_structs::AccessMode> for AccessMode {455 fn into(self) -> up_data_structs::AccessMode {456 match self {457 AccessMode::Normal => up_data_structs::AccessMode::Normal,458 AccessMode::AllowList => up_data_structs::AccessMode::AllowList,459 }460 }461}