difftreelog
Merge pull request #647 from UniqueNetwork/feature/supports-interface-for-erc721-metadata
in: master
57 files changed
.maintain/scripts/generate_sol.shdiffbeforeafterboth--- a/.maintain/scripts/generate_sol.sh
+++ b/.maintain/scripts/generate_sol.sh
@@ -11,4 +11,6 @@
formatted=$(mktemp)
prettier --config $PRETTIER_CONFIG $raw > $formatted
+sed -i -E -e "s/.+\/\/ FORMATTING: FORCE NEWLINE//g" $formatted
+
mv $formatted $OUTPUT
crates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth--- a/crates/evm-coder/procedural/src/solidity_interface.rs
+++ b/crates/evm-coder/procedural/src/solidity_interface.rs
@@ -291,22 +291,40 @@
struct MethodInfo {
rename_selector: Option<String>,
+ hide: bool,
}
impl Parse for MethodInfo {
fn parse(input: ParseStream) -> syn::Result<Self> {
let mut rename_selector = None;
- let lookahead = input.lookahead1();
- if lookahead.peek(kw::rename_selector) {
- let k = input.parse::<kw::rename_selector>()?;
- input.parse::<Token![=]>()?;
- if rename_selector
- .replace(input.parse::<LitStr>()?.value())
- .is_some()
- {
- return Err(syn::Error::new(k.span(), "rename_selector is already set"));
+ let mut hide = false;
+ while !input.is_empty() {
+ let lookahead = input.lookahead1();
+ if lookahead.peek(kw::rename_selector) {
+ let k = input.parse::<kw::rename_selector>()?;
+ input.parse::<Token![=]>()?;
+ if rename_selector
+ .replace(input.parse::<LitStr>()?.value())
+ .is_some()
+ {
+ return Err(syn::Error::new(k.span(), "rename_selector is already set"));
+ }
+ } else if lookahead.peek(kw::hide) {
+ input.parse::<kw::hide>()?;
+ hide = true;
+ } else {
+ return Err(lookahead.error());
+ }
+
+ if input.peek(Token![,]) {
+ input.parse::<Token![,]>()?;
+ } else if !input.is_empty() {
+ return Err(syn::Error::new(input.span(), "expected end"));
}
}
- Ok(Self { rename_selector })
+ Ok(Self {
+ rename_selector,
+ hide,
+ })
}
}
@@ -548,6 +566,7 @@
syn::custom_keyword!(expect_selector);
syn::custom_keyword!(rename_selector);
+ syn::custom_keyword!(hide);
}
/// Rust methods are parsed into this structure when Solidity code is generated
@@ -558,6 +577,7 @@
screaming_name: Ident,
selector_str: String,
selector: u32,
+ hide: bool,
args: Vec<MethodArg>,
has_normal_args: bool,
has_value_args: bool,
@@ -570,6 +590,7 @@
fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {
let mut info = MethodInfo {
rename_selector: None,
+ hide: false,
};
let mut docs = Vec::new();
let mut weight = None;
@@ -667,6 +688,7 @@
screaming_name: snake_ident_to_screaming(ident),
selector_str,
selector,
+ hide: info.hide,
args,
has_normal_args,
has_value_args,
@@ -826,12 +848,14 @@
let docs = &self.docs;
let selector_str = &self.selector_str;
let selector = self.selector;
+ let hide = self.hide;
let is_payable = self.has_value_args;
quote! {
SolidityFunction {
docs: &[#(#docs),*],
selector_str: #selector_str,
selector: #selector,
+ hide: #hide,
name: #camel_name,
mutability: #mutability,
is_payable: #is_payable,
crates/evm-coder/src/solidity.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -225,7 +225,7 @@
pub trait SolidityArguments {
fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;
- fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result;
+ fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result;
fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;
fn is_empty(&self) -> bool {
self.len() == 0
@@ -248,7 +248,7 @@
Ok(())
}
}
- fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {
+ fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {
Ok(())
}
fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
@@ -283,8 +283,8 @@
Ok(())
}
}
- fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {
- writeln!(writer, "\t\t{};", self.0)
+ fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {
+ writeln!(writer, "\t{prefix}\t{};", self.0)
}
fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
T::solidity_default(writer, tc)
@@ -318,8 +318,8 @@
Ok(())
}
}
- fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {
- writeln!(writer, "\t\t{};", self.1)
+ fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {
+ writeln!(writer, "\t{prefix}\t{};", self.1)
}
fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
T::solidity_default(writer, tc)
@@ -337,7 +337,7 @@
fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {
Ok(())
}
- fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {
+ fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {
Ok(())
}
fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {
@@ -365,9 +365,9 @@
)* );
Ok(())
}
- fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {
+ fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {
for_tuples!( #(
- Tuple.solidity_get(writer)?;
+ Tuple.solidity_get(prefix, writer)?;
)* );
Ok(())
}
@@ -418,6 +418,7 @@
pub docs: &'static [&'static str],
pub selector_str: &'static str,
pub selector: u32,
+ pub hide: bool,
pub name: &'static str,
pub args: A,
pub result: R,
@@ -431,16 +432,21 @@
writer: &mut impl fmt::Write,
tc: &TypeCollector,
) -> fmt::Result {
+ let hide_comment = self.hide.then(|| "// ").unwrap_or("");
for doc in self.docs {
- writeln!(writer, "\t///{}", doc)?;
+ writeln!(writer, "\t{hide_comment}///{}", doc)?;
}
writeln!(
writer,
- "\t/// @dev EVM selector for this function is: 0x{:0>8x},",
+ "\t{hide_comment}/// @dev EVM selector for this function is: 0x{:0>8x},",
self.selector
)?;
- writeln!(writer, "\t/// or in textual repr: {}", self.selector_str)?;
- write!(writer, "\tfunction {}(", self.name)?;
+ writeln!(
+ writer,
+ "\t{hide_comment}/// or in textual repr: {}",
+ self.selector_str
+ )?;
+ write!(writer, "\t{hide_comment}function {}(", self.name)?;
self.args.solidity_name(writer, tc)?;
write!(writer, ")")?;
if is_impl {
@@ -463,22 +469,25 @@
}
if is_impl {
writeln!(writer, " {{")?;
- writeln!(writer, "\t\trequire(false, stub_error);")?;
- self.args.solidity_get(writer)?;
+ writeln!(writer, "\t{hide_comment}\trequire(false, stub_error);")?;
+ self.args.solidity_get(hide_comment, writer)?;
match &self.mutability {
SolidityMutability::Pure => {}
- SolidityMutability::View => writeln!(writer, "\t\tdummy;")?,
- SolidityMutability::Mutable => writeln!(writer, "\t\tdummy = 0;")?,
+ SolidityMutability::View => writeln!(writer, "\t{hide_comment}\tdummy;")?,
+ SolidityMutability::Mutable => writeln!(writer, "\t{hide_comment}\tdummy = 0;")?,
}
if !self.result.is_empty() {
- write!(writer, "\t\treturn ")?;
+ write!(writer, "\t{hide_comment}\treturn ")?;
self.result.solidity_default(writer, tc)?;
writeln!(writer, ";")?;
}
- writeln!(writer, "\t}}")?;
+ writeln!(writer, "\t{hide_comment}}}")?;
} else {
writeln!(writer, ";")?;
}
+ if self.hide {
+ writeln!(writer, "// FORMATTING: FORCE NEWLINE")?;
+ }
Ok(())
}
}
pallets/common/src/dispatch.rsdiffbeforeafterboth--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -9,7 +9,7 @@
traits::Get,
};
use sp_runtime::DispatchError;
-use up_data_structs::{CollectionId, CreateCollectionData};
+use up_data_structs::{CollectionId, CreateCollectionData, CollectionFlags};
use crate::{pallet::Config, CommonCollectionOperations, CollectionHandle};
@@ -80,6 +80,7 @@
sender: T::CrossAccountId,
payer: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
+ flags: CollectionFlags,
) -> Result<CollectionId, DispatchError>;
/// Delete the collection.
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -592,6 +592,7 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
+ #[solidity(rename_selector = "changeCollectionOwner")]
fn set_owner(&mut self, caller: caller, new_owner: address) -> Result<void> {
self.consume_store_writes(1)?;
@@ -659,11 +660,6 @@
/// Keys.
pub mod key {
use super::*;
-
- /// Key "schemaName".
- pub fn schema_name() -> up_data_structs::PropertyKey {
- property_key_from_bytes(b"schemaName").expect(EXPECT_CONVERT_ERROR)
- }
/// Key "baseURI".
pub fn base_uri() -> up_data_structs::PropertyKey {
@@ -672,30 +668,17 @@
/// Key "url".
pub fn url() -> up_data_structs::PropertyKey {
- property_key_from_bytes(b"url").expect(EXPECT_CONVERT_ERROR)
+ property_key_from_bytes(b"URI").expect(EXPECT_CONVERT_ERROR)
}
/// Key "suffix".
pub fn suffix() -> up_data_structs::PropertyKey {
- property_key_from_bytes(b"suffix").expect(EXPECT_CONVERT_ERROR)
+ property_key_from_bytes(b"URISuffix").expect(EXPECT_CONVERT_ERROR)
}
/// Key "parentNft".
pub fn parent_nft() -> up_data_structs::PropertyKey {
property_key_from_bytes(b"parentNft").expect(EXPECT_CONVERT_ERROR)
- }
- }
-
- /// Values.
- pub mod value {
- use super::*;
-
- /// Value "ERC721Metadata".
- pub const ERC721_METADATA: &[u8] = b"ERC721Metadata";
-
- /// Value for [`ERC721_METADATA`].
- pub fn erc721() -> up_data_structs::PropertyValue {
- property_value_from_bytes(ERC721_METADATA).expect(EXPECT_CONVERT_ERROR)
}
}
pallets/common/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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63 ensure,64 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65 weights::Pays,66 transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70 COLLECTION_NUMBER_LIMIT,71 Collection,72 RpcCollection,73 CollectionFlags,74 CollectionId,75 CreateItemData,76 MAX_TOKEN_PREFIX_LENGTH,77 COLLECTION_ADMINS_LIMIT,78 TokenId,79 TokenChild,80 CollectionStats,81 MAX_TOKEN_OWNERSHIP,82 CollectionMode,83 NFT_SPONSOR_TRANSFER_TIMEOUT,84 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,85 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86 MAX_SPONSOR_TIMEOUT,87 CUSTOM_DATA_LIMIT,88 CollectionLimits,89 CreateCollectionData,90 SponsorshipState,91 CreateItemExData,92 SponsoringRateLimit,93 budget::Budget,94 PhantomType,95 Property,96 Properties,97 PropertiesPermissionMap,98 PropertyKey,99 PropertyValue,100 PropertyPermission,101 PropertiesError,102 PropertyKeyPermission,103 TokenData,104 TrySetProperty,105 PropertyScope,106 // RMRK107 RmrkCollectionInfo,108 RmrkInstanceInfo,109 RmrkResourceInfo,110 RmrkPropertyInfo,111 RmrkBaseInfo,112 RmrkPartType,113 RmrkBoundedTheme,114 RmrkNftChild,115 CollectionPermissions,116};117118pub use pallet::*;119use sp_core::H160;120use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};121#[cfg(feature = "runtime-benchmarks")]122pub mod benchmarking;123pub mod dispatch;124pub mod erc;125pub mod eth;126pub mod weights;127128/// Weight info.129pub type SelfWeightOf<T> = <T as Config>::WeightInfo;130131/// Collection handle contains information about collection data and id.132/// Also provides functionality to count consumed gas.133///134/// CollectionHandle is used as a generic wrapper for collections of all types.135/// It allows to perform common operations and queries on any collection type,136/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].137#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]138pub struct CollectionHandle<T: Config> {139 /// Collection id140 pub id: CollectionId,141 collection: Collection<T::AccountId>,142 /// Substrate recorder for counting consumed gas143 pub recorder: SubstrateRecorder<T>,144}145146impl<T: Config> WithRecorder<T> for CollectionHandle<T> {147 fn recorder(&self) -> &SubstrateRecorder<T> {148 &self.recorder149 }150 fn into_recorder(self) -> SubstrateRecorder<T> {151 self.recorder152 }153}154155impl<T: Config> CollectionHandle<T> {156 /// Same as [CollectionHandle::new] but with an explicit gas limit.157 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {158 <CollectionById<T>>::get(id).map(|collection| Self {159 id,160 collection,161 recorder: SubstrateRecorder::new(gas_limit),162 })163 }164165 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].166 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {167 <CollectionById<T>>::get(id).map(|collection| Self {168 id,169 collection,170 recorder,171 })172 }173174 /// Retrives collection data from storage and creates collection handle with default parameters.175 /// If collection not found return `None`176 pub fn new(id: CollectionId) -> Option<Self> {177 Self::new_with_gas_limit(id, u64::MAX)178 }179180 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.181 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {182 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)183 }184185 /// Consume gas for reading.186 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {187 self.recorder188 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(189 <T as frame_system::Config>::DbWeight::get()190 .read191 .saturating_mul(reads),192 )))193 }194195 /// Consume gas for writing.196 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {197 self.recorder198 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(199 <T as frame_system::Config>::DbWeight::get()200 .write201 .saturating_mul(writes),202 )))203 }204205 /// Consume gas for reading and writing.206 pub fn consume_store_reads_and_writes(207 &self,208 reads: u64,209 writes: u64,210 ) -> evm_coder::execution::Result<()> {211 let weight = <T as frame_system::Config>::DbWeight::get();212 let reads = weight.read.saturating_mul(reads);213 let writes = weight.read.saturating_mul(writes);214 self.recorder215 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(216 reads.saturating_add(writes),217 )))218 }219220 /// Save collection to storage.221 pub fn save(&self) -> DispatchResult {222 <CollectionById<T>>::insert(self.id, &self.collection);223 Ok(())224 }225226 /// Set collection sponsor.227 ///228 /// Unique collections allows sponsoring for certain actions.229 /// This method allows you to set the sponsor of the collection.230 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].231 pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {232 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);233 Ok(())234 }235236 /// Confirm sponsorship237 ///238 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.239 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].240 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {241 if self.collection.sponsorship.pending_sponsor() != Some(sender) {242 return Ok(false);243 }244245 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());246 Ok(true)247 }248249 /// Remove collection sponsor.250 pub fn remove_sponsor(&mut self) -> DispatchResult {251 self.collection.sponsorship = SponsorshipState::Disabled;252 Ok(())253 }254255 /// Checks that the collection was created with, and must be operated upon through **Unique API**.256 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.257 pub fn check_is_internal(&self) -> DispatchResult {258 if self.flags.external {259 return Err(<Error<T>>::CollectionIsExternal)?;260 }261262 Ok(())263 }264265 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.266 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.267 pub fn check_is_external(&self) -> DispatchResult {268 if !self.flags.external {269 return Err(<Error<T>>::CollectionIsInternal)?;270 }271272 Ok(())273 }274}275276impl<T: Config> Deref for CollectionHandle<T> {277 type Target = Collection<T::AccountId>;278279 fn deref(&self) -> &Self::Target {280 &self.collection281 }282}283284impl<T: Config> DerefMut for CollectionHandle<T> {285 fn deref_mut(&mut self) -> &mut Self::Target {286 &mut self.collection287 }288}289290impl<T: Config> CollectionHandle<T> {291 /// Checks if the `user` is the owner of the collection.292 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {293 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);294 Ok(())295 }296297 /// Returns **true** if the `user` is the owner or administrator of the collection.298 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {299 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))300 }301302 /// Checks if the `user` is the owner or administrator of the collection.303 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {304 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);305 Ok(())306 }307308 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.309 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {310 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)311 }312313 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.314 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {315 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)316 }317318 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.319 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {320 ensure!(321 <Allowlist<T>>::get((self.id, user)),322 <Error<T>>::AddressNotInAllowlist323 );324 Ok(())325 }326327 /// Changes collection owner to another account328 /// #### Store read/writes329 /// 1 writes330 fn set_owner_internal(331 &mut self,332 caller: T::CrossAccountId,333 new_owner: T::CrossAccountId,334 ) -> DispatchResult {335 self.check_is_owner(&caller)?;336 self.collection.owner = new_owner.as_sub().clone();337 self.save()338 }339}340341#[frame_support::pallet]342pub mod pallet {343 use super::*;344 use pallet_evm::account;345 use dispatch::CollectionDispatch;346 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};347 use frame_system::pallet_prelude::*;348 use frame_support::traits::Currency;349 use up_data_structs::{TokenId, mapping::TokenAddressMapping};350 use scale_info::TypeInfo;351 use weights::WeightInfo;352353 #[pallet::config]354 pub trait Config:355 frame_system::Config356 + pallet_evm_coder_substrate::Config357 + pallet_evm::Config358 + TypeInfo359 + account::Config360 {361 /// Weight information for functions of this pallet.362 type WeightInfo: WeightInfo;363364 /// Events compatible with [`frame_system::Config::Event`].365 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;366367 /// Handler of accounts and payment.368 type Currency: Currency<Self::AccountId>;369370 /// Set price to create a collection.371 #[pallet::constant]372 type CollectionCreationPrice: Get<373 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,374 >;375376 /// Dispatcher of operations on collections.377 type CollectionDispatch: CollectionDispatch<Self>;378379 /// Account which holds the chain's treasury.380 type TreasuryAccountId: Get<Self::AccountId>;381382 /// Address under which the CollectionHelper contract would be available.383 type ContractAddress: Get<H160>;384385 /// Mapper for token addresses to Ethereum addresses.386 type EvmTokenAddressMapping: TokenAddressMapping<H160>;387388 /// Mapper for token addresses to [`CrossAccountId`].389 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;390 }391392 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);393394 #[pallet::pallet]395 #[pallet::storage_version(STORAGE_VERSION)]396 #[pallet::generate_store(pub(super) trait Store)]397 pub struct Pallet<T>(_);398399 #[pallet::extra_constants]400 impl<T: Config> Pallet<T> {401 /// Maximum admins per collection.402 pub fn collection_admins_limit() -> u32 {403 COLLECTION_ADMINS_LIMIT404 }405 }406407 #[pallet::event]408 #[pallet::generate_deposit(pub fn deposit_event)]409 pub enum Event<T: Config> {410 /// New collection was created411 CollectionCreated(412 /// Globally unique identifier of newly created collection.413 CollectionId,414 /// [`CollectionMode`] converted into _u8_.415 u8,416 /// Collection owner.417 T::AccountId,418 ),419420 /// New collection was destroyed421 CollectionDestroyed(422 /// Globally unique identifier of collection.423 CollectionId,424 ),425426 /// New item was created.427 ItemCreated(428 /// Id of the collection where item was created.429 CollectionId,430 /// Id of an item. Unique within the collection.431 TokenId,432 /// Owner of newly created item433 T::CrossAccountId,434 /// Always 1 for NFT435 u128,436 ),437438 /// Collection item was burned.439 ItemDestroyed(440 /// Id of the collection where item was destroyed.441 CollectionId,442 /// Identifier of burned NFT.443 TokenId,444 /// Which user has destroyed its tokens.445 T::CrossAccountId,446 /// Amount of token pieces destroed. Always 1 for NFT.447 u128,448 ),449450 /// Item was transferred451 Transfer(452 /// Id of collection to which item is belong.453 CollectionId,454 /// Id of an item.455 TokenId,456 /// Original owner of item.457 T::CrossAccountId,458 /// New owner of item.459 T::CrossAccountId,460 /// Amount of token pieces transfered. Always 1 for NFT.461 u128,462 ),463464 /// Amount pieces of token owned by `sender` was approved for `spender`.465 Approved(466 /// Id of collection to which item is belong.467 CollectionId,468 /// Id of an item.469 TokenId,470 /// Original owner of item.471 T::CrossAccountId,472 /// Id for which the approval was granted.473 T::CrossAccountId,474 /// Amount of token pieces transfered. Always 1 for NFT.475 u128,476 ),477478 /// The colletion property has been added or edited.479 CollectionPropertySet(480 /// Id of collection to which property has been set.481 CollectionId,482 /// The property that was set.483 PropertyKey,484 ),485486 /// The property has been deleted.487 CollectionPropertyDeleted(488 /// Id of collection to which property has been deleted.489 CollectionId,490 /// The property that was deleted.491 PropertyKey,492 ),493494 /// The token property has been added or edited.495 TokenPropertySet(496 /// Identifier of the collection whose token has the property set.497 CollectionId,498 /// The token for which the property was set.499 TokenId,500 /// The property that was set.501 PropertyKey,502 ),503504 /// The token property has been deleted.505 TokenPropertyDeleted(506 /// Identifier of the collection whose token has the property deleted.507 CollectionId,508 /// The token for which the property was deleted.509 TokenId,510 /// The property that was deleted.511 PropertyKey,512 ),513514 /// The token property permission of a collection has been set.515 PropertyPermissionSet(516 /// ID of collection to which property permission has been set.517 CollectionId,518 /// The property permission that was set.519 PropertyKey,520 ),521 }522523 #[pallet::error]524 pub enum Error<T> {525 /// This collection does not exist.526 CollectionNotFound,527 /// Sender parameter and item owner must be equal.528 MustBeTokenOwner,529 /// No permission to perform action530 NoPermission,531 /// Destroying only empty collections is allowed532 CantDestroyNotEmptyCollection,533 /// Collection is not in mint mode.534 PublicMintingNotAllowed,535 /// Address is not in allow list.536 AddressNotInAllowlist,537538 /// Collection name can not be longer than 63 char.539 CollectionNameLimitExceeded,540 /// Collection description can not be longer than 255 char.541 CollectionDescriptionLimitExceeded,542 /// Token prefix can not be longer than 15 char.543 CollectionTokenPrefixLimitExceeded,544 /// Total collections bound exceeded.545 TotalCollectionsLimitExceeded,546 /// Exceeded max admin count547 CollectionAdminCountExceeded,548 /// Collection limit bounds per collection exceeded549 CollectionLimitBoundsExceeded,550 /// Tried to enable permissions which are only permitted to be disabled551 OwnerPermissionsCantBeReverted,552 /// Collection settings not allowing items transferring553 TransferNotAllowed,554 /// Account token limit exceeded per collection555 AccountTokenLimitExceeded,556 /// Collection token limit exceeded557 CollectionTokenLimitExceeded,558 /// Metadata flag frozen559 MetadataFlagFrozen,560561 /// Item does not exist562 TokenNotFound,563 /// Item is balance not enough564 TokenValueTooLow,565 /// Requested value is more than the approved566 ApprovedValueTooLow,567 /// Tried to approve more than owned568 CantApproveMoreThanOwned,569570 /// Can't transfer tokens to ethereum zero address571 AddressIsZero,572573 /// The operation is not supported574 UnsupportedOperation,575576 /// Insufficient funds to perform an action577 NotSufficientFounds,578579 /// User does not satisfy the nesting rule580 UserIsNotAllowedToNest,581 /// Only tokens from specific collections may nest tokens under this one582 SourceCollectionIsNotAllowedToNest,583584 /// Tried to store more data than allowed in collection field585 CollectionFieldSizeExceeded,586587 /// Tried to store more property data than allowed588 NoSpaceForProperty,589590 /// Tried to store more property keys than allowed591 PropertyLimitReached,592593 /// Property key is too long594 PropertyKeyIsTooLong,595596 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed597 InvalidCharacterInPropertyKey,598599 /// Empty property keys are forbidden600 EmptyPropertyKey,601602 /// Tried to access an external collection with an internal API603 CollectionIsExternal,604605 /// Tried to access an internal collection with an external API606 CollectionIsInternal,607 }608609 /// Storage of the count of created collections. Essentially contains the last collection ID.610 #[pallet::storage]611 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;612613 /// Storage of the count of deleted collections.614 #[pallet::storage]615 pub type DestroyedCollectionCount<T> =616 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;617618 /// Storage of collection info.619 #[pallet::storage]620 pub type CollectionById<T> = StorageMap<621 Hasher = Blake2_128Concat,622 Key = CollectionId,623 Value = Collection<<T as frame_system::Config>::AccountId>,624 QueryKind = OptionQuery,625 >;626627 /// Storage of collection properties.628 #[pallet::storage]629 #[pallet::getter(fn collection_properties)]630 pub type CollectionProperties<T> = StorageMap<631 Hasher = Blake2_128Concat,632 Key = CollectionId,633 Value = Properties,634 QueryKind = ValueQuery,635 OnEmpty = up_data_structs::CollectionProperties,636 >;637638 /// Storage of token property permissions of a collection.639 #[pallet::storage]640 #[pallet::getter(fn property_permissions)]641 pub type CollectionPropertyPermissions<T> = StorageMap<642 Hasher = Blake2_128Concat,643 Key = CollectionId,644 Value = PropertiesPermissionMap,645 QueryKind = ValueQuery,646 >;647648 /// Storage of the amount of collection admins.649 #[pallet::storage]650 pub type AdminAmount<T> = StorageMap<651 Hasher = Blake2_128Concat,652 Key = CollectionId,653 Value = u32,654 QueryKind = ValueQuery,655 >;656657 /// List of collection admins.658 #[pallet::storage]659 pub type IsAdmin<T: Config> = StorageNMap<660 Key = (661 Key<Blake2_128Concat, CollectionId>,662 Key<Blake2_128Concat, T::CrossAccountId>,663 ),664 Value = bool,665 QueryKind = ValueQuery,666 >;667668 /// Allowlisted collection users.669 #[pallet::storage]670 pub type Allowlist<T: Config> = StorageNMap<671 Key = (672 Key<Blake2_128Concat, CollectionId>,673 Key<Blake2_128Concat, T::CrossAccountId>,674 ),675 Value = bool,676 QueryKind = ValueQuery,677 >;678679 /// Not used by code, exists only to provide some types to metadata.680 #[pallet::storage]681 pub type DummyStorageValue<T: Config> = StorageValue<682 Value = (683 CollectionStats,684 CollectionId,685 TokenId,686 TokenChild,687 PhantomType<(688 TokenData<T::CrossAccountId>,689 RpcCollection<T::AccountId>,690 // RMRK691 RmrkCollectionInfo<T::AccountId>,692 RmrkInstanceInfo<T::AccountId>,693 RmrkResourceInfo,694 RmrkPropertyInfo,695 RmrkBaseInfo<T::AccountId>,696 RmrkPartType,697 RmrkBoundedTheme,698 RmrkNftChild,699 )>,700 ),701 QueryKind = OptionQuery,702 >;703704 #[pallet::hooks]705 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {706 fn on_runtime_upgrade() -> Weight {707 StorageVersion::new(1).put::<Pallet<T>>();708709 Weight::zero()710 }711 }712}713714impl<T: Config> Pallet<T> {715 /// Enshure that receiver address is correct.716 ///717 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.718 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {719 ensure!(720 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,721 <Error<T>>::AddressIsZero722 );723 Ok(())724 }725726 /// Get a vector of collection admins.727 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {728 <IsAdmin<T>>::iter_prefix((collection,))729 .map(|(a, _)| a)730 .collect()731 }732733 /// Get a vector of users allowed to mint tokens.734 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {735 <Allowlist<T>>::iter_prefix((collection,))736 .map(|(a, _)| a)737 .collect()738 }739740 /// Is `user` allowed to mint token in `collection`.741 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {742 <Allowlist<T>>::get((collection, user))743 }744745 /// Get statistics of collections.746 pub fn collection_stats() -> CollectionStats {747 let created = <CreatedCollectionCount<T>>::get();748 let destroyed = <DestroyedCollectionCount<T>>::get();749 CollectionStats {750 created: created.0,751 destroyed: destroyed.0,752 alive: created.0 - destroyed.0,753 }754 }755756 /// Get the effective limits for the collection.757 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {758 let collection = <CollectionById<T>>::get(collection)?;759 let limits = collection.limits;760 let effective_limits = CollectionLimits {761 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),762 sponsored_data_size: Some(limits.sponsored_data_size()),763 sponsored_data_rate_limit: Some(764 limits765 .sponsored_data_rate_limit766 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),767 ),768 token_limit: Some(limits.token_limit()),769 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(770 match collection.mode {771 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,772 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,773 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,774 },775 )),776 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),777 owner_can_transfer: Some(limits.owner_can_transfer()),778 owner_can_destroy: Some(limits.owner_can_destroy()),779 transfers_enabled: Some(limits.transfers_enabled()),780 };781782 Some(effective_limits)783 }784785 /// Returns information about the `collection` adapted for rpc.786 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {787 let Collection {788 name,789 description,790 owner,791 mode,792 token_prefix,793 sponsorship,794 limits,795 permissions,796 flags,797 } = <CollectionById<T>>::get(collection)?;798799 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)800 .into_iter()801 .map(|(key, permission)| PropertyKeyPermission { key, permission })802 .collect();803804 let properties = <CollectionProperties<T>>::get(collection)805 .into_iter()806 .map(|(key, value)| Property { key, value })807 .collect();808809 let permissions = CollectionPermissions {810 access: Some(permissions.access()),811 mint_mode: Some(permissions.mint_mode()),812 nesting: Some(permissions.nesting().clone()),813 };814815 Some(RpcCollection {816 name: name.into_inner(),817 description: description.into_inner(),818 owner,819 mode,820 token_prefix: token_prefix.into_inner(),821 sponsorship,822 limits,823 permissions,824 token_property_permissions,825 properties,826 read_only: flags.external,827 foreign: flags.foreign,828 })829 }830}831832macro_rules! limit_default {833 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{834 $(835 if let Some($new) = $new.$field {836 let $old = $old.$field($($arg)?);837 let _ = $new;838 let _ = $old;839 $check840 } else {841 $new.$field = $old.$field842 }843 )*844 }};845}846macro_rules! limit_default_clone {847 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{848 $(849 if let Some($new) = $new.$field.clone() {850 let $old = $old.$field($($arg)?);851 let _ = $new;852 let _ = $old;853 $check854 } else {855 $new.$field = $old.$field.clone()856 }857 )*858 }};859}860861impl<T: Config> Pallet<T> {862 /// Create new collection.863 ///864 /// * `owner` - The owner of the collection.865 /// * `data` - Description of the created collection.866 /// * `flags` - Extra flags to store.867 pub fn init_collection(868 owner: T::CrossAccountId,869 payer: T::CrossAccountId,870 data: CreateCollectionData<T::AccountId>,871 flags: CollectionFlags,872 ) -> Result<CollectionId, DispatchError> {873 {874 ensure!(875 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,876 Error::<T>::CollectionTokenPrefixLimitExceeded877 );878 }879880 let created_count = <CreatedCollectionCount<T>>::get()881 .0882 .checked_add(1)883 .ok_or(ArithmeticError::Overflow)?;884 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;885 let id = CollectionId(created_count);886887 // bound Total number of collections888 ensure!(889 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,890 <Error<T>>::TotalCollectionsLimitExceeded891 );892893 // =========894895 let collection = Collection {896 owner: owner.as_sub().clone(),897 name: data.name,898 mode: data.mode.clone(),899 description: data.description,900 token_prefix: data.token_prefix,901 sponsorship: data902 .pending_sponsor903 .map(SponsorshipState::Unconfirmed)904 .unwrap_or_default(),905 limits: data906 .limits907 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))908 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,909 permissions: data910 .permissions911 .map(|permissions| {912 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)913 })914 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,915 flags,916 };917918 let mut collection_properties = up_data_structs::CollectionProperties::get();919 collection_properties920 .try_set_from_iter(data.properties.into_iter())921 .map_err(<Error<T>>::from)?;922923 CollectionProperties::<T>::insert(id, collection_properties);924925 let mut token_props_permissions = PropertiesPermissionMap::new();926 token_props_permissions927 .try_set_from_iter(data.token_property_permissions.into_iter())928 .map_err(<Error<T>>::from)?;929930 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);931932 // Take a (non-refundable) deposit of collection creation933 {934 let mut imbalance =935 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();936 imbalance.subsume(937 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(938 &T::TreasuryAccountId::get(),939 T::CollectionCreationPrice::get(),940 ),941 );942 <T as Config>::Currency::settle(943 payer.as_sub(),944 imbalance,945 WithdrawReasons::TRANSFER,946 ExistenceRequirement::KeepAlive,947 )948 .map_err(|_| Error::<T>::NotSufficientFounds)?;949 }950951 <CreatedCollectionCount<T>>::put(created_count);952 <Pallet<T>>::deposit_event(Event::CollectionCreated(953 id,954 data.mode.id(),955 owner.as_sub().clone(),956 ));957 <PalletEvm<T>>::deposit_log(958 erc::CollectionHelpersEvents::CollectionCreated {959 owner: *owner.as_eth(),960 collection_id: eth::collection_id_to_address(id),961 }962 .to_log(T::ContractAddress::get()),963 );964 <CollectionById<T>>::insert(id, collection);965 Ok(id)966 }967968 /// Destroy collection.969 ///970 /// * `collection` - Collection handler.971 /// * `sender` - The owner or administrator of the collection.972 pub fn destroy_collection(973 collection: CollectionHandle<T>,974 sender: &T::CrossAccountId,975 ) -> DispatchResult {976 ensure!(977 collection.limits.owner_can_destroy(),978 <Error<T>>::NoPermission,979 );980 collection.check_is_owner(sender)?;981982 let destroyed_collections = <DestroyedCollectionCount<T>>::get()983 .0984 .checked_add(1)985 .ok_or(ArithmeticError::Overflow)?;986987 // =========988989 <DestroyedCollectionCount<T>>::put(destroyed_collections);990 <CollectionById<T>>::remove(collection.id);991 <AdminAmount<T>>::remove(collection.id);992 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);993 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);994 <CollectionProperties<T>>::remove(collection.id);995996 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));997 Ok(())998 }9991000 /// Set collection property.1001 ///1002 /// * `collection` - Collection handler.1003 /// * `sender` - The owner or administrator of the collection.1004 /// * `property` - The property to set.1005 pub fn set_collection_property(1006 collection: &CollectionHandle<T>,1007 sender: &T::CrossAccountId,1008 property: Property,1009 ) -> DispatchResult {1010 collection.check_is_owner_or_admin(sender)?;10111012 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1013 let property = property.clone();1014 properties.try_set(property.key, property.value)1015 })1016 .map_err(<Error<T>>::from)?;10171018 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));10191020 Ok(())1021 }10221023 /// Set scouped collection property.1024 ///1025 /// * `collection_id` - ID of the collection for which the property is being set.1026 /// * `scope` - Property scope.1027 /// * `property` - The property to set.1028 pub fn set_scoped_collection_property(1029 collection_id: CollectionId,1030 scope: PropertyScope,1031 property: Property,1032 ) -> DispatchResult {1033 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1034 properties.try_scoped_set(scope, property.key, property.value)1035 })1036 .map_err(<Error<T>>::from)?;10371038 Ok(())1039 }10401041 /// Set scouped collection properties.1042 ///1043 /// * `collection_id` - ID of the collection for which the properties is being set.1044 /// * `scope` - Property scope.1045 /// * `properties` - The properties to set.1046 pub fn set_scoped_collection_properties(1047 collection_id: CollectionId,1048 scope: PropertyScope,1049 properties: impl Iterator<Item = Property>,1050 ) -> DispatchResult {1051 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1052 stored_properties.try_scoped_set_from_iter(scope, properties)1053 })1054 .map_err(<Error<T>>::from)?;10551056 Ok(())1057 }10581059 /// Set collection properties.1060 ///1061 /// * `collection` - Collection handler.1062 /// * `sender` - The owner or administrator of the collection.1063 /// * `properties` - The properties to set.1064 #[transactional]1065 pub fn set_collection_properties(1066 collection: &CollectionHandle<T>,1067 sender: &T::CrossAccountId,1068 properties: Vec<Property>,1069 ) -> DispatchResult {1070 for property in properties {1071 Self::set_collection_property(collection, sender, property)?;1072 }10731074 Ok(())1075 }10761077 /// Delete collection property.1078 ///1079 /// * `collection` - Collection handler.1080 /// * `sender` - The owner or administrator of the collection.1081 /// * `property` - The property to delete.1082 pub fn delete_collection_property(1083 collection: &CollectionHandle<T>,1084 sender: &T::CrossAccountId,1085 property_key: PropertyKey,1086 ) -> DispatchResult {1087 collection.check_is_owner_or_admin(sender)?;10881089 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1090 properties.remove(&property_key)1091 })1092 .map_err(<Error<T>>::from)?;10931094 Self::deposit_event(Event::CollectionPropertyDeleted(1095 collection.id,1096 property_key,1097 ));10981099 Ok(())1100 }11011102 /// Delete collection properties.1103 ///1104 /// * `collection` - Collection handler.1105 /// * `sender` - The owner or administrator of the collection.1106 /// * `properties` - The properties to delete.1107 #[transactional]1108 pub fn delete_collection_properties(1109 collection: &CollectionHandle<T>,1110 sender: &T::CrossAccountId,1111 property_keys: Vec<PropertyKey>,1112 ) -> DispatchResult {1113 for key in property_keys {1114 Self::delete_collection_property(collection, sender, key)?;1115 }11161117 Ok(())1118 }11191120 /// Set collection propetry permission without any checks.1121 ///1122 /// Used for migrations.1123 ///1124 /// * `collection` - Collection handler.1125 /// * `property_permissions` - Property permissions.1126 pub fn set_property_permission_unchecked(1127 collection: CollectionId,1128 property_permission: PropertyKeyPermission,1129 ) -> DispatchResult {1130 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1131 permissions.try_set(property_permission.key, property_permission.permission)1132 })1133 .map_err(<Error<T>>::from)?;1134 Ok(())1135 }11361137 /// Set collection property permission.1138 ///1139 /// * `collection` - Collection handler.1140 /// * `sender` - The owner or administrator of the collection.1141 /// * `property_permission` - Property permission.1142 pub fn set_property_permission(1143 collection: &CollectionHandle<T>,1144 sender: &T::CrossAccountId,1145 property_permission: PropertyKeyPermission,1146 ) -> DispatchResult {1147 Self::set_scoped_property_permission(1148 collection,1149 sender,1150 PropertyScope::None,1151 property_permission,1152 )1153 }11541155 /// Set collection property permission with scope.1156 ///1157 /// * `collection` - Collection handler.1158 /// * `sender` - The owner or administrator of the collection.1159 /// * `scope` - Property scope.1160 /// * `property_permission` - Property permission.1161 pub fn set_scoped_property_permission(1162 collection: &CollectionHandle<T>,1163 sender: &T::CrossAccountId,1164 scope: PropertyScope,1165 property_permission: PropertyKeyPermission,1166 ) -> DispatchResult {1167 collection.check_is_owner_or_admin(sender)?;11681169 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1170 let current_permission = all_permissions.get(&property_permission.key);1171 if matches![1172 current_permission,1173 Some(PropertyPermission { mutable: false, .. })1174 ] {1175 return Err(<Error<T>>::NoPermission.into());1176 }11771178 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1179 let property_permission = property_permission.clone();1180 permissions.try_scoped_set(1181 scope,1182 property_permission.key,1183 property_permission.permission,1184 )1185 })1186 .map_err(<Error<T>>::from)?;11871188 Self::deposit_event(Event::PropertyPermissionSet(1189 collection.id,1190 property_permission.key,1191 ));11921193 Ok(())1194 }11951196 /// Set token property permission.1197 ///1198 /// * `collection` - Collection handler.1199 /// * `sender` - The owner or administrator of the collection.1200 /// * `property_permissions` - Property permissions.1201 #[transactional]1202 pub fn set_token_property_permissions(1203 collection: &CollectionHandle<T>,1204 sender: &T::CrossAccountId,1205 property_permissions: Vec<PropertyKeyPermission>,1206 ) -> DispatchResult {1207 Self::set_scoped_token_property_permissions(1208 collection,1209 sender,1210 PropertyScope::None,1211 property_permissions,1212 )1213 }12141215 /// Set token property permission with scope.1216 ///1217 /// * `collection` - Collection handler.1218 /// * `sender` - The owner or administrator of the collection.1219 /// * `scope` - Property scope.1220 /// * `property_permissions` - Property permissions.1221 #[transactional]1222 pub fn set_scoped_token_property_permissions(1223 collection: &CollectionHandle<T>,1224 sender: &T::CrossAccountId,1225 scope: PropertyScope,1226 property_permissions: Vec<PropertyKeyPermission>,1227 ) -> DispatchResult {1228 for prop_pemission in property_permissions {1229 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1230 }12311232 Ok(())1233 }12341235 /// Get collection property.1236 pub fn get_collection_property(1237 collection_id: CollectionId,1238 key: &PropertyKey,1239 ) -> Option<PropertyValue> {1240 Self::collection_properties(collection_id).get(key).cloned()1241 }12421243 /// Convert byte vector to property key vector.1244 pub fn bytes_keys_to_property_keys(1245 keys: Vec<Vec<u8>>,1246 ) -> Result<Vec<PropertyKey>, DispatchError> {1247 keys.into_iter()1248 .map(|key| -> Result<PropertyKey, DispatchError> {1249 key.try_into()1250 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1251 })1252 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1253 }12541255 /// Get properties according to given keys.1256 pub fn filter_collection_properties(1257 collection_id: CollectionId,1258 keys: Option<Vec<PropertyKey>>,1259 ) -> Result<Vec<Property>, DispatchError> {1260 let properties = Self::collection_properties(collection_id);12611262 let properties = keys1263 .map(|keys| {1264 keys.into_iter()1265 .filter_map(|key| {1266 properties.get(&key).map(|value| Property {1267 key,1268 value: value.clone(),1269 })1270 })1271 .collect()1272 })1273 .unwrap_or_else(|| {1274 properties1275 .into_iter()1276 .map(|(key, value)| Property { key, value })1277 .collect()1278 });12791280 Ok(properties)1281 }12821283 /// Get property permissions according to given keys.1284 pub fn filter_property_permissions(1285 collection_id: CollectionId,1286 keys: Option<Vec<PropertyKey>>,1287 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1288 let permissions = Self::property_permissions(collection_id);12891290 let key_permissions = keys1291 .map(|keys| {1292 keys.into_iter()1293 .filter_map(|key| {1294 permissions1295 .get(&key)1296 .map(|permission| PropertyKeyPermission {1297 key,1298 permission: permission.clone(),1299 })1300 })1301 .collect()1302 })1303 .unwrap_or_else(|| {1304 permissions1305 .into_iter()1306 .map(|(key, permission)| PropertyKeyPermission { key, permission })1307 .collect()1308 });13091310 Ok(key_permissions)1311 }13121313 /// Toggle `user` participation in the `collection`'s allow list.1314 /// #### Store read/writes1315 /// 1 writes1316 pub fn toggle_allowlist(1317 collection: &CollectionHandle<T>,1318 sender: &T::CrossAccountId,1319 user: &T::CrossAccountId,1320 allowed: bool,1321 ) -> DispatchResult {1322 collection.check_is_owner_or_admin(sender)?;13231324 // =========13251326 if allowed {1327 <Allowlist<T>>::insert((collection.id, user), true);1328 } else {1329 <Allowlist<T>>::remove((collection.id, user));1330 }13311332 Ok(())1333 }13341335 /// Toggle `user` participation in the `collection`'s admin list.1336 /// #### Store read/writes1337 /// 2 writes1338 pub fn toggle_admin(1339 collection: &CollectionHandle<T>,1340 sender: &T::CrossAccountId,1341 user: &T::CrossAccountId,1342 admin: bool,1343 ) -> DispatchResult {1344 collection.check_is_owner(sender)?;13451346 let was_admin = <IsAdmin<T>>::get((collection.id, user));1347 if was_admin == admin {1348 return Ok(());1349 }1350 let amount = <AdminAmount<T>>::get(collection.id);13511352 if admin {1353 let amount = amount1354 .checked_add(1)1355 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1356 ensure!(1357 amount <= Self::collection_admins_limit(),1358 <Error<T>>::CollectionAdminCountExceeded,1359 );13601361 // =========13621363 <AdminAmount<T>>::insert(collection.id, amount);1364 <IsAdmin<T>>::insert((collection.id, user), true);1365 } else {1366 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1367 <IsAdmin<T>>::remove((collection.id, user));1368 }13691370 Ok(())1371 }13721373 /// Merge set fields from `new_limit` to `old_limit`.1374 pub fn clamp_limits(1375 mode: CollectionMode,1376 old_limit: &CollectionLimits,1377 mut new_limit: CollectionLimits,1378 ) -> Result<CollectionLimits, DispatchError> {1379 let limits = old_limit;1380 limit_default!(old_limit, new_limit,1381 account_token_ownership_limit => ensure!(1382 new_limit <= MAX_TOKEN_OWNERSHIP,1383 <Error<T>>::CollectionLimitBoundsExceeded,1384 ),1385 sponsored_data_size => ensure!(1386 new_limit <= CUSTOM_DATA_LIMIT,1387 <Error<T>>::CollectionLimitBoundsExceeded,1388 ),13891390 sponsored_data_rate_limit => {},1391 token_limit => ensure!(1392 old_limit >= new_limit && new_limit > 0,1393 <Error<T>>::CollectionTokenLimitExceeded1394 ),13951396 sponsor_transfer_timeout(match mode {1397 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1398 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1399 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1400 }) => ensure!(1401 new_limit <= MAX_SPONSOR_TIMEOUT,1402 <Error<T>>::CollectionLimitBoundsExceeded,1403 ),1404 sponsor_approve_timeout => {},1405 owner_can_transfer => ensure!(1406 !limits.owner_can_transfer_instaled() ||1407 old_limit || !new_limit,1408 <Error<T>>::OwnerPermissionsCantBeReverted,1409 ),1410 owner_can_destroy => ensure!(1411 old_limit || !new_limit,1412 <Error<T>>::OwnerPermissionsCantBeReverted,1413 ),1414 transfers_enabled => {},1415 );1416 Ok(new_limit)1417 }14181419 /// Merge set fields from `new_permission` to `old_permission`.1420 pub fn clamp_permissions(1421 _mode: CollectionMode,1422 old_permission: &CollectionPermissions,1423 mut new_permission: CollectionPermissions,1424 ) -> Result<CollectionPermissions, DispatchError> {1425 limit_default_clone!(old_permission, new_permission,1426 access => {},1427 mint_mode => {},1428 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1429 );1430 Ok(new_permission)1431 }1432}14331434/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1435#[macro_export]1436macro_rules! unsupported {1437 ($runtime:path) => {1438 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1439 };1440}14411442/// Return weights for various worst-case operations.1443pub trait CommonWeightInfo<CrossAccountId> {1444 /// Weight of item creation.1445 fn create_item() -> Weight;14461447 /// Weight of items creation.1448 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14491450 /// Weight of items creation.1451 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14521453 /// The weight of the burning item.1454 fn burn_item() -> Weight;14551456 /// Property setting weight.1457 ///1458 /// * `amount`- The number of properties to set.1459 fn set_collection_properties(amount: u32) -> Weight;14601461 /// Collection property deletion weight.1462 ///1463 /// * `amount`- The number of properties to set.1464 fn delete_collection_properties(amount: u32) -> Weight;14651466 /// Token property setting weight.1467 ///1468 /// * `amount`- The number of properties to set.1469 fn set_token_properties(amount: u32) -> Weight;14701471 /// Token property deletion weight.1472 ///1473 /// * `amount`- The number of properties to delete.1474 fn delete_token_properties(amount: u32) -> Weight;14751476 /// Token property permissions set weight.1477 ///1478 /// * `amount`- The number of property permissions to set.1479 fn set_token_property_permissions(amount: u32) -> Weight;14801481 /// Transfer price of the token or its parts.1482 fn transfer() -> Weight;14831484 /// The price of setting the permission of the operation from another user.1485 fn approve() -> Weight;14861487 /// Transfer price from another user.1488 fn transfer_from() -> Weight;14891490 /// The price of burning a token from another user.1491 fn burn_from() -> Weight;14921493 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1494 /// whole users's balance.1495 ///1496 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1497 fn burn_recursively_self_raw() -> Weight;14981499 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1500 ///1501 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1502 fn burn_recursively_breadth_raw(amount: u32) -> Weight;15031504 /// The price of recursive burning a token.1505 ///1506 /// `max_selfs` - The maximum burning weight of the token itself.1507 /// `max_breadth` - The maximum number of nested tokens to burn.1508 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1509 Self::burn_recursively_self_raw()1510 .saturating_mul(max_selfs.max(1) as u64)1511 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1512 }15131514 /// The price of retrieving token owner1515 fn token_owner() -> Weight;1516}15171518/// Weight info extension trait for refungible pallet.1519pub trait RefungibleExtensionsWeightInfo {1520 /// Weight of token repartition.1521 fn repartition() -> Weight;1522}15231524/// Common collection operations.1525///1526/// It wraps methods in Fungible, Nonfungible and Refungible pallets1527/// and adds weight info.1528pub trait CommonCollectionOperations<T: Config> {1529 /// Create token.1530 ///1531 /// * `sender` - The user who mint the token and pays for the transaction.1532 /// * `to` - The user who will own the token.1533 /// * `data` - Token data.1534 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1535 fn create_item(1536 &self,1537 sender: T::CrossAccountId,1538 to: T::CrossAccountId,1539 data: CreateItemData,1540 nesting_budget: &dyn Budget,1541 ) -> DispatchResultWithPostInfo;15421543 /// Create multiple tokens.1544 ///1545 /// * `sender` - The user who mint the token and pays for the transaction.1546 /// * `to` - The user who will own the token.1547 /// * `data` - Token data.1548 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1549 fn create_multiple_items(1550 &self,1551 sender: T::CrossAccountId,1552 to: T::CrossAccountId,1553 data: Vec<CreateItemData>,1554 nesting_budget: &dyn Budget,1555 ) -> DispatchResultWithPostInfo;15561557 /// Create multiple tokens.1558 ///1559 /// * `sender` - The user who mint the token and pays for the transaction.1560 /// * `to` - The user who will own the token.1561 /// * `data` - Token data.1562 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1563 fn create_multiple_items_ex(1564 &self,1565 sender: T::CrossAccountId,1566 data: CreateItemExData<T::CrossAccountId>,1567 nesting_budget: &dyn Budget,1568 ) -> DispatchResultWithPostInfo;15691570 /// Burn token.1571 ///1572 /// * `sender` - The user who owns the token.1573 /// * `token` - Token id that will burned.1574 /// * `amount` - The number of parts of the token that will be burned.1575 fn burn_item(1576 &self,1577 sender: T::CrossAccountId,1578 token: TokenId,1579 amount: u128,1580 ) -> DispatchResultWithPostInfo;15811582 /// Burn token and all nested tokens recursievly.1583 ///1584 /// * `sender` - The user who owns the token.1585 /// * `token` - Token id that will burned.1586 /// * `self_budget` - The budget that can be spent on burning tokens.1587 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1588 fn burn_item_recursively(1589 &self,1590 sender: T::CrossAccountId,1591 token: TokenId,1592 self_budget: &dyn Budget,1593 breadth_budget: &dyn Budget,1594 ) -> DispatchResultWithPostInfo;15951596 /// Set collection properties.1597 ///1598 /// * `sender` - Must be either the owner of the collection or its admin.1599 /// * `properties` - Properties to be set.1600 fn set_collection_properties(1601 &self,1602 sender: T::CrossAccountId,1603 properties: Vec<Property>,1604 ) -> DispatchResultWithPostInfo;16051606 /// Delete collection properties.1607 ///1608 /// * `sender` - Must be either the owner of the collection or its admin.1609 /// * `properties` - The properties to be removed.1610 fn delete_collection_properties(1611 &self,1612 sender: &T::CrossAccountId,1613 property_keys: Vec<PropertyKey>,1614 ) -> DispatchResultWithPostInfo;16151616 /// Set token properties.1617 ///1618 /// The appropriate [`PropertyPermission`] for the token property1619 /// must be set with [`Self::set_token_property_permissions`].1620 ///1621 /// * `sender` - Must be either the owner of the token or its admin.1622 /// * `token_id` - The token for which the properties are being set.1623 /// * `properties` - Properties to be set.1624 /// * `budget` - Budget for setting properties.1625 fn set_token_properties(1626 &self,1627 sender: T::CrossAccountId,1628 token_id: TokenId,1629 properties: Vec<Property>,1630 budget: &dyn Budget,1631 ) -> DispatchResultWithPostInfo;16321633 /// Remove token properties.1634 ///1635 /// The appropriate [`PropertyPermission`] for the token property1636 /// must be set with [`Self::set_token_property_permissions`].1637 ///1638 /// * `sender` - Must be either the owner of the token or its admin.1639 /// * `token_id` - The token for which the properties are being remove.1640 /// * `property_keys` - Keys to remove corresponding properties.1641 /// * `budget` - Budget for removing properties.1642 fn delete_token_properties(1643 &self,1644 sender: T::CrossAccountId,1645 token_id: TokenId,1646 property_keys: Vec<PropertyKey>,1647 budget: &dyn Budget,1648 ) -> DispatchResultWithPostInfo;16491650 /// Set token property permissions.1651 ///1652 /// * `sender` - Must be either the owner of the token or its admin.1653 /// * `token_id` - The token for which the properties are being set.1654 /// * `property_permissions` - Property permissions to be set.1655 /// * `budget` - Budget for setting properties.1656 fn set_token_property_permissions(1657 &self,1658 sender: &T::CrossAccountId,1659 property_permissions: Vec<PropertyKeyPermission>,1660 ) -> DispatchResultWithPostInfo;16611662 /// Transfer amount of token pieces.1663 ///1664 /// * `sender` - Donor user.1665 /// * `to` - Recepient user.1666 /// * `token` - The token of which parts are being sent.1667 /// * `amount` - The number of parts of the token that will be transferred.1668 /// * `budget` - The maximum budget that can be spent on the transfer.1669 fn transfer(1670 &self,1671 sender: T::CrossAccountId,1672 to: T::CrossAccountId,1673 token: TokenId,1674 amount: u128,1675 budget: &dyn Budget,1676 ) -> DispatchResultWithPostInfo;16771678 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1679 ///1680 /// * `sender` - The user who grants access to the token.1681 /// * `spender` - The user to whom the rights are granted.1682 /// * `token` - The token to which access is granted.1683 /// * `amount` - The amount of pieces that another user can dispose of.1684 fn approve(1685 &self,1686 sender: T::CrossAccountId,1687 spender: T::CrossAccountId,1688 token: TokenId,1689 amount: u128,1690 ) -> DispatchResultWithPostInfo;16911692 /// Send parts of a token owned by another user.1693 ///1694 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1695 ///1696 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1697 /// * `from` - The user who owns the token.1698 /// * `to` - Recepient user.1699 /// * `token` - The token of which parts are being sent.1700 /// * `amount` - The number of parts of the token that will be transferred.1701 /// * `budget` - The maximum budget that can be spent on the transfer.1702 fn transfer_from(1703 &self,1704 sender: T::CrossAccountId,1705 from: T::CrossAccountId,1706 to: T::CrossAccountId,1707 token: TokenId,1708 amount: u128,1709 budget: &dyn Budget,1710 ) -> DispatchResultWithPostInfo;17111712 /// Burn parts of a token owned by another user.1713 ///1714 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1715 ///1716 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1717 /// * `from` - The user who owns the token.1718 /// * `token` - The token of which parts are being sent.1719 /// * `amount` - The number of parts of the token that will be transferred.1720 /// * `budget` - The maximum budget that can be spent on the burn.1721 fn burn_from(1722 &self,1723 sender: T::CrossAccountId,1724 from: T::CrossAccountId,1725 token: TokenId,1726 amount: u128,1727 budget: &dyn Budget,1728 ) -> DispatchResultWithPostInfo;17291730 /// Check permission to nest token.1731 ///1732 /// * `sender` - The user who initiated the check.1733 /// * `from` - The token that is checked for embedding.1734 /// * `under` - Token under which to check.1735 /// * `budget` - The maximum budget that can be spent on the check.1736 fn check_nesting(1737 &self,1738 sender: T::CrossAccountId,1739 from: (CollectionId, TokenId),1740 under: TokenId,1741 budget: &dyn Budget,1742 ) -> DispatchResult;17431744 /// Nest one token into another.1745 ///1746 /// * `under` - Token holder.1747 /// * `to_nest` - Nested token.1748 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17491750 /// Unnest token.1751 ///1752 /// * `under` - Token holder.1753 /// * `to_nest` - Token to unnest.1754 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17551756 /// Get all user tokens.1757 ///1758 /// * `account` - Account for which you need to get tokens.1759 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17601761 /// Get all the tokens in the collection.1762 fn collection_tokens(&self) -> Vec<TokenId>;17631764 /// Check if the token exists.1765 ///1766 /// * `token` - Id token to check.1767 fn token_exists(&self, token: TokenId) -> bool;17681769 /// Get the id of the last minted token.1770 fn last_token_id(&self) -> TokenId;17711772 /// Get the owner of the token.1773 ///1774 /// * `token` - The token for which you need to find out the owner.1775 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17761777 /// Returns 10 tokens owners in no particular order.1778 ///1779 /// * `token` - The token for which you need to find out the owners.1780 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;17811782 /// Get the value of the token property by key.1783 ///1784 /// * `token` - Token with the property to get.1785 /// * `key` - Property name.1786 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17871788 /// Get a set of token properties by key vector.1789 ///1790 /// * `token` - Token with the property to get.1791 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1792 /// then all properties are returned.1793 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17941795 /// Amount of unique collection tokens1796 fn total_supply(&self) -> u32;17971798 /// Amount of different tokens account has.1799 ///1800 /// * `account` - The account for which need to get the balance.1801 fn account_balance(&self, account: T::CrossAccountId) -> u32;18021803 /// Amount of specific token account have.1804 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;18051806 /// Amount of token pieces1807 fn total_pieces(&self, token: TokenId) -> Option<u128>;18081809 /// Get the number of parts of the token that a trusted user can manage.1810 ///1811 /// * `sender` - Trusted user.1812 /// * `spender` - Owner of the token.1813 /// * `token` - The token for which to get the value.1814 fn allowance(1815 &self,1816 sender: T::CrossAccountId,1817 spender: T::CrossAccountId,1818 token: TokenId,1819 ) -> u128;18201821 /// Get extension for RFT collection.1822 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1823}18241825/// Extension for RFT collection.1826pub trait RefungibleExtensions<T>1827where1828 T: Config,1829{1830 /// Change the number of parts of the token.1831 ///1832 /// When the value changes down, this function is equivalent to burning parts of the token.1833 ///1834 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.1835 /// * `token` - The token for which you want to change the number of parts.1836 /// * `amount` - The new value of the parts of the token.1837 fn repartition(1838 &self,1839 sender: &T::CrossAccountId,1840 token: TokenId,1841 amount: u128,1842 ) -> DispatchResultWithPostInfo;1843}18441845/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1846///1847/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1848pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1849 let post_info = PostDispatchInfo {1850 actual_weight: Some(weight),1851 pays_fee: Pays::Yes,1852 };1853 match res {1854 Ok(()) => Ok(post_info),1855 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1856 }1857}18581859impl<T: Config> From<PropertiesError> for Error<T> {1860 fn from(error: PropertiesError) -> Self {1861 match error {1862 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1863 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1864 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1865 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1866 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1867 }1868 }1869}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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63 ensure,64 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65 weights::Pays,66 transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70 COLLECTION_NUMBER_LIMIT,71 Collection,72 RpcCollection,73 CollectionFlags,74 RpcCollectionFlags,75 CollectionId,76 CreateItemData,77 MAX_TOKEN_PREFIX_LENGTH,78 COLLECTION_ADMINS_LIMIT,79 TokenId,80 TokenChild,81 CollectionStats,82 MAX_TOKEN_OWNERSHIP,83 CollectionMode,84 NFT_SPONSOR_TRANSFER_TIMEOUT,85 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87 MAX_SPONSOR_TIMEOUT,88 CUSTOM_DATA_LIMIT,89 CollectionLimits,90 CreateCollectionData,91 SponsorshipState,92 CreateItemExData,93 SponsoringRateLimit,94 budget::Budget,95 PhantomType,96 Property,97 Properties,98 PropertiesPermissionMap,99 PropertyKey,100 PropertyValue,101 PropertyPermission,102 PropertiesError,103 PropertyKeyPermission,104 TokenData,105 TrySetProperty,106 PropertyScope,107 // RMRK108 RmrkCollectionInfo,109 RmrkInstanceInfo,110 RmrkResourceInfo,111 RmrkPropertyInfo,112 RmrkBaseInfo,113 RmrkPartType,114 RmrkBoundedTheme,115 RmrkNftChild,116 CollectionPermissions,117};118119pub use pallet::*;120use sp_core::H160;121use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};122#[cfg(feature = "runtime-benchmarks")]123pub mod benchmarking;124pub mod dispatch;125pub mod erc;126pub mod eth;127pub mod weights;128129/// Weight info.130pub type SelfWeightOf<T> = <T as Config>::WeightInfo;131132/// Collection handle contains information about collection data and id.133/// Also provides functionality to count consumed gas.134///135/// CollectionHandle is used as a generic wrapper for collections of all types.136/// It allows to perform common operations and queries on any collection type,137/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].138#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]139pub struct CollectionHandle<T: Config> {140 /// Collection id141 pub id: CollectionId,142 collection: Collection<T::AccountId>,143 /// Substrate recorder for counting consumed gas144 pub recorder: SubstrateRecorder<T>,145}146147impl<T: Config> WithRecorder<T> for CollectionHandle<T> {148 fn recorder(&self) -> &SubstrateRecorder<T> {149 &self.recorder150 }151 fn into_recorder(self) -> SubstrateRecorder<T> {152 self.recorder153 }154}155156impl<T: Config> CollectionHandle<T> {157 /// Same as [CollectionHandle::new] but with an explicit gas limit.158 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {159 <CollectionById<T>>::get(id).map(|collection| Self {160 id,161 collection,162 recorder: SubstrateRecorder::new(gas_limit),163 })164 }165166 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].167 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {168 <CollectionById<T>>::get(id).map(|collection| Self {169 id,170 collection,171 recorder,172 })173 }174175 /// Retrives collection data from storage and creates collection handle with default parameters.176 /// If collection not found return `None`177 pub fn new(id: CollectionId) -> Option<Self> {178 Self::new_with_gas_limit(id, u64::MAX)179 }180181 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.182 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {183 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)184 }185186 /// Consume gas for reading.187 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {188 self.recorder189 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(190 <T as frame_system::Config>::DbWeight::get()191 .read192 .saturating_mul(reads),193 )))194 }195196 /// Consume gas for writing.197 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {198 self.recorder199 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(200 <T as frame_system::Config>::DbWeight::get()201 .write202 .saturating_mul(writes),203 )))204 }205206 /// Consume gas for reading and writing.207 pub fn consume_store_reads_and_writes(208 &self,209 reads: u64,210 writes: u64,211 ) -> evm_coder::execution::Result<()> {212 let weight = <T as frame_system::Config>::DbWeight::get();213 let reads = weight.read.saturating_mul(reads);214 let writes = weight.read.saturating_mul(writes);215 self.recorder216 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(217 reads.saturating_add(writes),218 )))219 }220221 /// Save collection to storage.222 pub fn save(&self) -> DispatchResult {223 <CollectionById<T>>::insert(self.id, &self.collection);224 Ok(())225 }226227 /// Set collection sponsor.228 ///229 /// Unique collections allows sponsoring for certain actions.230 /// This method allows you to set the sponsor of the collection.231 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].232 pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {233 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);234 Ok(())235 }236237 /// Confirm sponsorship238 ///239 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.240 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].241 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {242 if self.collection.sponsorship.pending_sponsor() != Some(sender) {243 return Ok(false);244 }245246 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());247 Ok(true)248 }249250 /// Remove collection sponsor.251 pub fn remove_sponsor(&mut self) -> DispatchResult {252 self.collection.sponsorship = SponsorshipState::Disabled;253 Ok(())254 }255256 /// Checks that the collection was created with, and must be operated upon through **Unique API**.257 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.258 pub fn check_is_internal(&self) -> DispatchResult {259 if self.flags.external {260 return Err(<Error<T>>::CollectionIsExternal)?;261 }262263 Ok(())264 }265266 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.267 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.268 pub fn check_is_external(&self) -> DispatchResult {269 if !self.flags.external {270 return Err(<Error<T>>::CollectionIsInternal)?;271 }272273 Ok(())274 }275}276277impl<T: Config> Deref for CollectionHandle<T> {278 type Target = Collection<T::AccountId>;279280 fn deref(&self) -> &Self::Target {281 &self.collection282 }283}284285impl<T: Config> DerefMut for CollectionHandle<T> {286 fn deref_mut(&mut self) -> &mut Self::Target {287 &mut self.collection288 }289}290291impl<T: Config> CollectionHandle<T> {292 /// Checks if the `user` is the owner of the collection.293 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {294 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);295 Ok(())296 }297298 /// Returns **true** if the `user` is the owner or administrator of the collection.299 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {300 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))301 }302303 /// Checks if the `user` is the owner or administrator of the collection.304 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {305 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);306 Ok(())307 }308309 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.310 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {311 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)312 }313314 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.315 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {316 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)317 }318319 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.320 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {321 ensure!(322 <Allowlist<T>>::get((self.id, user)),323 <Error<T>>::AddressNotInAllowlist324 );325 Ok(())326 }327328 /// Changes collection owner to another account329 /// #### Store read/writes330 /// 1 writes331 fn set_owner_internal(332 &mut self,333 caller: T::CrossAccountId,334 new_owner: T::CrossAccountId,335 ) -> DispatchResult {336 self.check_is_owner(&caller)?;337 self.collection.owner = new_owner.as_sub().clone();338 self.save()339 }340}341342#[frame_support::pallet]343pub mod pallet {344 use super::*;345 use pallet_evm::account;346 use dispatch::CollectionDispatch;347 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};348 use frame_system::pallet_prelude::*;349 use frame_support::traits::Currency;350 use up_data_structs::{TokenId, mapping::TokenAddressMapping};351 use scale_info::TypeInfo;352 use weights::WeightInfo;353354 #[pallet::config]355 pub trait Config:356 frame_system::Config357 + pallet_evm_coder_substrate::Config358 + pallet_evm::Config359 + TypeInfo360 + account::Config361 {362 /// Weight information for functions of this pallet.363 type WeightInfo: WeightInfo;364365 /// Events compatible with [`frame_system::Config::Event`].366 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;367368 /// Handler of accounts and payment.369 type Currency: Currency<Self::AccountId>;370371 /// Set price to create a collection.372 #[pallet::constant]373 type CollectionCreationPrice: Get<374 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,375 >;376377 /// Dispatcher of operations on collections.378 type CollectionDispatch: CollectionDispatch<Self>;379380 /// Account which holds the chain's treasury.381 type TreasuryAccountId: Get<Self::AccountId>;382383 /// Address under which the CollectionHelper contract would be available.384 type ContractAddress: Get<H160>;385386 /// Mapper for token addresses to Ethereum addresses.387 type EvmTokenAddressMapping: TokenAddressMapping<H160>;388389 /// Mapper for token addresses to [`CrossAccountId`].390 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;391 }392393 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);394395 #[pallet::pallet]396 #[pallet::storage_version(STORAGE_VERSION)]397 #[pallet::generate_store(pub(super) trait Store)]398 pub struct Pallet<T>(_);399400 #[pallet::extra_constants]401 impl<T: Config> Pallet<T> {402 /// Maximum admins per collection.403 pub fn collection_admins_limit() -> u32 {404 COLLECTION_ADMINS_LIMIT405 }406 }407408 #[pallet::event]409 #[pallet::generate_deposit(pub fn deposit_event)]410 pub enum Event<T: Config> {411 /// New collection was created412 CollectionCreated(413 /// Globally unique identifier of newly created collection.414 CollectionId,415 /// [`CollectionMode`] converted into _u8_.416 u8,417 /// Collection owner.418 T::AccountId,419 ),420421 /// New collection was destroyed422 CollectionDestroyed(423 /// Globally unique identifier of collection.424 CollectionId,425 ),426427 /// New item was created.428 ItemCreated(429 /// Id of the collection where item was created.430 CollectionId,431 /// Id of an item. Unique within the collection.432 TokenId,433 /// Owner of newly created item434 T::CrossAccountId,435 /// Always 1 for NFT436 u128,437 ),438439 /// Collection item was burned.440 ItemDestroyed(441 /// Id of the collection where item was destroyed.442 CollectionId,443 /// Identifier of burned NFT.444 TokenId,445 /// Which user has destroyed its tokens.446 T::CrossAccountId,447 /// Amount of token pieces destroed. Always 1 for NFT.448 u128,449 ),450451 /// Item was transferred452 Transfer(453 /// Id of collection to which item is belong.454 CollectionId,455 /// Id of an item.456 TokenId,457 /// Original owner of item.458 T::CrossAccountId,459 /// New owner of item.460 T::CrossAccountId,461 /// Amount of token pieces transfered. Always 1 for NFT.462 u128,463 ),464465 /// Amount pieces of token owned by `sender` was approved for `spender`.466 Approved(467 /// Id of collection to which item is belong.468 CollectionId,469 /// Id of an item.470 TokenId,471 /// Original owner of item.472 T::CrossAccountId,473 /// Id for which the approval was granted.474 T::CrossAccountId,475 /// Amount of token pieces transfered. Always 1 for NFT.476 u128,477 ),478479 /// The colletion property has been added or edited.480 CollectionPropertySet(481 /// Id of collection to which property has been set.482 CollectionId,483 /// The property that was set.484 PropertyKey,485 ),486487 /// The property has been deleted.488 CollectionPropertyDeleted(489 /// Id of collection to which property has been deleted.490 CollectionId,491 /// The property that was deleted.492 PropertyKey,493 ),494495 /// The token property has been added or edited.496 TokenPropertySet(497 /// Identifier of the collection whose token has the property set.498 CollectionId,499 /// The token for which the property was set.500 TokenId,501 /// The property that was set.502 PropertyKey,503 ),504505 /// The token property has been deleted.506 TokenPropertyDeleted(507 /// Identifier of the collection whose token has the property deleted.508 CollectionId,509 /// The token for which the property was deleted.510 TokenId,511 /// The property that was deleted.512 PropertyKey,513 ),514515 /// The token property permission of a collection has been set.516 PropertyPermissionSet(517 /// ID of collection to which property permission has been set.518 CollectionId,519 /// The property permission that was set.520 PropertyKey,521 ),522 }523524 #[pallet::error]525 pub enum Error<T> {526 /// This collection does not exist.527 CollectionNotFound,528 /// Sender parameter and item owner must be equal.529 MustBeTokenOwner,530 /// No permission to perform action531 NoPermission,532 /// Destroying only empty collections is allowed533 CantDestroyNotEmptyCollection,534 /// Collection is not in mint mode.535 PublicMintingNotAllowed,536 /// Address is not in allow list.537 AddressNotInAllowlist,538539 /// Collection name can not be longer than 63 char.540 CollectionNameLimitExceeded,541 /// Collection description can not be longer than 255 char.542 CollectionDescriptionLimitExceeded,543 /// Token prefix can not be longer than 15 char.544 CollectionTokenPrefixLimitExceeded,545 /// Total collections bound exceeded.546 TotalCollectionsLimitExceeded,547 /// Exceeded max admin count548 CollectionAdminCountExceeded,549 /// Collection limit bounds per collection exceeded550 CollectionLimitBoundsExceeded,551 /// Tried to enable permissions which are only permitted to be disabled552 OwnerPermissionsCantBeReverted,553 /// Collection settings not allowing items transferring554 TransferNotAllowed,555 /// Account token limit exceeded per collection556 AccountTokenLimitExceeded,557 /// Collection token limit exceeded558 CollectionTokenLimitExceeded,559 /// Metadata flag frozen560 MetadataFlagFrozen,561562 /// Item does not exist563 TokenNotFound,564 /// Item is balance not enough565 TokenValueTooLow,566 /// Requested value is more than the approved567 ApprovedValueTooLow,568 /// Tried to approve more than owned569 CantApproveMoreThanOwned,570571 /// Can't transfer tokens to ethereum zero address572 AddressIsZero,573574 /// The operation is not supported575 UnsupportedOperation,576577 /// Insufficient funds to perform an action578 NotSufficientFounds,579580 /// User does not satisfy the nesting rule581 UserIsNotAllowedToNest,582 /// Only tokens from specific collections may nest tokens under this one583 SourceCollectionIsNotAllowedToNest,584585 /// Tried to store more data than allowed in collection field586 CollectionFieldSizeExceeded,587588 /// Tried to store more property data than allowed589 NoSpaceForProperty,590591 /// Tried to store more property keys than allowed592 PropertyLimitReached,593594 /// Property key is too long595 PropertyKeyIsTooLong,596597 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed598 InvalidCharacterInPropertyKey,599600 /// Empty property keys are forbidden601 EmptyPropertyKey,602603 /// Tried to access an external collection with an internal API604 CollectionIsExternal,605606 /// Tried to access an internal collection with an external API607 CollectionIsInternal,608 }609610 /// Storage of the count of created collections. Essentially contains the last collection ID.611 #[pallet::storage]612 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;613614 /// Storage of the count of deleted collections.615 #[pallet::storage]616 pub type DestroyedCollectionCount<T> =617 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;618619 /// Storage of collection info.620 #[pallet::storage]621 pub type CollectionById<T> = StorageMap<622 Hasher = Blake2_128Concat,623 Key = CollectionId,624 Value = Collection<<T as frame_system::Config>::AccountId>,625 QueryKind = OptionQuery,626 >;627628 /// Storage of collection properties.629 #[pallet::storage]630 #[pallet::getter(fn collection_properties)]631 pub type CollectionProperties<T> = StorageMap<632 Hasher = Blake2_128Concat,633 Key = CollectionId,634 Value = Properties,635 QueryKind = ValueQuery,636 OnEmpty = up_data_structs::CollectionProperties,637 >;638639 /// Storage of token property permissions of a collection.640 #[pallet::storage]641 #[pallet::getter(fn property_permissions)]642 pub type CollectionPropertyPermissions<T> = StorageMap<643 Hasher = Blake2_128Concat,644 Key = CollectionId,645 Value = PropertiesPermissionMap,646 QueryKind = ValueQuery,647 >;648649 /// Storage of the amount of collection admins.650 #[pallet::storage]651 pub type AdminAmount<T> = StorageMap<652 Hasher = Blake2_128Concat,653 Key = CollectionId,654 Value = u32,655 QueryKind = ValueQuery,656 >;657658 /// List of collection admins.659 #[pallet::storage]660 pub type IsAdmin<T: Config> = StorageNMap<661 Key = (662 Key<Blake2_128Concat, CollectionId>,663 Key<Blake2_128Concat, T::CrossAccountId>,664 ),665 Value = bool,666 QueryKind = ValueQuery,667 >;668669 /// Allowlisted collection users.670 #[pallet::storage]671 pub type Allowlist<T: Config> = StorageNMap<672 Key = (673 Key<Blake2_128Concat, CollectionId>,674 Key<Blake2_128Concat, T::CrossAccountId>,675 ),676 Value = bool,677 QueryKind = ValueQuery,678 >;679680 /// Not used by code, exists only to provide some types to metadata.681 #[pallet::storage]682 pub type DummyStorageValue<T: Config> = StorageValue<683 Value = (684 CollectionStats,685 CollectionId,686 TokenId,687 TokenChild,688 PhantomType<(689 TokenData<T::CrossAccountId>,690 RpcCollection<T::AccountId>,691 // RMRK692 RmrkCollectionInfo<T::AccountId>,693 RmrkInstanceInfo<T::AccountId>,694 RmrkResourceInfo,695 RmrkPropertyInfo,696 RmrkBaseInfo<T::AccountId>,697 RmrkPartType,698 RmrkBoundedTheme,699 RmrkNftChild,700 )>,701 ),702 QueryKind = OptionQuery,703 >;704705 #[pallet::hooks]706 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {707 fn on_runtime_upgrade() -> Weight {708 StorageVersion::new(1).put::<Pallet<T>>();709710 Weight::zero()711 }712 }713}714715impl<T: Config> Pallet<T> {716 /// Enshure that receiver address is correct.717 ///718 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.719 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {720 ensure!(721 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,722 <Error<T>>::AddressIsZero723 );724 Ok(())725 }726727 /// Get a vector of collection admins.728 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {729 <IsAdmin<T>>::iter_prefix((collection,))730 .map(|(a, _)| a)731 .collect()732 }733734 /// Get a vector of users allowed to mint tokens.735 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {736 <Allowlist<T>>::iter_prefix((collection,))737 .map(|(a, _)| a)738 .collect()739 }740741 /// Is `user` allowed to mint token in `collection`.742 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {743 <Allowlist<T>>::get((collection, user))744 }745746 /// Get statistics of collections.747 pub fn collection_stats() -> CollectionStats {748 let created = <CreatedCollectionCount<T>>::get();749 let destroyed = <DestroyedCollectionCount<T>>::get();750 CollectionStats {751 created: created.0,752 destroyed: destroyed.0,753 alive: created.0 - destroyed.0,754 }755 }756757 /// Get the effective limits for the collection.758 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {759 let collection = <CollectionById<T>>::get(collection)?;760 let limits = collection.limits;761 let effective_limits = CollectionLimits {762 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),763 sponsored_data_size: Some(limits.sponsored_data_size()),764 sponsored_data_rate_limit: Some(765 limits766 .sponsored_data_rate_limit767 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),768 ),769 token_limit: Some(limits.token_limit()),770 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(771 match collection.mode {772 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,773 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,774 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,775 },776 )),777 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),778 owner_can_transfer: Some(limits.owner_can_transfer()),779 owner_can_destroy: Some(limits.owner_can_destroy()),780 transfers_enabled: Some(limits.transfers_enabled()),781 };782783 Some(effective_limits)784 }785786 /// Returns information about the `collection` adapted for rpc.787 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {788 let Collection {789 name,790 description,791 owner,792 mode,793 token_prefix,794 sponsorship,795 limits,796 permissions,797 flags,798 } = <CollectionById<T>>::get(collection)?;799800 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)801 .into_iter()802 .map(|(key, permission)| PropertyKeyPermission { key, permission })803 .collect();804805 let properties = <CollectionProperties<T>>::get(collection)806 .into_iter()807 .map(|(key, value)| Property { key, value })808 .collect();809810 let permissions = CollectionPermissions {811 access: Some(permissions.access()),812 mint_mode: Some(permissions.mint_mode()),813 nesting: Some(permissions.nesting().clone()),814 };815816 Some(RpcCollection {817 name: name.into_inner(),818 description: description.into_inner(),819 owner,820 mode,821 token_prefix: token_prefix.into_inner(),822 sponsorship,823 limits,824 permissions,825 token_property_permissions,826 properties,827 read_only: flags.external,828829 flags: RpcCollectionFlags {830 foreign: flags.foreign,831 erc721metadata: flags.erc721metadata,832 },833 })834 }835}836837macro_rules! limit_default {838 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{839 $(840 if let Some($new) = $new.$field {841 let $old = $old.$field($($arg)?);842 let _ = $new;843 let _ = $old;844 $check845 } else {846 $new.$field = $old.$field847 }848 )*849 }};850}851macro_rules! limit_default_clone {852 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{853 $(854 if let Some($new) = $new.$field.clone() {855 let $old = $old.$field($($arg)?);856 let _ = $new;857 let _ = $old;858 $check859 } else {860 $new.$field = $old.$field.clone()861 }862 )*863 }};864}865866impl<T: Config> Pallet<T> {867 /// Create new collection.868 ///869 /// * `owner` - The owner of the collection.870 /// * `data` - Description of the created collection.871 /// * `flags` - Extra flags to store.872 pub fn init_collection(873 owner: T::CrossAccountId,874 payer: T::CrossAccountId,875 data: CreateCollectionData<T::AccountId>,876 flags: CollectionFlags,877 ) -> Result<CollectionId, DispatchError> {878 {879 ensure!(880 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,881 Error::<T>::CollectionTokenPrefixLimitExceeded882 );883 }884885 let created_count = <CreatedCollectionCount<T>>::get()886 .0887 .checked_add(1)888 .ok_or(ArithmeticError::Overflow)?;889 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;890 let id = CollectionId(created_count);891892 // bound Total number of collections893 ensure!(894 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,895 <Error<T>>::TotalCollectionsLimitExceeded896 );897898 // =========899900 let collection = Collection {901 owner: owner.as_sub().clone(),902 name: data.name,903 mode: data.mode.clone(),904 description: data.description,905 token_prefix: data.token_prefix,906 sponsorship: data907 .pending_sponsor908 .map(SponsorshipState::Unconfirmed)909 .unwrap_or_default(),910 limits: data911 .limits912 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))913 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,914 permissions: data915 .permissions916 .map(|permissions| {917 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)918 })919 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,920 flags,921 };922923 let mut collection_properties = up_data_structs::CollectionProperties::get();924 collection_properties925 .try_set_from_iter(data.properties.into_iter())926 .map_err(<Error<T>>::from)?;927928 CollectionProperties::<T>::insert(id, collection_properties);929930 let mut token_props_permissions = PropertiesPermissionMap::new();931 token_props_permissions932 .try_set_from_iter(data.token_property_permissions.into_iter())933 .map_err(<Error<T>>::from)?;934935 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);936937 // Take a (non-refundable) deposit of collection creation938 {939 let mut imbalance =940 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();941 imbalance.subsume(942 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(943 &T::TreasuryAccountId::get(),944 T::CollectionCreationPrice::get(),945 ),946 );947 <T as Config>::Currency::settle(948 payer.as_sub(),949 imbalance,950 WithdrawReasons::TRANSFER,951 ExistenceRequirement::KeepAlive,952 )953 .map_err(|_| Error::<T>::NotSufficientFounds)?;954 }955956 <CreatedCollectionCount<T>>::put(created_count);957 <Pallet<T>>::deposit_event(Event::CollectionCreated(958 id,959 data.mode.id(),960 owner.as_sub().clone(),961 ));962 <PalletEvm<T>>::deposit_log(963 erc::CollectionHelpersEvents::CollectionCreated {964 owner: *owner.as_eth(),965 collection_id: eth::collection_id_to_address(id),966 }967 .to_log(T::ContractAddress::get()),968 );969 <CollectionById<T>>::insert(id, collection);970 Ok(id)971 }972973 /// Destroy collection.974 ///975 /// * `collection` - Collection handler.976 /// * `sender` - The owner or administrator of the collection.977 pub fn destroy_collection(978 collection: CollectionHandle<T>,979 sender: &T::CrossAccountId,980 ) -> DispatchResult {981 ensure!(982 collection.limits.owner_can_destroy(),983 <Error<T>>::NoPermission,984 );985 collection.check_is_owner(sender)?;986987 let destroyed_collections = <DestroyedCollectionCount<T>>::get()988 .0989 .checked_add(1)990 .ok_or(ArithmeticError::Overflow)?;991992 // =========993994 <DestroyedCollectionCount<T>>::put(destroyed_collections);995 <CollectionById<T>>::remove(collection.id);996 <AdminAmount<T>>::remove(collection.id);997 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);998 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);999 <CollectionProperties<T>>::remove(collection.id);10001001 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));1002 Ok(())1003 }10041005 /// Set collection property.1006 ///1007 /// * `collection` - Collection handler.1008 /// * `sender` - The owner or administrator of the collection.1009 /// * `property` - The property to set.1010 pub fn set_collection_property(1011 collection: &CollectionHandle<T>,1012 sender: &T::CrossAccountId,1013 property: Property,1014 ) -> DispatchResult {1015 collection.check_is_owner_or_admin(sender)?;10161017 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1018 let property = property.clone();1019 properties.try_set(property.key, property.value)1020 })1021 .map_err(<Error<T>>::from)?;10221023 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));10241025 Ok(())1026 }10271028 /// Set scouped collection property.1029 ///1030 /// * `collection_id` - ID of the collection for which the property is being set.1031 /// * `scope` - Property scope.1032 /// * `property` - The property to set.1033 pub fn set_scoped_collection_property(1034 collection_id: CollectionId,1035 scope: PropertyScope,1036 property: Property,1037 ) -> DispatchResult {1038 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1039 properties.try_scoped_set(scope, property.key, property.value)1040 })1041 .map_err(<Error<T>>::from)?;10421043 Ok(())1044 }10451046 /// Set scouped collection properties.1047 ///1048 /// * `collection_id` - ID of the collection for which the properties is being set.1049 /// * `scope` - Property scope.1050 /// * `properties` - The properties to set.1051 pub fn set_scoped_collection_properties(1052 collection_id: CollectionId,1053 scope: PropertyScope,1054 properties: impl Iterator<Item = Property>,1055 ) -> DispatchResult {1056 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1057 stored_properties.try_scoped_set_from_iter(scope, properties)1058 })1059 .map_err(<Error<T>>::from)?;10601061 Ok(())1062 }10631064 /// Set collection properties.1065 ///1066 /// * `collection` - Collection handler.1067 /// * `sender` - The owner or administrator of the collection.1068 /// * `properties` - The properties to set.1069 #[transactional]1070 pub fn set_collection_properties(1071 collection: &CollectionHandle<T>,1072 sender: &T::CrossAccountId,1073 properties: Vec<Property>,1074 ) -> DispatchResult {1075 for property in properties {1076 Self::set_collection_property(collection, sender, property)?;1077 }10781079 Ok(())1080 }10811082 /// Delete collection property.1083 ///1084 /// * `collection` - Collection handler.1085 /// * `sender` - The owner or administrator of the collection.1086 /// * `property` - The property to delete.1087 pub fn delete_collection_property(1088 collection: &CollectionHandle<T>,1089 sender: &T::CrossAccountId,1090 property_key: PropertyKey,1091 ) -> DispatchResult {1092 collection.check_is_owner_or_admin(sender)?;10931094 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1095 properties.remove(&property_key)1096 })1097 .map_err(<Error<T>>::from)?;10981099 Self::deposit_event(Event::CollectionPropertyDeleted(1100 collection.id,1101 property_key,1102 ));11031104 Ok(())1105 }11061107 /// Delete collection properties.1108 ///1109 /// * `collection` - Collection handler.1110 /// * `sender` - The owner or administrator of the collection.1111 /// * `properties` - The properties to delete.1112 #[transactional]1113 pub fn delete_collection_properties(1114 collection: &CollectionHandle<T>,1115 sender: &T::CrossAccountId,1116 property_keys: Vec<PropertyKey>,1117 ) -> DispatchResult {1118 for key in property_keys {1119 Self::delete_collection_property(collection, sender, key)?;1120 }11211122 Ok(())1123 }11241125 /// Set collection propetry permission without any checks.1126 ///1127 /// Used for migrations.1128 ///1129 /// * `collection` - Collection handler.1130 /// * `property_permissions` - Property permissions.1131 pub fn set_property_permission_unchecked(1132 collection: CollectionId,1133 property_permission: PropertyKeyPermission,1134 ) -> DispatchResult {1135 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1136 permissions.try_set(property_permission.key, property_permission.permission)1137 })1138 .map_err(<Error<T>>::from)?;1139 Ok(())1140 }11411142 /// Set collection property permission.1143 ///1144 /// * `collection` - Collection handler.1145 /// * `sender` - The owner or administrator of the collection.1146 /// * `property_permission` - Property permission.1147 pub fn set_property_permission(1148 collection: &CollectionHandle<T>,1149 sender: &T::CrossAccountId,1150 property_permission: PropertyKeyPermission,1151 ) -> DispatchResult {1152 Self::set_scoped_property_permission(1153 collection,1154 sender,1155 PropertyScope::None,1156 property_permission,1157 )1158 }11591160 /// Set collection property permission with scope.1161 ///1162 /// * `collection` - Collection handler.1163 /// * `sender` - The owner or administrator of the collection.1164 /// * `scope` - Property scope.1165 /// * `property_permission` - Property permission.1166 pub fn set_scoped_property_permission(1167 collection: &CollectionHandle<T>,1168 sender: &T::CrossAccountId,1169 scope: PropertyScope,1170 property_permission: PropertyKeyPermission,1171 ) -> DispatchResult {1172 collection.check_is_owner_or_admin(sender)?;11731174 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1175 let current_permission = all_permissions.get(&property_permission.key);1176 if matches![1177 current_permission,1178 Some(PropertyPermission { mutable: false, .. })1179 ] {1180 return Err(<Error<T>>::NoPermission.into());1181 }11821183 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1184 let property_permission = property_permission.clone();1185 permissions.try_scoped_set(1186 scope,1187 property_permission.key,1188 property_permission.permission,1189 )1190 })1191 .map_err(<Error<T>>::from)?;11921193 Self::deposit_event(Event::PropertyPermissionSet(1194 collection.id,1195 property_permission.key,1196 ));11971198 Ok(())1199 }12001201 /// Set token property permission.1202 ///1203 /// * `collection` - Collection handler.1204 /// * `sender` - The owner or administrator of the collection.1205 /// * `property_permissions` - Property permissions.1206 #[transactional]1207 pub fn set_token_property_permissions(1208 collection: &CollectionHandle<T>,1209 sender: &T::CrossAccountId,1210 property_permissions: Vec<PropertyKeyPermission>,1211 ) -> DispatchResult {1212 Self::set_scoped_token_property_permissions(1213 collection,1214 sender,1215 PropertyScope::None,1216 property_permissions,1217 )1218 }12191220 /// Set token property permission with scope.1221 ///1222 /// * `collection` - Collection handler.1223 /// * `sender` - The owner or administrator of the collection.1224 /// * `scope` - Property scope.1225 /// * `property_permissions` - Property permissions.1226 #[transactional]1227 pub fn set_scoped_token_property_permissions(1228 collection: &CollectionHandle<T>,1229 sender: &T::CrossAccountId,1230 scope: PropertyScope,1231 property_permissions: Vec<PropertyKeyPermission>,1232 ) -> DispatchResult {1233 for prop_pemission in property_permissions {1234 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1235 }12361237 Ok(())1238 }12391240 /// Get collection property.1241 pub fn get_collection_property(1242 collection_id: CollectionId,1243 key: &PropertyKey,1244 ) -> Option<PropertyValue> {1245 Self::collection_properties(collection_id).get(key).cloned()1246 }12471248 /// Convert byte vector to property key vector.1249 pub fn bytes_keys_to_property_keys(1250 keys: Vec<Vec<u8>>,1251 ) -> Result<Vec<PropertyKey>, DispatchError> {1252 keys.into_iter()1253 .map(|key| -> Result<PropertyKey, DispatchError> {1254 key.try_into()1255 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1256 })1257 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1258 }12591260 /// Get properties according to given keys.1261 pub fn filter_collection_properties(1262 collection_id: CollectionId,1263 keys: Option<Vec<PropertyKey>>,1264 ) -> Result<Vec<Property>, DispatchError> {1265 let properties = Self::collection_properties(collection_id);12661267 let properties = keys1268 .map(|keys| {1269 keys.into_iter()1270 .filter_map(|key| {1271 properties.get(&key).map(|value| Property {1272 key,1273 value: value.clone(),1274 })1275 })1276 .collect()1277 })1278 .unwrap_or_else(|| {1279 properties1280 .into_iter()1281 .map(|(key, value)| Property { key, value })1282 .collect()1283 });12841285 Ok(properties)1286 }12871288 /// Get property permissions according to given keys.1289 pub fn filter_property_permissions(1290 collection_id: CollectionId,1291 keys: Option<Vec<PropertyKey>>,1292 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1293 let permissions = Self::property_permissions(collection_id);12941295 let key_permissions = keys1296 .map(|keys| {1297 keys.into_iter()1298 .filter_map(|key| {1299 permissions1300 .get(&key)1301 .map(|permission| PropertyKeyPermission {1302 key,1303 permission: permission.clone(),1304 })1305 })1306 .collect()1307 })1308 .unwrap_or_else(|| {1309 permissions1310 .into_iter()1311 .map(|(key, permission)| PropertyKeyPermission { key, permission })1312 .collect()1313 });13141315 Ok(key_permissions)1316 }13171318 /// Toggle `user` participation in the `collection`'s allow list.1319 /// #### Store read/writes1320 /// 1 writes1321 pub fn toggle_allowlist(1322 collection: &CollectionHandle<T>,1323 sender: &T::CrossAccountId,1324 user: &T::CrossAccountId,1325 allowed: bool,1326 ) -> DispatchResult {1327 collection.check_is_owner_or_admin(sender)?;13281329 // =========13301331 if allowed {1332 <Allowlist<T>>::insert((collection.id, user), true);1333 } else {1334 <Allowlist<T>>::remove((collection.id, user));1335 }13361337 Ok(())1338 }13391340 /// Toggle `user` participation in the `collection`'s admin list.1341 /// #### Store read/writes1342 /// 2 writes1343 pub fn toggle_admin(1344 collection: &CollectionHandle<T>,1345 sender: &T::CrossAccountId,1346 user: &T::CrossAccountId,1347 admin: bool,1348 ) -> DispatchResult {1349 collection.check_is_owner(sender)?;13501351 let was_admin = <IsAdmin<T>>::get((collection.id, user));1352 if was_admin == admin {1353 return Ok(());1354 }1355 let amount = <AdminAmount<T>>::get(collection.id);13561357 if admin {1358 let amount = amount1359 .checked_add(1)1360 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1361 ensure!(1362 amount <= Self::collection_admins_limit(),1363 <Error<T>>::CollectionAdminCountExceeded,1364 );13651366 // =========13671368 <AdminAmount<T>>::insert(collection.id, amount);1369 <IsAdmin<T>>::insert((collection.id, user), true);1370 } else {1371 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1372 <IsAdmin<T>>::remove((collection.id, user));1373 }13741375 Ok(())1376 }13771378 /// Merge set fields from `new_limit` to `old_limit`.1379 pub fn clamp_limits(1380 mode: CollectionMode,1381 old_limit: &CollectionLimits,1382 mut new_limit: CollectionLimits,1383 ) -> Result<CollectionLimits, DispatchError> {1384 let limits = old_limit;1385 limit_default!(old_limit, new_limit,1386 account_token_ownership_limit => ensure!(1387 new_limit <= MAX_TOKEN_OWNERSHIP,1388 <Error<T>>::CollectionLimitBoundsExceeded,1389 ),1390 sponsored_data_size => ensure!(1391 new_limit <= CUSTOM_DATA_LIMIT,1392 <Error<T>>::CollectionLimitBoundsExceeded,1393 ),13941395 sponsored_data_rate_limit => {},1396 token_limit => ensure!(1397 old_limit >= new_limit && new_limit > 0,1398 <Error<T>>::CollectionTokenLimitExceeded1399 ),14001401 sponsor_transfer_timeout(match mode {1402 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1403 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1404 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1405 }) => ensure!(1406 new_limit <= MAX_SPONSOR_TIMEOUT,1407 <Error<T>>::CollectionLimitBoundsExceeded,1408 ),1409 sponsor_approve_timeout => {},1410 owner_can_transfer => ensure!(1411 !limits.owner_can_transfer_instaled() ||1412 old_limit || !new_limit,1413 <Error<T>>::OwnerPermissionsCantBeReverted,1414 ),1415 owner_can_destroy => ensure!(1416 old_limit || !new_limit,1417 <Error<T>>::OwnerPermissionsCantBeReverted,1418 ),1419 transfers_enabled => {},1420 );1421 Ok(new_limit)1422 }14231424 /// Merge set fields from `new_permission` to `old_permission`.1425 pub fn clamp_permissions(1426 _mode: CollectionMode,1427 old_permission: &CollectionPermissions,1428 mut new_permission: CollectionPermissions,1429 ) -> Result<CollectionPermissions, DispatchError> {1430 limit_default_clone!(old_permission, new_permission,1431 access => {},1432 mint_mode => {},1433 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1434 );1435 Ok(new_permission)1436 }1437}14381439/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1440#[macro_export]1441macro_rules! unsupported {1442 ($runtime:path) => {1443 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1444 };1445}14461447/// Return weights for various worst-case operations.1448pub trait CommonWeightInfo<CrossAccountId> {1449 /// Weight of item creation.1450 fn create_item() -> Weight;14511452 /// Weight of items creation.1453 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14541455 /// Weight of items creation.1456 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14571458 /// The weight of the burning item.1459 fn burn_item() -> Weight;14601461 /// Property setting weight.1462 ///1463 /// * `amount`- The number of properties to set.1464 fn set_collection_properties(amount: u32) -> Weight;14651466 /// Collection property deletion weight.1467 ///1468 /// * `amount`- The number of properties to set.1469 fn delete_collection_properties(amount: u32) -> Weight;14701471 /// Token property setting weight.1472 ///1473 /// * `amount`- The number of properties to set.1474 fn set_token_properties(amount: u32) -> Weight;14751476 /// Token property deletion weight.1477 ///1478 /// * `amount`- The number of properties to delete.1479 fn delete_token_properties(amount: u32) -> Weight;14801481 /// Token property permissions set weight.1482 ///1483 /// * `amount`- The number of property permissions to set.1484 fn set_token_property_permissions(amount: u32) -> Weight;14851486 /// Transfer price of the token or its parts.1487 fn transfer() -> Weight;14881489 /// The price of setting the permission of the operation from another user.1490 fn approve() -> Weight;14911492 /// Transfer price from another user.1493 fn transfer_from() -> Weight;14941495 /// The price of burning a token from another user.1496 fn burn_from() -> Weight;14971498 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1499 /// whole users's balance.1500 ///1501 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1502 fn burn_recursively_self_raw() -> Weight;15031504 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1505 ///1506 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1507 fn burn_recursively_breadth_raw(amount: u32) -> Weight;15081509 /// The price of recursive burning a token.1510 ///1511 /// `max_selfs` - The maximum burning weight of the token itself.1512 /// `max_breadth` - The maximum number of nested tokens to burn.1513 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1514 Self::burn_recursively_self_raw()1515 .saturating_mul(max_selfs.max(1) as u64)1516 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1517 }15181519 /// The price of retrieving token owner1520 fn token_owner() -> Weight;1521}15221523/// Weight info extension trait for refungible pallet.1524pub trait RefungibleExtensionsWeightInfo {1525 /// Weight of token repartition.1526 fn repartition() -> Weight;1527}15281529/// Common collection operations.1530///1531/// It wraps methods in Fungible, Nonfungible and Refungible pallets1532/// and adds weight info.1533pub trait CommonCollectionOperations<T: Config> {1534 /// Create token.1535 ///1536 /// * `sender` - The user who mint the token and pays for the transaction.1537 /// * `to` - The user who will own the token.1538 /// * `data` - Token data.1539 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1540 fn create_item(1541 &self,1542 sender: T::CrossAccountId,1543 to: T::CrossAccountId,1544 data: CreateItemData,1545 nesting_budget: &dyn Budget,1546 ) -> DispatchResultWithPostInfo;15471548 /// Create multiple tokens.1549 ///1550 /// * `sender` - The user who mint the token and pays for the transaction.1551 /// * `to` - The user who will own the token.1552 /// * `data` - Token data.1553 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1554 fn create_multiple_items(1555 &self,1556 sender: T::CrossAccountId,1557 to: T::CrossAccountId,1558 data: Vec<CreateItemData>,1559 nesting_budget: &dyn Budget,1560 ) -> DispatchResultWithPostInfo;15611562 /// Create multiple tokens.1563 ///1564 /// * `sender` - The user who mint the token and pays for the transaction.1565 /// * `to` - The user who will own the token.1566 /// * `data` - Token data.1567 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1568 fn create_multiple_items_ex(1569 &self,1570 sender: T::CrossAccountId,1571 data: CreateItemExData<T::CrossAccountId>,1572 nesting_budget: &dyn Budget,1573 ) -> DispatchResultWithPostInfo;15741575 /// Burn token.1576 ///1577 /// * `sender` - The user who owns the token.1578 /// * `token` - Token id that will burned.1579 /// * `amount` - The number of parts of the token that will be burned.1580 fn burn_item(1581 &self,1582 sender: T::CrossAccountId,1583 token: TokenId,1584 amount: u128,1585 ) -> DispatchResultWithPostInfo;15861587 /// Burn token and all nested tokens recursievly.1588 ///1589 /// * `sender` - The user who owns the token.1590 /// * `token` - Token id that will burned.1591 /// * `self_budget` - The budget that can be spent on burning tokens.1592 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1593 fn burn_item_recursively(1594 &self,1595 sender: T::CrossAccountId,1596 token: TokenId,1597 self_budget: &dyn Budget,1598 breadth_budget: &dyn Budget,1599 ) -> DispatchResultWithPostInfo;16001601 /// Set collection properties.1602 ///1603 /// * `sender` - Must be either the owner of the collection or its admin.1604 /// * `properties` - Properties to be set.1605 fn set_collection_properties(1606 &self,1607 sender: T::CrossAccountId,1608 properties: Vec<Property>,1609 ) -> DispatchResultWithPostInfo;16101611 /// Delete collection properties.1612 ///1613 /// * `sender` - Must be either the owner of the collection or its admin.1614 /// * `properties` - The properties to be removed.1615 fn delete_collection_properties(1616 &self,1617 sender: &T::CrossAccountId,1618 property_keys: Vec<PropertyKey>,1619 ) -> DispatchResultWithPostInfo;16201621 /// Set token properties.1622 ///1623 /// The appropriate [`PropertyPermission`] for the token property1624 /// must be set with [`Self::set_token_property_permissions`].1625 ///1626 /// * `sender` - Must be either the owner of the token or its admin.1627 /// * `token_id` - The token for which the properties are being set.1628 /// * `properties` - Properties to be set.1629 /// * `budget` - Budget for setting properties.1630 fn set_token_properties(1631 &self,1632 sender: T::CrossAccountId,1633 token_id: TokenId,1634 properties: Vec<Property>,1635 budget: &dyn Budget,1636 ) -> DispatchResultWithPostInfo;16371638 /// Remove token properties.1639 ///1640 /// The appropriate [`PropertyPermission`] for the token property1641 /// must be set with [`Self::set_token_property_permissions`].1642 ///1643 /// * `sender` - Must be either the owner of the token or its admin.1644 /// * `token_id` - The token for which the properties are being remove.1645 /// * `property_keys` - Keys to remove corresponding properties.1646 /// * `budget` - Budget for removing properties.1647 fn delete_token_properties(1648 &self,1649 sender: T::CrossAccountId,1650 token_id: TokenId,1651 property_keys: Vec<PropertyKey>,1652 budget: &dyn Budget,1653 ) -> DispatchResultWithPostInfo;16541655 /// Set token property permissions.1656 ///1657 /// * `sender` - Must be either the owner of the token or its admin.1658 /// * `token_id` - The token for which the properties are being set.1659 /// * `property_permissions` - Property permissions to be set.1660 /// * `budget` - Budget for setting properties.1661 fn set_token_property_permissions(1662 &self,1663 sender: &T::CrossAccountId,1664 property_permissions: Vec<PropertyKeyPermission>,1665 ) -> DispatchResultWithPostInfo;16661667 /// Transfer amount of token pieces.1668 ///1669 /// * `sender` - Donor user.1670 /// * `to` - Recepient user.1671 /// * `token` - The token of which parts are being sent.1672 /// * `amount` - The number of parts of the token that will be transferred.1673 /// * `budget` - The maximum budget that can be spent on the transfer.1674 fn transfer(1675 &self,1676 sender: T::CrossAccountId,1677 to: T::CrossAccountId,1678 token: TokenId,1679 amount: u128,1680 budget: &dyn Budget,1681 ) -> DispatchResultWithPostInfo;16821683 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1684 ///1685 /// * `sender` - The user who grants access to the token.1686 /// * `spender` - The user to whom the rights are granted.1687 /// * `token` - The token to which access is granted.1688 /// * `amount` - The amount of pieces that another user can dispose of.1689 fn approve(1690 &self,1691 sender: T::CrossAccountId,1692 spender: T::CrossAccountId,1693 token: TokenId,1694 amount: u128,1695 ) -> DispatchResultWithPostInfo;16961697 /// Send parts of a token owned by another user.1698 ///1699 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1700 ///1701 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1702 /// * `from` - The user who owns the token.1703 /// * `to` - Recepient user.1704 /// * `token` - The token of which parts are being sent.1705 /// * `amount` - The number of parts of the token that will be transferred.1706 /// * `budget` - The maximum budget that can be spent on the transfer.1707 fn transfer_from(1708 &self,1709 sender: T::CrossAccountId,1710 from: T::CrossAccountId,1711 to: T::CrossAccountId,1712 token: TokenId,1713 amount: u128,1714 budget: &dyn Budget,1715 ) -> DispatchResultWithPostInfo;17161717 /// Burn parts of a token owned by another user.1718 ///1719 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1720 ///1721 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1722 /// * `from` - The user who owns the token.1723 /// * `token` - The token of which parts are being sent.1724 /// * `amount` - The number of parts of the token that will be transferred.1725 /// * `budget` - The maximum budget that can be spent on the burn.1726 fn burn_from(1727 &self,1728 sender: T::CrossAccountId,1729 from: T::CrossAccountId,1730 token: TokenId,1731 amount: u128,1732 budget: &dyn Budget,1733 ) -> DispatchResultWithPostInfo;17341735 /// Check permission to nest token.1736 ///1737 /// * `sender` - The user who initiated the check.1738 /// * `from` - The token that is checked for embedding.1739 /// * `under` - Token under which to check.1740 /// * `budget` - The maximum budget that can be spent on the check.1741 fn check_nesting(1742 &self,1743 sender: T::CrossAccountId,1744 from: (CollectionId, TokenId),1745 under: TokenId,1746 budget: &dyn Budget,1747 ) -> DispatchResult;17481749 /// Nest one token into another.1750 ///1751 /// * `under` - Token holder.1752 /// * `to_nest` - Nested token.1753 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17541755 /// Unnest token.1756 ///1757 /// * `under` - Token holder.1758 /// * `to_nest` - Token to unnest.1759 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17601761 /// Get all user tokens.1762 ///1763 /// * `account` - Account for which you need to get tokens.1764 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17651766 /// Get all the tokens in the collection.1767 fn collection_tokens(&self) -> Vec<TokenId>;17681769 /// Check if the token exists.1770 ///1771 /// * `token` - Id token to check.1772 fn token_exists(&self, token: TokenId) -> bool;17731774 /// Get the id of the last minted token.1775 fn last_token_id(&self) -> TokenId;17761777 /// Get the owner of the token.1778 ///1779 /// * `token` - The token for which you need to find out the owner.1780 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17811782 /// Returns 10 tokens owners in no particular order.1783 ///1784 /// * `token` - The token for which you need to find out the owners.1785 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;17861787 /// Get the value of the token property by key.1788 ///1789 /// * `token` - Token with the property to get.1790 /// * `key` - Property name.1791 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17921793 /// Get a set of token properties by key vector.1794 ///1795 /// * `token` - Token with the property to get.1796 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1797 /// then all properties are returned.1798 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17991800 /// Amount of unique collection tokens1801 fn total_supply(&self) -> u32;18021803 /// Amount of different tokens account has.1804 ///1805 /// * `account` - The account for which need to get the balance.1806 fn account_balance(&self, account: T::CrossAccountId) -> u32;18071808 /// Amount of specific token account have.1809 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;18101811 /// Amount of token pieces1812 fn total_pieces(&self, token: TokenId) -> Option<u128>;18131814 /// Get the number of parts of the token that a trusted user can manage.1815 ///1816 /// * `sender` - Trusted user.1817 /// * `spender` - Owner of the token.1818 /// * `token` - The token for which to get the value.1819 fn allowance(1820 &self,1821 sender: T::CrossAccountId,1822 spender: T::CrossAccountId,1823 token: TokenId,1824 ) -> u128;18251826 /// Get extension for RFT collection.1827 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1828}18291830/// Extension for RFT collection.1831pub trait RefungibleExtensions<T>1832where1833 T: Config,1834{1835 /// Change the number of parts of the token.1836 ///1837 /// When the value changes down, this function is equivalent to burning parts of the token.1838 ///1839 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.1840 /// * `token` - The token for which you want to change the number of parts.1841 /// * `amount` - The new value of the parts of the token.1842 fn repartition(1843 &self,1844 sender: &T::CrossAccountId,1845 token: TokenId,1846 amount: u128,1847 ) -> DispatchResultWithPostInfo;1848}18491850/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1851///1852/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1853pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1854 let post_info = PostDispatchInfo {1855 actual_weight: Some(weight),1856 pays_fee: Pays::Yes,1857 };1858 match res {1859 Ok(()) => Ok(post_info),1860 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1861 }1862}18631864impl<T: Config> From<PropertiesError> for Error<T> {1865 fn from(error: PropertiesError) -> Self {1866 match error {1867 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1868 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1869 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1870 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1871 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1872 }1873 }1874}pallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -212,8 +212,9 @@
owner: T::CrossAccountId,
payer: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
+ flags: CollectionFlags,
) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, payer, data, CollectionFlags::default())
+ <PalletCommon<T>>::init_collection(owner, payer, data, flags)
}
/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.
pallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -18,7 +18,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -296,9 +296,9 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
- /// @dev EVM selector for this function is: 0x13af4035,
- /// or in textual repr: setOwner(address)
- function setOwner(address newOwner) public {
+ /// @dev EVM selector for this function is: 0x4f53e226,
+ /// or in textual repr: changeCollectionOwner(address)
+ function changeCollectionOwner(address newOwner) public {
require(false, stub_error);
newOwner;
dummy = 0;
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -55,7 +55,7 @@
owner,
CollectionMode::NFT,
|owner: T::CrossAccountId, data| {
- <Pallet<T>>::init_collection(owner.clone(), owner, data, true)
+ <Pallet<T>>::init_collection(owner.clone(), owner, data, Default::default())
},
NonfungibleHandle::cast,
)
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -33,16 +33,12 @@
use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_std::vec::Vec;
use pallet_common::{
- erc::{
- CommonEvmHandler, PrecompileResult, CollectionCall,
- static_property::{key, value as property_value},
- },
+ erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
CollectionHandle, CollectionPropertyPermissions,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::call;
use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
-use alloc::string::ToString;
use crate::{
AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,
@@ -194,7 +190,7 @@
}
#[derive(ToLog)]
-pub enum ERC721MintableEvents {
+pub enum ERC721UniqueMintableEvents {
#[allow(dead_code)]
MintingFinished {},
}
@@ -204,15 +200,17 @@
#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]
impl<T: Config> NonfungibleHandle<T> {
/// @notice A descriptive name for a collection of NFTs in this contract
- fn name(&self) -> Result<string> {
- Ok(decode_utf16(self.name.iter().copied())
- .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
- .collect::<string>())
+ /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ #[solidity(hide, rename_selector = "name")]
+ fn name_proxy(&self) -> Result<string> {
+ self.name()
}
/// @notice An abbreviated name for NFTs in this contract
- fn symbol(&self) -> Result<string> {
- Ok(string::from_utf8_lossy(&self.token_prefix).into())
+ /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ #[solidity(hide, rename_selector = "symbol")]
+ fn symbol_proxy(&self) -> Result<string> {
+ self.symbol()
}
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
@@ -228,35 +226,38 @@
fn token_uri(&self, token_id: uint256) -> Result<string> {
let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
- if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {
- if !url.is_empty() {
- return Ok(url);
+ match get_token_property(self, token_id_u32, &key::url()).as_deref() {
+ Err(_) | Ok("") => (),
+ Ok(url) => {
+ return Ok(url.into());
}
- } else if !is_erc721_metadata_compatible::<T>(self.id) {
- return Err("tokenURI not set".into());
- }
+ };
- if let Some(base_uri) =
+ let base_uri =
pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())
- {
- if !base_uri.is_empty() {
- let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {
+ .map(BoundedVec::into_inner)
+ .map(string::from_utf8)
+ .transpose()
+ .map_err(|e| {
Error::Revert(alloc::format!(
"Can not convert value \"baseURI\" to string with error \"{}\"",
e
))
})?;
- if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {
- if !suffix.is_empty() {
- return Ok(base_uri + suffix.as_str());
- }
- }
- return Ok(base_uri + token_id.to_string().as_str());
+ let base_uri = match base_uri.as_deref() {
+ None | Some("") => {
+ return Ok("".into());
}
- }
+ Some(base_uri) => base_uri.into(),
+ };
- Ok("".into())
+ Ok(
+ match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {
+ Err(_) | Ok("") => base_uri,
+ Ok(suffix) => base_uri + suffix,
+ },
+ )
}
}
@@ -427,19 +428,33 @@
}
/// @title ERC721 minting logic.
-#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]
+#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]
impl<T: Config> NonfungibleHandle<T> {
fn minting_finished(&self) -> Result<bool> {
Ok(false)
}
/// @notice Function to mint token.
+ /// @param to The new owner
+ /// @return uint256 The id of the newly minted token
+ #[weight(<SelfWeightOf<T>>::create_item())]
+ fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {
+ let token_id: uint256 = <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ .into();
+ self.mint_check_id(caller, to, token_id)?;
+ Ok(token_id)
+ }
+
+ /// @notice Function to mint token.
/// @dev `tokenId` should be obtained with `nextTokenId` method,
/// unlike standard, you can't specify it manually
/// @param to The new owner
/// @param tokenId ID of the minted NFT
+ #[solidity(hide, rename_selector = "mint")]
#[weight(<SelfWeightOf<T>>::create_item())]
- fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
+ fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
let token_id: u32 = token_id.try_into()?;
@@ -470,14 +485,34 @@
}
/// @notice Function to mint token with the given tokenUri.
+ /// @param to The new owner
+ /// @param tokenUri Token URI that would be stored in the NFT properties
+ /// @return uint256 The id of the newly minted token
+ #[solidity(rename_selector = "mintWithTokenURI")]
+ #[weight(<SelfWeightOf<T>>::create_item())]
+ fn mint_with_token_uri(
+ &mut self,
+ caller: caller,
+ to: address,
+ token_uri: string,
+ ) -> Result<uint256> {
+ let token_id: uint256 = <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ .into();
+ self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;
+ Ok(token_id)
+ }
+
+ /// @notice Function to mint token with the given tokenUri.
/// @dev `tokenId` should be obtained with `nextTokenId` method,
/// unlike standard, you can't specify it manually
/// @param to The new owner
/// @param tokenId ID of the minted NFT
/// @param tokenUri Token URI that would be stored in the NFT properties
- #[solidity(rename_selector = "mintWithTokenURI")]
+ #[solidity(hide, rename_selector = "mintWithTokenURI")]
#[weight(<SelfWeightOf<T>>::create_item())]
- fn mint_with_token_uri(
+ fn mint_with_token_uri_check_id(
&mut self,
caller: caller,
to: address,
@@ -550,17 +585,6 @@
Err("Property tokenURI not found".into())
}
-fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {
- if let Some(shema_name) =
- pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())
- {
- let shema_name = shema_name.into_inner();
- shema_name == property_value::ERC721_METADATA
- } else {
- false
- }
-}
-
fn get_token_permission<T: Config>(
collection_id: CollectionId,
key: &PropertyKey,
@@ -575,21 +599,23 @@
Error::Revert(alloc::format!("No permission for key {}", key))
})?;
Ok(a)
-}
-
-fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {
- if let Ok(token_property_permissions) =
- CollectionPropertyPermissions::<T>::try_get(collection_id)
- {
- return token_property_permissions.contains_key(key);
- }
-
- false
}
/// @title Unique extensions for ERC721.
#[solidity_interface(name = ERC721UniqueExtensions)]
impl<T: Config> NonfungibleHandle<T> {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ fn name(&self) -> Result<string> {
+ Ok(decode_utf16(self.name.iter().copied())
+ .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
+ .collect::<string>())
+ }
+
+ /// @notice An abbreviated name for NFTs in this contract
+ fn symbol(&self) -> Result<string> {
+ Ok(string::from_utf8_lossy(&self.token_prefix).into())
+ }
+
/// @notice Transfer ownership of an NFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid NFT.
@@ -642,6 +668,7 @@
/// should be obtained with `nextTokenId` method
/// @param to The new owner
/// @param tokenIds IDs of the minted NFTs
+ // #[solidity(hide)]
#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]
fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -678,7 +705,7 @@
/// numbers and first number should be obtained with `nextTokenId` method
/// @param to The new owner
/// @param tokens array of pairs of token ID and token URI for minted tokens
- #[solidity(rename_selector = "mintBulkWithTokenURI")]
+ #[solidity(/*hide,*/ rename_selector = "mintBulkWithTokenURI")]
#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]
fn mint_bulk_with_token_uri(
&mut self,
@@ -731,11 +758,11 @@
name = UniqueNFT,
is(
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
- ERC721Mintable,
+ ERC721UniqueMintable,
ERC721Burnable,
+ ERC721Metadata(if(this.flags.erc721metadata)),
Collection(via(common_mut returns CollectionHandle<T>)),
TokenProperties,
)
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -295,6 +295,7 @@
&mut self.0
}
}
+
impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {
fn recorder(&self) -> &SubstrateRecorder<T> {
self.0.recorder()
@@ -407,17 +408,9 @@
owner: T::CrossAccountId,
payer: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
- is_external: bool,
+ flags: CollectionFlags,
) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(
- owner,
- payer,
- data,
- CollectionFlags {
- external: is_external,
- ..Default::default()
- },
- )
+ <PalletCommon<T>>::init_collection(owner, payer, data, flags)
}
/// Destroy NFT collection
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
@@ -91,7 +91,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -369,9 +369,9 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
- /// @dev EVM selector for this function is: 0x13af4035,
- /// or in textual repr: setOwner(address)
- function setOwner(address newOwner) public {
+ /// @dev EVM selector for this function is: 0x4f53e226,
+ /// or in textual repr: changeCollectionOwner(address)
+ function changeCollectionOwner(address newOwner) public {
require(false, stub_error);
newOwner;
dummy = 0;
@@ -384,6 +384,49 @@
uint256 field_1;
}
+/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
+/// @dev See https://eips.ethereum.org/EIPS/eip-721
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+contract ERC721Metadata is Dummy, ERC165 {
+ // /// @notice A descriptive name for a collection of NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x06fdde03,
+ // /// or in textual repr: name()
+ // function name() public view returns (string memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return "";
+ // }
+
+ // /// @notice An abbreviated name for NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x95d89b41,
+ // /// or in textual repr: symbol()
+ // function symbol() public view returns (string memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return "";
+ // }
+
+ /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+ ///
+ /// @dev If the token has a `url` property and it is not empty, it is returned.
+ /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
+ /// If the collection property `baseURI` is empty or absent, return "" (empty string)
+ /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
+ /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
+ ///
+ /// @return token's const_metadata
+ /// @dev EVM selector for this function is: 0xc87b56dd,
+ /// or in textual repr: tokenURI(uint256)
+ function tokenURI(uint256 tokenId) public view returns (string memory) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return "";
+ }
+}
+
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
contract ERC721Burnable is Dummy, ERC165 {
@@ -401,13 +444,13 @@
}
/// @dev inlined interface
-contract ERC721MintableEvents {
+contract ERC721UniqueMintableEvents {
event MintingFinished();
}
/// @title ERC721 minting logic.
-/// @dev the ERC-165 identifier for this interface is 0x68ccfe89
-contract ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+/// @dev the ERC-165 identifier for this interface is 0x476ff149
+contract ERC721UniqueMintable is Dummy, ERC165, ERC721UniqueMintableEvents {
/// @dev EVM selector for this function is: 0x05d2035b,
/// or in textual repr: mintingFinished()
function mintingFinished() public view returns (bool) {
@@ -417,41 +460,63 @@
}
/// @notice Function to mint token.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted NFT
- /// @dev EVM selector for this function is: 0x40c10f19,
- /// or in textual repr: mint(address,uint256)
- function mint(address to, uint256 tokenId) public returns (bool) {
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x6a627842,
+ /// or in textual repr: mint(address)
+ function mint(address to) public returns (uint256) {
require(false, stub_error);
to;
- tokenId;
dummy = 0;
- return false;
+ return 0;
}
+ // /// @notice Function to mint token.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted NFT
+ // /// @dev EVM selector for this function is: 0x40c10f19,
+ // /// or in textual repr: mint(address,uint256)
+ // function mint(address to, uint256 tokenId) public returns (bool) {
+ // require(false, stub_error);
+ // to;
+ // tokenId;
+ // dummy = 0;
+ // return false;
+ // }
+
/// @notice Function to mint token with the given tokenUri.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted NFT
/// @param tokenUri Token URI that would be stored in the NFT properties
- /// @dev EVM selector for this function is: 0x50bb4e7f,
- /// or in textual repr: mintWithTokenURI(address,uint256,string)
- function mintWithTokenURI(
- address to,
- uint256 tokenId,
- string memory tokenUri
- ) public returns (bool) {
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x45c17782,
+ /// or in textual repr: mintWithTokenURI(address,string)
+ function mintWithTokenURI(address to, string memory tokenUri) public returns (uint256) {
require(false, stub_error);
to;
- tokenId;
tokenUri;
dummy = 0;
- return false;
+ return 0;
}
+ // /// @notice Function to mint token with the given tokenUri.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted NFT
+ // /// @param tokenUri Token URI that would be stored in the NFT properties
+ // /// @dev EVM selector for this function is: 0x50bb4e7f,
+ // /// or in textual repr: mintWithTokenURI(address,uint256,string)
+ // function mintWithTokenURI(address to, uint256 tokenId, string memory tokenUri) public returns (bool) {
+ // require(false, stub_error);
+ // to;
+ // tokenId;
+ // tokenUri;
+ // dummy = 0;
+ // return false;
+ // }
+
/// @dev Not implemented
/// @dev EVM selector for this function is: 0x7d64bcb4,
/// or in textual repr: finishMinting()
@@ -463,8 +528,26 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xd74d154f
+/// @dev the ERC-165 identifier for this interface is 0x4468500d
contract ERC721UniqueExtensions is Dummy, ERC165 {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ /// @dev EVM selector for this function is: 0x06fdde03,
+ /// or in textual repr: name()
+ function name() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ /// @notice An abbreviated name for NFTs in this contract
+ /// @dev EVM selector for this function is: 0x95d89b41,
+ /// or in textual repr: symbol()
+ function symbol() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
/// @notice Transfer ownership of an NFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid NFT.
@@ -525,7 +608,7 @@
/// @param tokens array of pairs of token ID and token URI for minted tokens
/// @dev EVM selector for this function is: 0x36543006,
/// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) public returns (bool) {
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) public returns (bool) {
require(false, stub_error);
to;
tokens;
@@ -535,7 +618,7 @@
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
uint256 field_0;
string field_1;
}
@@ -579,48 +662,7 @@
return 0;
}
}
-
-/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
-/// @dev See https://eips.ethereum.org/EIPS/eip-721
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-contract ERC721Metadata is Dummy, ERC165 {
- /// @notice A descriptive name for a collection of NFTs in this contract
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- /// @notice An abbreviated name for NFTs in this contract
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
- /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
- ///
- /// @dev If the token has a `url` property and it is not empty, it is returned.
- /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
- /// If the collection property `baseURI` is empty or absent, return "" (empty string)
- /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
- /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
- ///
- /// @return token's const_metadata
- /// @dev EVM selector for this function is: 0xc87b56dd,
- /// or in textual repr: tokenURI(uint256)
- function tokenURI(uint256 tokenId) public view returns (string memory) {
- require(false, stub_error);
- tokenId;
- dummy;
- return "";
- }
-}
-
/// @dev inlined interface
contract ERC721Events {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
@@ -766,11 +808,11 @@
Dummy,
ERC165,
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
- ERC721Mintable,
+ ERC721UniqueMintable,
ERC721Burnable,
+ ERC721Metadata,
Collection,
TokenProperties
{}
pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -1448,7 +1448,15 @@
data: CreateCollectionData<T::AccountId>,
properties: impl Iterator<Item = Property>,
) -> Result<CollectionId, DispatchError> {
- let collection_id = <PalletNft<T>>::init_collection(sender.clone(), sender, data, true);
+ let collection_id = <PalletNft<T>>::init_collection(
+ sender.clone(),
+ sender,
+ data,
+ up_data_structs::CollectionFlags {
+ external: true,
+ ..Default::default()
+ },
+ );
if let Err(DispatchError::Arithmetic(_)) = &collection_id {
return Err(<Error<T>>::NoAvailableCollectionId.into());
pallets/proxy-rmrk-equip/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-equip/src/lib.rs
+++ b/pallets/proxy-rmrk-equip/src/lib.rs
@@ -254,7 +254,10 @@
cross_sender.clone(),
cross_sender.clone(),
data,
- true,
+ up_data_structs::CollectionFlags {
+ external: true,
+ ..Default::default()
+ },
);
if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -21,19 +21,15 @@
extern crate alloc;
-use alloc::string::ToString;
use core::{
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
};
use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
-use frame_support::BoundedBTreeMap;
+use frame_support::{BoundedBTreeMap, BoundedVec};
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions,
- erc::{
- CommonEvmHandler, CollectionCall,
- static_property::{key, value as property_value},
- },
+ erc::{CommonEvmHandler, CollectionCall, static_property::key},
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
@@ -191,7 +187,7 @@
}
#[derive(ToLog)]
-pub enum ERC721MintableEvents {
+pub enum ERC721UniqueMintableEvents {
/// @dev Not supported
#[allow(dead_code)]
MintingFinished {},
@@ -199,16 +195,18 @@
#[solidity_interface(name = ERC721Metadata)]
impl<T: Config> RefungibleHandle<T> {
- /// @notice A descriptive name for a collection of RFTs in this contract
- fn name(&self) -> Result<string> {
- Ok(decode_utf16(self.name.iter().copied())
- .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
- .collect::<string>())
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ #[solidity(hide, rename_selector = "name")]
+ fn name_proxy(&self) -> Result<string> {
+ self.name()
}
- /// @notice An abbreviated name for RFTs in this contract
- fn symbol(&self) -> Result<string> {
- Ok(string::from_utf8_lossy(&self.token_prefix).into())
+ /// @notice An abbreviated name for NFTs in this contract
+ /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ #[solidity(hide, rename_selector = "symbol")]
+ fn symbol_proxy(&self) -> Result<string> {
+ self.symbol()
}
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
@@ -224,35 +222,38 @@
fn token_uri(&self, token_id: uint256) -> Result<string> {
let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
- if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {
- if !url.is_empty() {
- return Ok(url);
+ match get_token_property(self, token_id_u32, &key::url()).as_deref() {
+ Err(_) | Ok("") => (),
+ Ok(url) => {
+ return Ok(url.into());
}
- } else if !is_erc721_metadata_compatible::<T>(self.id) {
- return Err("tokenURI not set".into());
- }
+ };
- if let Some(base_uri) =
+ let base_uri =
pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())
- {
- if !base_uri.is_empty() {
- let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {
+ .map(BoundedVec::into_inner)
+ .map(string::from_utf8)
+ .transpose()
+ .map_err(|e| {
Error::Revert(alloc::format!(
"Can not convert value \"baseURI\" to string with error \"{}\"",
e
))
})?;
- if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {
- if !suffix.is_empty() {
- return Ok(base_uri + suffix.as_str());
- }
- }
- return Ok(base_uri + token_id.to_string().as_str());
+ let base_uri = match base_uri.as_deref() {
+ None | Some("") => {
+ return Ok("".into());
}
- }
+ Some(base_uri) => base_uri.into(),
+ };
- Ok("".into())
+ Ok(
+ match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {
+ Err(_) | Ok("") => base_uri,
+ Ok(suffix) => base_uri + suffix,
+ },
+ )
}
}
@@ -448,19 +449,33 @@
}
/// @title ERC721 minting logic.
-#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]
+#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]
impl<T: Config> RefungibleHandle<T> {
fn minting_finished(&self) -> Result<bool> {
Ok(false)
}
/// @notice Function to mint token.
+ /// @param to The new owner
+ /// @return uint256 The id of the newly minted token
+ #[weight(<SelfWeightOf<T>>::create_item())]
+ fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {
+ let token_id: uint256 = <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ .into();
+ self.mint_check_id(caller, to, token_id)?;
+ Ok(token_id)
+ }
+
+ /// @notice Function to mint token.
/// @dev `tokenId` should be obtained with `nextTokenId` method,
/// unlike standard, you can't specify it manually
/// @param to The new owner
/// @param tokenId ID of the minted RFT
+ #[solidity(hide, rename_selector = "mint")]
#[weight(<SelfWeightOf<T>>::create_item())]
- fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
+ fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
let token_id: u32 = token_id.try_into()?;
@@ -496,14 +511,34 @@
}
/// @notice Function to mint token with the given tokenUri.
+ /// @param to The new owner
+ /// @param tokenUri Token URI that would be stored in the NFT properties
+ /// @return uint256 The id of the newly minted token
+ #[solidity(rename_selector = "mintWithTokenURI")]
+ #[weight(<SelfWeightOf<T>>::create_item())]
+ fn mint_with_token_uri(
+ &mut self,
+ caller: caller,
+ to: address,
+ token_uri: string,
+ ) -> Result<uint256> {
+ let token_id: uint256 = <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ .into();
+ self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;
+ Ok(token_id)
+ }
+
+ /// @notice Function to mint token with the given tokenUri.
/// @dev `tokenId` should be obtained with `nextTokenId` method,
/// unlike standard, you can't specify it manually
/// @param to The new owner
/// @param tokenId ID of the minted RFT
/// @param tokenUri Token URI that would be stored in the RFT properties
- #[solidity(rename_selector = "mintWithTokenURI")]
+ #[solidity(hide, rename_selector = "mintWithTokenURI")]
#[weight(<SelfWeightOf<T>>::create_item())]
- fn mint_with_token_uri(
+ fn mint_with_token_uri_check_id(
&mut self,
caller: caller,
to: address,
@@ -578,17 +613,6 @@
Err("Property tokenURI not found".into())
}
-fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {
- if let Some(shema_name) =
- pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())
- {
- let shema_name = shema_name.into_inner();
- shema_name == property_value::ERC721_METADATA
- } else {
- false
- }
-}
-
fn get_token_permission<T: Config>(
collection_id: CollectionId,
key: &PropertyKey,
@@ -608,6 +632,18 @@
/// @title Unique extensions for ERC721.
#[solidity_interface(name = ERC721UniqueExtensions)]
impl<T: Config> RefungibleHandle<T> {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ fn name(&self) -> Result<string> {
+ Ok(decode_utf16(self.name.iter().copied())
+ .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
+ .collect::<string>())
+ }
+
+ /// @notice An abbreviated name for NFTs in this contract
+ fn symbol(&self) -> Result<string> {
+ Ok(string::from_utf8_lossy(&self.token_prefix).into())
+ }
+
/// @notice Transfer ownership of an RFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid RFT.
@@ -669,6 +705,7 @@
/// should be obtained with `nextTokenId` method
/// @param to The new owner
/// @param tokenIds IDs of the minted RFTs
+ // #[solidity(hide)]
#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]
fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -711,7 +748,7 @@
/// numbers and first number should be obtained with `nextTokenId` method
/// @param to The new owner
/// @param tokens array of pairs of token ID and token URI for minted tokens
- #[solidity(rename_selector = "mintBulkWithTokenURI")]
+ #[solidity(/*hide,*/ rename_selector = "mintBulkWithTokenURI")]
#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]
fn mint_bulk_with_token_uri(
&mut self,
@@ -780,11 +817,11 @@
name = UniqueRefungible,
is(
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
- ERC721Mintable,
+ ERC721UniqueMintable,
ERC721Burnable,
+ ERC721Metadata(if(this.flags.erc721metadata)),
Collection(via(common_mut returns CollectionHandle<T>)),
TokenProperties,
)
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -92,9 +92,11 @@
use codec::{Encode, Decode, MaxEncodedLen};
use core::ops::Deref;
+use derivative::Derivative;
use evm_coder::ToLog;
use frame_support::{
- BoundedVec, ensure, fail, storage::with_transaction, transactional, pallet_prelude::ConstU32,
+ BoundedBTreeMap, BoundedVec, ensure, fail, storage::with_transaction, transactional,
+ pallet_prelude::ConstU32,
};
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_evm_coder_substrate::WithRecorder;
@@ -113,8 +115,6 @@
MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,
PropertyScope, PropertyValue, TokenId, TrySetProperty,
};
-use frame_support::BoundedBTreeMap;
-use derivative::Derivative;
pub use pallet::*;
#[cfg(feature = "runtime-benchmarks")]
@@ -371,8 +371,9 @@
owner: T::CrossAccountId,
payer: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
+ flags: CollectionFlags,
) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, payer, data, CollectionFlags::default())
+ <PalletCommon<T>>::init_collection(owner, payer, data, flags)
}
/// Destroy RFT collection
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -91,7 +91,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -369,9 +369,9 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
- /// @dev EVM selector for this function is: 0x13af4035,
- /// or in textual repr: setOwner(address)
- function setOwner(address newOwner) public {
+ /// @dev EVM selector for this function is: 0x4f53e226,
+ /// or in textual repr: changeCollectionOwner(address)
+ function changeCollectionOwner(address newOwner) public {
require(false, stub_error);
newOwner;
dummy = 0;
@@ -384,6 +384,47 @@
uint256 field_1;
}
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+contract ERC721Metadata is Dummy, ERC165 {
+ // /// @notice A descriptive name for a collection of NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x06fdde03,
+ // /// or in textual repr: name()
+ // function name() public view returns (string memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return "";
+ // }
+
+ // /// @notice An abbreviated name for NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x95d89b41,
+ // /// or in textual repr: symbol()
+ // function symbol() public view returns (string memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return "";
+ // }
+
+ /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+ ///
+ /// @dev If the token has a `url` property and it is not empty, it is returned.
+ /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
+ /// If the collection property `baseURI` is empty or absent, return "" (empty string)
+ /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
+ /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
+ ///
+ /// @return token's const_metadata
+ /// @dev EVM selector for this function is: 0xc87b56dd,
+ /// or in textual repr: tokenURI(uint256)
+ function tokenURI(uint256 tokenId) public view returns (string memory) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return "";
+ }
+}
+
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
contract ERC721Burnable is Dummy, ERC165 {
@@ -401,13 +442,13 @@
}
/// @dev inlined interface
-contract ERC721MintableEvents {
+contract ERC721UniqueMintableEvents {
event MintingFinished();
}
/// @title ERC721 minting logic.
-/// @dev the ERC-165 identifier for this interface is 0x68ccfe89
-contract ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+/// @dev the ERC-165 identifier for this interface is 0x476ff149
+contract ERC721UniqueMintable is Dummy, ERC165, ERC721UniqueMintableEvents {
/// @dev EVM selector for this function is: 0x05d2035b,
/// or in textual repr: mintingFinished()
function mintingFinished() public view returns (bool) {
@@ -417,41 +458,63 @@
}
/// @notice Function to mint token.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted RFT
- /// @dev EVM selector for this function is: 0x40c10f19,
- /// or in textual repr: mint(address,uint256)
- function mint(address to, uint256 tokenId) public returns (bool) {
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x6a627842,
+ /// or in textual repr: mint(address)
+ function mint(address to) public returns (uint256) {
require(false, stub_error);
to;
- tokenId;
dummy = 0;
- return false;
+ return 0;
}
+ // /// @notice Function to mint token.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted RFT
+ // /// @dev EVM selector for this function is: 0x40c10f19,
+ // /// or in textual repr: mint(address,uint256)
+ // function mint(address to, uint256 tokenId) public returns (bool) {
+ // require(false, stub_error);
+ // to;
+ // tokenId;
+ // dummy = 0;
+ // return false;
+ // }
+
/// @notice Function to mint token with the given tokenUri.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted RFT
- /// @param tokenUri Token URI that would be stored in the RFT properties
- /// @dev EVM selector for this function is: 0x50bb4e7f,
- /// or in textual repr: mintWithTokenURI(address,uint256,string)
- function mintWithTokenURI(
- address to,
- uint256 tokenId,
- string memory tokenUri
- ) public returns (bool) {
+ /// @param tokenUri Token URI that would be stored in the NFT properties
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x45c17782,
+ /// or in textual repr: mintWithTokenURI(address,string)
+ function mintWithTokenURI(address to, string memory tokenUri) public returns (uint256) {
require(false, stub_error);
to;
- tokenId;
tokenUri;
dummy = 0;
- return false;
+ return 0;
}
+ // /// @notice Function to mint token with the given tokenUri.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted RFT
+ // /// @param tokenUri Token URI that would be stored in the RFT properties
+ // /// @dev EVM selector for this function is: 0x50bb4e7f,
+ // /// or in textual repr: mintWithTokenURI(address,uint256,string)
+ // function mintWithTokenURI(address to, uint256 tokenId, string memory tokenUri) public returns (bool) {
+ // require(false, stub_error);
+ // to;
+ // tokenId;
+ // tokenUri;
+ // dummy = 0;
+ // return false;
+ // }
+
/// @dev Not implemented
/// @dev EVM selector for this function is: 0x7d64bcb4,
/// or in textual repr: finishMinting()
@@ -463,8 +526,26 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x7c3bef89
+/// @dev the ERC-165 identifier for this interface is 0xef1eaacb
contract ERC721UniqueExtensions is Dummy, ERC165 {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ /// @dev EVM selector for this function is: 0x06fdde03,
+ /// or in textual repr: name()
+ function name() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ /// @notice An abbreviated name for NFTs in this contract
+ /// @dev EVM selector for this function is: 0x95d89b41,
+ /// or in textual repr: symbol()
+ function symbol() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
/// @notice Transfer ownership of an RFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid RFT.
@@ -527,7 +608,7 @@
/// @param tokens array of pairs of token ID and token URI for minted tokens
/// @dev EVM selector for this function is: 0x36543006,
/// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) public returns (bool) {
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) public returns (bool) {
require(false, stub_error);
to;
tokens;
@@ -549,7 +630,7 @@
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
uint256 field_0;
string field_1;
}
@@ -591,46 +672,7 @@
require(false, stub_error);
dummy;
return 0;
- }
-}
-
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-contract ERC721Metadata is Dummy, ERC165 {
- /// @notice A descriptive name for a collection of RFTs in this contract
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- /// @notice An abbreviated name for RFTs in this contract
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
}
-
- /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
- ///
- /// @dev If the token has a `url` property and it is not empty, it is returned.
- /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
- /// If the collection property `baseURI` is empty or absent, return "" (empty string)
- /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
- /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
- ///
- /// @return token's const_metadata
- /// @dev EVM selector for this function is: 0xc87b56dd,
- /// or in textual repr: tokenURI(uint256)
- function tokenURI(uint256 tokenId) public view returns (string memory) {
- require(false, stub_error);
- tokenId;
- dummy;
- return "";
- }
}
/// @dev inlined interface
@@ -776,11 +818,11 @@
Dummy,
ERC165,
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
- ERC721Mintable,
+ ERC721UniqueMintable,
ERC721Burnable,
+ ERC721Metadata,
Collection,
TokenProperties
{}
pallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -25,14 +25,16 @@
dispatch::CollectionDispatch,
erc::{
CollectionHelpersEvents,
- static_property::{key, value as property_value},
+ static_property::{key},
},
+ Pallet as PalletCommon,
};
use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};
use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
+use sp_std::vec;
use up_data_structs::{
CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,
- CollectionMode, PropertyValue,
+ CollectionMode, PropertyValue, CollectionFlags,
};
use crate::{Config, SelfWeightOf, weights::WeightInfo};
@@ -57,13 +59,11 @@
name: string,
description: string,
token_prefix: string,
- base_uri: string,
) -> Result<(
T::CrossAccountId,
CollectionName,
CollectionDescription,
CollectionTokenPrefix,
- PropertyValue,
)> {
let caller = T::CrossAccountId::from_eth(caller);
let name = name
@@ -81,75 +81,7 @@
let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {
error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())
})?;
- let base_uri_value = base_uri
- .into_bytes()
- .try_into()
- .map_err(|_| error_field_too_long(stringify!(token_prefix), PropertyValue::bound()))?;
- Ok((caller, name, description, token_prefix, base_uri_value))
-}
-
-fn make_data<T: Config>(
- name: CollectionName,
- mode: CollectionMode,
- description: CollectionDescription,
- token_prefix: CollectionTokenPrefix,
- base_uri_value: PropertyValue,
- add_properties: bool,
-) -> Result<CreateCollectionData<T::AccountId>> {
- let mut properties = up_data_structs::CollectionPropertiesVec::default();
- let mut token_property_permissions =
- up_data_structs::CollectionPropertiesPermissionsVec::default();
-
- token_property_permissions
- .try_push(up_data_structs::PropertyKeyPermission {
- key: key::url(),
- permission: up_data_structs::PropertyPermission {
- mutable: false,
- collection_admin: true,
- token_owner: false,
- },
- })
- .map_err(|e| Error::Revert(format!("{:?}", e)))?;
-
- if add_properties {
- token_property_permissions
- .try_push(up_data_structs::PropertyKeyPermission {
- key: key::suffix(),
- permission: up_data_structs::PropertyPermission {
- mutable: false,
- collection_admin: true,
- token_owner: false,
- },
- })
- .map_err(|e| Error::Revert(format!("{:?}", e)))?;
-
- properties
- .try_push(up_data_structs::Property {
- key: key::schema_name(),
- value: property_value::erc721(),
- })
- .map_err(|e| Error::Revert(format!("{:?}", e)))?;
-
- if !base_uri_value.is_empty() {
- properties
- .try_push(up_data_structs::Property {
- key: key::base_uri(),
- value: base_uri_value,
- })
- .map_err(|e| Error::Revert(format!("{:?}", e)))?;
- }
- }
-
- let data = CreateCollectionData {
- name,
- mode,
- description,
- token_prefix,
- token_property_permissions,
- properties,
- ..Default::default()
- };
- Ok(data)
+ Ok((caller, name, description, token_prefix))
}
fn create_refungible_collection_internal<
@@ -160,26 +92,27 @@
name: string,
description: string,
token_prefix: string,
- base_uri: string,
- add_properties: bool,
) -> Result<address> {
- let (caller, name, description, token_prefix, base_uri_value) =
- convert_data::<T>(caller, name, description, token_prefix, base_uri)?;
- let data = make_data::<T>(
+ let (caller, name, description, token_prefix) =
+ convert_data::<T>(caller, name, description, token_prefix)?;
+ let data = CreateCollectionData {
name,
- CollectionMode::ReFungible,
+ mode: CollectionMode::ReFungible,
description,
token_prefix,
- base_uri_value,
- add_properties,
- )?;
+ ..Default::default()
+ };
check_sent_amount_equals_collection_creation_price::<T>(value)?;
let collection_helpers_address =
T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id =
- T::CollectionDispatch::create(caller.clone(), collection_helpers_address, data)
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ let collection_id = T::CollectionDispatch::create(
+ caller.clone(),
+ collection_helpers_address,
+ data,
+ Default::default(),
+ )
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
}
@@ -212,7 +145,8 @@
/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
/// @return address Address of the newly created collection
#[weight(<SelfWeightOf<T>>::create_collection())]
- fn create_nonfungible_collection(
+ #[solidity(rename_selector = "createNFTCollection")]
+ fn create_nft_collection(
&mut self,
caller: caller,
value: value,
@@ -220,60 +154,51 @@
description: string,
token_prefix: string,
) -> Result<address> {
- let (caller, name, description, token_prefix, _base_uri_value) =
- convert_data::<T>(caller, name, description, token_prefix, "".into())?;
- let data = make_data::<T>(
+ let (caller, name, description, token_prefix) =
+ convert_data::<T>(caller, name, description, token_prefix)?;
+ let data = CreateCollectionData {
name,
- CollectionMode::NFT,
+ mode: CollectionMode::NFT,
description,
token_prefix,
- Default::default(),
- false,
- )?;
+ ..Default::default()
+ };
check_sent_amount_equals_collection_creation_price::<T>(value)?;
let collection_helpers_address =
T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
- .map_err(dispatch_to_evm::<T>)?;
+ let collection_id = T::CollectionDispatch::create(
+ caller,
+ collection_helpers_address,
+ data,
+ Default::default(),
+ )
+ .map_err(dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
}
-
+ /// Create an NFT collection
+ /// @param name Name of the collection
+ /// @param description Informative description of the collection
+ /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
+ /// @return address Address of the newly created collection
#[weight(<SelfWeightOf<T>>::create_collection())]
- #[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]
- fn create_nonfungible_collection_with_properties(
+ #[deprecated(note = "mathod was renamed to `create_nft_collection`, prefer it instead")]
+ #[solidity(hide)]
+ fn create_nonfungible_collection(
&mut self,
caller: caller,
value: value,
name: string,
description: string,
token_prefix: string,
- base_uri: string,
) -> Result<address> {
- let (caller, name, description, token_prefix, base_uri_value) =
- convert_data::<T>(caller, name, description, token_prefix, base_uri)?;
- let data = make_data::<T>(
- name,
- CollectionMode::NFT,
- description,
- token_prefix,
- base_uri_value,
- true,
- )?;
- check_sent_amount_equals_collection_creation_price::<T>(value)?;
- let collection_helpers_address =
- T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
-
- let address = pallet_common::eth::collection_id_to_address(collection_id);
- Ok(address)
+ self.create_nft_collection(caller, value, name, description, token_prefix)
}
#[weight(<SelfWeightOf<T>>::create_collection())]
#[solidity(rename_selector = "createRFTCollection")]
- fn create_refungible_collection(
+ fn create_rft_collection(
&mut self,
caller: caller,
value: value,
@@ -281,37 +206,94 @@
description: string,
token_prefix: string,
) -> Result<address> {
- create_refungible_collection_internal::<T>(
- caller,
- value,
- name,
- description,
- token_prefix,
- Default::default(),
- false,
- )
+ create_refungible_collection_internal::<T>(caller, value, name, description, token_prefix)
}
- #[weight(<SelfWeightOf<T>>::create_collection())]
- #[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]
- fn create_refungible_collection_with_properties(
+ #[solidity(rename_selector = "makeCollectionERC721MetadataCompatible")]
+ fn make_collection_metadata_compatible(
&mut self,
caller: caller,
- value: value,
- name: string,
- description: string,
- token_prefix: string,
+ collection: address,
base_uri: string,
- ) -> Result<address> {
- create_refungible_collection_internal::<T>(
- caller,
- value,
- name,
- description,
- token_prefix,
- base_uri,
- true,
- )
+ ) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let collection =
+ pallet_common::eth::map_eth_to_id(&collection).ok_or("not a collection address")?;
+ let mut collection =
+ <crate::CollectionHandle<T>>::new(collection).ok_or("collection not found")?;
+
+ if !matches!(
+ collection.mode,
+ CollectionMode::NFT | CollectionMode::ReFungible
+ ) {
+ return Err("target collection should be either NFT or Refungible".into());
+ }
+
+ self.recorder().consume_sstore()?;
+ collection
+ .check_is_owner_or_admin(&caller)
+ .map_err(dispatch_to_evm::<T>)?;
+
+ if collection.flags.erc721metadata {
+ return Err("target collection is already Erc721Metadata compatible".into());
+ }
+ collection.flags.erc721metadata = true;
+
+ let all_permissions = <pallet_common::CollectionPropertyPermissions<T>>::get(collection.id);
+ if all_permissions.get(&key::url()).is_none() {
+ self.recorder().consume_sstore()?;
+ <PalletCommon<T>>::set_property_permission(
+ &collection,
+ &caller,
+ up_data_structs::PropertyKeyPermission {
+ key: key::url(),
+ permission: up_data_structs::PropertyPermission {
+ mutable: true,
+ collection_admin: true,
+ token_owner: false,
+ },
+ },
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+ }
+ if all_permissions.get(&key::suffix()).is_none() {
+ self.recorder().consume_sstore()?;
+ <PalletCommon<T>>::set_property_permission(
+ &collection,
+ &caller,
+ up_data_structs::PropertyKeyPermission {
+ key: key::suffix(),
+ permission: up_data_structs::PropertyPermission {
+ mutable: true,
+ collection_admin: true,
+ token_owner: false,
+ },
+ },
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+ }
+
+ let all_properties = <pallet_common::CollectionProperties<T>>::get(collection.id);
+ if all_properties.get(&key::base_uri()).is_none() && !base_uri.is_empty() {
+ self.recorder().consume_sstore()?;
+ <PalletCommon<T>>::set_collection_properties(
+ &collection,
+ &caller,
+ vec![up_data_structs::Property {
+ key: key::base_uri(),
+ value: base_uri
+ .into_bytes()
+ .try_into()
+ .map_err(|_| "base uri is too large")?,
+ }],
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+ }
+
+ self.recorder().consume_sstore()?;
+ collection.save().map_err(dispatch_to_evm::<T>)?;
+
+ Ok(())
}
/// Check if a collection exists
pallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -23,16 +23,16 @@
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0x5ad4f440
+/// @dev the ERC-165 identifier for this interface is 0x58918631
contract CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
/// Create an NFT collection
/// @param name Name of the collection
/// @param description Informative description of the collection
/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
/// @return address Address of the newly created collection
- /// @dev EVM selector for this function is: 0xe34a6844,
- /// or in textual repr: createNonfungibleCollection(string,string,string)
- function createNonfungibleCollection(
+ /// @dev EVM selector for this function is: 0x844af658,
+ /// or in textual repr: createNFTCollection(string,string,string)
+ function createNFTCollection(
string memory name,
string memory description,
string memory tokenPrefix
@@ -45,22 +45,21 @@
return 0x0000000000000000000000000000000000000000;
}
- /// @dev EVM selector for this function is: 0xa634a5f9,
- /// or in textual repr: createERC721MetadataCompatibleCollection(string,string,string,string)
- function createERC721MetadataCompatibleCollection(
- string memory name,
- string memory description,
- string memory tokenPrefix,
- string memory baseUri
- ) public payable returns (address) {
- require(false, stub_error);
- name;
- description;
- tokenPrefix;
- baseUri;
- dummy = 0;
- return 0x0000000000000000000000000000000000000000;
- }
+ // /// Create an NFT collection
+ // /// @param name Name of the collection
+ // /// @param description Informative description of the collection
+ // /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
+ // /// @return address Address of the newly created collection
+ // /// @dev EVM selector for this function is: 0xe34a6844,
+ // /// or in textual repr: createNonfungibleCollection(string,string,string)
+ // function createNonfungibleCollection(string memory name, string memory description, string memory tokenPrefix) public payable returns (address) {
+ // require(false, stub_error);
+ // name;
+ // description;
+ // tokenPrefix;
+ // dummy = 0;
+ // return 0x0000000000000000000000000000000000000000;
+ // }
/// @dev EVM selector for this function is: 0xab173450,
/// or in textual repr: createRFTCollection(string,string,string)
@@ -77,21 +76,13 @@
return 0x0000000000000000000000000000000000000000;
}
- /// @dev EVM selector for this function is: 0xa5596388,
- /// or in textual repr: createERC721MetadataCompatibleRFTCollection(string,string,string,string)
- function createERC721MetadataCompatibleRFTCollection(
- string memory name,
- string memory description,
- string memory tokenPrefix,
- string memory baseUri
- ) public payable returns (address) {
+ /// @dev EVM selector for this function is: 0x85624258,
+ /// or in textual repr: makeCollectionERC721MetadataCompatible(address,string)
+ function makeCollectionERC721MetadataCompatible(address collection, string memory baseUri) public {
require(false, stub_error);
- name;
- description;
- tokenPrefix;
+ collection;
baseUri;
dummy = 0;
- return 0x0000000000000000000000000000000000000000;
}
/// Check if a collection exists
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -345,7 +345,7 @@
// =========
let sender = T::CrossAccountId::from_sub(sender);
- let _id = T::CollectionDispatch::create(sender.clone(), sender, data)?;
+ let _id = T::CollectionDispatch::create(sender.clone(), sender, data, Default::default())?;
Ok(())
}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -365,11 +365,14 @@
/// Tokens in foreign collections can be transferred, but not burnt
#[bondrewd(bits = "0..1")]
pub foreign: bool,
+ /// Supports ERC721Metadata
+ #[bondrewd(bits = "1..2")]
+ pub erc721metadata: bool,
/// External collections can't be managed using `unique` api
#[bondrewd(bits = "7..8")]
pub external: bool,
- #[bondrewd(reserve, bits = "1..7")]
+ #[bondrewd(reserve, bits = "2..7")]
pub reserved: u8,
}
bondrewd_codec!(CollectionFlags);
@@ -434,6 +437,15 @@
pub meta_update_permission: MetaUpdatePermission,
}
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct RpcCollectionFlags {
+ /// Is collection is foreign.
+ pub foreign: bool,
+ /// Collection supports ERC721Metadata.
+ pub erc721metadata: bool,
+}
+
/// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).
#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
@@ -471,8 +483,8 @@
/// Is collection read only.
pub read_only: bool,
- /// Is collection is foreign.
- pub foreign: bool,
+ /// Extra collection flags
+ pub flags: RpcCollectionFlags,
}
/// Data used for create collection.
runtime/common/dispatch.rsdiffbeforeafterboth--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -31,7 +31,7 @@
};
use up_data_structs::{
CollectionMode, CreateCollectionData, MAX_DECIMAL_POINTS, mapping::TokenAddressMapping,
- CollectionId,
+ CollectionId, CollectionFlags,
};
#[cfg(not(feature = "refungible"))]
@@ -57,10 +57,11 @@
sender: T::CrossAccountId,
payer: T::CrossAccountId,
data: CreateCollectionData<T::AccountId>,
+ flags: CollectionFlags,
) -> Result<CollectionId, DispatchError> {
let id = match data.mode {
CollectionMode::NFT => {
- <PalletNonfungible<T>>::init_collection(sender, payer, data, false)?
+ <PalletNonfungible<T>>::init_collection(sender, payer, data, flags)?
}
CollectionMode::Fungible(decimal_points) => {
// check params
@@ -68,11 +69,13 @@
decimal_points <= MAX_DECIMAL_POINTS,
pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded
);
- <PalletFungible<T>>::init_collection(sender, payer, data)?
+ <PalletFungible<T>>::init_collection(sender, payer, data, flags)?
}
#[cfg(feature = "refungible")]
- CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, payer, data)?,
+ CollectionMode::ReFungible => {
+ <PalletRefungible<T>>::init_collection(sender, payer, data, flags)?
+ }
#[cfg(not(feature = "refungible"))]
CollectionMode::ReFungible => return unsupported!(T),
runtime/common/ethereum/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -24,7 +24,7 @@
use pallet_nonfungible::{
Config as NonfungibleConfig,
erc::{
- UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721MintableCall, ERC721Call,
+ UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721UniqueMintableCall, ERC721Call,
TokenPropertiesCall,
},
};
@@ -82,18 +82,17 @@
let token_id: TokenId = token_id.try_into().ok()?;
withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)
}
- UniqueNFTCall::ERC721Mintable(
- ERC721MintableCall::Mint { token_id, .. }
- | ERC721MintableCall::MintWithTokenUri { token_id, .. },
- ) => {
- let _token_id: TokenId = token_id.try_into().ok()?;
- withdraw_create_item::<T>(
- &collection,
- &who,
- &CreateItemData::NFT(CreateNftData::default()),
- )
- .map(|()| sponsor)
- }
+ UniqueNFTCall::ERC721UniqueMintable(
+ ERC721UniqueMintableCall::Mint { .. }
+ | ERC721UniqueMintableCall::MintCheckId { .. }
+ | ERC721UniqueMintableCall::MintWithTokenUri { .. }
+ | ERC721UniqueMintableCall::MintWithTokenUriCheckId { .. },
+ ) => withdraw_create_item::<T>(
+ &collection,
+ &who,
+ &CreateItemData::NFT(CreateNftData::default()),
+ )
+ .map(|()| sponsor),
UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, from, .. }) => {
let token_id: TokenId = token_id.try_into().ok()?;
let from = T::CrossAccountId::from_eth(from);
tests/src/eth/allowlist.test.tsdiffbeforeafterboth--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -78,7 +78,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const user = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
@@ -94,7 +94,7 @@
// const owner = await helper.eth.createAccountWithBalance(donor);
// const user = donor;
- // const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ // const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
// const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
// expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
@@ -110,7 +110,7 @@
const notOwner = await helper.eth.createAccountWithBalance(donor);
const user = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
@@ -129,7 +129,7 @@
// const notOwner = await helper.eth.createAccountWithBalance(donor);
// const user = donor;
- // const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ // const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
// const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
// expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
tests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -18,29 +18,29 @@
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0x5ad4f440
+/// @dev the ERC-165 identifier for this interface is 0x58918631
interface CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
/// Create an NFT collection
/// @param name Name of the collection
/// @param description Informative description of the collection
/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
/// @return address Address of the newly created collection
- /// @dev EVM selector for this function is: 0xe34a6844,
- /// or in textual repr: createNonfungibleCollection(string,string,string)
- function createNonfungibleCollection(
+ /// @dev EVM selector for this function is: 0x844af658,
+ /// or in textual repr: createNFTCollection(string,string,string)
+ function createNFTCollection(
string memory name,
string memory description,
string memory tokenPrefix
) external payable returns (address);
- /// @dev EVM selector for this function is: 0xa634a5f9,
- /// or in textual repr: createERC721MetadataCompatibleCollection(string,string,string,string)
- function createERC721MetadataCompatibleCollection(
- string memory name,
- string memory description,
- string memory tokenPrefix,
- string memory baseUri
- ) external payable returns (address);
+ // /// Create an NFT collection
+ // /// @param name Name of the collection
+ // /// @param description Informative description of the collection
+ // /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
+ // /// @return address Address of the newly created collection
+ // /// @dev EVM selector for this function is: 0xe34a6844,
+ // /// or in textual repr: createNonfungibleCollection(string,string,string)
+ // function createNonfungibleCollection(string memory name, string memory description, string memory tokenPrefix) external payable returns (address);
/// @dev EVM selector for this function is: 0xab173450,
/// or in textual repr: createRFTCollection(string,string,string)
@@ -50,14 +50,9 @@
string memory tokenPrefix
) external payable returns (address);
- /// @dev EVM selector for this function is: 0xa5596388,
- /// or in textual repr: createERC721MetadataCompatibleRFTCollection(string,string,string,string)
- function createERC721MetadataCompatibleRFTCollection(
- string memory name,
- string memory description,
- string memory tokenPrefix,
- string memory baseUri
- ) external payable returns (address);
+ /// @dev EVM selector for this function is: 0x85624258,
+ /// or in textual repr: makeCollectionERC721MetadataCompatible(address,string)
+ function makeCollectionERC721MetadataCompatible(address collection, string memory baseUri) external;
/// Check if a collection exists
/// @param collectionAddress Address of the collection in question
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -13,7 +13,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -194,9 +194,9 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
- /// @dev EVM selector for this function is: 0x13af4035,
- /// or in textual repr: setOwner(address)
- function setOwner(address newOwner) external;
+ /// @dev EVM selector for this function is: 0x4f53e226,
+ /// or in textual repr: changeCollectionOwner(address)
+ function changeCollectionOwner(address newOwner) external;
}
/// @dev the ERC-165 identifier for this interface is 0x63034ac5
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -62,7 +62,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -243,9 +243,9 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
- /// @dev EVM selector for this function is: 0x13af4035,
- /// or in textual repr: setOwner(address)
- function setOwner(address newOwner) external;
+ /// @dev EVM selector for this function is: 0x4f53e226,
+ /// or in textual repr: changeCollectionOwner(address)
+ function changeCollectionOwner(address newOwner) external;
}
/// @dev anonymous struct
@@ -254,6 +254,36 @@
uint256 field_1;
}
+/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
+/// @dev See https://eips.ethereum.org/EIPS/eip-721
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+interface ERC721Metadata is Dummy, ERC165 {
+ // /// @notice A descriptive name for a collection of NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x06fdde03,
+ // /// or in textual repr: name()
+ // function name() external view returns (string memory);
+
+ // /// @notice An abbreviated name for NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x95d89b41,
+ // /// or in textual repr: symbol()
+ // function symbol() external view returns (string memory);
+
+ /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+ ///
+ /// @dev If the token has a `url` property and it is not empty, it is returned.
+ /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
+ /// If the collection property `baseURI` is empty or absent, return "" (empty string)
+ /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
+ /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
+ ///
+ /// @return token's const_metadata
+ /// @dev EVM selector for this function is: 0xc87b56dd,
+ /// or in textual repr: tokenURI(uint256)
+ function tokenURI(uint256 tokenId) external view returns (string memory);
+}
+
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
interface ERC721Burnable is Dummy, ERC165 {
@@ -267,39 +297,50 @@
}
/// @dev inlined interface
-interface ERC721MintableEvents {
+interface ERC721UniqueMintableEvents {
event MintingFinished();
}
/// @title ERC721 minting logic.
-/// @dev the ERC-165 identifier for this interface is 0x68ccfe89
-interface ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+/// @dev the ERC-165 identifier for this interface is 0x476ff149
+interface ERC721UniqueMintable is Dummy, ERC165, ERC721UniqueMintableEvents {
/// @dev EVM selector for this function is: 0x05d2035b,
/// or in textual repr: mintingFinished()
function mintingFinished() external view returns (bool);
/// @notice Function to mint token.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted NFT
- /// @dev EVM selector for this function is: 0x40c10f19,
- /// or in textual repr: mint(address,uint256)
- function mint(address to, uint256 tokenId) external returns (bool);
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x6a627842,
+ /// or in textual repr: mint(address)
+ function mint(address to) external returns (uint256);
+
+ // /// @notice Function to mint token.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted NFT
+ // /// @dev EVM selector for this function is: 0x40c10f19,
+ // /// or in textual repr: mint(address,uint256)
+ // function mint(address to, uint256 tokenId) external returns (bool);
/// @notice Function to mint token with the given tokenUri.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted NFT
/// @param tokenUri Token URI that would be stored in the NFT properties
- /// @dev EVM selector for this function is: 0x50bb4e7f,
- /// or in textual repr: mintWithTokenURI(address,uint256,string)
- function mintWithTokenURI(
- address to,
- uint256 tokenId,
- string memory tokenUri
- ) external returns (bool);
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x45c17782,
+ /// or in textual repr: mintWithTokenURI(address,string)
+ function mintWithTokenURI(address to, string memory tokenUri) external returns (uint256);
+
+ // /// @notice Function to mint token with the given tokenUri.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted NFT
+ // /// @param tokenUri Token URI that would be stored in the NFT properties
+ // /// @dev EVM selector for this function is: 0x50bb4e7f,
+ // /// or in textual repr: mintWithTokenURI(address,uint256,string)
+ // function mintWithTokenURI(address to, uint256 tokenId, string memory tokenUri) external returns (bool);
/// @dev Not implemented
/// @dev EVM selector for this function is: 0x7d64bcb4,
@@ -308,8 +349,18 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xd74d154f
+/// @dev the ERC-165 identifier for this interface is 0x4468500d
interface ERC721UniqueExtensions is Dummy, ERC165 {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ /// @dev EVM selector for this function is: 0x06fdde03,
+ /// or in textual repr: name()
+ function name() external view returns (string memory);
+
+ /// @notice An abbreviated name for NFTs in this contract
+ /// @dev EVM selector for this function is: 0x95d89b41,
+ /// or in textual repr: symbol()
+ function symbol() external view returns (string memory);
+
/// @notice Transfer ownership of an NFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid NFT.
@@ -350,11 +401,11 @@
/// @param tokens array of pairs of token ID and token URI for minted tokens
/// @dev EVM selector for this function is: 0x36543006,
/// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) external returns (bool);
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) external returns (bool);
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
uint256 field_0;
string field_1;
}
@@ -384,34 +435,6 @@
function totalSupply() external view returns (uint256);
}
-/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
-/// @dev See https://eips.ethereum.org/EIPS/eip-721
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-interface ERC721Metadata is Dummy, ERC165 {
- /// @notice A descriptive name for a collection of NFTs in this contract
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() external view returns (string memory);
-
- /// @notice An abbreviated name for NFTs in this contract
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() external view returns (string memory);
-
- /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
- ///
- /// @dev If the token has a `url` property and it is not empty, it is returned.
- /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
- /// If the collection property `baseURI` is empty or absent, return "" (empty string)
- /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
- /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
- ///
- /// @return token's const_metadata
- /// @dev EVM selector for this function is: 0xc87b56dd,
- /// or in textual repr: tokenURI(uint256)
- function tokenURI(uint256 tokenId) external view returns (string memory);
-}
-
/// @dev inlined interface
interface ERC721Events {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
@@ -507,11 +530,11 @@
Dummy,
ERC165,
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
- ERC721Mintable,
+ ERC721UniqueMintable,
ERC721Burnable,
+ ERC721Metadata,
Collection,
TokenProperties
{}
tests/src/eth/api/UniqueRFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRFT.sol
+++ /dev/null
@@ -1,163 +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: 7d9262e6
-interface Collection is Dummy, ERC165 {
- // Set collection property.
- //
- // @param key Property key.
- // @param value Propery value.
- //
- // Selector: setCollectionProperty(string,bytes) 2f073f66
- function setCollectionProperty(string memory key, bytes memory value)
- external;
-
- // Delete collection property.
- //
- // @param key Property key.
- //
- // Selector: deleteCollectionProperty(string) 7b7debce
- function deleteCollectionProperty(string memory key) external;
-
- // Get collection property.
- //
- // @dev Throws error if key not found.
- //
- // @param key Property key.
- // @return bytes The property corresponding to the key.
- //
- // Selector: collectionProperty(string) cf24fd6d
- function collectionProperty(string memory key)
- external
- view
- returns (bytes memory);
-
- // Set the sponsor of the collection.
- //
- // @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
- //
- // @param sponsor Address of the sponsor from whose account funds will be debited for operations with the contract.
- //
- // Selector: setCollectionSponsor(address) 7623402e
- function setCollectionSponsor(address sponsor) external;
-
- // Collection sponsorship confirmation.
- //
- // @dev After setting the sponsor for the collection, it must be confirmed with this function.
- //
- // Selector: confirmCollectionSponsorship() 3c50e97a
- function confirmCollectionSponsorship() external;
-
- // Set limits for the collection.
- // @dev Throws error if limit not found.
- // @param limit Name of the limit. Valid names:
- // "accountTokenOwnershipLimit",
- // "sponsoredDataSize",
- // "sponsoredDataRateLimit",
- // "tokenLimit",
- // "sponsorTransferTimeout",
- // "sponsorApproveTimeout"
- // @param value Value of the limit.
- //
- // Selector: setCollectionLimit(string,uint32) 6a3841db
- function setCollectionLimit(string memory limit, uint32 value) external;
-
- // Set limits for the collection.
- // @dev Throws error if limit not found.
- // @param limit Name of the limit. Valid names:
- // "ownerCanTransfer",
- // "ownerCanDestroy",
- // "transfersEnabled"
- // @param value Value of the limit.
- //
- // Selector: setCollectionLimit(string,bool) 993b7fba
- function setCollectionLimit(string memory limit, bool value) external;
-
- // Get contract address.
- //
- // Selector: contractAddress() f6b4dfb4
- function contractAddress() external view returns (address);
-
- // Add collection admin by substrate address.
- // @param new_admin Substrate administrator address.
- //
- // Selector: addCollectionAdminSubstrate(uint256) 5730062b
- function addCollectionAdminSubstrate(uint256 newAdmin) external;
-
- // Remove collection admin by substrate address.
- // @param admin Substrate administrator address.
- //
- // Selector: removeCollectionAdminSubstrate(uint256) 4048fcf9
- function removeCollectionAdminSubstrate(uint256 admin) external;
-
- // Add collection admin.
- // @param new_admin Address of the added administrator.
- //
- // Selector: addCollectionAdmin(address) 92e462c7
- function addCollectionAdmin(address newAdmin) external;
-
- // Remove collection admin.
- //
- // @param new_admin Address of the removed administrator.
- //
- // Selector: removeCollectionAdmin(address) fafd7b42
- function removeCollectionAdmin(address admin) external;
-
- // Toggle accessibility of collection nesting.
- //
- // @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
- //
- // Selector: setCollectionNesting(bool) 112d4586
- function setCollectionNesting(bool enable) external;
-
- // Toggle accessibility of collection nesting.
- //
- // @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
- // @param collections Addresses of collections that will be available for nesting.
- //
- // Selector: setCollectionNesting(bool,address[]) 64872396
- function setCollectionNesting(bool enable, address[] memory collections)
- external;
-
- // Set the collection access method.
- // @param mode Access mode
- // 0 for Normal
- // 1 for AllowList
- //
- // Selector: setCollectionAccess(uint8) 41835d4c
- function setCollectionAccess(uint8 mode) external;
-
- // Add the user to the allowed list.
- //
- // @param user Address of a trusted user.
- //
- // Selector: addToCollectionAllowList(address) 67844fe6
- function addToCollectionAllowList(address user) external;
-
- // Remove the user from the allowed list.
- //
- // @param user Address of a removed user.
- //
- // Selector: removeFromCollectionAllowList(address) 85c51acb
- function removeFromCollectionAllowList(address user) external;
-
- // Switch permission for minting.
- //
- // @param mode Enable if "true".
- //
- // Selector: setCollectionMintMode(bool) 00018e84
- function setCollectionMintMode(bool mode) external;
-}
-
-interface UniqueRFT is Dummy, ERC165, Collection {}
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -62,7 +62,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -243,9 +243,9 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
- /// @dev EVM selector for this function is: 0x13af4035,
- /// or in textual repr: setOwner(address)
- function setOwner(address newOwner) external;
+ /// @dev EVM selector for this function is: 0x4f53e226,
+ /// or in textual repr: changeCollectionOwner(address)
+ function changeCollectionOwner(address newOwner) external;
}
/// @dev anonymous struct
@@ -254,6 +254,34 @@
uint256 field_1;
}
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+interface ERC721Metadata is Dummy, ERC165 {
+ // /// @notice A descriptive name for a collection of NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x06fdde03,
+ // /// or in textual repr: name()
+ // function name() external view returns (string memory);
+
+ // /// @notice An abbreviated name for NFTs in this contract
+ // /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+ // /// @dev EVM selector for this function is: 0x95d89b41,
+ // /// or in textual repr: symbol()
+ // function symbol() external view returns (string memory);
+
+ /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+ ///
+ /// @dev If the token has a `url` property and it is not empty, it is returned.
+ /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
+ /// If the collection property `baseURI` is empty or absent, return "" (empty string)
+ /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
+ /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
+ ///
+ /// @return token's const_metadata
+ /// @dev EVM selector for this function is: 0xc87b56dd,
+ /// or in textual repr: tokenURI(uint256)
+ function tokenURI(uint256 tokenId) external view returns (string memory);
+}
+
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
interface ERC721Burnable is Dummy, ERC165 {
@@ -267,40 +295,51 @@
}
/// @dev inlined interface
-interface ERC721MintableEvents {
+interface ERC721UniqueMintableEvents {
event MintingFinished();
}
/// @title ERC721 minting logic.
-/// @dev the ERC-165 identifier for this interface is 0x68ccfe89
-interface ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+/// @dev the ERC-165 identifier for this interface is 0x476ff149
+interface ERC721UniqueMintable is Dummy, ERC165, ERC721UniqueMintableEvents {
/// @dev EVM selector for this function is: 0x05d2035b,
/// or in textual repr: mintingFinished()
function mintingFinished() external view returns (bool);
/// @notice Function to mint token.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted RFT
- /// @dev EVM selector for this function is: 0x40c10f19,
- /// or in textual repr: mint(address,uint256)
- function mint(address to, uint256 tokenId) external returns (bool);
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x6a627842,
+ /// or in textual repr: mint(address)
+ function mint(address to) external returns (uint256);
+
+ // /// @notice Function to mint token.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted RFT
+ // /// @dev EVM selector for this function is: 0x40c10f19,
+ // /// or in textual repr: mint(address,uint256)
+ // function mint(address to, uint256 tokenId) external returns (bool);
/// @notice Function to mint token with the given tokenUri.
- /// @dev `tokenId` should be obtained with `nextTokenId` method,
- /// unlike standard, you can't specify it manually
/// @param to The new owner
- /// @param tokenId ID of the minted RFT
- /// @param tokenUri Token URI that would be stored in the RFT properties
- /// @dev EVM selector for this function is: 0x50bb4e7f,
- /// or in textual repr: mintWithTokenURI(address,uint256,string)
- function mintWithTokenURI(
- address to,
- uint256 tokenId,
- string memory tokenUri
- ) external returns (bool);
+ /// @param tokenUri Token URI that would be stored in the NFT properties
+ /// @return uint256 The id of the newly minted token
+ /// @dev EVM selector for this function is: 0x45c17782,
+ /// or in textual repr: mintWithTokenURI(address,string)
+ function mintWithTokenURI(address to, string memory tokenUri) external returns (uint256);
+ // /// @notice Function to mint token with the given tokenUri.
+ // /// @dev `tokenId` should be obtained with `nextTokenId` method,
+ // /// unlike standard, you can't specify it manually
+ // /// @param to The new owner
+ // /// @param tokenId ID of the minted RFT
+ // /// @param tokenUri Token URI that would be stored in the RFT properties
+ // /// @dev EVM selector for this function is: 0x50bb4e7f,
+ // /// or in textual repr: mintWithTokenURI(address,uint256,string)
+ // function mintWithTokenURI(address to, uint256 tokenId, string memory tokenUri) external returns (bool);
+
/// @dev Not implemented
/// @dev EVM selector for this function is: 0x7d64bcb4,
/// or in textual repr: finishMinting()
@@ -308,8 +347,18 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x7c3bef89
+/// @dev the ERC-165 identifier for this interface is 0xef1eaacb
interface ERC721UniqueExtensions is Dummy, ERC165 {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ /// @dev EVM selector for this function is: 0x06fdde03,
+ /// or in textual repr: name()
+ function name() external view returns (string memory);
+
+ /// @notice An abbreviated name for NFTs in this contract
+ /// @dev EVM selector for this function is: 0x95d89b41,
+ /// or in textual repr: symbol()
+ function symbol() external view returns (string memory);
+
/// @notice Transfer ownership of an RFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid RFT.
@@ -352,7 +401,7 @@
/// @param tokens array of pairs of token ID and token URI for minted tokens
/// @dev EVM selector for this function is: 0x36543006,
/// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) external returns (bool);
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) external returns (bool);
/// Returns EVM address for refungible token
///
@@ -363,7 +412,7 @@
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
uint256 field_0;
string field_1;
}
@@ -393,32 +442,6 @@
function totalSupply() external view returns (uint256);
}
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-interface ERC721Metadata is Dummy, ERC165 {
- /// @notice A descriptive name for a collection of RFTs in this contract
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() external view returns (string memory);
-
- /// @notice An abbreviated name for RFTs in this contract
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() external view returns (string memory);
-
- /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
- ///
- /// @dev If the token has a `url` property and it is not empty, it is returned.
- /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
- /// If the collection property `baseURI` is empty or absent, return "" (empty string)
- /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
- /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
- ///
- /// @return token's const_metadata
- /// @dev EVM selector for this function is: 0xc87b56dd,
- /// or in textual repr: tokenURI(uint256)
- function tokenURI(uint256 tokenId) external view returns (string memory);
-}
-
/// @dev inlined interface
interface ERC721Events {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
@@ -512,11 +535,11 @@
Dummy,
ERC165,
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
- ERC721Mintable,
+ ERC721UniqueMintable,
ERC721Burnable,
+ ERC721Metadata,
Collection,
TokenProperties
{}
tests/src/eth/base.test.tsdiffbeforeafterboth--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -23,7 +23,7 @@
describe('Contract calls', () => {
let donor: IKeyringPair;
- before(async function() {
+ before(async function () {
await usingEthPlaygrounds(async (_helper, privateKey) => {
donor = await privateKey({filename: __filename});
});
@@ -40,7 +40,12 @@
itEth('Balance transfer fee is less than 0.2 UNQ', async ({helper}) => {
const userA = await helper.eth.createAccountWithBalance(donor);
const userB = helper.eth.createAccount();
- const cost = await helper.eth.calculateFee({Ethereum: userA}, () => helper.getWeb3().eth.sendTransaction({from: userA, to: userB, value: '1000000', gas: helper.eth.DEFAULT_GAS}));
+ const cost = await helper.eth.calculateFee({Ethereum: userA}, () => helper.getWeb3().eth.sendTransaction({
+ from: userA,
+ to: userB,
+ value: '1000000',
+ gas: helper.eth.DEFAULT_GAS
+ }));
const balanceB = await helper.balance.getEthereum(userB);
expect(cost - balanceB < BigInt(0.2 * Number(helper.balance.getOneTokenNominal()))).to.be.true;
});
@@ -69,51 +74,59 @@
describe('ERC165 tests', async () => {
// https://eips.ethereum.org/EIPS/eip-165
- let collection: number;
+ let erc721MetadataCompatibleNftCollectionId: number;
+ let simpleNftCollectionId: number;
let minter: string;
- function contract(helper: EthUniqueHelper): Contract {
- return helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(collection), 'nft', minter);
+ const BASE_URI = 'base/';
+
+ async function checkInterface(helper: EthUniqueHelper, interfaceId: string, simpleResult: boolean, compatibleResult: boolean) {
+ const simple = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(simpleNftCollectionId), 'nft', minter);
+ const compatible = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(erc721MetadataCompatibleNftCollectionId), 'nft', minter);
+
+ expect(await simple.methods.supportsInterface(interfaceId).call()).to.equal(simpleResult, `empty (not ERC721Metadata compatible) NFT collection returns not ${simpleResult}`);
+ expect(await compatible.methods.supportsInterface(interfaceId).call()).to.equal(compatibleResult, `ERC721Metadata compatible NFT collection returns not ${compatibleResult}`);
}
before(async () => {
await usingEthPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({filename: __filename});
const [alice] = await helper.arrange.createAccounts([10n], donor);
- ({collectionId: collection} = await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'}));
+ ({collectionId: simpleNftCollectionId} = await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'}));
minter = helper.eth.createAccount();
+ ({collectionId: erc721MetadataCompatibleNftCollectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(minter, 'n', 'd', 'p', BASE_URI));
});
});
- itEth('interfaceID == 0xffffffff always false', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0xffffffff').call()).to.be.false;
+ itEth('nonexistent interfaceID - 0xffffffff - always false', async ({helper}) => {
+ await checkInterface(helper, '0xffffffff', false, false);
});
- itEth('ERC721 support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0x780e9d63').call()).to.be.true;
+ itEth('ERC721 - 0x780e9d63 - support', async ({helper}) => {
+ await checkInterface(helper, '0x780e9d63', true, true);
});
- itEth('ERC721Metadata support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0x5b5e139f').call()).to.be.true;
+ itEth('ERC721Metadata - 0x5b5e139f - support', async ({helper}) => {
+ await checkInterface(helper, '0x5b5e139f', false, true);
});
- itEth('ERC721Mintable support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0x68ccfe89').call()).to.be.true;
+ itEth('ERC721UniqueMintable - 0x476ff149 - support', async ({helper}) => {
+ await checkInterface(helper, '0x476ff149', true, true);
});
- itEth('ERC721Enumerable support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0x780e9d63').call()).to.be.true;
+ itEth('ERC721Enumerable - 0x780e9d63 - support', async ({helper}) => {
+ await checkInterface(helper, '0x780e9d63', true, true);
});
- itEth('ERC721UniqueExtensions support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0xd74d154f').call()).to.be.true;
+ itEth('ERC721UniqueExtensions - 0x4468500d - support', async ({helper}) => {
+ await checkInterface(helper, '0x4468500d', true, true);
});
- itEth('ERC721Burnable support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0x42966c68').call()).to.be.true;
+ itEth('ERC721Burnable - 0x42966c68 - support', async ({helper}) => {
+ await checkInterface(helper, '0x42966c68', true, true);
});
- itEth('ERC165 support', async ({helper}) => {
- expect(await contract(helper).methods.supportsInterface('0x01ffc9a7').call()).to.be.true;
+ itEth('ERC165 - 0x01ffc9a7 - support', async ({helper}) => {
+ await checkInterface(helper, '0x01ffc9a7', true, true);
});
});
tests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -38,7 +38,7 @@
itEth('Add admin by owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const newAdmin = helper.eth.createAccount();
@@ -51,7 +51,7 @@
itEth.skip('Add substrate admin by owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const [newAdmin] = await helper.arrange.createAccounts([10n], donor);
@@ -64,7 +64,7 @@
itEth('Verify owner or admin', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const newAdmin = helper.eth.createAccount();
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -75,7 +75,7 @@
itEth('(!negative tests!) Add admin by ADMIN is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const admin = await helper.eth.createAccountWithBalance(donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -93,7 +93,7 @@
itEth('(!negative tests!) Add admin by USER is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const notAdmin = await helper.eth.createAccountWithBalance(donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -108,7 +108,7 @@
itEth.skip('(!negative tests!) Add substrate admin by ADMIN is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const admin = await helper.eth.createAccountWithBalance(donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -126,7 +126,7 @@
itEth.skip('(!negative tests!) Add substrate admin by USER is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const notAdmin0 = await helper.eth.createAccountWithBalance(donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -150,7 +150,7 @@
itEth('Remove admin by owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const newAdmin = helper.eth.createAccount();
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -170,7 +170,7 @@
itEth.skip('Remove substrate admin by owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const [newAdmin] = await helper.arrange.createAccounts([10n], donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -188,7 +188,7 @@
itEth('(!negative tests!) Remove admin by ADMIN is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -210,7 +210,7 @@
itEth('(!negative tests!) Remove admin by USER is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -230,7 +230,7 @@
itEth.skip('(!negative tests!) Remove substrate admin by ADMIN is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const [adminSub] = await helper.arrange.createAccounts([10n], donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -250,7 +250,7 @@
itEth.skip('(!negative tests!) Remove substrate admin by USER is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const [adminSub] = await helper.arrange.createAccounts([10n], donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -279,10 +279,10 @@
itEth('Change owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const newOwner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- await collectionEvm.methods.setOwner(newOwner).send();
+ await collectionEvm.methods.changeCollectionOwner(newOwner).send();
expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.false;
expect(await collectionEvm.methods.isOwnerOrAdmin(newOwner).call()).to.be.true;
@@ -291,9 +291,9 @@
itEth('change owner call fee', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const newOwner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- const cost = await recordEthFee(helper, owner, () => collectionEvm.methods.setOwner(newOwner).send());
+ const cost = await recordEthFee(helper, owner, () => collectionEvm.methods.changeCollectionOwner(newOwner).send());
expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
expect(cost > 0);
});
@@ -301,10 +301,10 @@
itEth('(!negative tests!) call setOwner by non owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const newOwner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- await expect(collectionEvm.methods.setOwner(newOwner).send({from: newOwner})).to.be.rejected;
+ await expect(collectionEvm.methods.changeCollectionOwner(newOwner).send({from: newOwner})).to.be.rejected;
expect(await collectionEvm.methods.isOwnerOrAdmin(newOwner).call()).to.be.false;
});
});
@@ -321,7 +321,7 @@
itEth.skip('Change owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const [newOwner] = await helper.arrange.createAccounts([10n], donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.true;
@@ -336,7 +336,7 @@
itEth.skip('change owner call fee', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const [newOwner] = await helper.arrange.createAccounts([10n], donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const cost = await recordEthFee(helper, owner, () => collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send());
@@ -348,7 +348,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const otherReceiver = await helper.eth.createAccountWithBalance(donor);
const [newOwner] = await helper.arrange.createAccounts([10n], donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
await expect(collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send({from: otherReceiver})).to.be.rejected;
tests/src/eth/collectionHelpersAbi.jsondiffbeforeafterboth--- a/tests/src/eth/collectionHelpersAbi.json
+++ b/tests/src/eth/collectionHelpersAbi.json
@@ -29,33 +29,9 @@
"inputs": [
{ "internalType": "string", "name": "name", "type": "string" },
{ "internalType": "string", "name": "description", "type": "string" },
- { "internalType": "string", "name": "tokenPrefix", "type": "string" },
- { "internalType": "string", "name": "baseUri", "type": "string" }
- ],
- "name": "createERC721MetadataCompatibleCollection",
- "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
- "stateMutability": "payable",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "string", "name": "name", "type": "string" },
- { "internalType": "string", "name": "description", "type": "string" },
- { "internalType": "string", "name": "tokenPrefix", "type": "string" },
- { "internalType": "string", "name": "baseUri", "type": "string" }
- ],
- "name": "createERC721MetadataCompatibleRFTCollection",
- "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
- "stateMutability": "payable",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "string", "name": "name", "type": "string" },
- { "internalType": "string", "name": "description", "type": "string" },
{ "internalType": "string", "name": "tokenPrefix", "type": "string" }
],
- "name": "createNonfungibleCollection",
+ "name": "createNFTCollection",
"outputs": [{ "internalType": "address", "name": "", "type": "address" }],
"stateMutability": "payable",
"type": "function"
@@ -86,6 +62,16 @@
},
{
"inputs": [
+ { "internalType": "address", "name": "collection", "type": "address" },
+ { "internalType": "string", "name": "baseUri", "type": "string" }
+ ],
+ "name": "makeCollectionERC721MetadataCompatible",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
],
"name": "supportsInterface",
tests/src/eth/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionProperties.test.ts
+++ b/tests/src/eth/collectionProperties.test.ts
@@ -14,8 +14,11 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import {itEth, usingEthPlaygrounds, expect} from './util';
+import {itEth, usingEthPlaygrounds, expect, EthUniqueHelper} from './util';
+import {Pallets} from '../util';
+import {IProperty, ITokenPropertyPermission} from '../util/playgrounds/types';
import {IKeyringPair} from '@polkadot/types/types';
+import {Contract} from 'web3-eth-contract';
describe('EVM collection properties', () => {
let donor: IKeyringPair;
@@ -30,7 +33,7 @@
itEth('Can be set', async({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(alice, {name: 'name', description: 'test', tokenPrefix: 'test'});
+ const collection = await helper.nft.mintCollection(alice, {name: 'name', description: 'test', tokenPrefix: 'test', properties: []});
await collection.addAdmin(alice, {Ethereum: caller});
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
@@ -70,3 +73,92 @@
expect(value).to.equal(helper.getWeb3().utils.toHex('testValue'));
});
});
+
+describe('Supports ERC721Metadata', () => {
+ let donor: IKeyringPair;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (_helper, privateKey) => {
+ donor = await privateKey({filename: __filename});
+ });
+ });
+
+ const checkERC721Metadata = async (helper: EthUniqueHelper, mode: 'nft' | 'rft') => {
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const bruh = await helper.eth.createAccountWithBalance(donor);
+
+ const BASE_URI = 'base/'
+ const SUFFIX = 'suffix1'
+ const URI = 'uri1'
+
+ const collectionHelpers = helper.ethNativeContract.collectionHelpers(caller);
+ const creatorMethod = mode === 'rft' ? 'createRFTCollection' : 'createNFTCollection'
+
+ const {collectionId, collectionAddress} = await helper.eth[creatorMethod](caller, 'n', 'd', 'p')
+
+ const contract = helper.ethNativeContract.collectionById(collectionId, mode, caller);
+ await contract.methods.addCollectionAdmin(bruh).send(); // to check that admin will work too
+
+ const collection1 = await helper.nft.getCollectionObject(collectionId);
+ const data1 = await collection1.getData()
+ expect(data1?.raw.flags.erc721metadata).to.be.false;
+ expect(await contract.methods.supportsInterface('0x5b5e139f').call()).to.be.false;
+
+ await collectionHelpers.methods.makeCollectionERC721MetadataCompatible(collectionAddress, BASE_URI)
+ .send({from: bruh});
+
+ expect(await contract.methods.supportsInterface('0x5b5e139f').call()).to.be.true;
+
+ const collection2 = await helper.nft.getCollectionObject(collectionId);
+ const data2 = await collection2.getData()
+ expect(data2?.raw.flags.erc721metadata).to.be.true;
+
+ const TPPs = data2?.raw.tokenPropertyPermissions
+ expect(TPPs?.length).to.equal(2);
+
+ expect(TPPs.find((tpp: ITokenPropertyPermission) => {
+ return tpp.key === "URI" && tpp.permission.mutable && tpp.permission.collectionAdmin && !tpp.permission.tokenOwner
+ })).to.be.not.null
+
+ expect(TPPs.find((tpp: ITokenPropertyPermission) => {
+ return tpp.key === "URISuffix" && tpp.permission.mutable && tpp.permission.collectionAdmin && !tpp.permission.tokenOwner
+ })).to.be.not.null
+
+ expect(data2?.raw.properties?.find((property: IProperty) => {
+ return property.key === "baseURI" && property.value === BASE_URI
+ })).to.be.not.null
+
+ const token1Result = await contract.methods.mint(bruh).send();
+ const tokenId1 = token1Result.events.Transfer.returnValues.tokenId;
+
+ expect(await contract.methods.tokenURI(tokenId1).call()).to.equal(BASE_URI);
+
+ await contract.methods.setProperty(tokenId1, "URISuffix", Buffer.from(SUFFIX)).send();
+ expect(await contract.methods.tokenURI(tokenId1).call()).to.equal(BASE_URI + SUFFIX);
+
+ await contract.methods.setProperty(tokenId1, "URI", Buffer.from(URI)).send();
+ expect(await contract.methods.tokenURI(tokenId1).call()).to.equal(URI);
+
+ await contract.methods.deleteProperty(tokenId1, "URI").send();
+ expect(await contract.methods.tokenURI(tokenId1).call()).to.equal(BASE_URI + SUFFIX);
+
+ const token2Result = await contract.methods.mintWithTokenURI(bruh, URI).send();
+ const tokenId2 = token2Result.events.Transfer.returnValues.tokenId;
+
+ expect(await contract.methods.tokenURI(tokenId2).call()).to.equal(URI);
+
+ await contract.methods.deleteProperty(tokenId2, "URI").send();
+ expect(await contract.methods.tokenURI(tokenId2).call()).to.equal(BASE_URI);
+
+ await contract.methods.setProperty(tokenId2, "URISuffix", Buffer.from(SUFFIX)).send();
+ expect(await contract.methods.tokenURI(tokenId2).call()).to.equal(BASE_URI + SUFFIX);
+ }
+
+ itEth('ERC721Metadata property can be set for NFT collection', async({helper}) => {
+ await checkERC721Metadata(helper, 'nft');
+ });
+
+ itEth.ifWithPallets('ERC721Metadata property can be set for RFT collection', [Pallets.ReFungible], async({helper}) => {
+ await checkERC721Metadata(helper, 'rft');
+ });
+});
tests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -44,9 +44,8 @@
await collection.addToAllowList(alice, {Ethereum: minter});
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.equal('1');
- const result = await contract.methods.mint(minter, nextTokenId).send();
+ const result = await contract.methods.mint(minter).send();
+
const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
@@ -55,7 +54,7 @@
args: {
from: '0x0000000000000000000000000000000000000000',
to: minter,
- tokenId: nextTokenId,
+ tokenId: '1',
},
},
]);
@@ -65,7 +64,7 @@
// itWeb3('Set substrate sponsor', async ({api, web3, privateKeyWrapper}) => {
// const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
// const collectionHelpers = evmCollectionHelpers(web3, owner);
- // let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
+ // let result = await collectionHelpers.methods.createNFTCollection('Sponsor collection', '1', '1').send();
// const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
// const sponsor = privateKeyWrapper('//Alice');
// const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
@@ -73,11 +72,11 @@
// expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
// result = await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});
// expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
-
+
// const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);
// await submitTransactionAsync(sponsor, confirmTx);
// expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
-
+
// const sponsorTuple = await collectionEvm.methods.collectionSponsor().call({from: owner});
// expect(bigIntToSub(api, BigInt(sponsorTuple[1]))).to.be.eq(sponsor.address);
// });
@@ -86,7 +85,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
+ let result = await collectionHelpers.methods.createNFTCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const sponsor = await helper.eth.createAccountWithBalance(donor);
const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
@@ -94,28 +93,26 @@
expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
result = await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
-
+
await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
-
+
await collectionEvm.methods.removeCollectionSponsor().send({from: owner});
-
+
const sponsorTuple = await collectionEvm.methods.collectionSponsor().call({from: owner});
expect(sponsorTuple.field_0).to.be.eq('0x0000000000000000000000000000000000000000');
});
itEth('Sponsoring collection from evm address via access list', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
- const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
- const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
+ const {collectionId, collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Sponsor collection', '1', '1', '');
+
const collection = helper.nft.getCollectionObject(collectionId);
const sponsor = await helper.eth.createAccountWithBalance(donor);
- const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- result = await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
+ await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
let collectionData = (await collection.getData())!;
expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
@@ -144,23 +141,17 @@
const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
{
- const nextTokenId = await collectionEvm.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- const result = await collectionEvm.methods.mintWithTokenURI(
- user,
- nextTokenId,
- 'Test URI',
- ).send({from: user});
+ const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
- address: collectionIdAddress,
+ address: collectionAddress,
event: 'Transfer',
args: {
from: '0x0000000000000000000000000000000000000000',
to: user,
- tokenId: nextTokenId,
+ tokenId: '1',
},
},
]);
@@ -178,16 +169,16 @@
// itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {
// const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
// const collectionHelpers = evmCollectionHelpers(web3, owner);
- // const result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
+ // const result = await collectionHelpers.methods.createERC721MetadataCompatibleNFTCollection('Sponsor collection', '1', '1', '').send();
// const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
// const sponsor = privateKeyWrapper('//Alice');
// const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
// await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});
-
+
// const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);
// await submitTransactionAsync(sponsor, confirmTx);
-
+
// const user = createEthAccount(web3);
// const nextTokenId = await collectionEvm.methods.nextTokenId().call();
// expect(nextTokenId).to.be.equal('1');
@@ -232,39 +223,32 @@
itEth('Check that transaction via EVM spend money from sponsor address', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
- const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
- const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
+ const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner,'Sponsor collection', '1', '1', '');
const collection = helper.nft.getCollectionObject(collectionId);
const sponsor = await helper.eth.createAccountWithBalance(donor);
- const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- result = await collectionEvm.methods.setCollectionSponsor(sponsor).send();
+ await collectionEvm.methods.setCollectionSponsor(sponsor).send();
let collectionData = (await collection.getData())!;
expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
- const sponsorCollection = helper.ethNativeContract.collection(collectionIdAddress, 'nft', sponsor);
+ const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', sponsor);
await sponsorCollection.methods.confirmCollectionSponsorship().send();
collectionData = (await collection.getData())!;
expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
const user = helper.eth.createAccount();
await collectionEvm.methods.addCollectionAdmin(user).send();
-
+
const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
- const userCollectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', user);
- const nextTokenId = await userCollectionEvm.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- result = await userCollectionEvm.methods.mintWithTokenURI(
- user,
- nextTokenId,
- 'Test URI',
- ).send();
+ const userCollectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', user);
+
+ let result = await userCollectionEvm.methods.mintWithTokenURI(user, 'Test URI',).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const events = helper.eth.normalizeEvents(result.events);
const address = helper.ethAddress.fromCollectionId(collectionId);
@@ -276,12 +260,12 @@
args: {
from: '0x0000000000000000000000000000000000000000',
to: user,
- tokenId: nextTokenId,
+ tokenId: '1',
},
},
]);
- expect(await userCollectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
-
+ expect(await userCollectionEvm.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
+
const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
tests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -35,13 +35,49 @@
const description = 'Some description';
const prefix = 'token prefix';
- const {collectionId} = await helper.eth.createNonfungibleCollection(owner, name, description, prefix);
+ const {collectionId} = await helper.eth.createNFTCollection(owner, name, description, prefix);
const data = (await helper.rft.getData(collectionId))!;
+ const collection = helper.nft.getCollectionObject(collectionId);
+
+ expect(data.name).to.be.eq(name);
+ expect(data.description).to.be.eq(description);
+ expect(data.raw.tokenPrefix).to.be.eq(prefix);
+ expect(data.raw.mode).to.be.eq('NFT');
+
+ const options = await collection.getOptions();
+
+ expect(options.tokenPropertyPermissions).to.be.empty;
+ });
+
+ itEth('Create collection with properties', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const name = 'CollectionEVM';
+ const description = 'Some description';
+ const prefix = 'token prefix';
+ const baseUri = 'BaseURI';
+
+ const {collectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, name, description, prefix, baseUri);
+
+ const collection = helper.nft.getCollectionObject(collectionId);
+ const data = (await collection.getData())!;
expect(data.name).to.be.eq(name);
expect(data.description).to.be.eq(description);
expect(data.raw.tokenPrefix).to.be.eq(prefix);
expect(data.raw.mode).to.be.eq('NFT');
+
+ const options = await collection.getOptions();
+ expect(options.tokenPropertyPermissions).to.be.deep.equal([
+ {
+ key: 'URI',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ {
+ key: 'URISuffix',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ ]);
});
// this test will occasionally fail when in async environment.
@@ -57,7 +93,7 @@
.call()).to.be.false;
await collectionHelpers.methods
- .createNonfungibleCollection('A', 'A', 'A')
+ .createNFTCollection('A', 'A', 'A')
.send({value: Number(2n * helper.balance.getOneTokenNominal())});
expect(await collectionHelpers.methods
@@ -69,7 +105,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const sponsor = await helper.eth.createAccountWithBalance(donor);
const ss58Format = helper.chain.getChainProperties().ss58Format;
- const {collectionId, collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Sponsor', 'absolutely anything', 'ROC');
+ const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(owner, 'Sponsor', 'absolutely anything', 'ROC');
const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
await collection.methods.setCollectionSponsor(sponsor).send();
@@ -88,7 +124,7 @@
itEth('Set limits', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionId, collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Limits', 'absolutely anything', 'FLO');
+ const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(owner, 'Limits', 'absolutely anything', 'FLO');
const limits = {
accountTokenOwnershipLimit: 1000,
sponsoredDataSize: 1024,
@@ -131,7 +167,7 @@
.methods.isCollectionExist(collectionAddressForNonexistentCollection).call())
.to.be.false;
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Exister', 'absolutely anything', 'EVC');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'Exister', 'absolutely anything', 'EVC');
expect(await helper.ethNativeContract.collectionHelpers(collectionAddress)
.methods.isCollectionExist(collectionAddress).call())
.to.be.true;
@@ -159,7 +195,7 @@
const tokenPrefix = 'A';
await expect(collectionHelper.methods
- .createNonfungibleCollection(collectionName, description, tokenPrefix)
+ .createNFTCollection(collectionName, description, tokenPrefix)
.call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
}
@@ -169,7 +205,7 @@
const description = 'A'.repeat(MAX_DESCRIPTION_LENGTH + 1);
const tokenPrefix = 'A';
await expect(collectionHelper.methods
- .createNonfungibleCollection(collectionName, description, tokenPrefix)
+ .createNFTCollection(collectionName, description, tokenPrefix)
.call({value: Number(2n * nominal)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
}
{
@@ -178,7 +214,7 @@
const description = 'A';
const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGTH + 1);
await expect(collectionHelper.methods
- .createNonfungibleCollection(collectionName, description, tokenPrefix)
+ .createNFTCollection(collectionName, description, tokenPrefix)
.call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
}
});
@@ -187,14 +223,14 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
await expect(collectionHelper.methods
- .createNonfungibleCollection('Peasantry', 'absolutely anything', 'CVE')
+ .createNFTCollection('Peasantry', 'absolutely anything', 'CVE')
.call({value: Number(1n * nominal)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
});
itEth('(!negative test!) Check owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const malfeasant = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Transgressed', 'absolutely anything', 'COR');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'Transgressed', 'absolutely anything', 'COR');
const malfeasantCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', malfeasant);
const EXPECTED_ERROR = 'NoPermission';
{
@@ -217,10 +253,10 @@
itEth('(!negative test!) Set limits', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Limits', 'absolutely anything', 'OLF');
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'Limits', 'absolutely anything', 'OLF');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
await expect(collectionEvm.methods
.setCollectionLimit('badLimit', 'true')
.call()).to.be.rejectedWith('unknown boolean limit "badLimit"');
});
-});
\ No newline at end of file
+});
tests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -37,13 +37,51 @@
const description = 'Some description';
const prefix = 'token prefix';
- const {collectionId} = await helper.eth.createRefungibleCollection(owner, name, description, prefix);
+ const {collectionId} = await helper.eth.createRFTCollection(owner, name, description, prefix);
const data = (await helper.rft.getData(collectionId))!;
+ const collection = helper.rft.getCollectionObject(collectionId);
+
+ expect(data.name).to.be.eq(name);
+ expect(data.description).to.be.eq(description);
+ expect(data.raw.tokenPrefix).to.be.eq(prefix);
+ expect(data.raw.mode).to.be.eq('ReFungible');
+
+ const options = await collection.getOptions();
+
+ expect(options.tokenPropertyPermissions).to.be.empty;
+ });
+
+
+
+ itEth('Create collection with properties', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const name = 'CollectionEVM';
+ const description = 'Some description';
+ const prefix = 'token prefix';
+ const baseUri = 'BaseURI';
+
+ const {collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, name, description, prefix, baseUri);
+ const collection = helper.rft.getCollectionObject(collectionId);
+ const data = (await collection.getData())!;
+
expect(data.name).to.be.eq(name);
expect(data.description).to.be.eq(description);
expect(data.raw.tokenPrefix).to.be.eq(prefix);
expect(data.raw.mode).to.be.eq('ReFungible');
+
+ const options = await collection.getOptions();
+ expect(options.tokenPropertyPermissions).to.be.deep.equal([
+ {
+ key: 'URI',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ {
+ key: 'URISuffix',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ ]);
});
// this test will occasionally fail when in async environment.
@@ -71,7 +109,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const sponsor = await helper.eth.createAccountWithBalance(donor);
const ss58Format = helper.chain.getChainProperties().ss58Format;
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Sponsor', 'absolutely anything', 'ENVY');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(owner, 'Sponsor', 'absolutely anything', 'ENVY');
const collection = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
await collection.methods.setCollectionSponsor(sponsor).send();
@@ -90,7 +128,7 @@
itEth('Set limits', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Limits', 'absolutely anything', 'INSI');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(owner, 'Limits', 'absolutely anything', 'INSI');
const limits = {
accountTokenOwnershipLimit: 1000,
sponsoredDataSize: 1024,
@@ -133,7 +171,7 @@
.methods.isCollectionExist(collectionAddressForNonexistentCollection).call())
.to.be.false;
- const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Exister', 'absolutely anything', 'WIWT');
+ const {collectionAddress} = await helper.eth.createRFTCollection(owner, 'Exister', 'absolutely anything', 'WIWT');
expect(await helper.ethNativeContract.collectionHelpers(collectionAddress)
.methods.isCollectionExist(collectionAddress).call())
.to.be.true;
@@ -196,7 +234,7 @@
itEth('(!negative test!) Check owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const peasant = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Transgressed', 'absolutely anything', 'YVNE');
+ const {collectionAddress} = await helper.eth.createRFTCollection(owner, 'Transgressed', 'absolutely anything', 'YVNE');
const peasantCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', peasant);
const EXPECTED_ERROR = 'NoPermission';
{
@@ -219,7 +257,7 @@
itEth('(!negative test!) Set limits', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Limits', 'absolutely anything', 'ISNI');
+ const {collectionAddress} = await helper.eth.createRFTCollection(owner, 'Limits', 'absolutely anything', 'ISNI');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
await expect(collectionEvm.methods
.setCollectionLimit('badLimit', 'true')
tests/src/eth/evmCoder.test.tsdiffbeforeafterboth--- a/tests/src/eth/evmCoder.test.ts
+++ b/tests/src/eth/evmCoder.test.ts
@@ -65,7 +65,7 @@
itEth('Call non-existing function', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.eth.createNonfungibleCollection(owner, 'EVMCODER', '', 'TEST');
+ const collection = await helper.eth.createNFTCollection(owner, 'EVMCODER', '', 'TEST');
const contract = await helper.ethContract.deployByCode(owner, 'Test', getContractSource(collection.collectionAddress, '0x1bfed5D614b886b9Ab2eA4CBAc22A96B7EC29c9c'));
const testContract = await helper.ethContract.deployByCode(owner, 'Test', getContractSource(collection.collectionAddress, contract.options.address));
{
tests/src/eth/fractionalizer/Fractionalizer.soldiffbeforeafterboth--- a/tests/src/eth/fractionalizer/Fractionalizer.sol
+++ b/tests/src/eth/fractionalizer/Fractionalizer.sol
@@ -124,8 +124,7 @@
address rftTokenAddress;
UniqueRefungibleToken rftTokenContract;
if (nft2rftMapping[_collection][_token] == 0) {
- rftTokenId = rftCollectionContract.nextTokenId();
- rftCollectionContract.mint(address(this), rftTokenId);
+ rftTokenId = rftCollectionContract.mint(address(this));
rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);
nft2rftMapping[_collection][_token] = rftTokenId;
rft2nftMapping[rftTokenAddress] = Token(_collection, _token);
tests/src/eth/fractionalizer/fractionalizer.test.tsdiffbeforeafterboth--- a/tests/src/eth/fractionalizer/fractionalizer.test.ts
+++ b/tests/src/eth/fractionalizer/fractionalizer.test.ts
@@ -62,10 +62,10 @@
const mintRFTToken = async (helper: EthUniqueHelper, owner: string, fractionalizer: Contract, amount: bigint): Promise<{
nftCollectionAddress: string, nftTokenId: number, rftTokenAddress: string
}> => {
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
await fractionalizer.methods.setNftCollectionIsAllowed(nftCollection.collectionAddress, true).send({from: owner});
await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send({from: owner});
@@ -92,7 +92,7 @@
itEth('Set RFT collection', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 10n);
const fractionalizer = await deployContract(helper, owner);
- const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+ const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
const rftContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
await rftContract.methods.addCollectionAdmin(fractionalizer.options.address).send({from: owner});
@@ -121,7 +121,7 @@
itEth('Set Allowlist', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
const {contract: fractionalizer} = await initContract(helper, owner);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const result1 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollection.collectionAddress, true).send({from: owner});
expect(result1.events).to.be.like({
@@ -146,10 +146,10 @@
itEth('NFT to RFT', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
const {contract: fractionalizer} = await initContract(helper, owner);
@@ -231,7 +231,7 @@
itEth('call setRFTCollection twice', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+ const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
const refungibleContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
const fractionalizer = await deployContract(helper, owner);
@@ -244,7 +244,7 @@
itEth('call setRFTCollection with NFT collection', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
const fractionalizer = await deployContract(helper, owner);
@@ -257,7 +257,7 @@
itEth('call setRFTCollection while not collection admin', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
const fractionalizer = await deployContract(helper, owner);
- const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+ const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
await expect(fractionalizer.methods.setRFTCollection(rftCollection.collectionAddress).call())
.to.be.rejectedWith(/Fractionalizer contract should be an admin of the collection$/g);
@@ -278,10 +278,10 @@
itEth('call nft2rft without setting RFT collection for contract', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
const fractionalizer = await deployContract(helper, owner);
@@ -293,10 +293,10 @@
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
const nftOwner = await helper.eth.createAccountWithBalance(donor, 10n);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
await nftContract.methods.transfer(nftOwner, 1).send({from: owner});
@@ -310,10 +310,10 @@
itEth('call nft2rft while not in list of allowed accounts', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
const {contract: fractionalizer} = await initContract(helper, owner);
@@ -325,10 +325,10 @@
itEth('call nft2rft while fractionalizer doesnt have approval for nft token', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
const {contract: fractionalizer} = await initContract(helper, owner);
@@ -341,11 +341,11 @@
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
const fractionalizer = await deployContract(helper, owner);
- const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+ const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
const refungibleContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
- const rftTokenId = await refungibleContract.methods.nextTokenId().call();
- await refungibleContract.methods.mint(owner, rftTokenId).send({from: owner});
-
+ const mintResult = await refungibleContract.methods.mint(owner).send({from: owner});
+ const rftTokenId = mintResult.events.Transfer.returnValues.tokenId;
+
await expect(fractionalizer.methods.rft2nft(rftCollection.collectionAddress, rftTokenId).call({from: owner}))
.to.be.rejectedWith(/RFT collection is not set$/g);
});
@@ -354,18 +354,18 @@
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
const {contract: fractionalizer} = await initContract(helper, owner);
- const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+ const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
const refungibleContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
- const rftTokenId = await refungibleContract.methods.nextTokenId().call();
- await refungibleContract.methods.mint(owner, rftTokenId).send({from: owner});
-
+ const mintResult = await refungibleContract.methods.mint(owner).send({from: owner});
+ const rftTokenId = mintResult.events.Transfer.returnValues.tokenId;
+
await expect(fractionalizer.methods.rft2nft(rftCollection.collectionAddress, rftTokenId).call())
.to.be.rejectedWith(/Wrong RFT collection$/g);
});
itEth('call rft2nft for RFT token that was not minted by fractionalizer contract', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
- const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+ const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
const refungibleContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
const fractionalizer = await deployContract(helper, owner);
@@ -373,9 +373,9 @@
await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send({from: owner});
await fractionalizer.methods.setRFTCollection(rftCollection.collectionAddress).send({from: owner});
- const rftTokenId = await refungibleContract.methods.nextTokenId().call();
- await refungibleContract.methods.mint(owner, rftTokenId).send({from: owner});
-
+ const mintResult = await refungibleContract.methods.mint(owner).send({from: owner});
+ const rftTokenId = mintResult.events.Transfer.returnValues.tokenId;
+
await expect(fractionalizer.methods.rft2nft(rftCollection.collectionAddress, rftTokenId).call())
.to.be.rejectedWith(/No corresponding NFT token found$/g);
});
@@ -386,7 +386,7 @@
const {contract: fractionalizer, rftCollectionAddress} = await initContract(helper, owner);
const {rftTokenAddress} = await mintRFTToken(helper, owner, fractionalizer, 100n);
-
+
const {tokenId} = helper.ethAddress.extractTokenId(rftTokenAddress);
const refungibleTokenContract = helper.ethNativeContract.rftToken(rftTokenAddress, owner);
await refungibleTokenContract.methods.transfer(receiver, 50).send({from: owner});
@@ -420,7 +420,7 @@
await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftToken.tokenId, 100).call())
.to.be.rejectedWith(/TransferNotAllowed$/g);
});
-
+
itEth('fractionalize NFT with RFT transfers disallowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor, 20n);
@@ -432,10 +432,10 @@
await fractionalizer.methods.setRFTCollection(rftCollectionAddress).send({from: owner});
await helper.executeExtrinsic(donor, 'api.tx.unique.setTransfersEnabledFlag', [rftCollection.collectionId, false], true);
- const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+ const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+ const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
await fractionalizer.methods.setNftCollectionIsAllowed(nftCollection.collectionAddress, true).send({from: owner});
await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send({from: owner});
tests/src/eth/fungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -116,6 +116,15 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "address", "name": "newOwner", "type": "address" }
+ ],
+ "name": "changeCollectionOwner",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "collectionOwner",
"outputs": [
@@ -329,15 +338,6 @@
{ "internalType": "address", "name": "sponsor", "type": "address" }
],
"name": "setCollectionSponsor",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "address", "name": "newOwner", "type": "address" }
- ],
- "name": "setOwner",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
tests/src/eth/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/eth/nesting/nest.test.ts
+++ b/tests/src/eth/nesting/nest.test.ts
@@ -7,7 +7,7 @@
helper: EthUniqueHelper,
owner: string,
): Promise<{ collectionId: number, collectionAddress: string, contract: Contract }> => {
- const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
await contract.methods.setCollectionNesting(true).send({from: owner});
@@ -29,74 +29,53 @@
itEth('NFT: allows an Owner to nest/unnest their token', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionId, contract} = await createNestingCollection(helper, owner);
-
- // Create a token to be nested
- const targetNFTTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- targetNFTTokenId,
- ).send({from: owner});
-
+
+ // Create a token to be nested to
+ const mintingTargetNFTTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const targetNFTTokenId = mintingTargetNFTTokenIdResult.events.Transfer.returnValues.tokenId;
const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNFTTokenId);
-
+
// Create a nested token
- const firstTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- targetNftTokenAddress,
- firstTokenId,
- ).send({from: owner});
-
+ const mintingFirstTokenIdResult = await contract.methods.mint(targetNftTokenAddress).send({from: owner});
+ const firstTokenId = mintingFirstTokenIdResult.events.Transfer.returnValues.tokenId;
expect(await contract.methods.ownerOf(firstTokenId).call()).to.be.equal(targetNftTokenAddress);
-
+
// Create a token to be nested and nest
- const secondTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- secondTokenId,
- ).send({from: owner});
-
+ const mintingSecondTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const secondTokenId = mintingSecondTokenIdResult.events.Transfer.returnValues.tokenId;
+
await contract.methods.transfer(targetNftTokenAddress, secondTokenId).send({from: owner});
-
expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(targetNftTokenAddress);
-
+
// Unnest token back
await contract.methods.transferFrom(targetNftTokenAddress, owner, secondTokenId).send({from: owner});
expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(owner);
});
-
+
itEth('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
-
+
const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
-
+
// Create a token to nest into
- const targetNftTokenId = await contractA.methods.nextTokenId().call();
- await contractA.methods.mint(
- owner,
- targetNftTokenId,
- ).send({from: owner});
+ const mintingtargetNftTokenIdResult = await contractA.methods.mint(owner).send({from: owner});
+ const targetNftTokenId = mintingtargetNftTokenIdResult.events.Transfer.returnValues.tokenId;
const nftTokenAddressA1 = helper.ethAddress.fromTokenId(collectionIdA, targetNftTokenId);
-
+
// Create a token for nesting in the same collection as the target
- const nftTokenIdA = await contractA.methods.nextTokenId().call();
- await contractA.methods.mint(
- owner,
- nftTokenIdA,
- ).send({from: owner});
-
+ const mintingTokenIdAResult = await contractA.methods.mint(owner).send({from: owner});
+ const nftTokenIdA = mintingTokenIdAResult.events.Transfer.returnValues.tokenId;
+
// Create a token for nesting in a different collection
- const nftTokenIdB = await contractB.methods.nextTokenId().call();
- await contractB.methods.mint(
- owner,
- nftTokenIdB,
- ).send({from: owner});
-
+ const mintingTokenIdBResult = await contractB.methods.mint(owner).send({from: owner});
+ const nftTokenIdB = mintingTokenIdBResult.events.Transfer.returnValues.tokenId;
+
// Nest
await contractA.methods.transfer(nftTokenAddressA1, nftTokenIdA).send({from: owner});
expect(await contractA.methods.ownerOf(nftTokenIdA).call()).to.be.equal(nftTokenAddressA1);
-
+
await contractB.methods.transfer(nftTokenAddressA1, nftTokenIdB).send({from: owner});
expect(await contractB.methods.ownerOf(nftTokenIdB).call()).to.be.equal(nftTokenAddressA1);
});
@@ -105,112 +84,88 @@
describe('Negative Test: EVM Nesting', async() => {
itEth('NFT: disallows to nest token if nesting is disabled', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
-
+
const {collectionId, contract} = await createNestingCollection(helper, owner);
await contract.methods.setCollectionNesting(false).send({from: owner});
-
+
// Create a token to nest into
- const targetNftTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- targetNftTokenId,
- ).send({from: owner});
-
- const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNftTokenId);
-
+ const mintingTargetTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
+ const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetTokenId);
+
// Create a token to nest
- const nftTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- nftTokenId,
- ).send({from: owner});
-
+ const mintingNftTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintingNftTokenIdResult.events.Transfer.returnValues.tokenId;
+
// Try to nest
await expect(contract.methods
.transfer(targetNftTokenAddress, nftTokenId)
.call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
});
-
+
itEth('NFT: disallows a non-Owner to nest someone else\'s token', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const malignant = await helper.eth.createAccountWithBalance(donor);
-
+
const {collectionId, contract} = await createNestingCollection(helper, owner);
-
+
// Mint a token
- const targetTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- owner,
- targetTokenId,
- ).send({from: owner});
+ const mintingTargetTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
const targetTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetTokenId);
-
+
// Mint a token belonging to a different account
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(
- malignant,
- tokenId,
- ).send({from: owner});
-
+ const mintingTokenIdResult = await contract.methods.mint(malignant).send({from: owner});
+ const tokenId = mintingTokenIdResult.events.Transfer.returnValues.tokenId;
+
// Try to nest one token in another as a non-owner account
await expect(contract.methods
.transfer(targetTokenAddress, tokenId)
.call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
});
-
+
itEth('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const malignant = await helper.eth.createAccountWithBalance(donor);
-
+
const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
-
+
await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
-
+
// Create a token in one collection
- const nftTokenIdA = await contractA.methods.nextTokenId().call();
- await contractA.methods.mint(
- owner,
- nftTokenIdA,
- ).send({from: owner});
+ const mintingTokenIdAResult = await contractA.methods.mint(owner).send({from: owner});
+ const nftTokenIdA = mintingTokenIdAResult.events.Transfer.returnValues.tokenId;
const nftTokenAddressA = helper.ethAddress.fromTokenId(collectionIdA, nftTokenIdA);
-
- // Create a token in another collection belonging to someone else
- const nftTokenIdB = await contractB.methods.nextTokenId().call();
- await contractB.methods.mint(
- malignant,
- nftTokenIdB,
- ).send({from: owner});
-
+
+ // Create a token in another collection
+ const mintingTokenIdBResult = await contractB.methods.mint(malignant).send({from: owner});
+ const nftTokenIdB = mintingTokenIdBResult.events.Transfer.returnValues.tokenId;
+
// Try to drag someone else's token into the other collection and nest
await expect(contractB.methods
.transfer(nftTokenAddressA, nftTokenIdB)
.call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
});
-
+
itEth('NFT: disallows to nest token in an unlisted collection', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
-
+
const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
const {contract: contractB} = await createNestingCollection(helper, owner);
-
+
await contractA.methods.setCollectionNesting(true, [collectionAddressA]).send({from: owner});
-
+
// Create a token in one collection
- const nftTokenIdA = await contractA.methods.nextTokenId().call();
- await contractA.methods.mint(
- owner,
- nftTokenIdA,
- ).send({from: owner});
+ const mintingTokenIdAResult = await contractA.methods.mint(owner).send({from: owner});
+ const nftTokenIdA = mintingTokenIdAResult.events.Transfer.returnValues.tokenId;
const nftTokenAddressA = helper.ethAddress.fromTokenId(collectionIdA, nftTokenIdA);
-
+
// Create a token in another collection
- const nftTokenIdB = await contractB.methods.nextTokenId().call();
- await contractB.methods.mint(
- owner,
- nftTokenIdB,
- ).send({from: owner});
-
+ const mintingTokenIdBResult = await contractB.methods.mint(owner).send({from: owner});
+ const nftTokenIdB = mintingTokenIdBResult.events.Transfer.returnValues.tokenId;
+
+
// Try to nest into a token in the other collection, disallowed in the first
await expect(contractB.methods
.transfer(nftTokenAddressA, nftTokenIdB)
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -29,7 +29,7 @@
[alice] = await helper.arrange.createAccounts([10n], donor);
});
});
-
+
itEth('totalSupply', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {});
await collection.mintToken(alice);
@@ -68,6 +68,16 @@
expect(owner).to.equal(caller);
});
+
+ itEth('name/symbol is available regardless of ERC721Metadata support', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'test', tokenPrefix: 'TEST'});
+ const caller = helper.eth.createAccount();
+
+ const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
+
+ expect(await contract.methods.name().call()).to.equal('test');
+ expect(await contract.methods.symbol().call()).to.equal('TEST');
+ });
});
describe('Check ERC721 token URI for NFT', () => {
@@ -79,34 +89,29 @@
});
});
- async function setup(helper: EthUniqueHelper, tokenPrefix: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
+ async function setup(helper: EthUniqueHelper, baseUri: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
- const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', 'a', 'b', baseUri);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
-
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- result = await contract.methods.mint(
- receiver,
- nextTokenId,
- ).send();
+ const result = await contract.methods.mint(receiver).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+ expect(tokenId).to.be.equal('1');
+
if (propertyKey && propertyValue) {
// Set URL or suffix
- await contract.methods.setProperty(nextTokenId, propertyKey, Buffer.from(propertyValue)).send();
+ await contract.methods.setProperty(tokenId, propertyKey, Buffer.from(propertyValue)).send();
}
const event = result.events.Transfer;
expect(event.address).to.be.equal(collectionAddress);
expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
expect(event.returnValues.to).to.be.equal(receiver);
- expect(event.returnValues.tokenId).to.be.equal(nextTokenId);
+ expect(event.returnValues.tokenId).to.be.equal(tokenId);
- return {contract, nextTokenId};
+ return {contract, nextTokenId: tokenId};
}
itEth('Empty tokenURI', async ({helper}) => {
@@ -115,18 +120,18 @@
});
itEth('TokenURI from url', async ({helper}) => {
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');
});
- itEth('TokenURI from baseURI + tokenId', async ({helper}) => {
+ itEth('TokenURI from baseURI', async ({helper}) => {
const {contract, nextTokenId} = await setup(helper, 'BaseURI_');
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + nextTokenId);
+ expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_');
});
itEth('TokenURI from baseURI + suffix', async ({helper}) => {
const suffix = '/some/suffix';
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);
});
});
@@ -146,24 +151,19 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Minty', '6', '6');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', '6', '6', '');
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- const result = await contract.methods.mintWithTokenURI(
- receiver,
- nextTokenId,
- 'Test URI',
- ).send();
+ const result = await contract.methods.mintWithTokenURI(receiver, 'Test URI').send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+ expect(tokenId).to.be.equal('1');
const event = result.events.Transfer;
expect(event.address).to.be.equal(collectionAddress);
expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
expect(event.returnValues.to).to.be.equal(receiver);
- expect(event.returnValues.tokenId).to.be.equal(nextTokenId);
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+ expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
// TODO: this wont work right now, need release 919000 first
// await helper.methods.setOffchainSchema(collectionIdAddress, 'https://offchain-service.local/token-info/{id}').send();
@@ -216,7 +216,7 @@
{
const result = await contract.methods.burn(tokenId).send({from: caller});
-
+
const event = result.events.Transfer;
expect(event.address).to.be.equal(collectionAddress);
expect(event.returnValues.from).to.be.equal(caller);
@@ -322,7 +322,7 @@
[alice] = await helper.arrange.createAccounts([10n], donor);
});
});
-
+
itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const spender = helper.eth.createAccount();
@@ -403,7 +403,7 @@
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
-
+
const events: any = [];
contract.events.allEvents((_: any, event: any) => {
events.push(event);
@@ -428,7 +428,7 @@
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
-
+
const events: any = [];
contract.events.allEvents((_: any, event: any) => {
events.push(event);
@@ -455,13 +455,14 @@
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
-
+
const events: any = [];
contract.events.allEvents((_: any, event: any) => {
events.push(event);
});
await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver});
+
if (events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
@@ -479,13 +480,14 @@
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
-
+
const events: any = [];
contract.events.allEvents((_: any, event: any) => {
events.push(event);
});
await token.transfer(alice, {Ethereum: receiver});
+
if (events.length == 0) await helper.wait.newBlocks(1);
const event = events[0];
@@ -509,7 +511,23 @@
itEth('Returns collection name', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(alice, {name: 'oh River', tokenPrefix: 'CHANGE'});
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const collection = await helper.nft.mintCollection(
+ alice,
+ {
+ name: 'oh River',
+ tokenPrefix: 'CHANGE',
+ properties: [{key: 'ERC721Metadata', value: '1'}],
+ tokenPropertyPermissions,
+ },
+ );
const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
const name = await contract.methods.name().call();
@@ -518,10 +536,26 @@
itEth('Returns symbol name', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(alice, {name: 'oh River', tokenPrefix: 'CHANGE'});
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const collection = await helper.nft.mintCollection(
+ alice,
+ {
+ name: 'oh River',
+ tokenPrefix: 'CHANGE',
+ properties: [{key: 'ERC721Metadata', value: '1'}],
+ tokenPropertyPermissions,
+ },
+ );
const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
const symbol = await contract.methods.symbol().call();
expect(symbol).to.equal('CHANGE');
});
-});
\ No newline at end of file
+});
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -146,6 +146,15 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "address", "name": "newOwner", "type": "address" }
+ ],
+ "name": "changeCollectionOwner",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "collectionOwner",
"outputs": [
@@ -260,12 +269,9 @@
"type": "function"
},
{
- "inputs": [
- { "internalType": "address", "name": "to", "type": "address" },
- { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
- ],
+ "inputs": [{ "internalType": "address", "name": "to", "type": "address" }],
"name": "mint",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
"stateMutability": "nonpayable",
"type": "function"
},
@@ -287,7 +293,7 @@
{ "internalType": "uint256", "name": "field_0", "type": "uint256" },
{ "internalType": "string", "name": "field_1", "type": "string" }
],
- "internalType": "struct Tuple8[]",
+ "internalType": "struct Tuple6[]",
"name": "tokens",
"type": "tuple[]"
}
@@ -300,11 +306,10 @@
{
"inputs": [
{ "internalType": "address", "name": "to", "type": "address" },
- { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
{ "internalType": "string", "name": "tokenUri", "type": "string" }
],
"name": "mintWithTokenURI",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
"stateMutability": "nonpayable",
"type": "function"
},
@@ -476,15 +481,6 @@
{ "internalType": "address", "name": "sponsor", "type": "address" }
],
"name": "setCollectionSponsor",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "address", "name": "newOwner", "type": "address" }
- ],
- "name": "setOwner",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
tests/src/eth/payable.test.tsdiffbeforeafterboth--- a/tests/src/eth/payable.test.ts
+++ b/tests/src/eth/payable.test.ts
@@ -118,7 +118,7 @@
const deployer = await helper.eth.createAccountWithBalance(donor);
const caller = await helper.eth.createAccountWithBalance(donor);
const contract = await helper.eth.deployFlipper(deployer);
-
+
const initialCallerBalance = await helper.balance.getEthereum(caller);
await contract.methods.flip().send({from: caller});
const finalCallerBalance = await helper.balance.getEthereum(caller);
@@ -129,7 +129,7 @@
const deployer = await helper.eth.createAccountWithBalance(donor);
const caller = await helper.eth.createAccountWithBalance(donor);
const contract = await deployProxyContract(helper, deployer);
-
+
const initialCallerBalance = await helper.balance.getEthereum(caller);
const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
await contract.methods.flip().send({from: caller});
@@ -138,7 +138,7 @@
expect(finalCallerBalance < initialCallerBalance).to.be.true;
expect(finalContractBalance == initialContractBalance).to.be.true;
});
-
+
itEth('Fee for nested calls to native methods is withdrawn from the user', async({helper}) => {
const CONTRACT_BALANCE = 2n * helper.balance.getOneTokenNominal();
@@ -146,7 +146,7 @@
const caller = await helper.eth.createAccountWithBalance(donor);
const contract = await deployProxyContract(helper, deployer);
- const collectionAddress = (await contract.methods.createNonfungibleCollection().send({from: caller, value: Number(CONTRACT_BALANCE)})).events.CollectionCreated.returnValues.collection;
+ const collectionAddress = (await contract.methods.createNFTCollection().send({from: caller, value: Number(CONTRACT_BALANCE)})).events.CollectionCreated.returnValues.collection;
const initialCallerBalance = await helper.balance.getEthereum(caller);
const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
await contract.methods.mintNftToken(collectionAddress).send({from: caller});
@@ -155,7 +155,7 @@
expect(finalCallerBalance < initialCallerBalance).to.be.true;
expect(finalContractBalance == initialContractBalance).to.be.true;
});
-
+
itEth('Fee for nested calls to create*Collection methods is withdrawn from the user and from the contract', async({helper}) => {
const CONTRACT_BALANCE = 2n * helper.balance.getOneTokenNominal();
const deployer = await helper.eth.createAccountWithBalance(donor);
@@ -164,7 +164,7 @@
const initialCallerBalance = await helper.balance.getEthereum(caller);
const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
- await contract.methods.createNonfungibleCollection().send({from: caller, value: Number(CONTRACT_BALANCE)});
+ await contract.methods.createNFTCollection().send({from: caller, value: Number(CONTRACT_BALANCE)});
const finalCallerBalance = await helper.balance.getEthereum(caller);
const finalContractBalance = await helper.balance.getEthereum(contract.options.address);
expect(finalCallerBalance < initialCallerBalance).to.be.true;
@@ -176,9 +176,9 @@
const BIG_FEE = 3n * helper.balance.getOneTokenNominal();
const caller = await helper.eth.createAccountWithBalance(donor);
const collectionHelper = helper.ethNativeContract.collectionHelpers(caller);
-
- await expect(collectionHelper.methods.createNonfungibleCollection('A', 'B', 'C').call({value: Number(SMALL_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
- await expect(collectionHelper.methods.createNonfungibleCollection('A', 'B', 'C').call({value: Number(BIG_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+
+ await expect(collectionHelper.methods.createNFTCollection('A', 'B', 'C').call({value: Number(SMALL_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+ await expect(collectionHelper.methods.createNFTCollection('A', 'B', 'C').call({value: Number(BIG_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
});
itEth('Negative test: call createRFTCollection with wrong fee', async({helper}) => {
@@ -186,7 +186,7 @@
const BIG_FEE = 3n * helper.balance.getOneTokenNominal();
const caller = await helper.eth.createAccountWithBalance(donor);
const collectionHelper = helper.ethNativeContract.collectionHelpers(caller);
-
+
await expect(collectionHelper.methods.createRFTCollection('A', 'B', 'C').call({value: Number(SMALL_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
await expect(collectionHelper.methods.createRFTCollection('A', 'B', 'C').call({value: Number(BIG_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
});
@@ -227,16 +227,15 @@
InnerContract(innerContract).flip();
}
- function createNonfungibleCollection() external payable {
+ function createNFTCollection() external payable {
address collectionHelpers = 0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F;
- address nftCollection = CollectionHelpers(collectionHelpers).createNonfungibleCollection{value: msg.value}("A", "B", "C");
+ address nftCollection = CollectionHelpers(collectionHelpers).createNFTCollection{value: msg.value}("A", "B", "C");
emit CollectionCreated(nftCollection);
}
function mintNftToken(address collectionAddress) external {
UniqueNFT collection = UniqueNFT(collectionAddress);
- uint256 tokenId = collection.nextTokenId();
- collection.mint(msg.sender, tokenId);
+ uint256 tokenId = collection.mint(msg.sender);
emit TokenMinted(tokenId);
}
tests/src/eth/proxy/UniqueNFTProxy.soldiffbeforeafterboth--- a/tests/src/eth/proxy/UniqueNFTProxy.sol
+++ b/tests/src/eth/proxy/UniqueNFTProxy.sol
@@ -120,20 +120,19 @@
return proxied.mintingFinished();
}
- function mint(address to, uint256 tokenId)
+ function mint(address to)
external
override
- returns (bool)
+ returns (uint256)
{
- return proxied.mint(to, tokenId);
+ return proxied.mint(to);
}
function mintWithTokenURI(
address to,
- uint256 tokenId,
string memory tokenUri
- ) external override returns (bool) {
- return proxied.mintWithTokenURI(to, tokenId, tokenUri);
+ ) external override returns (uint256) {
+ return proxied.mintWithTokenURI(to, tokenUri);
}
function finishMinting() external override returns (bool) {
@@ -169,7 +168,7 @@
return proxied.mintBulk(to, tokenIds);
}
- function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens)
external
override
returns (bool)
tests/src/eth/proxy/nonFungibleProxy.test.tsdiffbeforeafterboth--- a/tests/src/eth/proxy/nonFungibleProxy.test.ts
+++ b/tests/src/eth/proxy/nonFungibleProxy.test.ts
@@ -101,7 +101,7 @@
itEth('Can perform mint()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'A', 'A');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'A', 'A', 'A', '');
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
@@ -111,13 +111,11 @@
await collectionEvmOwned.methods.addCollectionAdmin(contract.options.address).send();
{
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- const result = await contract.methods.mintWithTokenURI(
- receiver,
- nextTokenId,
- 'Test URI',
- ).send({from: caller});
+ const nextTokenId = await contract.methods.nextTokenId().call()
+ const result = await contract.methods.mintWithTokenURI(receiver, nextTokenId, 'Test URI').send({from: caller});
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+ expect(tokenId).to.be.equal('1');
+
const events = helper.eth.normalizeEvents(result.events);
events[0].address = events[0].address.toLocaleLowerCase();
@@ -128,12 +126,12 @@
args: {
from: '0x0000000000000000000000000000000000000000',
to: receiver,
- tokenId: nextTokenId,
+ tokenId,
},
},
]);
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+ expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
}
});
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -31,31 +31,23 @@
itEth('totalSupply', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'TotalSupply', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'TotalSupply', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const nextTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, nextTokenId).send();
+
+ await contract.methods.mint(caller).send();
+
const totalSupply = await contract.methods.totalSupply().call();
expect(totalSupply).to.equal('1');
});
itEth('balanceOf', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'BalanceOf', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'BalanceOf', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- {
- const nextTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, nextTokenId).send();
- }
- {
- const nextTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, nextTokenId).send();
- }
- {
- const nextTokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, nextTokenId).send();
- }
+ await contract.methods.mint(caller).send();
+ await contract.methods.mint(caller).send();
+ await contract.methods.mint(caller).send();
const balance = await contract.methods.balanceOf(caller).call();
expect(balance).to.equal('3');
@@ -63,11 +55,11 @@
itEth('ownerOf', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'OwnerOf', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'OwnerOf', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const owner = await contract.methods.ownerOf(tokenId).call();
expect(owner).to.equal(caller);
@@ -76,11 +68,11 @@
itEth('ownerOf after burn', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'OwnerOf-AfterBurn', '6', '6');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'OwnerOf-AfterBurn', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
await tokenContract.methods.repartition(2).send();
@@ -95,11 +87,11 @@
itEth('ownerOf for partial ownership', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Partial-OwnerOf', '6', '6');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Partial-OwnerOf', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
await tokenContract.methods.repartition(2).send();
@@ -124,30 +116,25 @@
itEth('Can perform mint()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Minty', '6', '6');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Minty', '6', '6', '');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
-
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- const result = await contract.methods.mintWithTokenURI(
- receiver,
- nextTokenId,
- 'Test URI',
- ).send();
+ const result = await contract.methods.mintWithTokenURI(receiver, 'Test URI').send();
+
const event = result.events.Transfer;
expect(event.address).to.equal(collectionAddress);
expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
expect(event.returnValues.to).to.equal(receiver);
- expect(event.returnValues.tokenId).to.equal(nextTokenId);
+ const tokenId = event.returnValues.tokenId;
+ expect(tokenId).to.be.equal('1');
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+ expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
});
itEth('Can perform mintBulk()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'MintBulky', '6', '6');
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'MintBulky', '6', '6', '');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
{
@@ -179,11 +166,11 @@
itEth('Can perform burn()', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Burny', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Burny', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
{
const result = await contract.methods.burn(tokenId).send();
const event = result.events.Transfer;
@@ -197,12 +184,13 @@
itEth('Can perform transferFrom()', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'TransferFromy', '6', '6');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'TransferFromy', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+
const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);
- await contract.methods.mint(caller, tokenId).send();
const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, caller);
await tokenContract.methods.repartition(15).send();
@@ -241,15 +229,15 @@
itEth('Can perform transfer()', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
{
const result = await contract.methods.transfer(receiver, tokenId).send();
-
+
const event = result.events.Transfer;
expect(event.address).to.equal(collectionAddress);
expect(event.returnValues.from).to.equal(caller);
@@ -271,11 +259,11 @@
itEth('transfer event on transfer from partial ownership to full ownership', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry-Partial-to-Full', '6', '6');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry-Partial-to-Full', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
@@ -300,11 +288,11 @@
itEth('transfer event on transfer from full ownership to partial ownership', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry-Full-to-Partial', '6', '6');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry-Full-to-Partial', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
@@ -340,11 +328,11 @@
itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Feeful-Transfer-From', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Feeful-Transfer-From', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transferFrom(caller, receiver, tokenId).send());
expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
@@ -354,11 +342,11 @@
itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Feeful-Transfer', '6', '6');
+ const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Feeful-Transfer', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transfer(receiver, tokenId).send());
expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
@@ -381,8 +369,24 @@
itEth('Returns collection name', async ({helper}) => {
const caller = helper.eth.createAccount();
- const collection = await helper.rft.mintCollection(alice, {name: 'Leviathan', tokenPrefix: '11'});
-
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const collection = await helper.rft.mintCollection(
+ alice,
+ {
+ name: 'Leviathan',
+ tokenPrefix: '11',
+ properties: [{key: 'ERC721Metadata', value: '1'}],
+ tokenPropertyPermissions,
+ },
+ );
+
const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'rft', caller);
const name = await contract.methods.name().call();
expect(name).to.equal('Leviathan');
@@ -390,8 +394,25 @@
itEth('Returns symbol name', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Leviathan', '', '12');
- const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const {collectionId} = await helper.rft.mintCollection(
+ alice,
+ {
+ name: 'Leviathan',
+ tokenPrefix: '12',
+ properties: [{key: 'ERC721Metadata', value: '1'}],
+ tokenPropertyPermissions,
+ },
+ );
+
+ const contract = helper.ethNativeContract.collectionById(collectionId, 'rft', caller);
const symbol = await contract.methods.symbol().call();
expect(symbol).to.equal('12');
});
tests/src/eth/reFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -146,6 +146,15 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "address", "name": "newOwner", "type": "address" }
+ ],
+ "name": "changeCollectionOwner",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "collectionOwner",
"outputs": [
@@ -260,12 +269,9 @@
"type": "function"
},
{
- "inputs": [
- { "internalType": "address", "name": "to", "type": "address" },
- { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
- ],
+ "inputs": [{ "internalType": "address", "name": "to", "type": "address" }],
"name": "mint",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
"stateMutability": "nonpayable",
"type": "function"
},
@@ -287,7 +293,7 @@
{ "internalType": "uint256", "name": "field_0", "type": "uint256" },
{ "internalType": "string", "name": "field_1", "type": "string" }
],
- "internalType": "struct Tuple8[]",
+ "internalType": "struct Tuple6[]",
"name": "tokens",
"type": "tuple[]"
}
@@ -300,11 +306,10 @@
{
"inputs": [
{ "internalType": "address", "name": "to", "type": "address" },
- { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
{ "internalType": "string", "name": "tokenUri", "type": "string" }
],
"name": "mintWithTokenURI",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
"stateMutability": "nonpayable",
"type": "function"
},
@@ -476,15 +481,6 @@
{ "internalType": "address", "name": "sponsor", "type": "address" }
],
"name": "setCollectionSponsor",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "address", "name": "newOwner", "type": "address" }
- ],
- "name": "setOwner",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -76,34 +76,28 @@
});
});
- async function setup(helper: EthUniqueHelper, tokenPrefix: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
+ async function setup(helper: EthUniqueHelper, baseUri: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
- let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
- const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Mint collection', 'a', 'b', baseUri);
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
-
- const nextTokenId = await contract.methods.nextTokenId().call();
- expect(nextTokenId).to.be.equal('1');
- result = await contract.methods.mint(
- receiver,
- nextTokenId,
- ).send();
- if (propertyKey && propertyValue) {
- // Set URL or suffix
- await contract.methods.setProperty(nextTokenId, propertyKey, Buffer.from(propertyValue)).send();
- }
+ const result = await contract.methods.mint(receiver).send();
const event = result.events.Transfer;
+ const tokenId = event.returnValues.tokenId;
+ expect(tokenId).to.be.equal('1');
expect(event.address).to.be.equal(collectionAddress);
expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
expect(event.returnValues.to).to.be.equal(receiver);
- expect(event.returnValues.tokenId).to.be.equal(nextTokenId);
- return {contract, nextTokenId};
+ if (propertyKey && propertyValue) {
+ // Set URL or suffix
+ await contract.methods.setProperty(tokenId, propertyKey, Buffer.from(propertyValue)).send();
+ }
+
+ return {contract, nextTokenId: tokenId};
}
itEth('Empty tokenURI', async ({helper}) => {
@@ -112,18 +106,18 @@
});
itEth('TokenURI from url', async ({helper}) => {
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');
});
- itEth('TokenURI from baseURI + tokenId', async ({helper}) => {
+ itEth('TokenURI from baseURI', async ({helper}) => {
const {contract, nextTokenId} = await setup(helper, 'BaseURI_');
- expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + nextTokenId);
+ expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_');
});
itEth('TokenURI from baseURI + suffix', async ({helper}) => {
const suffix = '/some/suffix';
- const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);
+ const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);
expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);
});
});
@@ -294,11 +288,11 @@
itEth('Receiving Transfer event on burning into full ownership', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = await helper.eth.createAccountWithBalance(donor);
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Devastation', '6', '6');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Devastation', '6', '6');
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
- const tokenId = await contract.methods.nextTokenId().call();
- await contract.methods.mint(caller, tokenId).send();
+ const result = await contract.methods.mint(caller).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);
const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, caller);
@@ -484,11 +478,12 @@
itEth('Default parent token address and id', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Sands', '', 'GRAIN');
+ const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(owner, 'Sands', '', 'GRAIN');
const collectionContract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
-
- const tokenId = await collectionContract.methods.nextTokenId().call();
- await collectionContract.methods.mint(owner, tokenId).send();
+
+ const result = await collectionContract.methods.mint(owner).send();
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+
const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);
const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, owner);
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -43,12 +43,12 @@
if(!imports) return function(path: string) {
return {error: `File not found: ${path}`};
};
-
+
const knownImports = {} as {[key: string]: string};
for(const imp of imports) {
knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();
}
-
+
return function(path: string) {
if(path in knownImports) return {contents: knownImports[path]};
return {error: `File not found: ${path}`};
@@ -71,7 +71,7 @@
},
},
}), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];
-
+
return {
abi: out.abi,
object: '0x' + out.evm.bytecode.object,
@@ -94,7 +94,7 @@
}
}
-
+
class NativeContractGroup extends EthGroupBase {
contractHelpers(caller: string): Contract {
@@ -145,14 +145,14 @@
async createAccountWithBalance(donor: IKeyringPair, amount=100n) {
const account = this.createAccount();
await this.transferBalanceFromSubstrate(donor, account, amount);
-
+
return account;
}
async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=100n, inTokens=true) {
return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));
}
-
+
async getCollectionCreationFee(signer: string) {
const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
return await collectionHelper.methods.collectionCreationFee().call();
@@ -174,22 +174,32 @@
return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);
}
- async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
+ async createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
-
- const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
+ const result = await collectionHelper.methods.createNFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
+
const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);
return {collectionId, collectionAddress};
}
- async createRefungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
+ async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {
+ const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
+
+ const {collectionId, collectionAddress} = await this.createNFTCollection(signer, name, description, tokenPrefix)
+
+ await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
+
+ return {collectionId, collectionAddress};
+ }
+
+ async createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
-
+
const result = await collectionHelper.methods.createRFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
@@ -198,6 +208,16 @@
return {collectionId, collectionAddress};
}
+ async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {
+ const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
+
+ const {collectionId, collectionAddress} = await this.createRFTCollection(signer, name, description, tokenPrefix)
+
+ await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
+
+ return {collectionId, collectionAddress};
+ }
+
async deployCollectorContract(signer: string): Promise<Contract> {
return await this.helper.ethContract.deployByCode(signer, 'Collector', `
// SPDX-License-Identifier: UNLICENSED
@@ -288,7 +308,7 @@
};
return await this.helper.arrange.calculcateFee(address, wrappedCode);
}
-}
+}
class EthAddressGroup extends EthGroupBase {
extractCollectionId(address: string): number {
@@ -319,8 +339,8 @@
normalizeAddress(address: string): string {
return '0x' + address.substring(address.length - 40);
}
-}
-
+}
+
export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;
export class EthUniqueHelper extends DevUniqueHelper {
@@ -373,4 +393,3 @@
return newHelper;
}
}
-
\ No newline at end of file
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -1026,6 +1026,10 @@
return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();
}
+ async getCollectionOptions(collectionId: number) {
+ return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();
+ }
+
/**
* Deletes onchain properties from the collection.
*
@@ -2839,6 +2843,10 @@
return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);
}
+ async getOptions() {
+ return await this.helper.collection.getCollectionOptions(this.collectionId);
+ }
+
async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {
return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);
}