difftreelog
CORE-337 Rewrite set limits
in: master
9 files changed
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -16,10 +16,11 @@
use evm_coder::{solidity_interface, types::*, execution::{Result, Error}};
pub use pallet_evm::{PrecompileOutput, PrecompileResult, account::CrossAccountId};
-use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder};
+use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_core::{H160, U256};
use sp_std::vec::Vec;
-use up_data_structs::Property;
+use up_data_structs::{Property, SponsoringRateLimit};
+use alloc::format;
use crate::{Pallet, CollectionHandle, Config, CollectionProperties};
@@ -87,37 +88,53 @@
Ok(())
}
- fn set_limits(
- &self,
+ fn set_limit(
+ &mut self,
caller: caller,
- limits_json: string,
+ limit: string,
+ value: string,
) -> Result<void> {
- // let mut collection = collection_from_address::<T>(self.contract_address(caller).unwrap(), self.1.gas_left())?;
- // check_is_owner(caller, &collection)?;
+ check_is_owner(caller, self)?;
+ let mut limits = self.limits.clone();
- // let limits = serde_json_core::from_str(limits_json.as_ref())
- // .map_err(|e| Error::Revert(format!("Parse JSON error: {}", e)))?;
- // collection.limits = limits.0;
- // collection.save().map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ match limit.as_str() {
+ "accountTokenOwnershipLimit" => {
+ limits.account_token_ownership_limit = parse_int(value)?;
+ },
+ "sponsoredDataSize" => {
+ limits.sponsored_data_size = parse_int(value)?;
+ },
+ "sponsoredDataRateLimit" => {
+ limits.sponsored_data_rate_limit = Some(SponsoringRateLimit::Blocks(parse_int(value)?.unwrap()));
+ },
+ "tokenLimit" => {
+ limits.token_limit = parse_int(value)?;
+ },
+ "sponsorTransferTimeout" => {
+ limits.sponsor_transfer_timeout = parse_int(value)?;
+ },
+ "sponsorApproveTimeout" => {
+ limits.sponsor_approve_timeout = parse_int(value)?;
+ },
+ "ownerCanTransfer" => {
+ limits.owner_can_transfer = parse_bool(value)?;
+ },
+ "ownerCanDestroy" => {
+ limits.owner_can_destroy = parse_bool(value)?;
+ },
+ "transfersEnabled" => {
+ limits.transfers_enabled = parse_bool(value)?;
+ },
+ _ => return Err(Error::Revert(format!("Unknown limit \"{}\"", limit)))
+ }
+ self.limits = limits;
+ save(self);
Ok(())
}
fn contract_address(&self, _caller: caller) -> Result<address> {
Ok(crate::eth::collection_id_to_address(self.id))
}
-}
-
-fn collection_from_address<T: Config>(
- collection_address: address,
- gas_limit: u64
-) -> Result<CollectionHandle<T>> {
- let collection_id = crate::eth::map_eth_to_id(&collection_address)
- .ok_or(Error::Revert("Contract is not an unique collection".into()))?;
- let recorder = <SubstrateRecorder<T>>::new(gas_limit);
- let collection =
- CollectionHandle::new_with_recorder(collection_id, recorder)
- .ok_or(Error::Revert("Create collection handle error".into()))?;
- Ok(collection)
}
fn check_is_owner<T: Config>(caller: caller, collection: &CollectionHandle<T>) -> Result<()> {
@@ -130,4 +147,16 @@
fn save<T: Config>(collection: &CollectionHandle<T>) {
<crate::CollectionById<T>>::insert(collection.id, collection.collection.clone());
+}
+
+fn parse_int(value: string) -> Result<Option<u32>> {
+ value.parse::<u32>()
+ .map_err(|e| Error::Revert(format!("Int value \"{}\" parse error: {}", value, e)))
+ .map(|value| Some(value))
+}
+
+fn parse_bool(value: string) -> Result<Option<bool>> {
+ value.parse::<bool>()
+ .map_err(|e| Error::Revert(format!("Bool value \"{}\" parse error: {}", value, e)))
+ .map(|value| Some(value))
}
\ No newline at end of file
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -51,67 +51,6 @@
event MintingFinished();
}
-// Selector: 38e33c60
-contract Collection is Dummy, ERC165 {
- // Selector: setCollectionProperty(string,bytes) 2f073f66
- function setCollectionProperty(string memory key, bytes memory value)
- public
- {
- require(false, stub_error);
- key;
- value;
- dummy = 0;
- }
-
- // Selector: deleteCollectionProperty(string) 7b7debce
- function deleteCollectionProperty(string memory key) public {
- require(false, stub_error);
- key;
- dummy = 0;
- }
-
- // Throws error if key not found
- //
- // Selector: collectionProperty(string) cf24fd6d
- function collectionProperty(string memory key)
- public
- view
- returns (bytes memory)
- {
- require(false, stub_error);
- key;
- dummy;
- return hex"";
- }
-
- // Selector: ethSetSponsor(address) 8f9af356
- function ethSetSponsor(address sponsor) public {
- require(false, stub_error);
- sponsor;
- dummy = 0;
- }
-
- // Selector: ethConfirmSponsorship() a8580d1a
- function ethConfirmSponsorship() public {
- require(false, stub_error);
- dummy = 0;
- }
-
- // Selector: setLimits(string) 72cb345d
- function setLimits(string memory limitsJson) public view {
- require(false, stub_error);
- limitsJson;
- dummy;
- }
-
- // Selector: contractAddress() f6b4dfb4
- function contractAddress() public view returns (address) {
- require(false, stub_error);
- dummy;
- return 0x0000000000000000000000000000000000000000;
- }
-}
-
// Selector: 41369377
contract TokenProperties is Dummy, ERC165 {
// Selector: setTokenPropertyPermission(string,bool,bool,bool) 222d97fa
@@ -441,6 +380,68 @@
}
}
+// Selector: f5652829
+contract Collection is Dummy, ERC165 {
+ // Selector: setCollectionProperty(string,bytes) 2f073f66
+ function setCollectionProperty(string memory key, bytes memory value)
+ public
+ {
+ require(false, stub_error);
+ key;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: deleteCollectionProperty(string) 7b7debce
+ function deleteCollectionProperty(string memory key) public {
+ require(false, stub_error);
+ key;
+ dummy = 0;
+ }
+
+ // Throws error if key not found
+ //
+ // Selector: collectionProperty(string) cf24fd6d
+ function collectionProperty(string memory key)
+ public
+ view
+ returns (bytes memory)
+ {
+ require(false, stub_error);
+ key;
+ dummy;
+ return hex"";
+ }
+
+ // Selector: ethSetSponsor(address) 8f9af356
+ function ethSetSponsor(address sponsor) public {
+ require(false, stub_error);
+ sponsor;
+ dummy = 0;
+ }
+
+ // Selector: ethConfirmSponsorship() a8580d1a
+ function ethConfirmSponsorship() public {
+ require(false, stub_error);
+ dummy = 0;
+ }
+
+ // Selector: setLimit(string,string) bf4d2014
+ function setLimit(string memory limit, string memory value) public {
+ require(false, stub_error);
+ limit;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() public view returns (address) {
+ require(false, stub_error);
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+}
+
contract UniqueNFT is
Dummy,
ERC165,
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -26,7 +26,7 @@
};
use frame_support::traits::Get;
use sp_core::H160;
- use pallet_common::{CollectionHandle, CollectionById};
+ use pallet_common::CollectionById;
use sp_std::vec::Vec;
use alloc::format;
primitives/data-structs/src/lib.rsdiffbeforeafterboth1// 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::Get,26 parameter_types,27};2829#[cfg(feature = "serde")]30use serde::{Serialize, Deserialize};3132use sp_core::U256;33use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, Permill};34use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};35use frame_support::{BoundedVec, traits::ConstU32};36use derivative::Derivative;37use scale_info::TypeInfo;3839pub mod rmrk;4041// RMRK42use rmrk::{43 CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,44};45pub use rmrk::{46 primitives::{47 CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,48 PartId as RmrkPartId, ResourceId as RmrkResourceId,49 },50 NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,51 FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart, EquippableList as RmrkEquippableList,52 BasicResource as RmrkBasicResource, ComposableResource as RmrkComposableResource, SlotResource as RmrkSlotResource,53};5455mod bounded;56pub mod budget;57pub mod mapping;58mod migration;5960pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;61pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;62pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;6364pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {65 100_00066} else {67 1068};69pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {70 100_00071} else {72 1073};74pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {75 204876} else {77 1078};79pub const COLLECTION_ADMINS_LIMIT: u32 = 5;80pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;81pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {82 1_000_00083} else {84 1085};8687// Timeouts for item types in passed blocks88pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;89pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;90pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;9192pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;9394// Schema limits95pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;96pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;97pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;9899pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;100101pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;102pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;103pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;104105pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;106pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;107pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;108109pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;110pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;111112// RMRK constants113pub const RMRK_STRING_LIMIT: u32 = 128;114pub const RMRK_COLLECTION_SYMBOL_LIMIT: u32 = 100;115pub const RMRK_RESOURCE_SYMBOL_LIMIT: u32 = 10;116pub const RMRK_KEY_LIMIT: u32 = 32;117pub const RMRK_VALUE_LIMIT: u32 = 256;118119/// How much items can be created per single120/// create_many call121pub const MAX_ITEMS_PER_BATCH: u32 = 200;122123pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;124125#[derive(126 Encode,127 Decode,128 PartialEq,129 Eq,130 PartialOrd,131 Ord,132 Clone,133 Copy,134 Debug,135 Default,136 TypeInfo,137 MaxEncodedLen,138)]139#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]140pub struct CollectionId(pub u32);141impl EncodeLike<u32> for CollectionId {}142impl EncodeLike<CollectionId> for u32 {}143144#[derive(145 Encode,146 Decode,147 PartialEq,148 Eq,149 PartialOrd,150 Ord,151 Clone,152 Copy,153 Debug,154 Default,155 TypeInfo,156 MaxEncodedLen,157)]158#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]159pub struct TokenId(pub u32);160impl EncodeLike<u32> for TokenId {}161impl EncodeLike<TokenId> for u32 {}162163impl TokenId {164 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {165 self.0166 .checked_add(1)167 .ok_or(ArithmeticError::Overflow)168 .map(Self)169 }170}171172impl From<TokenId> for U256 {173 fn from(t: TokenId) -> Self {174 t.0.into()175 }176}177178impl TryFrom<U256> for TokenId {179 type Error = &'static str;180181 fn try_from(value: U256) -> Result<Self, Self::Error> {182 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))183 }184}185186#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]187#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]188pub struct TokenData<CrossAccountId> {189 pub properties: Vec<Property>,190 pub owner: Option<CrossAccountId>,191}192193pub struct OverflowError;194impl From<OverflowError> for &'static str {195 fn from(_: OverflowError) -> Self {196 "overflow occured"197 }198}199200pub type DecimalPoints = u8;201202#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]203#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]204pub enum CollectionMode {205 NFT,206 // decimal points207 Fungible(DecimalPoints),208 ReFungible,209}210211impl CollectionMode {212 pub fn id(&self) -> u8 {213 match self {214 CollectionMode::NFT => 1,215 CollectionMode::Fungible(_) => 2,216 CollectionMode::ReFungible => 3,217 }218 }219}220221pub trait SponsoringResolve<AccountId, Call> {222 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;223}224225#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]226#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]227pub enum AccessMode {228 Normal,229 AllowList,230}231impl Default for AccessMode {232 fn default() -> Self {233 Self::Normal234 }235}236237#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]238#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]239pub enum SchemaVersion {240 ImageURL,241 Unique,242}243impl Default for SchemaVersion {244 fn default() -> Self {245 Self::ImageURL246 }247}248249#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]250#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]251pub struct Ownership<AccountId> {252 pub owner: AccountId,253 pub fraction: u128,254}255256#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]257#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]258pub enum SponsorshipState<AccountId> {259 /// The fees are applied to the transaction sender260 Disabled,261 Unconfirmed(AccountId),262 /// Transactions are sponsored by specified account263 Confirmed(AccountId),264}265266impl<AccountId> SponsorshipState<AccountId> {267 pub fn sponsor(&self) -> Option<&AccountId> {268 match self {269 Self::Confirmed(sponsor) => Some(sponsor),270 _ => None,271 }272 }273274 pub fn pending_sponsor(&self) -> Option<&AccountId> {275 match self {276 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),277 _ => None,278 }279 }280281 pub fn confirmed(&self) -> bool {282 matches!(self, Self::Confirmed(_))283 }284}285286impl<T> Default for SponsorshipState<T> {287 fn default() -> Self {288 Self::Disabled289 }290}291292/// Used in storage293#[struct_versioning::versioned(version = 2, upper)]294#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]295pub struct Collection<AccountId> {296 pub owner: AccountId,297 pub mode: CollectionMode,298 #[version(..2)]299 pub access: AccessMode,300 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,301 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,302 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,303304 #[version(..2)]305 pub mint_mode: bool,306307 #[version(..2)]308 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,309310 #[version(..2)]311 pub schema_version: SchemaVersion,312 pub sponsorship: SponsorshipState<AccountId>,313314 pub limits: CollectionLimits,315316 #[version(2.., upper(Default::default()))]317 pub permissions: CollectionPermissions,318319 #[version(..2)]320 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,321322 #[version(..2)]323 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,324325 #[version(..2)]326 pub meta_update_permission: MetaUpdatePermission,327}328329/// Used in RPC calls330#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]331#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]332pub struct RpcCollection<AccountId> {333 pub owner: AccountId,334 pub mode: CollectionMode,335 pub name: Vec<u16>,336 pub description: Vec<u16>,337 pub token_prefix: Vec<u8>,338 pub sponsorship: SponsorshipState<AccountId>,339 pub limits: CollectionLimits,340 pub permissions: CollectionPermissions,341 pub token_property_permissions: Vec<PropertyKeyPermission>,342 pub properties: Vec<Property>,343}344345#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]346#[derivative(Debug, Default(bound = ""))]347pub struct CreateCollectionData<AccountId> {348 #[derivative(Default(value = "CollectionMode::NFT"))]349 pub mode: CollectionMode,350 pub access: Option<AccessMode>,351 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,352 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,353 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,354 pub pending_sponsor: Option<AccountId>,355 pub limits: Option<CollectionLimits>,356 pub permissions: Option<CollectionPermissions>,357 pub token_property_permissions: CollectionPropertiesPermissionsVec,358 pub properties: CollectionPropertiesVec,359}360361pub type CollectionPropertiesPermissionsVec =362 BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;363364pub type CollectionPropertiesVec =365 BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;366367/// All fields are wrapped in `Option`s, where None means chain default368#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]369#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]370pub struct CollectionLimits {371 #[serde(alias = "accountTokenOwnershipLimit")]372 pub account_token_ownership_limit: Option<u32>,373 #[serde(alias = "sponsoredDataSize")]374 pub sponsored_data_size: Option<u32>,375376 /// FIXME should we delete this or repurpose it?377 /// None - setVariableMetadata is not sponsored378 /// Some(v) - setVariableMetadata is sponsored379 /// if there is v block between txs380 #[serde(alias = "sponsoredDataRateLimit")]381 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,382 #[serde(alias = "tokenLimit")]383 pub token_limit: Option<u32>,384385 // Timeouts for item types in passed blocks386 #[serde(alias = "sponsorTransferTimeout")]387 pub sponsor_transfer_timeout: Option<u32>,388 #[serde(alias = "sponsorApproveTimeout")]389 pub sponsor_approve_timeout: Option<u32>,390 #[serde(alias = "ownerCanTransfer")]391 pub owner_can_transfer: Option<bool>,392 #[serde(alias = "ownerCanDestroy")]393 pub owner_can_destroy: Option<bool>,394 #[serde(alias = "transfersEnabled")]395 pub transfers_enabled: Option<bool>,396}397398impl CollectionLimits {399 pub fn account_token_ownership_limit(&self) -> u32 {400 self.account_token_ownership_limit401 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)402 .min(MAX_TOKEN_OWNERSHIP)403 }404 pub fn sponsored_data_size(&self) -> u32 {405 self.sponsored_data_size406 .unwrap_or(CUSTOM_DATA_LIMIT)407 .min(CUSTOM_DATA_LIMIT)408 }409 pub fn token_limit(&self) -> u32 {410 self.token_limit411 .unwrap_or(COLLECTION_TOKEN_LIMIT)412 .min(COLLECTION_TOKEN_LIMIT)413 }414 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {415 self.sponsor_transfer_timeout416 .unwrap_or(default)417 .min(MAX_SPONSOR_TIMEOUT)418 }419 pub fn sponsor_approve_timeout(&self) -> u32 {420 self.sponsor_approve_timeout421 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)422 .min(MAX_SPONSOR_TIMEOUT)423 }424 pub fn owner_can_transfer(&self) -> bool {425 self.owner_can_transfer.unwrap_or(true)426 }427 pub fn owner_can_destroy(&self) -> bool {428 self.owner_can_destroy.unwrap_or(true)429 }430 pub fn transfers_enabled(&self) -> bool {431 self.transfers_enabled.unwrap_or(true)432 }433 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {434 match self435 .sponsored_data_rate_limit436 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)437 {438 SponsoringRateLimit::SponsoringDisabled => None,439 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),440 }441 }442}443444#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]445#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]446pub struct CollectionPermissions {447 pub access: Option<AccessMode>,448 pub mint_mode: Option<bool>,449 pub nesting: Option<NestingRule>,450}451452impl CollectionPermissions {453 pub fn access(&self) -> AccessMode {454 self.access.unwrap_or(AccessMode::Normal)455 }456 pub fn mint_mode(&self) -> bool {457 self.mint_mode.unwrap_or(false)458 }459 pub fn nesting(&self) -> &NestingRule {460 static DEFAULT: NestingRule = NestingRule::Disabled;461 self.nesting.as_ref().unwrap_or(&DEFAULT)462 }463}464465#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]466#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]467#[derivative(Debug)]468pub enum NestingRule {469 /// No one can nest tokens470 Disabled,471 /// Owner can nest any tokens472 Owner,473 /// Owner can nest tokens from specified collections474 OwnerRestricted(475 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]476 #[derivative(Debug(format_with = "bounded::set_debug"))]477 BoundedBTreeSet<CollectionId, ConstU32<16>>,478 ),479}480481#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]482#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]483pub enum SponsoringRateLimit {484 SponsoringDisabled,485 Blocks(u32),486}487488#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]489#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]490#[derivative(Debug)]491pub struct CreateNftData {492 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]493 #[derivative(Debug(format_with = "bounded::vec_debug"))]494 pub const_data: BoundedVec<u8, CustomDataLimit>,495496 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]497 #[derivative(Debug(format_with = "bounded::vec_debug"))]498 pub properties: CollectionPropertiesVec,499}500501#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]502#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]503pub struct CreateFungibleData {504 pub value: u128,505}506507#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]508#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]509#[derivative(Debug)]510pub struct CreateReFungibleData {511 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]512 #[derivative(Debug(format_with = "bounded::vec_debug"))]513 pub const_data: BoundedVec<u8, CustomDataLimit>,514 pub pieces: u128,515}516517#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]518#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]519pub enum MetaUpdatePermission {520 ItemOwner,521 Admin,522 None,523}524525#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]526#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]527pub enum CreateItemData {528 NFT(CreateNftData),529 Fungible(CreateFungibleData),530 ReFungible(CreateReFungibleData),531}532533#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]534#[derivative(Debug)]535pub struct CreateNftExData<CrossAccountId> {536 #[derivative(Debug(format_with = "bounded::vec_debug"))]537 pub properties: CollectionPropertiesVec,538 pub owner: CrossAccountId,539}540541#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]542#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]543pub struct CreateRefungibleExData<CrossAccountId> {544 #[derivative(Debug(format_with = "bounded::vec_debug"))]545 pub const_data: BoundedVec<u8, CustomDataLimit>,546 #[derivative(Debug(format_with = "bounded::map_debug"))]547 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,548}549550#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]551#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]552pub enum CreateItemExData<CrossAccountId> {553 NFT(554 #[derivative(Debug(format_with = "bounded::vec_debug"))]555 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,556 ),557 Fungible(558 #[derivative(Debug(format_with = "bounded::map_debug"))]559 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,560 ),561 /// Many tokens, each may have only one owner562 RefungibleMultipleItems(563 #[derivative(Debug(format_with = "bounded::vec_debug"))]564 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,565 ),566 /// Single token, which may have many owners567 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),568}569570impl CreateItemData {571 pub fn data_size(&self) -> usize {572 match self {573 CreateItemData::NFT(data) => data.const_data.len(),574 CreateItemData::ReFungible(data) => data.const_data.len(),575 _ => 0,576 }577 }578}579580impl From<CreateNftData> for CreateItemData {581 fn from(item: CreateNftData) -> Self {582 CreateItemData::NFT(item)583 }584}585586impl From<CreateReFungibleData> for CreateItemData {587 fn from(item: CreateReFungibleData) -> Self {588 CreateItemData::ReFungible(item)589 }590}591592impl From<CreateFungibleData> for CreateItemData {593 fn from(item: CreateFungibleData) -> Self {594 CreateItemData::Fungible(item)595 }596}597598#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]599#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]600pub struct CollectionStats {601 pub created: u32,602 pub destroyed: u32,603 pub alive: u32,604}605606#[derive(Encode, Decode, Clone, Debug)]607#[cfg_attr(feature = "std", derive(PartialEq))]608pub struct PhantomType<T>(core::marker::PhantomData<T>);609610impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {611 type Identity = PhantomType<T>;612613 fn type_info() -> scale_info::Type {614 use scale_info::{615 Type, Path,616 build::{FieldsBuilder, UnnamedFields},617 type_params,618 };619 Type::builder()620 .path(Path::new("up_data_structs", "PhantomType"))621 .type_params(type_params!(T))622 .composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))623 }624}625impl<T> MaxEncodedLen for PhantomType<T> {626 fn max_encoded_len() -> usize {627 0628 }629}630631pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;632pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;633634#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]635#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]636pub struct PropertyPermission {637 pub mutable: bool,638 pub collection_admin: bool,639 pub token_owner: bool,640}641642impl PropertyPermission {643 pub fn none() -> Self {644 Self {645 mutable: true,646 collection_admin: false,647 token_owner: false,648 }649 }650}651652#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]653#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]654pub struct Property {655 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]656 pub key: PropertyKey,657658 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]659 pub value: PropertyValue,660}661662impl Into<(PropertyKey, PropertyValue)> for Property {663 fn into(self) -> (PropertyKey, PropertyValue) {664 (self.key, self.value)665 }666}667668#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]669#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]670pub struct PropertyKeyPermission {671 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]672 pub key: PropertyKey,673674 pub permission: PropertyPermission,675}676677impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {678 fn into(self) -> (PropertyKey, PropertyPermission) {679 (self.key, self.permission)680 }681}682683#[derive(Debug)]684pub enum PropertiesError {685 NoSpaceForProperty,686 PropertyLimitReached,687 InvalidCharacterInPropertyKey,688 PropertyKeyIsTooLong,689 EmptyPropertyKey,690}691692#[derive(Clone, Copy)]693pub enum PropertyScope {694 None,695 Rmrk,696}697698impl PropertyScope {699 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {700 let scope_str: &[u8] = match self {701 Self::None => return Ok(key),702 Self::Rmrk => b"rmrk",703 };704705 [scope_str, b":", key.as_slice()]706 .concat()707 .try_into()708 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)709 }710}711712pub trait TrySetProperty: Sized {713 type Value;714715 fn try_scoped_set(716 &mut self,717 scope: PropertyScope,718 key: PropertyKey,719 value: Self::Value,720 ) -> Result<(), PropertiesError>;721722 fn try_scoped_set_from_iter<I, KV>(723 &mut self,724 scope: PropertyScope,725 iter: I,726 ) -> Result<(), PropertiesError>727 where728 I: Iterator<Item = KV>,729 KV: Into<(PropertyKey, Self::Value)>,730 {731 for kv in iter {732 let (key, value) = kv.into();733 self.try_scoped_set(scope, key, value)?;734 }735736 Ok(())737 }738739 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {740 self.try_scoped_set(PropertyScope::None, key, value)741 }742743 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>744 where745 I: Iterator<Item = KV>,746 KV: Into<(PropertyKey, Self::Value)>,747 {748 self.try_scoped_set_from_iter(PropertyScope::None, iter)749 }750}751752#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]753#[derivative(Default(bound = ""))]754pub struct PropertiesMap<Value>(755 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,756);757758impl<Value> PropertiesMap<Value> {759 pub fn new() -> Self {760 Self(BoundedBTreeMap::new())761 }762763 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {764 Self::check_property_key(key)?;765766 Ok(self.0.remove(key))767 }768769 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {770 self.0.get(key)771 }772773 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {774 if key.is_empty() {775 return Err(PropertiesError::EmptyPropertyKey);776 }777778 for byte in key.as_slice().iter() {779 let byte = *byte;780781 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {782 return Err(PropertiesError::InvalidCharacterInPropertyKey);783 }784 }785786 Ok(())787 }788}789790impl<Value> IntoIterator for PropertiesMap<Value> {791 type Item = (PropertyKey, Value);792 type IntoIter = <793 BoundedBTreeMap<794 PropertyKey,795 Value,796 ConstU32<MAX_PROPERTIES_PER_ITEM>797 > as IntoIterator798 >::IntoIter;799800 fn into_iter(self) -> Self::IntoIter {801 self.0.into_iter()802 }803}804805impl<Value> TrySetProperty for PropertiesMap<Value> {806 type Value = Value;807808 fn try_scoped_set(809 &mut self,810 scope: PropertyScope,811 key: PropertyKey,812 value: Self::Value,813 ) -> Result<(), PropertiesError> {814 Self::check_property_key(&key)?;815816 let key = scope.apply(key)?;817 self.0818 .try_insert(key, value)819 .map_err(|_| PropertiesError::PropertyLimitReached)?;820821 Ok(())822 }823}824825pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;826827#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]828pub struct Properties {829 map: PropertiesMap<PropertyValue>,830 consumed_space: u32,831 space_limit: u32,832}833834impl Properties {835 pub fn new(space_limit: u32) -> Self {836 Self {837 map: PropertiesMap::new(),838 consumed_space: 0,839 space_limit,840 }841 }842843 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {844 let value = self.map.remove(key)?;845846 if let Some(ref value) = value {847 let value_len = value.len() as u32;848 self.consumed_space -= value_len;849 }850851 Ok(value)852 }853854 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {855 self.map.get(key)856 }857}858859impl IntoIterator for Properties {860 type Item = (PropertyKey, PropertyValue);861 type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;862863 fn into_iter(self) -> Self::IntoIter {864 self.map.into_iter()865 }866}867868impl TrySetProperty for Properties {869 type Value = PropertyValue;870871 fn try_scoped_set(872 &mut self,873 scope: PropertyScope,874 key: PropertyKey,875 value: Self::Value,876 ) -> Result<(), PropertiesError> {877 let value_len = value.len();878879 if self.consumed_space as usize + value_len > self.space_limit as usize880 && !cfg!(feature = "runtime-benchmarks")881 {882 return Err(PropertiesError::NoSpaceForProperty);883 }884885 self.map.try_scoped_set(scope, key, value)?;886887 self.consumed_space += value_len as u32;888889 Ok(())890 }891}892893pub struct CollectionProperties;894895impl Get<Properties> for CollectionProperties {896 fn get() -> Properties {897 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)898 }899}900901pub struct TokenProperties;902903impl Get<Properties> for TokenProperties {904 fn get() -> Properties {905 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)906 }907}908909// RMRK910// todo document?911parameter_types! {912 #[derive(PartialEq, TypeInfo)]913 pub const RmrkStringLimit: u32 = 128;914 #[derive(PartialEq)]915 pub const RmrkCollectionSymbolLimit: u32 = 100;916 #[derive(PartialEq)]917 pub const RmrkResourceSymbolLimit: u32 = 10;918 #[derive(PartialEq)]919 pub const RmrkKeyLimit: u32 = 32;920 #[derive(PartialEq)]921 pub const RmrkValueLimit: u32 = 256;922 #[derive(PartialEq)]923 pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;924 #[derive(PartialEq)]925 pub const RmrkPartsLimit: u32 = 3;926}927928impl From<RmrkCollectionId> for CollectionId {929 fn from(id: RmrkCollectionId) -> Self {930 Self(id)931 }932}933934impl From<RmrkNftId> for TokenId {935 fn from(id: RmrkNftId) -> Self {936 Self(id)937 }938}939940pub type RmrkCollectionInfo<AccountId> =941 CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;942pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;943pub type RmrkResourceInfo = ResourceInfo<944 RmrkBoundedResource,945 RmrkString,946 RmrkBoundedParts,947>;948pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;949pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;950pub type RmrkPartType =951 PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;952pub type RmrkThemeProperty = ThemeProperty<RmrkString>;953pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;954955pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;956pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;957pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;958959type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;960type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>;961962pub type RmrkRpcString = Vec<u8>;963pub type RmrkThemeName = RmrkRpcString;964pub type RmrkPropertyKey = RmrkRpcString;965966pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;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::Get,26 parameter_types,27};2829#[cfg(feature = "serde")]30use serde::{Serialize, Deserialize};3132use sp_core::U256;33use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, Permill};34use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};35use frame_support::{BoundedVec, traits::ConstU32};36use derivative::Derivative;37use scale_info::TypeInfo;3839pub mod rmrk;4041// RMRK42use rmrk::{43 CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,44};45pub use rmrk::{46 primitives::{47 CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,48 PartId as RmrkPartId, ResourceId as RmrkResourceId,49 },50 NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,51 FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart, EquippableList as RmrkEquippableList,52 BasicResource as RmrkBasicResource, ComposableResource as RmrkComposableResource, SlotResource as RmrkSlotResource,53};5455mod bounded;56pub mod budget;57pub mod mapping;58mod migration;5960pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;61pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;62pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;6364pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {65 100_00066} else {67 1068};69pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {70 100_00071} else {72 1073};74pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {75 204876} else {77 1078};79pub const COLLECTION_ADMINS_LIMIT: u32 = 5;80pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;81pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {82 1_000_00083} else {84 1085};8687// Timeouts for item types in passed blocks88pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;89pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;90pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;9192pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;9394// Schema limits95pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;96pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;97pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;9899pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;100101pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;102pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;103pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;104105pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;106pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;107pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;108109pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;110pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;111112// RMRK constants113pub const RMRK_STRING_LIMIT: u32 = 128;114pub const RMRK_COLLECTION_SYMBOL_LIMIT: u32 = 100;115pub const RMRK_RESOURCE_SYMBOL_LIMIT: u32 = 10;116pub const RMRK_KEY_LIMIT: u32 = 32;117pub const RMRK_VALUE_LIMIT: u32 = 256;118119/// How much items can be created per single120/// create_many call121pub const MAX_ITEMS_PER_BATCH: u32 = 200;122123pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;124125#[derive(126 Encode,127 Decode,128 PartialEq,129 Eq,130 PartialOrd,131 Ord,132 Clone,133 Copy,134 Debug,135 Default,136 TypeInfo,137 MaxEncodedLen,138)]139#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]140pub struct CollectionId(pub u32);141impl EncodeLike<u32> for CollectionId {}142impl EncodeLike<CollectionId> for u32 {}143144#[derive(145 Encode,146 Decode,147 PartialEq,148 Eq,149 PartialOrd,150 Ord,151 Clone,152 Copy,153 Debug,154 Default,155 TypeInfo,156 MaxEncodedLen,157)]158#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]159pub struct TokenId(pub u32);160impl EncodeLike<u32> for TokenId {}161impl EncodeLike<TokenId> for u32 {}162163impl TokenId {164 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {165 self.0166 .checked_add(1)167 .ok_or(ArithmeticError::Overflow)168 .map(Self)169 }170}171172impl From<TokenId> for U256 {173 fn from(t: TokenId) -> Self {174 t.0.into()175 }176}177178impl TryFrom<U256> for TokenId {179 type Error = &'static str;180181 fn try_from(value: U256) -> Result<Self, Self::Error> {182 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))183 }184}185186#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]187#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]188pub struct TokenData<CrossAccountId> {189 pub properties: Vec<Property>,190 pub owner: Option<CrossAccountId>,191}192193pub struct OverflowError;194impl From<OverflowError> for &'static str {195 fn from(_: OverflowError) -> Self {196 "overflow occured"197 }198}199200pub type DecimalPoints = u8;201202#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]203#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]204pub enum CollectionMode {205 NFT,206 // decimal points207 Fungible(DecimalPoints),208 ReFungible,209}210211impl CollectionMode {212 pub fn id(&self) -> u8 {213 match self {214 CollectionMode::NFT => 1,215 CollectionMode::Fungible(_) => 2,216 CollectionMode::ReFungible => 3,217 }218 }219}220221pub trait SponsoringResolve<AccountId, Call> {222 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;223}224225#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]226#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]227pub enum AccessMode {228 Normal,229 AllowList,230}231impl Default for AccessMode {232 fn default() -> Self {233 Self::Normal234 }235}236237#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]238#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]239pub enum SchemaVersion {240 ImageURL,241 Unique,242}243impl Default for SchemaVersion {244 fn default() -> Self {245 Self::ImageURL246 }247}248249#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]250#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]251pub struct Ownership<AccountId> {252 pub owner: AccountId,253 pub fraction: u128,254}255256#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]257#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]258pub enum SponsorshipState<AccountId> {259 /// The fees are applied to the transaction sender260 Disabled,261 Unconfirmed(AccountId),262 /// Transactions are sponsored by specified account263 Confirmed(AccountId),264}265266impl<AccountId> SponsorshipState<AccountId> {267 pub fn sponsor(&self) -> Option<&AccountId> {268 match self {269 Self::Confirmed(sponsor) => Some(sponsor),270 _ => None,271 }272 }273274 pub fn pending_sponsor(&self) -> Option<&AccountId> {275 match self {276 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),277 _ => None,278 }279 }280281 pub fn confirmed(&self) -> bool {282 matches!(self, Self::Confirmed(_))283 }284}285286impl<T> Default for SponsorshipState<T> {287 fn default() -> Self {288 Self::Disabled289 }290}291292/// Used in storage293#[struct_versioning::versioned(version = 2, upper)]294#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]295pub struct Collection<AccountId> {296 pub owner: AccountId,297 pub mode: CollectionMode,298 #[version(..2)]299 pub access: AccessMode,300 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,301 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,302 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,303304 #[version(..2)]305 pub mint_mode: bool,306307 #[version(..2)]308 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,309310 #[version(..2)]311 pub schema_version: SchemaVersion,312 pub sponsorship: SponsorshipState<AccountId>,313314 pub limits: CollectionLimits,315316 #[version(2.., upper(Default::default()))]317 pub permissions: CollectionPermissions,318319 #[version(..2)]320 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,321322 #[version(..2)]323 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,324325 #[version(..2)]326 pub meta_update_permission: MetaUpdatePermission,327}328329/// Used in RPC calls330#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]331#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]332pub struct RpcCollection<AccountId> {333 pub owner: AccountId,334 pub mode: CollectionMode,335 pub name: Vec<u16>,336 pub description: Vec<u16>,337 pub token_prefix: Vec<u8>,338 pub sponsorship: SponsorshipState<AccountId>,339 pub limits: CollectionLimits,340 pub permissions: CollectionPermissions,341 pub token_property_permissions: Vec<PropertyKeyPermission>,342 pub properties: Vec<Property>,343}344345#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]346#[derivative(Debug, Default(bound = ""))]347pub struct CreateCollectionData<AccountId> {348 #[derivative(Default(value = "CollectionMode::NFT"))]349 pub mode: CollectionMode,350 pub access: Option<AccessMode>,351 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,352 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,353 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,354 pub pending_sponsor: Option<AccountId>,355 pub limits: Option<CollectionLimits>,356 pub permissions: Option<CollectionPermissions>,357 pub token_property_permissions: CollectionPropertiesPermissionsVec,358 pub properties: CollectionPropertiesVec,359}360361pub type CollectionPropertiesPermissionsVec =362 BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;363364pub type CollectionPropertiesVec =365 BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;366367/// All fields are wrapped in `Option`s, where None means chain default368#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]369#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]370pub struct CollectionLimits {371 pub account_token_ownership_limit: Option<u32>,372 pub sponsored_data_size: Option<u32>,373374 /// FIXME should we delete this or repurpose it?375 /// None - setVariableMetadata is not sponsored376 /// Some(v) - setVariableMetadata is sponsored377 /// if there is v block between txs378 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,379 pub token_limit: Option<u32>,380381 // Timeouts for item types in passed blocks382 pub sponsor_transfer_timeout: Option<u32>,383 pub sponsor_approve_timeout: Option<u32>,384 pub owner_can_transfer: Option<bool>,385 pub owner_can_destroy: Option<bool>,386 pub transfers_enabled: Option<bool>,387}388389impl CollectionLimits {390 pub fn account_token_ownership_limit(&self) -> u32 {391 self.account_token_ownership_limit392 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)393 .min(MAX_TOKEN_OWNERSHIP)394 }395 pub fn sponsored_data_size(&self) -> u32 {396 self.sponsored_data_size397 .unwrap_or(CUSTOM_DATA_LIMIT)398 .min(CUSTOM_DATA_LIMIT)399 }400 pub fn token_limit(&self) -> u32 {401 self.token_limit402 .unwrap_or(COLLECTION_TOKEN_LIMIT)403 .min(COLLECTION_TOKEN_LIMIT)404 }405 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {406 self.sponsor_transfer_timeout407 .unwrap_or(default)408 .min(MAX_SPONSOR_TIMEOUT)409 }410 pub fn sponsor_approve_timeout(&self) -> u32 {411 self.sponsor_approve_timeout412 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)413 .min(MAX_SPONSOR_TIMEOUT)414 }415 pub fn owner_can_transfer(&self) -> bool {416 self.owner_can_transfer.unwrap_or(true)417 }418 pub fn owner_can_destroy(&self) -> bool {419 self.owner_can_destroy.unwrap_or(true)420 }421 pub fn transfers_enabled(&self) -> bool {422 self.transfers_enabled.unwrap_or(true)423 }424 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {425 match self426 .sponsored_data_rate_limit427 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)428 {429 SponsoringRateLimit::SponsoringDisabled => None,430 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),431 }432 }433}434435#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]436#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]437pub struct CollectionPermissions {438 pub access: Option<AccessMode>,439 pub mint_mode: Option<bool>,440 pub nesting: Option<NestingRule>,441}442443impl CollectionPermissions {444 pub fn access(&self) -> AccessMode {445 self.access.unwrap_or(AccessMode::Normal)446 }447 pub fn mint_mode(&self) -> bool {448 self.mint_mode.unwrap_or(false)449 }450 pub fn nesting(&self) -> &NestingRule {451 static DEFAULT: NestingRule = NestingRule::Disabled;452 self.nesting.as_ref().unwrap_or(&DEFAULT)453 }454}455456#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]457#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]458#[derivative(Debug)]459pub enum NestingRule {460 /// No one can nest tokens461 Disabled,462 /// Owner can nest any tokens463 Owner,464 /// Owner can nest tokens from specified collections465 OwnerRestricted(466 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]467 #[derivative(Debug(format_with = "bounded::set_debug"))]468 BoundedBTreeSet<CollectionId, ConstU32<16>>,469 ),470}471472#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]473#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]474pub enum SponsoringRateLimit {475 SponsoringDisabled,476 Blocks(u32),477}478479#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]480#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]481#[derivative(Debug)]482pub struct CreateNftData {483 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]484 #[derivative(Debug(format_with = "bounded::vec_debug"))]485 pub const_data: BoundedVec<u8, CustomDataLimit>,486487 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]488 #[derivative(Debug(format_with = "bounded::vec_debug"))]489 pub properties: CollectionPropertiesVec,490}491492#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]493#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]494pub struct CreateFungibleData {495 pub value: u128,496}497498#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]499#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]500#[derivative(Debug)]501pub struct CreateReFungibleData {502 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]503 #[derivative(Debug(format_with = "bounded::vec_debug"))]504 pub const_data: BoundedVec<u8, CustomDataLimit>,505 pub pieces: u128,506}507508#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]509#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]510pub enum MetaUpdatePermission {511 ItemOwner,512 Admin,513 None,514}515516#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]517#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]518pub enum CreateItemData {519 NFT(CreateNftData),520 Fungible(CreateFungibleData),521 ReFungible(CreateReFungibleData),522}523524#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]525#[derivative(Debug)]526pub struct CreateNftExData<CrossAccountId> {527 #[derivative(Debug(format_with = "bounded::vec_debug"))]528 pub properties: CollectionPropertiesVec,529 pub owner: CrossAccountId,530}531532#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]533#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]534pub struct CreateRefungibleExData<CrossAccountId> {535 #[derivative(Debug(format_with = "bounded::vec_debug"))]536 pub const_data: BoundedVec<u8, CustomDataLimit>,537 #[derivative(Debug(format_with = "bounded::map_debug"))]538 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,539}540541#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]542#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]543pub enum CreateItemExData<CrossAccountId> {544 NFT(545 #[derivative(Debug(format_with = "bounded::vec_debug"))]546 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,547 ),548 Fungible(549 #[derivative(Debug(format_with = "bounded::map_debug"))]550 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,551 ),552 /// Many tokens, each may have only one owner553 RefungibleMultipleItems(554 #[derivative(Debug(format_with = "bounded::vec_debug"))]555 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,556 ),557 /// Single token, which may have many owners558 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),559}560561impl CreateItemData {562 pub fn data_size(&self) -> usize {563 match self {564 CreateItemData::NFT(data) => data.const_data.len(),565 CreateItemData::ReFungible(data) => data.const_data.len(),566 _ => 0,567 }568 }569}570571impl From<CreateNftData> for CreateItemData {572 fn from(item: CreateNftData) -> Self {573 CreateItemData::NFT(item)574 }575}576577impl From<CreateReFungibleData> for CreateItemData {578 fn from(item: CreateReFungibleData) -> Self {579 CreateItemData::ReFungible(item)580 }581}582583impl From<CreateFungibleData> for CreateItemData {584 fn from(item: CreateFungibleData) -> Self {585 CreateItemData::Fungible(item)586 }587}588589#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]590#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]591pub struct CollectionStats {592 pub created: u32,593 pub destroyed: u32,594 pub alive: u32,595}596597#[derive(Encode, Decode, Clone, Debug)]598#[cfg_attr(feature = "std", derive(PartialEq))]599pub struct PhantomType<T>(core::marker::PhantomData<T>);600601impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {602 type Identity = PhantomType<T>;603604 fn type_info() -> scale_info::Type {605 use scale_info::{606 Type, Path,607 build::{FieldsBuilder, UnnamedFields},608 type_params,609 };610 Type::builder()611 .path(Path::new("up_data_structs", "PhantomType"))612 .type_params(type_params!(T))613 .composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))614 }615}616impl<T> MaxEncodedLen for PhantomType<T> {617 fn max_encoded_len() -> usize {618 0619 }620}621622pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;623pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;624625#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]626#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]627pub struct PropertyPermission {628 pub mutable: bool,629 pub collection_admin: bool,630 pub token_owner: bool,631}632633impl PropertyPermission {634 pub fn none() -> Self {635 Self {636 mutable: true,637 collection_admin: false,638 token_owner: false,639 }640 }641}642643#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]644#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]645pub struct Property {646 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]647 pub key: PropertyKey,648649 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]650 pub value: PropertyValue,651}652653impl Into<(PropertyKey, PropertyValue)> for Property {654 fn into(self) -> (PropertyKey, PropertyValue) {655 (self.key, self.value)656 }657}658659#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]660#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]661pub struct PropertyKeyPermission {662 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]663 pub key: PropertyKey,664665 pub permission: PropertyPermission,666}667668impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {669 fn into(self) -> (PropertyKey, PropertyPermission) {670 (self.key, self.permission)671 }672}673674#[derive(Debug)]675pub enum PropertiesError {676 NoSpaceForProperty,677 PropertyLimitReached,678 InvalidCharacterInPropertyKey,679 PropertyKeyIsTooLong,680 EmptyPropertyKey,681}682683#[derive(Clone, Copy)]684pub enum PropertyScope {685 None,686 Rmrk,687}688689impl PropertyScope {690 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {691 let scope_str: &[u8] = match self {692 Self::None => return Ok(key),693 Self::Rmrk => b"rmrk",694 };695696 [scope_str, b":", key.as_slice()]697 .concat()698 .try_into()699 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)700 }701}702703pub trait TrySetProperty: Sized {704 type Value;705706 fn try_scoped_set(707 &mut self,708 scope: PropertyScope,709 key: PropertyKey,710 value: Self::Value,711 ) -> Result<(), PropertiesError>;712713 fn try_scoped_set_from_iter<I, KV>(714 &mut self,715 scope: PropertyScope,716 iter: I,717 ) -> Result<(), PropertiesError>718 where719 I: Iterator<Item = KV>,720 KV: Into<(PropertyKey, Self::Value)>,721 {722 for kv in iter {723 let (key, value) = kv.into();724 self.try_scoped_set(scope, key, value)?;725 }726727 Ok(())728 }729730 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {731 self.try_scoped_set(PropertyScope::None, key, value)732 }733734 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>735 where736 I: Iterator<Item = KV>,737 KV: Into<(PropertyKey, Self::Value)>,738 {739 self.try_scoped_set_from_iter(PropertyScope::None, iter)740 }741}742743#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]744#[derivative(Default(bound = ""))]745pub struct PropertiesMap<Value>(746 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,747);748749impl<Value> PropertiesMap<Value> {750 pub fn new() -> Self {751 Self(BoundedBTreeMap::new())752 }753754 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {755 Self::check_property_key(key)?;756757 Ok(self.0.remove(key))758 }759760 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {761 self.0.get(key)762 }763764 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {765 if key.is_empty() {766 return Err(PropertiesError::EmptyPropertyKey);767 }768769 for byte in key.as_slice().iter() {770 let byte = *byte;771772 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {773 return Err(PropertiesError::InvalidCharacterInPropertyKey);774 }775 }776777 Ok(())778 }779}780781impl<Value> IntoIterator for PropertiesMap<Value> {782 type Item = (PropertyKey, Value);783 type IntoIter = <784 BoundedBTreeMap<785 PropertyKey,786 Value,787 ConstU32<MAX_PROPERTIES_PER_ITEM>788 > as IntoIterator789 >::IntoIter;790791 fn into_iter(self) -> Self::IntoIter {792 self.0.into_iter()793 }794}795796impl<Value> TrySetProperty for PropertiesMap<Value> {797 type Value = Value;798799 fn try_scoped_set(800 &mut self,801 scope: PropertyScope,802 key: PropertyKey,803 value: Self::Value,804 ) -> Result<(), PropertiesError> {805 Self::check_property_key(&key)?;806807 let key = scope.apply(key)?;808 self.0809 .try_insert(key, value)810 .map_err(|_| PropertiesError::PropertyLimitReached)?;811812 Ok(())813 }814}815816pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;817818#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]819pub struct Properties {820 map: PropertiesMap<PropertyValue>,821 consumed_space: u32,822 space_limit: u32,823}824825impl Properties {826 pub fn new(space_limit: u32) -> Self {827 Self {828 map: PropertiesMap::new(),829 consumed_space: 0,830 space_limit,831 }832 }833834 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {835 let value = self.map.remove(key)?;836837 if let Some(ref value) = value {838 let value_len = value.len() as u32;839 self.consumed_space -= value_len;840 }841842 Ok(value)843 }844845 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {846 self.map.get(key)847 }848}849850impl IntoIterator for Properties {851 type Item = (PropertyKey, PropertyValue);852 type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;853854 fn into_iter(self) -> Self::IntoIter {855 self.map.into_iter()856 }857}858859impl TrySetProperty for Properties {860 type Value = PropertyValue;861862 fn try_scoped_set(863 &mut self,864 scope: PropertyScope,865 key: PropertyKey,866 value: Self::Value,867 ) -> Result<(), PropertiesError> {868 let value_len = value.len();869870 if self.consumed_space as usize + value_len > self.space_limit as usize871 && !cfg!(feature = "runtime-benchmarks")872 {873 return Err(PropertiesError::NoSpaceForProperty);874 }875876 self.map.try_scoped_set(scope, key, value)?;877878 self.consumed_space += value_len as u32;879880 Ok(())881 }882}883884pub struct CollectionProperties;885886impl Get<Properties> for CollectionProperties {887 fn get() -> Properties {888 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)889 }890}891892pub struct TokenProperties;893894impl Get<Properties> for TokenProperties {895 fn get() -> Properties {896 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)897 }898}899900// RMRK901// todo document?902parameter_types! {903 #[derive(PartialEq, TypeInfo)]904 pub const RmrkStringLimit: u32 = 128;905 #[derive(PartialEq)]906 pub const RmrkCollectionSymbolLimit: u32 = 100;907 #[derive(PartialEq)]908 pub const RmrkResourceSymbolLimit: u32 = 10;909 #[derive(PartialEq)]910 pub const RmrkKeyLimit: u32 = 32;911 #[derive(PartialEq)]912 pub const RmrkValueLimit: u32 = 256;913 #[derive(PartialEq)]914 pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;915 #[derive(PartialEq)]916 pub const RmrkPartsLimit: u32 = 3;917}918919impl From<RmrkCollectionId> for CollectionId {920 fn from(id: RmrkCollectionId) -> Self {921 Self(id)922 }923}924925impl From<RmrkNftId> for TokenId {926 fn from(id: RmrkNftId) -> Self {927 Self(id)928 }929}930931pub type RmrkCollectionInfo<AccountId> =932 CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;933pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;934pub type RmrkResourceInfo = ResourceInfo<935 RmrkBoundedResource,936 RmrkString,937 RmrkBoundedParts,938>;939pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;940pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;941pub type RmrkPartType =942 PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;943pub type RmrkThemeProperty = ThemeProperty<RmrkString>;944pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;945946pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;947pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;948pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;949950type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;951type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>;952953pub type RmrkRpcString = Vec<u8>;954pub type RmrkThemeName = RmrkRpcString;955pub type RmrkPropertyKey = RmrkRpcString;956957pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;tests/src/eth/api/Collection.soldiffbeforeafterboth--- a/tests/src/eth/api/Collection.sol
+++ /dev/null
@@ -1,28 +0,0 @@
-// SPDX-License-Identifier: OTHER
-// This code is automatically generated
-
-pragma solidity >=0.8.0 <0.9.0;
-
-// Common stubs holder
-interface Dummy {
-
-}
-
-interface ERC165 is Dummy {
- function supportsInterface(bytes4 interfaceID) external view returns (bool);
-}
-
-// Selector: 15cc740e
-interface Collection is Dummy, ERC165 {
- // Selector: setSponsor(address) 59753fb1
- function setSponsor(address sponsor) external view;
-
- // Selector: confirmSponsorship() c8c6a056
- function confirmSponsorship() external view;
-
- // Selector: setLimits(string) 72cb345d
- function setLimits(string memory limitsJson) external view;
-
- // Selector: contractAddress() f6b4dfb4
- function contractAddress() external view returns (address);
-}
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -42,36 +42,6 @@
event MintingFinished();
}
-// Selector: 38e33c60
-interface Collection is Dummy, ERC165 {
- // Selector: setCollectionProperty(string,bytes) 2f073f66
- function setCollectionProperty(string memory key, bytes memory value)
- external;
-
- // Selector: deleteCollectionProperty(string) 7b7debce
- function deleteCollectionProperty(string memory key) external;
-
- // Throws error if key not found
- //
- // Selector: collectionProperty(string) cf24fd6d
- function collectionProperty(string memory key)
- external
- view
- returns (bytes memory);
-
- // Selector: ethSetSponsor(address) 8f9af356
- function ethSetSponsor(address sponsor) external;
-
- // Selector: ethConfirmSponsorship() a8580d1a
- function ethConfirmSponsorship() external;
-
- // Selector: setLimits(string) 72cb345d
- function setLimits(string memory limitsJson) external view;
-
- // Selector: contractAddress() f6b4dfb4
- function contractAddress() external view returns (address);
-}
-
// Selector: 41369377
interface TokenProperties is Dummy, ERC165 {
// Selector: setTokenPropertyPermission(string,bool,bool,bool) 222d97fa
@@ -243,6 +213,36 @@
returns (bool);
}
+// Selector: f5652829
+interface Collection is Dummy, ERC165 {
+ // Selector: setCollectionProperty(string,bytes) 2f073f66
+ function setCollectionProperty(string memory key, bytes memory value)
+ external;
+
+ // Selector: deleteCollectionProperty(string) 7b7debce
+ function deleteCollectionProperty(string memory key) external;
+
+ // Throws error if key not found
+ //
+ // Selector: collectionProperty(string) cf24fd6d
+ function collectionProperty(string memory key)
+ external
+ view
+ returns (bytes memory);
+
+ // Selector: ethSetSponsor(address) 8f9af356
+ function ethSetSponsor(address sponsor) external;
+
+ // Selector: ethConfirmSponsorship() a8580d1a
+ function ethConfirmSponsorship() external;
+
+ // Selector: setLimit(string,string) bf4d2014
+ function setLimit(string memory limit, string memory value) external;
+
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() external view returns (address);
+}
+
interface UniqueNFT is
Dummy,
ERC165,
tests/src/eth/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createCollection.test.ts
+++ b/tests/src/eth/createCollection.test.ts
@@ -108,7 +108,7 @@
const limits = {
accountTokenOwnershipLimit: 1000,
sponsoredDataSize: 1024,
- sponsoredDataRateLimit: {Blocks: 30},
+ sponsoredDataRateLimit: 30,
tokenLimit: 1000000,
sponsorTransferTimeout: 6,
sponsorApproveTimeout: 6,
@@ -117,14 +117,21 @@
transfersEnabled: false,
};
- const limitsJson = JSON.stringify(limits, null, 1);
const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
- await collectionEvm.methods.setLimits(limitsJson).send();
+ await collectionEvm.methods.setLimit('accountTokenOwnershipLimit', limits.accountTokenOwnershipLimit.toString()).send();
+ await collectionEvm.methods.setLimit('sponsoredDataSize', limits.sponsoredDataSize.toString()).send();
+ await collectionEvm.methods.setLimit('sponsoredDataRateLimit', limits.sponsoredDataRateLimit.toString()).send();
+ await collectionEvm.methods.setLimit('tokenLimit', limits.tokenLimit.toString()).send();
+ await collectionEvm.methods.setLimit('sponsorTransferTimeout', limits.sponsorTransferTimeout.toString()).send();
+ await collectionEvm.methods.setLimit('sponsorApproveTimeout', limits.sponsorApproveTimeout.toString()).send();
+ await collectionEvm.methods.setLimit('ownerCanTransfer', limits.ownerCanTransfer.toString()).send();
+ await collectionEvm.methods.setLimit('ownerCanDestroy', limits.ownerCanDestroy.toString()).send();
+ await collectionEvm.methods.setLimit('transfersEnabled', limits.transfersEnabled.toString()).send();
const collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
expect(collectionSub.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);
expect(collectionSub.limits.sponsoredDataSize.unwrap().toNumber()).to.be.eq(limits.sponsoredDataSize);
- expect(collectionSub.limits.sponsoredDataRateLimit.unwrap().asBlocks.toNumber()).to.be.eq(limits.sponsoredDataRateLimit.Blocks);
+ expect(collectionSub.limits.sponsoredDataRateLimit.unwrap().asBlocks.toNumber()).to.be.eq(limits.sponsoredDataRateLimit);
expect(collectionSub.limits.tokenLimit.unwrap().toNumber()).to.be.eq(limits.tokenLimit);
expect(collectionSub.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorTransferTimeout);
expect(collectionSub.limits.sponsorApproveTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorApproveTimeout);
@@ -171,6 +178,21 @@
// const tokenUri = await contract.methods.tokenURI(nextTokenId).call();
// expect(tokenUri).to.be.equal(`https://offchain-service.local/token-info/${nextTokenId}`);
});
+
+ itWeb3('Collection address exist', async ({api, web3}) => {
+ const owner = await createEthAccountWithBalance(api, web3);
+ const collectionAddressForNonexistentCollection = '0x17C4E6453CC49AAAAEACA894E6D9683E00112233';
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ expect(await collectionHelper.methods
+ .isCollectionExist(collectionAddressForNonexistentCollection).call())
+ .to.be.false;
+
+ const result = await collectionHelper.methods.create721Collection('Const collection', '5', '5').send();
+ const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+ expect(await collectionHelper.methods
+ .isCollectionExist(collectionIdAddress).call())
+ .to.be.true;
+ });
});
describe('(!negative tests!) Create collection from EVM', () => {
@@ -218,30 +240,6 @@
await expect(helper.methods
.create721Collection(collectionName, description, tokenPrefix)
.call()).to.be.rejectedWith('NotSufficientFounds');
- });
-
- itWeb3('(!negative test!) Collection address (Create collection handle error)', async ({api, web3}) => {
- const owner = await createEthAccountWithBalance(api, web3);
- const collectionAddressForNonexistentCollection = '0x17C4E6453CC49AAAAEACA894E6D9683E00112233';
- const collectionEvm = evmCollection(web3, owner, collectionAddressForNonexistentCollection);
- const EXPECTED_ERROR = 'Create collection handle error';
- {
- const sponsor = await createEthAccountWithBalance(api, web3);
- await expect(collectionEvm.methods
- .setSponsor(sponsor)
- .call()).to.be.rejectedWith(EXPECTED_ERROR);
-
- const sponsorCollection = evmCollection(web3, sponsor, collectionAddressForNonexistentCollection);
- await expect(sponsorCollection.methods
- .confirmSponsorship()
- .call()).to.be.rejectedWith(EXPECTED_ERROR);
- }
- {
- const limits = '{"account_token_ownership_limit":1000}';
- await expect(collectionEvm.methods
- .setLimits(limits)
- .call()).to.be.rejectedWith(EXPECTED_ERROR);
- }
});
itWeb3('(!negative test!) Check owner', async ({api, web3}) => {
@@ -255,18 +253,17 @@
{
const sponsor = await createEthAccountWithBalance(api, web3);
await expect(contractEvmFromNotOwner.methods
- .setSponsor(sponsor)
+ .ethSetSponsor(sponsor)
.call()).to.be.rejectedWith(EXPECTED_ERROR);
const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
await expect(sponsorCollection.methods
- .confirmSponsorship()
+ .ethConfirmSponsorship()
.call()).to.be.rejectedWith('Caller is not set as sponsor');
}
{
- const limits = '{"account_token_ownership_limit":1000}';
await expect(contractEvmFromNotOwner.methods
- .setLimits(limits)
+ .setLimit('account_token_ownership_limit', '1000')
.call()).to.be.rejectedWith(EXPECTED_ERROR);
}
});
@@ -277,9 +274,14 @@
const result = await collectionHelper.methods.create721Collection('Schema collection', 'A', 'A').send();
const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
- const badJson = '{accountTokenOwnershipLimit: 1000}';
await expect(collectionEvm.methods
- .setLimits(badJson)
- .call()).to.be.rejectedWith('Parse JSON error:');
+ .setLimit('badLimit', 'true')
+ .call()).to.be.rejectedWith('Unknown limit "badLimit"');
+ await expect(collectionEvm.methods
+ .setLimit('sponsoredDataSize', 'badValue')
+ .call()).to.be.rejectedWith('Int value "badValue" parse error:');
+ await expect(collectionEvm.methods
+ .setLimit('ownerCanTransfer', 'badValue')
+ .call()).to.be.rejectedWith('Bool value "badValue" parse error:');
});
});
\ No newline at end of file
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -325,11 +325,12 @@
},
{
"inputs": [
- { "internalType": "string", "name": "limitsJson", "type": "string" }
+ { "internalType": "string", "name": "limit", "type": "string" },
+ { "internalType": "string", "name": "value", "type": "string" }
],
- "name": "setLimits",
+ "name": "setLimit",
"outputs": [],
- "stateMutability": "view",
+ "stateMutability": "nonpayable",
"type": "function"
},
{