difftreelog
feat(refungible-pallet) ERC-721 EVM API
in: master
12 files changed
Makefilediffbeforeafterboth--- a/Makefile
+++ b/Makefile
@@ -15,8 +15,9 @@
NONFUNGIBLE_EVM_STUBS=./pallets/nonfungible/src/stubs
NONFUNGIBLE_EVM_ABI=./tests/src/eth/nonFungibleAbi.json
-RENFUNGIBLE_EVM_ABI=./tests/src/eth/reFungibleAbi.json
-RENFUNGIBLE_TOKEN_EVM_ABI=./tests/src/eth/reFungibleTokenAbi.json
+REFUNGIBLE_EVM_STUBS=./pallets/refungible/src/stubs
+REFUNGIBLE_EVM_ABI=./tests/src/eth/reFungibleAbi.json
+REFUNGIBLE_TOKEN_EVM_ABI=./tests/src/eth/reFungibleTokenAbi.json
CONTRACT_HELPERS_STUBS=./pallets/evm-contract-helpers/src/stubs/
CONTRACT_HELPERS_ABI=./tests/src/eth/util/contractHelpersAbi.json
@@ -36,6 +37,10 @@
UniqueNFT.sol:
PACKAGE=pallet-nonfungible NAME=erc::gen_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
PACKAGE=pallet-nonfungible NAME=erc::gen_impl OUTPUT=$(NONFUNGIBLE_EVM_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+
+UniqueRefungible.sol:
+ PACKAGE=pallet-refungible NAME=erc::gen_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
+ PACKAGE=pallet-refungible NAME=erc::gen_impl OUTPUT=$(REFUNGIBLE_EVM_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
UniqueRefungible.sol:
PACKAGE=pallet-refungible NAME=erc::gen_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
@@ -61,9 +66,13 @@
INPUT=$(NONFUNGIBLE_EVM_STUBS)/$< OUTPUT=$(NONFUNGIBLE_EVM_STUBS)/UniqueNFT.raw ./.maintain/scripts/compile_stub.sh
INPUT=$(NONFUNGIBLE_EVM_STUBS)/$< OUTPUT=$(NONFUNGIBLE_EVM_ABI) ./.maintain/scripts/generate_abi.sh
+UniqueRefungible: UniqueRefungible.sol
+ INPUT=$(REFUNGIBLE_EVM_STUBS)/$< OUTPUT=$(REFUNGIBLE_EVM_STUBS)/UniqueRefungible.raw ./.maintain/scripts/compile_stub.sh
+ INPUT=$(REFUNGIBLE_EVM_STUBS)/$< OUTPUT=$(REFUNGIBLE_EVM_ABI) ./.maintain/scripts/generate_abi.sh
+
UniqueRefungibleToken: UniqueRefungibleToken.sol
INPUT=$(REFUNGIBLE_EVM_STUBS)/$< OUTPUT=$(REFUNGIBLE_EVM_STUBS)/UniqueRefungibleToken.raw ./.maintain/scripts/compile_stub.sh
- INPUT=$(REFUNGIBLE_EVM_STUBS)/$< OUTPUT=$(RENFUNGIBLE_TOKEN_EVM_ABI) ./.maintain/scripts/generate_abi.sh
+ INPUT=$(REFUNGIBLE_EVM_STUBS)/$< OUTPUT=$(REFUNGIBLE_TOKEN_EVM_ABI) ./.maintain/scripts/generate_abi.sh
UniqueRefungible: UniqueRefungible.sol
INPUT=$(REFUNGIBLE_EVM_STUBS)/$< OUTPUT=$(REFUNGIBLE_EVM_STUBS)/UniqueRefungible.raw ./.maintain/scripts/compile_stub.sh
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -15,18 +15,607 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
extern crate alloc;
-use evm_coder::{generate_stubgen, solidity_interface, types::*};
-use pallet_common::{CollectionHandle, erc::CollectionCall, erc::CommonEvmHandler};
+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, BoundedVec};
+use pallet_common::{
+ CollectionHandle, CollectionPropertyPermissions,
+ erc::{
+ CommonEvmHandler, CollectionCall,
+ static_property::{key, value as property_value},
+ },
+};
+use pallet_evm::{account::CrossAccountId, PrecompileHandle};
+use pallet_evm_coder_substrate::{call, dispatch_to_evm};
+use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
+use sp_core::H160;
+use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};
+use up_data_structs::{
+ CollectionId, CollectionPropertiesVec, Property, PropertyKey, PropertyKeyPermission,
+ PropertyPermission, TokenId,
+};
+
+use crate::{
+ AccountBalance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,
+ TokenProperties, TokensMinted, weights::WeightInfo,
+};
-use pallet_evm::PrecompileHandle;
-use pallet_evm_coder_substrate::call;
+#[solidity_interface(name = "TokenProperties")]
+impl<T: Config> RefungibleHandle<T> {
+ fn set_token_property_permission(
+ &mut self,
+ caller: caller,
+ key: string,
+ is_mutable: bool,
+ collection_admin: bool,
+ token_owner: bool,
+ ) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ <Pallet<T>>::set_token_property_permissions(
+ self,
+ &caller,
+ vec![PropertyKeyPermission {
+ key: <Vec<u8>>::from(key)
+ .try_into()
+ .map_err(|_| "too long key")?,
+ permission: PropertyPermission {
+ mutable: is_mutable,
+ collection_admin,
+ token_owner,
+ },
+ }],
+ )
+ .map_err(dispatch_to_evm::<T>)
+ }
-use crate::{Config, RefungibleHandle};
+ fn set_property(
+ &mut self,
+ caller: caller,
+ token_id: uint256,
+ key: string,
+ value: bytes,
+ ) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
+ let key = <Vec<u8>>::from(key)
+ .try_into()
+ .map_err(|_| "key too long")?;
+ let value = value.try_into().map_err(|_| "value too long")?;
+ let nesting_budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ <Pallet<T>>::set_token_property(
+ self,
+ &caller,
+ TokenId(token_id),
+ Property { key, value },
+ &nesting_budget,
+ )
+ .map_err(dispatch_to_evm::<T>)
+ }
+
+ fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
+ let key = <Vec<u8>>::from(key)
+ .try_into()
+ .map_err(|_| "key too long")?;
+
+ let nesting_budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)
+ .map_err(dispatch_to_evm::<T>)
+ }
+
+ /// Throws error if key not found
+ fn property(&self, token_id: uint256, key: string) -> Result<bytes> {
+ let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
+ let key = <Vec<u8>>::from(key)
+ .try_into()
+ .map_err(|_| "key too long")?;
+
+ let props = <TokenProperties<T>>::get((self.id, token_id));
+ let prop = props.get(&key).ok_or("key not found")?;
+
+ Ok(prop.to_vec())
+ }
+}
+
+#[derive(ToLog)]
+pub enum ERC721Events {
+ Transfer {
+ #[indexed]
+ from: address,
+ #[indexed]
+ to: address,
+ #[indexed]
+ token_id: uint256,
+ },
+ /// @dev Not supported
+ Approval {
+ #[indexed]
+ owner: address,
+ #[indexed]
+ approved: address,
+ #[indexed]
+ token_id: uint256,
+ },
+ /// @dev Not supported
+ #[allow(dead_code)]
+ ApprovalForAll {
+ #[indexed]
+ owner: address,
+ #[indexed]
+ operator: address,
+ approved: bool,
+ },
+}
+
+#[derive(ToLog)]
+pub enum ERC721MintableEvents {
+ /// @dev Not supported
+ #[allow(dead_code)]
+ MintingFinished {},
+}
+
+#[solidity_interface(name = "ERC721Metadata")]
+impl<T: Config> RefungibleHandle<T> {
+ fn name(&self) -> Result<string> {
+ Ok(decode_utf16(self.name.iter().copied())
+ .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
+ .collect::<string>())
+ }
+
+ fn symbol(&self) -> Result<string> {
+ Ok(string::from_utf8_lossy(&self.token_prefix).into())
+ }
+
+ /// @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
+ #[solidity(rename_selector = "tokenURI")]
+ 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);
+ }
+ } else if !is_erc721_metadata_compatible::<T>(self.id) {
+ return Err("tokenURI not set".into());
+ }
+
+ if let Some(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| {
+ 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());
+ }
+ }
+
+ Ok("".into())
+ }
+}
+
+#[solidity_interface(name = "ERC721Enumerable")]
+impl<T: Config> RefungibleHandle<T> {
+ fn token_by_index(&self, index: uint256) -> Result<uint256> {
+ Ok(index)
+ }
+
+ /// Not implemented
+ fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {
+ // TODO: Not implemetable
+ Err("not implemented".into())
+ }
+
+ fn total_supply(&self) -> Result<uint256> {
+ self.consume_store_reads(1)?;
+ Ok(<Pallet<T>>::total_supply(self).into())
+ }
+}
+
+#[solidity_interface(name = "ERC721", events(ERC721Events))]
+impl<T: Config> RefungibleHandle<T> {
+ fn balance_of(&self, owner: address) -> Result<uint256> {
+ self.consume_store_reads(1)?;
+ let owner = T::CrossAccountId::from_eth(owner);
+ let balance = <AccountBalance<T>>::get((self.id, owner));
+ Ok(balance.into())
+ }
+
+ fn owner_of(&self, token_id: uint256) -> Result<address> {
+ self.consume_store_reads(2)?;
+ let token = token_id.try_into()?;
+ let owner = <Pallet<T>>::token_owner(self.id, token);
+ Ok(owner
+ .map(|address| *address.as_eth())
+ .unwrap_or_else(|| H160::default()))
+ }
+
+ /// @dev Not implemented
+ fn safe_transfer_from_with_data(
+ &mut self,
+ _from: address,
+ _to: address,
+ _token_id: uint256,
+ _data: bytes,
+ _value: value,
+ ) -> Result<void> {
+ // TODO: Not implemetable
+ Err("not implemented".into())
+ }
+
+ /// @dev Not implemented
+ fn safe_transfer_from(
+ &mut self,
+ _from: address,
+ _to: address,
+ _token_id: uint256,
+ _value: value,
+ ) -> Result<void> {
+ // TODO: Not implemetable
+ Err("not implemented".into())
+ }
+
+ /// @dev Not implemented
+ fn transfer_from(
+ &mut self,
+ _caller: caller,
+ _from: address,
+ _to: address,
+ _token_id: uint256,
+ _value: value,
+ ) -> Result<void> {
+ Err("not implemented".into())
+ }
+
+ /// @dev Not implemented
+ fn approve(
+ &mut self,
+ _caller: caller,
+ _approved: address,
+ _token_id: uint256,
+ _value: value,
+ ) -> Result<void> {
+ Err("not implemented".into())
+ }
+
+ /// @dev Not implemented
+ fn set_approval_for_all(
+ &mut self,
+ _caller: caller,
+ _operator: address,
+ _approved: bool,
+ ) -> Result<void> {
+ // TODO: Not implemetable
+ Err("not implemented".into())
+ }
+
+ /// @dev Not implemented
+ fn get_approved(&self, _token_id: uint256) -> Result<address> {
+ // TODO: Not implemetable
+ Err("not implemented".into())
+ }
+
+ /// @dev Not implemented
+ fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {
+ // TODO: Not implemetable
+ Err("not implemented".into())
+ }
+}
+
+#[solidity_interface(name = "ERC721Burnable")]
+impl<T: Config> RefungibleHandle<T> {
+ /// @dev Not implemented
+ fn burn(&mut self, _caller: caller, _token_id: uint256, _value: value) -> Result<void> {
+ Err("not implemented".into())
+ }
+}
+
+#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]
+impl<T: Config> RefungibleHandle<T> {
+ fn minting_finished(&self) -> Result<bool> {
+ Ok(false)
+ }
+
+ /// `token_id` should be obtained with `next_token_id` method,
+ /// unlike standard, you can't specify it manually
+ #[weight(<SelfWeightOf<T>>::create_item())]
+ fn mint(&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()?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ if <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ != token_id
+ {
+ return Err("item id should be next".into());
+ }
+
+ let const_data = BoundedVec::default();
+ let users = [(to.clone(), 1)]
+ .into_iter()
+ .collect::<BTreeMap<_, _>>()
+ .try_into()
+ .unwrap();
+ <Pallet<T>>::create_item(
+ self,
+ &caller,
+ CreateItemData::<T> {
+ const_data,
+ users,
+ properties: CollectionPropertiesVec::default(),
+ },
+ &budget,
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+
+ Ok(true)
+ }
+
+ /// `token_id` should be obtained with `next_token_id` method,
+ /// unlike standard, you can't specify it manually
+ #[solidity(rename_selector = "mintWithTokenURI")]
+ #[weight(<SelfWeightOf<T>>::create_item())]
+ fn mint_with_token_uri(
+ &mut self,
+ caller: caller,
+ to: address,
+ token_id: uint256,
+ token_uri: string,
+ ) -> Result<bool> {
+ let key = key::url();
+ let permission = get_token_permission::<T>(self.id, &key)?;
+ if !permission.collection_admin {
+ return Err("Operation is not allowed".into());
+ }
+
+ let caller = T::CrossAccountId::from_eth(caller);
+ let to = T::CrossAccountId::from_eth(to);
+ let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ if <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ != token_id
+ {
+ return Err("item id should be next".into());
+ }
+
+ let mut properties = CollectionPropertiesVec::default();
+ properties
+ .try_push(Property {
+ key,
+ value: token_uri
+ .into_bytes()
+ .try_into()
+ .map_err(|_| "token uri is too long")?,
+ })
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+
+ let const_data = BoundedVec::default();
+ let users = [(to.clone(), 1)]
+ .into_iter()
+ .collect::<BTreeMap<_, _>>()
+ .try_into()
+ .unwrap();
+ <Pallet<T>>::create_item(
+ self,
+ &caller,
+ CreateItemData::<T> {
+ const_data,
+ users,
+ properties,
+ },
+ &budget,
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+
+ /// @dev Not implemented
+ fn finish_minting(&mut self, _caller: caller) -> Result<bool> {
+ Err("not implementable".into())
+ }
+}
+
+fn get_token_property<T: Config>(
+ collection: &CollectionHandle<T>,
+ token_id: u32,
+ key: &up_data_structs::PropertyKey,
+) -> Result<string> {
+ collection.consume_store_reads(1)?;
+ let properties = <TokenProperties<T>>::try_get((collection.id, token_id))
+ .map_err(|_| Error::Revert("Token properties not found".into()))?;
+ if let Some(property) = properties.get(key) {
+ return Ok(string::from_utf8_lossy(property).into());
+ }
+
+ 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,
+) -> Result<PropertyPermission> {
+ let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)
+ .map_err(|_| Error::Revert("No permissions for collection".into()))?;
+ let a = token_property_permissions
+ .get(key)
+ .map(Clone::clone)
+ .ok_or_else(|| {
+ let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();
+ Error::Revert(alloc::format!("No permission for key {}", key))
+ })?;
+ Ok(a)
+}
+
+#[solidity_interface(name = "ERC721UniqueExtensions")]
+impl<T: Config> RefungibleHandle<T> {
+ /// @notice Returns next free RFT ID.
+ fn next_token_id(&self) -> Result<uint256> {
+ self.consume_store_reads(1)?;
+ Ok(<TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ .into())
+ }
+
+ #[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);
+ let to = T::CrossAccountId::from_eth(to);
+ let mut expected_index = <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ let total_tokens = token_ids.len();
+ for id in token_ids.into_iter() {
+ let id: u32 = id.try_into().map_err(|_| "token id overflow")?;
+ if id != expected_index {
+ return Err("item id should be next".into());
+ }
+ expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
+ }
+ let const_data = BoundedVec::default();
+ let users = [(to.clone(), 1)]
+ .into_iter()
+ .collect::<BTreeMap<_, _>>()
+ .try_into()
+ .unwrap();
+ let create_item_data = CreateItemData::<T> {
+ const_data,
+ users,
+ properties: CollectionPropertiesVec::default(),
+ };
+ let data = (0..total_tokens)
+ .map(|_| create_item_data.clone())
+ .collect();
+
+ <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+
+ #[solidity(rename_selector = "mintBulkWithTokenURI")]
+ #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]
+ fn mint_bulk_with_token_uri(
+ &mut self,
+ caller: caller,
+ to: address,
+ tokens: Vec<(uint256, string)>,
+ ) -> Result<bool> {
+ let key = key::url();
+ let caller = T::CrossAccountId::from_eth(caller);
+ let to = T::CrossAccountId::from_eth(to);
+ let mut expected_index = <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ let mut data = Vec::with_capacity(tokens.len());
+ let const_data = BoundedVec::default();
+ let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]
+ .into_iter()
+ .collect::<BTreeMap<_, _>>()
+ .try_into()
+ .unwrap();
+ for (id, token_uri) in tokens {
+ let id: u32 = id.try_into().map_err(|_| "token id overflow")?;
+ if id != expected_index {
+ return Err("item id should be next".into());
+ }
+ expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
+
+ let mut properties = CollectionPropertiesVec::default();
+ properties
+ .try_push(Property {
+ key: key.clone(),
+ value: token_uri
+ .into_bytes()
+ .try_into()
+ .map_err(|_| "token uri is too long")?,
+ })
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+
+ let create_item_data = CreateItemData::<T> {
+ const_data: const_data.clone(),
+ users: users.clone(),
+ properties,
+ };
+ data.push(create_item_data);
+ }
+
+ <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+}
+
#[solidity_interface(
name = "UniqueRefungible",
- is(via("CollectionHandle<T>", common_mut, Collection),)
+ is(
+ ERC721,
+ ERC721Metadata,
+ ERC721Enumerable,
+ ERC721UniqueExtensions,
+ ERC721Mintable,
+ ERC721Burnable,
+ via("CollectionHandle<T>", common_mut, Collection),
+ TokenProperties,
+ )
)]
impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> {}
pallets/refungible/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//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//! of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//! Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//! transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//! an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//! with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//! collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//! Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;9192use codec::{Encode, Decode, MaxEncodedLen};93use core::ops::Deref;94use evm_coder::ToLog;95use frame_support::{BoundedVec, ensure, fail, storage::with_transaction, transactional};96use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};97use pallet_evm_coder_substrate::WithRecorder;98use pallet_common::{99 CommonCollectionOperations, Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,100};101use pallet_structure::Pallet as PalletStructure;102use scale_info::TypeInfo;103use sp_core::H160;104use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};105use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};106use up_data_structs::{107 AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData,108 CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId, Property,109 PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,110 TrySetProperty,111};112113pub use pallet::*;114#[cfg(feature = "runtime-benchmarks")]115pub mod benchmarking;116pub mod common;117pub mod erc;118pub mod erc_token;119pub mod weights;120pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;121122/// Token data, stored independently from other data used to describe it123/// for the convenience of database access. Notably contains the token metadata.124#[struct_versioning::versioned(version = 2, upper)]125#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]126pub struct ItemData {127 pub const_data: BoundedVec<u8, CustomDataLimit>,128129 #[version(..2)]130 pub variable_data: BoundedVec<u8, CustomDataLimit>,131}132133#[frame_support::pallet]134pub mod pallet {135 use super::*;136 use frame_support::{137 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,138 traits::StorageVersion,139 };140 use frame_system::pallet_prelude::*;141 use up_data_structs::{CollectionId, TokenId};142 use super::weights::WeightInfo;143144 #[pallet::error]145 pub enum Error<T> {146 /// Not Refungible item data used to mint in Refungible collection.147 NotRefungibleDataUsedToMintFungibleCollectionToken,148 /// Maximum refungibility exceeded.149 WrongRefungiblePieces,150 /// Refungible token can't be repartitioned by user who isn't owns all pieces.151 RepartitionWhileNotOwningAllPieces,152 /// Refungible token can't nest other tokens.153 RefungibleDisallowsNesting,154 /// Setting item properties is not allowed.155 SettingPropertiesNotAllowed,156 }157158 #[pallet::config]159 pub trait Config:160 frame_system::Config + pallet_common::Config + pallet_structure::Config161 {162 type WeightInfo: WeightInfo;163 }164165 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);166167 #[pallet::pallet]168 #[pallet::storage_version(STORAGE_VERSION)]169 #[pallet::generate_store(pub(super) trait Store)]170 pub struct Pallet<T>(_);171172 /// Total amount of minted tokens in a collection.173 #[pallet::storage]174 pub type TokensMinted<T: Config> =175 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;176177 /// Amount of tokens burnt in a collection.178 #[pallet::storage]179 pub type TokensBurnt<T: Config> =180 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;181182 /// Token data, used to partially describe a token.183 #[pallet::storage]184 pub type TokenData<T: Config> = StorageNMap<185 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),186 Value = ItemData,187 QueryKind = ValueQuery,188 >;189190 /// Amount of pieces a refungible token is split into.191 #[pallet::storage]192 #[pallet::getter(fn token_properties)]193 pub type TokenProperties<T: Config> = StorageNMap<194 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),195 Value = up_data_structs::Properties,196 QueryKind = ValueQuery,197 OnEmpty = up_data_structs::TokenProperties,198 >;199200 /// Total amount of pieces for token201 #[pallet::storage]202 pub type TotalSupply<T: Config> = StorageNMap<203 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),204 Value = u128,205 QueryKind = ValueQuery,206 >;207208 /// Used to enumerate tokens owned by account.209 #[pallet::storage]210 pub type Owned<T: Config> = StorageNMap<211 Key = (212 Key<Twox64Concat, CollectionId>,213 Key<Blake2_128Concat, T::CrossAccountId>,214 Key<Twox64Concat, TokenId>,215 ),216 Value = bool,217 QueryKind = ValueQuery,218 >;219220 /// Amount of tokens (not pieces) partially owned by an account within a collection.221 #[pallet::storage]222 pub type AccountBalance<T: Config> = StorageNMap<223 Key = (224 Key<Twox64Concat, CollectionId>,225 // Owner226 Key<Blake2_128Concat, T::CrossAccountId>,227 ),228 Value = u32,229 QueryKind = ValueQuery,230 >;231232 /// Amount of token pieces owned by account.233 #[pallet::storage]234 pub type Balance<T: Config> = StorageNMap<235 Key = (236 Key<Twox64Concat, CollectionId>,237 Key<Twox64Concat, TokenId>,238 // Owner239 Key<Blake2_128Concat, T::CrossAccountId>,240 ),241 Value = u128,242 QueryKind = ValueQuery,243 >;244245 /// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.246 #[pallet::storage]247 pub type Allowance<T: Config> = StorageNMap<248 Key = (249 Key<Twox64Concat, CollectionId>,250 Key<Twox64Concat, TokenId>,251 // Owner252 Key<Blake2_128, T::CrossAccountId>,253 // Spender254 Key<Blake2_128Concat, T::CrossAccountId>,255 ),256 Value = u128,257 QueryKind = ValueQuery,258 >;259260 #[pallet::hooks]261 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {262 fn on_runtime_upgrade() -> Weight {263 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {264 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {265 Some(<ItemDataVersion2>::from(v))266 })267 }268269 0270 }271 }272}273274pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);275impl<T: Config> RefungibleHandle<T> {276 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {277 Self(inner)278 }279 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {280 self.0281 }282 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {283 &mut self.0284 }285}286287impl<T: Config> Deref for RefungibleHandle<T> {288 type Target = pallet_common::CollectionHandle<T>;289290 fn deref(&self) -> &Self::Target {291 &self.0292 }293}294295impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {296 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {297 self.0.recorder()298 }299 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {300 self.0.into_recorder()301 }302}303304impl<T: Config> Pallet<T> {305 /// Get number of RFT tokens in collection306 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {307 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)308 }309310 /// Check that RFT token exists311 ///312 /// - `token`: Token ID.313 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {314 <TotalSupply<T>>::contains_key((collection.id, token))315 }316317 pub fn set_scoped_token_property(318 collection_id: CollectionId,319 token_id: TokenId,320 scope: PropertyScope,321 property: Property,322 ) -> DispatchResult {323 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {324 properties.try_scoped_set(scope, property.key, property.value)325 })326 .map_err(<CommonError<T>>::from)?;327328 Ok(())329 }330331 pub fn set_scoped_token_properties(332 collection_id: CollectionId,333 token_id: TokenId,334 scope: PropertyScope,335 properties: impl Iterator<Item = Property>,336 ) -> DispatchResult {337 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {338 stored_properties.try_scoped_set_from_iter(scope, properties)339 })340 .map_err(<CommonError<T>>::from)?;341342 Ok(())343 }344}345346// unchecked calls skips any permission checks347impl<T: Config> Pallet<T> {348 /// Create RFT collection349 ///350 /// `init_collection` will take non-refundable deposit for collection creation.351 ///352 /// - `data`: Contains settings for collection limits and permissions.353 pub fn init_collection(354 owner: T::CrossAccountId,355 data: CreateCollectionData<T::AccountId>,356 ) -> Result<CollectionId, DispatchError> {357 <PalletCommon<T>>::init_collection(owner, data, false)358 }359360 /// Destroy RFT collection361 ///362 /// `destroy_collection` will throw error if collection contains any tokens.363 /// Only owner can destroy collection.364 pub fn destroy_collection(365 collection: RefungibleHandle<T>,366 sender: &T::CrossAccountId,367 ) -> DispatchResult {368 let id = collection.id;369370 if Self::collection_has_tokens(id) {371 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());372 }373374 // =========375376 PalletCommon::destroy_collection(collection.0, sender)?;377378 <TokensMinted<T>>::remove(id);379 <TokensBurnt<T>>::remove(id);380 <TokenData<T>>::remove_prefix((id,), None);381 <TotalSupply<T>>::remove_prefix((id,), None);382 <Balance<T>>::remove_prefix((id,), None);383 <Allowance<T>>::remove_prefix((id,), None);384 <Owned<T>>::remove_prefix((id,), None);385 <AccountBalance<T>>::remove_prefix((id,), None);386 Ok(())387 }388389 fn collection_has_tokens(collection_id: CollectionId) -> bool {390 <TokenData<T>>::iter_prefix((collection_id,))391 .next()392 .is_some()393 }394395 pub fn burn_token_unchecked(396 collection: &RefungibleHandle<T>,397 token_id: TokenId,398 ) -> DispatchResult {399 let burnt = <TokensBurnt<T>>::get(collection.id)400 .checked_add(1)401 .ok_or(ArithmeticError::Overflow)?;402403 <TokensBurnt<T>>::insert(collection.id, burnt);404 <TokenData<T>>::remove((collection.id, token_id));405 <TokenProperties<T>>::remove((collection.id, token_id));406 <TotalSupply<T>>::remove((collection.id, token_id));407 <Balance<T>>::remove_prefix((collection.id, token_id), None);408 <Allowance<T>>::remove_prefix((collection.id, token_id), None);409 // TODO: ERC721 transfer event410 Ok(())411 }412413 /// Burn RFT token pieces414 ///415 /// `burn` will decrease total amount of token pieces and amount owned by sender.416 /// `burn` can be called even if there are multiple owners of the RFT token.417 /// If sender wouldn't have any pieces left after `burn` than she will stop being418 /// one of the owners of the token. If there is no account that owns any pieces of419 /// the token than token will be burned too.420 ///421 /// - `amount`: Amount of token pieces to burn.422 /// - `token`: Token who's pieces should be burned423 /// - `collection`: Collection that contains the token424 pub fn burn(425 collection: &RefungibleHandle<T>,426 owner: &T::CrossAccountId,427 token: TokenId,428 amount: u128,429 ) -> DispatchResult {430 let total_supply = <TotalSupply<T>>::get((collection.id, token))431 .checked_sub(amount)432 .ok_or(<CommonError<T>>::TokenValueTooLow)?;433434 // This was probally last owner of this token?435 if total_supply == 0 {436 // Ensure user actually owns this amount437 ensure!(438 <Balance<T>>::get((collection.id, token, owner)) == amount,439 <CommonError<T>>::TokenValueTooLow440 );441 let account_balance = <AccountBalance<T>>::get((collection.id, owner))442 .checked_sub(1)443 // Should not occur444 .ok_or(ArithmeticError::Underflow)?;445446 // =========447448 <Owned<T>>::remove((collection.id, owner, token));449 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);450 <AccountBalance<T>>::insert((collection.id, owner), account_balance);451 Self::burn_token_unchecked(collection, token)?;452 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(453 collection.id,454 token,455 owner.clone(),456 amount,457 ));458 return Ok(());459 }460461 let balance = <Balance<T>>::get((collection.id, token, owner))462 .checked_sub(amount)463 .ok_or(<CommonError<T>>::TokenValueTooLow)?;464 let account_balance = if balance == 0 {465 <AccountBalance<T>>::get((collection.id, owner))466 .checked_sub(1)467 // Should not occur468 .ok_or(ArithmeticError::Underflow)?469 } else {470 0471 };472473 // =========474475 if balance == 0 {476 <Owned<T>>::remove((collection.id, owner, token));477 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);478 <Balance<T>>::remove((collection.id, token, owner));479 <AccountBalance<T>>::insert((collection.id, owner), account_balance);480 } else {481 <Balance<T>>::insert((collection.id, token, owner), balance);482 }483 <TotalSupply<T>>::insert((collection.id, token), total_supply);484485 <PalletEvm<T>>::deposit_log(486 ERC20Events::Transfer {487 from: *owner.as_eth(),488 to: H160::default(),489 value: amount.into(),490 }491 .to_log(T::EvmTokenAddressMapping::token_to_address(492 collection.id,493 token,494 )),495 );496 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(497 collection.id,498 token,499 owner.clone(),500 amount,501 ));502 Ok(())503 }504505 #[transactional]506 fn modify_token_properties(507 collection: &RefungibleHandle<T>,508 sender: &T::CrossAccountId,509 token_id: TokenId,510 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,511 is_token_create: bool,512 nesting_budget: &dyn Budget,513 ) -> DispatchResult {514 let is_collection_admin = || collection.is_owner_or_admin(sender);515 let is_token_owner = || -> Result<bool, DispatchError> {516 let balance = collection.balance(sender.clone(), token_id);517 let total_pieces: u128 =518 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);519 if balance != total_pieces {520 return Ok(false);521 }522523 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(524 sender.clone(),525 collection.id,526 token_id,527 None,528 nesting_budget,529 )?;530531 Ok(is_bundle_owner)532 };533534 for (key, value) in properties {535 let permission = <PalletCommon<T>>::property_permissions(collection.id)536 .get(&key)537 .cloned()538 .unwrap_or_else(PropertyPermission::none);539540 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))541 .get(&key)542 .is_some();543544 match permission {545 PropertyPermission { mutable: false, .. } if is_property_exists => {546 return Err(<CommonError<T>>::NoPermission.into());547 }548549 PropertyPermission {550 collection_admin,551 token_owner,552 ..553 } => {554 //TODO: investigate threats during public minting.555 let is_token_create =556 is_token_create && (collection_admin || token_owner) && value.is_some();557 if !(is_token_create558 || (collection_admin && is_collection_admin())559 || (token_owner && is_token_owner()?))560 {561 fail!(<CommonError<T>>::NoPermission);562 }563 }564 }565566 match value {567 Some(value) => {568 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {569 properties.try_set(key.clone(), value)570 })571 .map_err(<CommonError<T>>::from)?;572573 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(574 collection.id,575 token_id,576 key,577 ));578 }579 None => {580 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {581 properties.remove(&key)582 })583 .map_err(<CommonError<T>>::from)?;584585 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(586 collection.id,587 token_id,588 key,589 ));590 }591 }592 }593594 Ok(())595 }596597 pub fn set_token_properties(598 collection: &RefungibleHandle<T>,599 sender: &T::CrossAccountId,600 token_id: TokenId,601 properties: impl Iterator<Item = Property>,602 is_token_create: bool,603 nesting_budget: &dyn Budget,604 ) -> DispatchResult {605 Self::modify_token_properties(606 collection,607 sender,608 token_id,609 properties.map(|p| (p.key, Some(p.value))),610 is_token_create,611 nesting_budget,612 )613 }614615 pub fn set_token_property(616 collection: &RefungibleHandle<T>,617 sender: &T::CrossAccountId,618 token_id: TokenId,619 property: Property,620 nesting_budget: &dyn Budget,621 ) -> DispatchResult {622 let is_token_create = false;623624 Self::set_token_properties(625 collection,626 sender,627 token_id,628 [property].into_iter(),629 is_token_create,630 nesting_budget,631 )632 }633634 pub fn delete_token_properties(635 collection: &RefungibleHandle<T>,636 sender: &T::CrossAccountId,637 token_id: TokenId,638 property_keys: impl Iterator<Item = PropertyKey>,639 nesting_budget: &dyn Budget,640 ) -> DispatchResult {641 let is_token_create = false;642643 Self::modify_token_properties(644 collection,645 sender,646 token_id,647 property_keys.into_iter().map(|key| (key, None)),648 is_token_create,649 nesting_budget,650 )651 }652653 pub fn delete_token_property(654 collection: &RefungibleHandle<T>,655 sender: &T::CrossAccountId,656 token_id: TokenId,657 property_key: PropertyKey,658 nesting_budget: &dyn Budget,659 ) -> DispatchResult {660 Self::delete_token_properties(661 collection,662 sender,663 token_id,664 [property_key].into_iter(),665 nesting_budget,666 )667 }668669 /// Transfer RFT token pieces from one account to another.670 ///671 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.672 ///673 /// - `from`: Owner of token pieces to transfer.674 /// - `to`: Recepient of transfered token pieces.675 /// - `amount`: Amount of token pieces to transfer.676 /// - `token`: Token whos pieces should be transfered677 /// - `collection`: Collection that contains the token678 pub fn transfer(679 collection: &RefungibleHandle<T>,680 from: &T::CrossAccountId,681 to: &T::CrossAccountId,682 token: TokenId,683 amount: u128,684 nesting_budget: &dyn Budget,685 ) -> DispatchResult {686 ensure!(687 collection.limits.transfers_enabled(),688 <CommonError<T>>::TransferNotAllowed689 );690691 if collection.permissions.access() == AccessMode::AllowList {692 collection.check_allowlist(from)?;693 collection.check_allowlist(to)?;694 }695 <PalletCommon<T>>::ensure_correct_receiver(to)?;696697 let balance_from = <Balance<T>>::get((collection.id, token, from))698 .checked_sub(amount)699 .ok_or(<CommonError<T>>::TokenValueTooLow)?;700 let mut create_target = false;701 let from_to_differ = from != to;702 let balance_to = if from != to {703 let old_balance = <Balance<T>>::get((collection.id, token, to));704 if old_balance == 0 {705 create_target = true;706 }707 Some(708 old_balance709 .checked_add(amount)710 .ok_or(ArithmeticError::Overflow)?,711 )712 } else {713 None714 };715716 let account_balance_from = if balance_from == 0 {717 Some(718 <AccountBalance<T>>::get((collection.id, from))719 .checked_sub(1)720 // Should not occur721 .ok_or(ArithmeticError::Underflow)?,722 )723 } else {724 None725 };726 // Account data is created in token, AccountBalance should be increased727 // But only if from != to as we shouldn't check overflow in this case728 let account_balance_to = if create_target && from_to_differ {729 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))730 .checked_add(1)731 .ok_or(ArithmeticError::Overflow)?;732 ensure!(733 account_balance_to < collection.limits.account_token_ownership_limit(),734 <CommonError<T>>::AccountTokenLimitExceeded,735 );736737 Some(account_balance_to)738 } else {739 None740 };741742 // =========743744 <PalletStructure<T>>::nest_if_sent_to_token(745 from.clone(),746 to,747 collection.id,748 token,749 nesting_budget,750 )?;751752 if let Some(balance_to) = balance_to {753 // from != to754 if balance_from == 0 {755 <Balance<T>>::remove((collection.id, token, from));756 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);757 } else {758 <Balance<T>>::insert((collection.id, token, from), balance_from);759 }760 <Balance<T>>::insert((collection.id, token, to), balance_to);761 if let Some(account_balance_from) = account_balance_from {762 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);763 <Owned<T>>::remove((collection.id, from, token));764 }765 if let Some(account_balance_to) = account_balance_to {766 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);767 <Owned<T>>::insert((collection.id, to, token), true);768 }769 }770771 <PalletEvm<T>>::deposit_log(772 ERC20Events::Transfer {773 from: *from.as_eth(),774 to: *to.as_eth(),775 value: amount.into(),776 }777 .to_log(T::EvmTokenAddressMapping::token_to_address(778 collection.id,779 token,780 )),781 );782 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(783 collection.id,784 token,785 from.clone(),786 to.clone(),787 amount,788 ));789 Ok(())790 }791792 /// Batched operation to create multiple RFT tokens.793 ///794 /// Same as `create_item` but creates multiple tokens.795 ///796 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.797 pub fn create_multiple_items(798 collection: &RefungibleHandle<T>,799 sender: &T::CrossAccountId,800 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,801 nesting_budget: &dyn Budget,802 ) -> DispatchResult {803 if !collection.is_owner_or_admin(sender) {804 ensure!(805 collection.permissions.mint_mode(),806 <CommonError<T>>::PublicMintingNotAllowed807 );808 collection.check_allowlist(sender)?;809810 for item in data.iter() {811 for user in item.users.keys() {812 collection.check_allowlist(user)?;813 }814 }815 }816817 for item in data.iter() {818 for (owner, _) in item.users.iter() {819 <PalletCommon<T>>::ensure_correct_receiver(owner)?;820 }821 }822823 // Total pieces per tokens824 let totals = data825 .iter()826 .map(|data| {827 Ok(data828 .users829 .iter()830 .map(|u| u.1)831 .try_fold(0u128, |acc, v| acc.checked_add(*v))832 .ok_or(ArithmeticError::Overflow)?)833 })834 .collect::<Result<Vec<_>, DispatchError>>()?;835 for total in &totals {836 ensure!(837 *total <= MAX_REFUNGIBLE_PIECES,838 <Error<T>>::WrongRefungiblePieces839 );840 }841842 let first_token_id = <TokensMinted<T>>::get(collection.id);843 let tokens_minted = first_token_id844 .checked_add(data.len() as u32)845 .ok_or(ArithmeticError::Overflow)?;846 ensure!(847 tokens_minted < collection.limits.token_limit(),848 <CommonError<T>>::CollectionTokenLimitExceeded849 );850851 let mut balances = BTreeMap::new();852 for data in &data {853 for owner in data.users.keys() {854 let balance = balances855 .entry(owner)856 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));857 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;858859 ensure!(860 *balance <= collection.limits.account_token_ownership_limit(),861 <CommonError<T>>::AccountTokenLimitExceeded,862 );863 }864 }865866 for (i, token) in data.iter().enumerate() {867 let token_id = TokenId(first_token_id + i as u32 + 1);868 for (to, _) in token.users.iter() {869 <PalletStructure<T>>::check_nesting(870 sender.clone(),871 to,872 collection.id,873 token_id,874 nesting_budget,875 )?;876 }877 }878879 // =========880881 with_transaction(|| {882 for (i, data) in data.iter().enumerate() {883 let token_id = first_token_id + i as u32 + 1;884 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);885886 <TokenData<T>>::insert(887 (collection.id, token_id),888 ItemData {889 const_data: data.const_data.clone(),890 },891 );892893 for (user, amount) in data.users.iter() {894 if *amount == 0 {895 continue;896 }897 <Balance<T>>::insert((collection.id, token_id, &user), amount);898 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);899 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(900 user,901 collection.id,902 TokenId(token_id),903 );904 }905906 if let Err(e) = Self::set_token_properties(907 collection,908 sender,909 TokenId(token_id),910 data.properties.clone().into_iter(),911 true,912 nesting_budget,913 ) {914 return TransactionOutcome::Rollback(Err(e));915 }916 }917 TransactionOutcome::Commit(Ok(()))918 })?;919920 <TokensMinted<T>>::insert(collection.id, tokens_minted);921922 for (account, balance) in balances {923 <AccountBalance<T>>::insert((collection.id, account), balance);924 }925926 for (i, token) in data.into_iter().enumerate() {927 let token_id = first_token_id + i as u32 + 1;928929 for (user, amount) in token.users.into_iter() {930 if amount == 0 {931 continue;932 }933934 <PalletEvm<T>>::deposit_log(935 ERC20Events::Transfer {936 from: H160::default(),937 to: *user.as_eth(),938 value: amount.into(),939 }940 .to_log(T::EvmTokenAddressMapping::token_to_address(941 collection.id,942 TokenId(token_id),943 )),944 );945 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(946 collection.id,947 TokenId(token_id),948 user,949 amount,950 ));951 }952 }953 Ok(())954 }955956 pub fn set_allowance_unchecked(957 collection: &RefungibleHandle<T>,958 sender: &T::CrossAccountId,959 spender: &T::CrossAccountId,960 token: TokenId,961 amount: u128,962 ) {963 if amount == 0 {964 <Allowance<T>>::remove((collection.id, token, sender, spender));965 } else {966 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);967 }968969 <PalletEvm<T>>::deposit_log(970 ERC20Events::Approval {971 owner: *sender.as_eth(),972 spender: *spender.as_eth(),973 value: amount.into(),974 }975 .to_log(T::EvmTokenAddressMapping::token_to_address(976 collection.id,977 token,978 )),979 );980 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(981 collection.id,982 token,983 sender.clone(),984 spender.clone(),985 amount,986 ))987 }988989 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.990 ///991 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.992 pub fn set_allowance(993 collection: &RefungibleHandle<T>,994 sender: &T::CrossAccountId,995 spender: &T::CrossAccountId,996 token: TokenId,997 amount: u128,998 ) -> DispatchResult {999 if collection.permissions.access() == AccessMode::AllowList {1000 collection.check_allowlist(sender)?;1001 collection.check_allowlist(spender)?;1002 }10031004 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10051006 if <Balance<T>>::get((collection.id, token, sender)) < amount {1007 ensure!(1008 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1009 <CommonError<T>>::CantApproveMoreThanOwned1010 );1011 }10121013 // =========10141015 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1016 Ok(())1017 }10181019 /// Returns allowance, which should be set after transaction1020 fn check_allowed(1021 collection: &RefungibleHandle<T>,1022 spender: &T::CrossAccountId,1023 from: &T::CrossAccountId,1024 token: TokenId,1025 amount: u128,1026 nesting_budget: &dyn Budget,1027 ) -> Result<Option<u128>, DispatchError> {1028 if spender.conv_eq(from) {1029 return Ok(None);1030 }1031 if collection.permissions.access() == AccessMode::AllowList {1032 // `from`, `to` checked in [`transfer`]1033 collection.check_allowlist(spender)?;1034 }1035 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1036 // TODO: should collection owner be allowed to perform this transfer?1037 ensure!(1038 <PalletStructure<T>>::check_indirectly_owned(1039 spender.clone(),1040 source.0,1041 source.1,1042 None,1043 nesting_budget1044 )?,1045 <CommonError<T>>::ApprovedValueTooLow,1046 );1047 return Ok(None);1048 }1049 let allowance =1050 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1051 if allowance.is_none() {1052 ensure!(1053 collection.ignores_allowance(spender),1054 <CommonError<T>>::ApprovedValueTooLow1055 );1056 }1057 Ok(allowance)1058 }10591060 /// Transfer RFT token pieces from one account to another.1061 ///1062 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1063 /// The owner should set allowance for the spender to transfer pieces.1064 ///1065 /// [`transfer`]: struct.Pallet.html#method.transfer1066 pub fn transfer_from(1067 collection: &RefungibleHandle<T>,1068 spender: &T::CrossAccountId,1069 from: &T::CrossAccountId,1070 to: &T::CrossAccountId,1071 token: TokenId,1072 amount: u128,1073 nesting_budget: &dyn Budget,1074 ) -> DispatchResult {1075 let allowance =1076 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10771078 // =========10791080 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1081 if let Some(allowance) = allowance {1082 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1083 }1084 Ok(())1085 }10861087 /// Burn RFT token pieces from the account.1088 ///1089 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1090 /// set allowance for the spender to burn pieces1091 ///1092 /// [`burn`]: struct.Pallet.html#method.burn1093 pub fn burn_from(1094 collection: &RefungibleHandle<T>,1095 spender: &T::CrossAccountId,1096 from: &T::CrossAccountId,1097 token: TokenId,1098 amount: u128,1099 nesting_budget: &dyn Budget,1100 ) -> DispatchResult {1101 let allowance =1102 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11031104 // =========11051106 Self::burn(collection, from, token, amount)?;1107 if let Some(allowance) = allowance {1108 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1109 }1110 Ok(())1111 }11121113 /// Create RFT token.1114 ///1115 /// The sender should be the owner/admin of the collection or collection should be configured1116 /// to allow public minting.1117 ///1118 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1119 /// of token pieces they will receive.1120 pub fn create_item(1121 collection: &RefungibleHandle<T>,1122 sender: &T::CrossAccountId,1123 data: CreateRefungibleExData<T::CrossAccountId>,1124 nesting_budget: &dyn Budget,1125 ) -> DispatchResult {1126 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1127 }11281129 /// Repartition RFT token.1130 ///1131 /// `repartition` will set token balance of the sender and total amount of token pieces.1132 /// Sender should own all of the token pieces. `repartition' could be done even if some1133 /// token pieces were burned before.1134 ///1135 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1136 pub fn repartition(1137 collection: &RefungibleHandle<T>,1138 owner: &T::CrossAccountId,1139 token: TokenId,1140 amount: u128,1141 ) -> DispatchResult {1142 ensure!(1143 amount <= MAX_REFUNGIBLE_PIECES,1144 <Error<T>>::WrongRefungiblePieces1145 );1146 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1147 // Ensure user owns all pieces1148 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1149 let balance = <Balance<T>>::get((collection.id, token, owner));1150 ensure!(1151 total_pieces == balance,1152 <Error<T>>::RepartitionWhileNotOwningAllPieces1153 );11541155 <Balance<T>>::insert((collection.id, token, owner), amount);1156 <TotalSupply<T>>::insert((collection.id, token), amount);11571158 if amount > total_pieces {1159 let mint_amount = amount - total_pieces;1160 <PalletEvm<T>>::deposit_log(1161 ERC20Events::Transfer {1162 from: H160::default(),1163 to: *owner.as_eth(),1164 value: mint_amount.into(),1165 }1166 .to_log(T::EvmTokenAddressMapping::token_to_address(1167 collection.id,1168 token,1169 )),1170 );1171 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1172 collection.id,1173 token,1174 owner.clone(),1175 mint_amount,1176 ));1177 } else if total_pieces > amount {1178 let burn_amount = total_pieces - amount;1179 <PalletEvm<T>>::deposit_log(1180 ERC20Events::Transfer {1181 from: *owner.as_eth(),1182 to: H160::default(),1183 value: burn_amount.into(),1184 }1185 .to_log(T::EvmTokenAddressMapping::token_to_address(1186 collection.id,1187 token,1188 )),1189 );1190 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1191 collection.id,1192 token,1193 owner.clone(),1194 burn_amount,1195 ));1196 }11971198 Ok(())1199 }12001201 fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1202 let mut owner = None;1203 let mut count = 0;1204 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1205 count += 1;1206 if count > 1 {1207 return None;1208 }1209 owner = Some(key);1210 }1211 owner1212 }12131214 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1215 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1216 }12171218 pub fn set_collection_properties(1219 collection: &RefungibleHandle<T>,1220 sender: &T::CrossAccountId,1221 properties: Vec<Property>,1222 ) -> DispatchResult {1223 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)1224 }12251226 pub fn delete_collection_properties(1227 collection: &RefungibleHandle<T>,1228 sender: &T::CrossAccountId,1229 property_keys: Vec<PropertyKey>,1230 ) -> DispatchResult {1231 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1232 }12331234 pub fn set_token_property_permissions(1235 collection: &RefungibleHandle<T>,1236 sender: &T::CrossAccountId,1237 property_permissions: Vec<PropertyKeyPermission>,1238 ) -> DispatchResult {1239 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1240 }12411242 /// Returns 10 token in no particular order.1243 ///1244 /// There is no direct way to get token holders in ascending order,1245 /// since `iter_prefix` returns values in no particular order.1246 /// Therefore, getting the 10 largest holders with a large value of holders1247 /// can lead to impact memory allocation + sorting with `n * log (n)`.1248 pub fn token_owners(1249 collection_id: CollectionId,1250 token: TokenId,1251 ) -> Option<Vec<T::CrossAccountId>> {1252 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1253 .map(|(owner, _amount)| owner)1254 .take(10)1255 .collect();12561257 if res.is_empty() {1258 None1259 } else {1260 Some(res)1261 }1262 }1263}pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -3,6 +3,12 @@
pragma solidity >=0.8.0 <0.9.0;
+// Anonymous struct
+struct Tuple0 {
+ uint256 field_0;
+ string field_1;
+}
+
// Common stubs holder
contract Dummy {
uint8 dummy;
@@ -21,6 +27,351 @@
}
}
+// Inline
+contract ERC721Events {
+ event Transfer(
+ address indexed from,
+ address indexed to,
+ uint256 indexed tokenId
+ );
+ event Approval(
+ address indexed owner,
+ address indexed approved,
+ uint256 indexed tokenId
+ );
+ event ApprovalForAll(
+ address indexed owner,
+ address indexed operator,
+ bool approved
+ );
+}
+
+// Inline
+contract ERC721MintableEvents {
+ event MintingFinished();
+}
+
+// Selector: 0784ee64
+contract ERC721UniqueExtensions is Dummy, ERC165 {
+ // @notice Returns next free RFT ID.
+ //
+ // Selector: nextTokenId() 75794a3c
+ function nextTokenId() public view returns (uint256) {
+ require(false, stub_error);
+ dummy;
+ return 0;
+ }
+
+ // Selector: mintBulk(address,uint256[]) 44a9945e
+ function mintBulk(address to, uint256[] memory tokenIds)
+ public
+ returns (bool)
+ {
+ require(false, stub_error);
+ to;
+ tokenIds;
+ dummy = 0;
+ return false;
+ }
+
+ // Selector: mintBulkWithTokenURI(address,(uint256,string)[]) 36543006
+ function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
+ public
+ returns (bool)
+ {
+ require(false, stub_error);
+ to;
+ tokens;
+ dummy = 0;
+ return false;
+ }
+}
+
+// Selector: 41369377
+contract TokenProperties is Dummy, ERC165 {
+ // Selector: setTokenPropertyPermission(string,bool,bool,bool) 222d97fa
+ function setTokenPropertyPermission(
+ string memory key,
+ bool isMutable,
+ bool collectionAdmin,
+ bool tokenOwner
+ ) public {
+ require(false, stub_error);
+ key;
+ isMutable;
+ collectionAdmin;
+ tokenOwner;
+ dummy = 0;
+ }
+
+ // Selector: setProperty(uint256,string,bytes) 1752d67b
+ function setProperty(
+ uint256 tokenId,
+ string memory key,
+ bytes memory value
+ ) public {
+ require(false, stub_error);
+ tokenId;
+ key;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: deleteProperty(uint256,string) 066111d1
+ function deleteProperty(uint256 tokenId, string memory key) public {
+ require(false, stub_error);
+ tokenId;
+ key;
+ dummy = 0;
+ }
+
+ // Throws error if key not found
+ //
+ // Selector: property(uint256,string) 7228c327
+ function property(uint256 tokenId, string memory key)
+ public
+ view
+ returns (bytes memory)
+ {
+ require(false, stub_error);
+ tokenId;
+ key;
+ dummy;
+ return hex"";
+ }
+}
+
+// Selector: 42966c68
+contract ERC721Burnable is Dummy, ERC165 {
+ // @dev Not implemented
+ //
+ // Selector: burn(uint256) 42966c68
+ function burn(uint256 tokenId) public {
+ require(false, stub_error);
+ tokenId;
+ dummy = 0;
+ }
+}
+
+// Selector: 58800161
+contract ERC721 is Dummy, ERC165, ERC721Events {
+ // Selector: balanceOf(address) 70a08231
+ function balanceOf(address owner) public view returns (uint256) {
+ require(false, stub_error);
+ owner;
+ dummy;
+ return 0;
+ }
+
+ // Selector: ownerOf(uint256) 6352211e
+ function ownerOf(uint256 tokenId) public view returns (address) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+
+ // @dev Not implemented
+ //
+ // Selector: safeTransferFromWithData(address,address,uint256,bytes) 60a11672
+ function safeTransferFromWithData(
+ address from,
+ address to,
+ uint256 tokenId,
+ bytes memory data
+ ) public {
+ require(false, stub_error);
+ from;
+ to;
+ tokenId;
+ data;
+ dummy = 0;
+ }
+
+ // @dev Not implemented
+ //
+ // Selector: safeTransferFrom(address,address,uint256) 42842e0e
+ function safeTransferFrom(
+ address from,
+ address to,
+ uint256 tokenId
+ ) public {
+ require(false, stub_error);
+ from;
+ to;
+ tokenId;
+ dummy = 0;
+ }
+
+ // @dev Not implemented
+ //
+ // Selector: transferFrom(address,address,uint256) 23b872dd
+ function transferFrom(
+ address from,
+ address to,
+ uint256 tokenId
+ ) public {
+ require(false, stub_error);
+ from;
+ to;
+ tokenId;
+ dummy = 0;
+ }
+
+ // @dev Not implemented
+ //
+ // Selector: approve(address,uint256) 095ea7b3
+ function approve(address approved, uint256 tokenId) public {
+ require(false, stub_error);
+ approved;
+ tokenId;
+ dummy = 0;
+ }
+
+ // @dev Not implemented
+ //
+ // Selector: setApprovalForAll(address,bool) a22cb465
+ function setApprovalForAll(address operator, bool approved) public {
+ require(false, stub_error);
+ operator;
+ approved;
+ dummy = 0;
+ }
+
+ // @dev Not implemented
+ //
+ // Selector: getApproved(uint256) 081812fc
+ function getApproved(uint256 tokenId) public view returns (address) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+
+ // @dev Not implemented
+ //
+ // Selector: isApprovedForAll(address,address) e985e9c5
+ function isApprovedForAll(address owner, address operator)
+ public
+ view
+ returns (address)
+ {
+ require(false, stub_error);
+ owner;
+ operator;
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+}
+
+// Selector: 5b5e139f
+contract ERC721Metadata is Dummy, ERC165 {
+ // Selector: name() 06fdde03
+ function name() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ // Selector: symbol() 95d89b41
+ function symbol() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ // Returns token's const_metadata
+ //
+ // Selector: tokenURI(uint256) c87b56dd
+ function tokenURI(uint256 tokenId) public view returns (string memory) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return "";
+ }
+}
+
+// Selector: 68ccfe89
+contract ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+ // Selector: mintingFinished() 05d2035b
+ function mintingFinished() public view returns (bool) {
+ require(false, stub_error);
+ dummy;
+ return false;
+ }
+
+ // `token_id` should be obtained with `next_token_id` method,
+ // unlike standard, you can't specify it manually
+ //
+ // Selector: mint(address,uint256) 40c10f19
+ function mint(address to, uint256 tokenId) public returns (bool) {
+ require(false, stub_error);
+ to;
+ tokenId;
+ dummy = 0;
+ return false;
+ }
+
+ // `token_id` should be obtained with `next_token_id` method,
+ // unlike standard, you can't specify it manually
+ //
+ // Selector: mintWithTokenURI(address,uint256,string) 50bb4e7f
+ 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
+ //
+ // Selector: finishMinting() 7d64bcb4
+ function finishMinting() public returns (bool) {
+ require(false, stub_error);
+ dummy = 0;
+ return false;
+ }
+}
+
+// Selector: 780e9d63
+contract ERC721Enumerable is Dummy, ERC165 {
+ // Selector: tokenByIndex(uint256) 4f6ccce7
+ function tokenByIndex(uint256 index) public view returns (uint256) {
+ require(false, stub_error);
+ index;
+ dummy;
+ return 0;
+ }
+
+ // Not implemented
+ //
+ // Selector: tokenOfOwnerByIndex(address,uint256) 2f745c59
+ function tokenOfOwnerByIndex(address owner, uint256 index)
+ public
+ view
+ returns (uint256)
+ {
+ require(false, stub_error);
+ owner;
+ index;
+ dummy;
+ return 0;
+ }
+
+ // Selector: totalSupply() 18160ddd
+ function totalSupply() public view returns (uint256) {
+ require(false, stub_error);
+ dummy;
+ return 0;
+ }
+}
+
// Selector: 7d9262e6
contract Collection is Dummy, ERC165 {
// Set collection property.
@@ -248,4 +599,15 @@
}
}
-contract UniqueRefungible is Dummy, ERC165, Collection {}
+contract UniqueRefungible is
+ Dummy,
+ ERC165,
+ ERC721,
+ ERC721Metadata,
+ ERC721Enumerable,
+ ERC721UniqueExtensions,
+ ERC721Mintable,
+ ERC721Burnable,
+ Collection,
+ TokenProperties
+{}
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -3,6 +3,12 @@
pragma solidity >=0.8.0 <0.9.0;
+// Anonymous struct
+struct Tuple0 {
+ uint256 field_0;
+ string field_1;
+}
+
// Common stubs holder
interface Dummy {
@@ -12,6 +18,203 @@
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
+// Inline
+interface ERC721Events {
+ event Transfer(
+ address indexed from,
+ address indexed to,
+ uint256 indexed tokenId
+ );
+ event Approval(
+ address indexed owner,
+ address indexed approved,
+ uint256 indexed tokenId
+ );
+ event ApprovalForAll(
+ address indexed owner,
+ address indexed operator,
+ bool approved
+ );
+}
+
+// Inline
+interface ERC721MintableEvents {
+ event MintingFinished();
+}
+
+// Selector: 0784ee64
+interface ERC721UniqueExtensions is Dummy, ERC165 {
+ // @notice Returns next free RFT ID.
+ //
+ // Selector: nextTokenId() 75794a3c
+ function nextTokenId() external view returns (uint256);
+
+ // Selector: mintBulk(address,uint256[]) 44a9945e
+ function mintBulk(address to, uint256[] memory tokenIds)
+ external
+ returns (bool);
+
+ // Selector: mintBulkWithTokenURI(address,(uint256,string)[]) 36543006
+ function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
+ external
+ returns (bool);
+}
+
+// Selector: 41369377
+interface TokenProperties is Dummy, ERC165 {
+ // Selector: setTokenPropertyPermission(string,bool,bool,bool) 222d97fa
+ function setTokenPropertyPermission(
+ string memory key,
+ bool isMutable,
+ bool collectionAdmin,
+ bool tokenOwner
+ ) external;
+
+ // Selector: setProperty(uint256,string,bytes) 1752d67b
+ function setProperty(
+ uint256 tokenId,
+ string memory key,
+ bytes memory value
+ ) external;
+
+ // Selector: deleteProperty(uint256,string) 066111d1
+ function deleteProperty(uint256 tokenId, string memory key) external;
+
+ // Throws error if key not found
+ //
+ // Selector: property(uint256,string) 7228c327
+ function property(uint256 tokenId, string memory key)
+ external
+ view
+ returns (bytes memory);
+}
+
+// Selector: 42966c68
+interface ERC721Burnable is Dummy, ERC165 {
+ // @dev Not implemented
+ //
+ // Selector: burn(uint256) 42966c68
+ function burn(uint256 tokenId) external;
+}
+
+// Selector: 58800161
+interface ERC721 is Dummy, ERC165, ERC721Events {
+ // Selector: balanceOf(address) 70a08231
+ function balanceOf(address owner) external view returns (uint256);
+
+ // Selector: ownerOf(uint256) 6352211e
+ function ownerOf(uint256 tokenId) external view returns (address);
+
+ // @dev Not implemented
+ //
+ // Selector: safeTransferFromWithData(address,address,uint256,bytes) 60a11672
+ function safeTransferFromWithData(
+ address from,
+ address to,
+ uint256 tokenId,
+ bytes memory data
+ ) external;
+
+ // @dev Not implemented
+ //
+ // Selector: safeTransferFrom(address,address,uint256) 42842e0e
+ function safeTransferFrom(
+ address from,
+ address to,
+ uint256 tokenId
+ ) external;
+
+ // @dev Not implemented
+ //
+ // Selector: transferFrom(address,address,uint256) 23b872dd
+ function transferFrom(
+ address from,
+ address to,
+ uint256 tokenId
+ ) external;
+
+ // @dev Not implemented
+ //
+ // Selector: approve(address,uint256) 095ea7b3
+ function approve(address approved, uint256 tokenId) external;
+
+ // @dev Not implemented
+ //
+ // Selector: setApprovalForAll(address,bool) a22cb465
+ function setApprovalForAll(address operator, bool approved) external;
+
+ // @dev Not implemented
+ //
+ // Selector: getApproved(uint256) 081812fc
+ function getApproved(uint256 tokenId) external view returns (address);
+
+ // @dev Not implemented
+ //
+ // Selector: isApprovedForAll(address,address) e985e9c5
+ function isApprovedForAll(address owner, address operator)
+ external
+ view
+ returns (address);
+}
+
+// Selector: 5b5e139f
+interface ERC721Metadata is Dummy, ERC165 {
+ // Selector: name() 06fdde03
+ function name() external view returns (string memory);
+
+ // Selector: symbol() 95d89b41
+ function symbol() external view returns (string memory);
+
+ // Returns token's const_metadata
+ //
+ // Selector: tokenURI(uint256) c87b56dd
+ function tokenURI(uint256 tokenId) external view returns (string memory);
+}
+
+// Selector: 68ccfe89
+interface ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+ // Selector: mintingFinished() 05d2035b
+ function mintingFinished() external view returns (bool);
+
+ // `token_id` should be obtained with `next_token_id` method,
+ // unlike standard, you can't specify it manually
+ //
+ // Selector: mint(address,uint256) 40c10f19
+ function mint(address to, uint256 tokenId) external returns (bool);
+
+ // `token_id` should be obtained with `next_token_id` method,
+ // unlike standard, you can't specify it manually
+ //
+ // Selector: mintWithTokenURI(address,uint256,string) 50bb4e7f
+ function mintWithTokenURI(
+ address to,
+ uint256 tokenId,
+ string memory tokenUri
+ ) external returns (bool);
+
+ // @dev Not implemented
+ //
+ // Selector: finishMinting() 7d64bcb4
+ function finishMinting() external returns (bool);
+}
+
+// Selector: 780e9d63
+interface ERC721Enumerable is Dummy, ERC165 {
+ // Selector: tokenByIndex(uint256) 4f6ccce7
+ function tokenByIndex(uint256 index) external view returns (uint256);
+
+ // Not implemented
+ //
+ // Selector: tokenOfOwnerByIndex(address,uint256) 2f745c59
+ function tokenOfOwnerByIndex(address owner, uint256 index)
+ external
+ view
+ returns (uint256);
+
+ // Selector: totalSupply() 18160ddd
+ function totalSupply() external view returns (uint256);
+}
+
// Selector: 7d9262e6
interface Collection is Dummy, ERC165 {
// Set collection property.
@@ -160,4 +363,15 @@
function setCollectionMintMode(bool mode) external;
}
-interface UniqueRefungible is Dummy, ERC165, Collection {}
+interface UniqueRefungible is
+ Dummy,
+ ERC165,
+ ERC721,
+ ERC721Metadata,
+ ERC721Enumerable,
+ ERC721UniqueExtensions,
+ ERC721Mintable,
+ ERC721Burnable,
+ Collection,
+ TokenProperties
+{}
tests/src/eth/reFungibleAbi.jsondiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/reFungibleAbi.json
@@ -0,0 +1,510 @@
+[
+ {
+ "anonymous": false,
+ "inputs": [
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "owner",
+ "type": "address"
+ },
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "approved",
+ "type": "address"
+ },
+ {
+ "indexed": true,
+ "internalType": "uint256",
+ "name": "tokenId",
+ "type": "uint256"
+ }
+ ],
+ "name": "Approval",
+ "type": "event"
+ },
+ {
+ "anonymous": false,
+ "inputs": [
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "owner",
+ "type": "address"
+ },
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "operator",
+ "type": "address"
+ },
+ {
+ "indexed": false,
+ "internalType": "bool",
+ "name": "approved",
+ "type": "bool"
+ }
+ ],
+ "name": "ApprovalForAll",
+ "type": "event"
+ },
+ {
+ "anonymous": false,
+ "inputs": [],
+ "name": "MintingFinished",
+ "type": "event"
+ },
+ {
+ "anonymous": false,
+ "inputs": [
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "from",
+ "type": "address"
+ },
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "to",
+ "type": "address"
+ },
+ {
+ "indexed": true,
+ "internalType": "uint256",
+ "name": "tokenId",
+ "type": "uint256"
+ }
+ ],
+ "name": "Transfer",
+ "type": "event"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "newAdmin", "type": "address" }
+ ],
+ "name": "addCollectionAdmin",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "newAdmin", "type": "uint256" }
+ ],
+ "name": "addCollectionAdminSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "user", "type": "address" }
+ ],
+ "name": "addToCollectionAllowList",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "approved", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "approve",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "owner", "type": "address" }
+ ],
+ "name": "balanceOf",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "burn",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
+ "name": "collectionProperty",
+ "outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "confirmCollectionSponsorship",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "contractAddress",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
+ "name": "deleteCollectionProperty",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "string", "name": "key", "type": "string" }
+ ],
+ "name": "deleteProperty",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "finishMinting",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "getApproved",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "owner", "type": "address" },
+ { "internalType": "address", "name": "operator", "type": "address" }
+ ],
+ "name": "isApprovedForAll",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "mint",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256[]", "name": "tokenIds", "type": "uint256[]" }
+ ],
+ "name": "mintBulk",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ {
+ "components": [
+ { "internalType": "uint256", "name": "field_0", "type": "uint256" },
+ { "internalType": "string", "name": "field_1", "type": "string" }
+ ],
+ "internalType": "struct Tuple0[]",
+ "name": "tokens",
+ "type": "tuple[]"
+ }
+ ],
+ "name": "mintBulkWithTokenURI",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "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" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "mintingFinished",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "name",
+ "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "nextTokenId",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "ownerOf",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "string", "name": "key", "type": "string" }
+ ],
+ "name": "property",
+ "outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "admin", "type": "address" }
+ ],
+ "name": "removeCollectionAdmin",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "admin", "type": "uint256" }
+ ],
+ "name": "removeCollectionAdminSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "user", "type": "address" }
+ ],
+ "name": "removeFromCollectionAllowList",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "from", "type": "address" },
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "safeTransferFrom",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "from", "type": "address" },
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "bytes", "name": "data", "type": "bytes" }
+ ],
+ "name": "safeTransferFromWithData",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "operator", "type": "address" },
+ { "internalType": "bool", "name": "approved", "type": "bool" }
+ ],
+ "name": "setApprovalForAll",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [{ "internalType": "uint8", "name": "mode", "type": "uint8" }],
+ "name": "setCollectionAccess",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "string", "name": "limit", "type": "string" },
+ { "internalType": "uint32", "name": "value", "type": "uint32" }
+ ],
+ "name": "setCollectionLimit",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "string", "name": "limit", "type": "string" },
+ { "internalType": "bool", "name": "value", "type": "bool" }
+ ],
+ "name": "setCollectionLimit",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [{ "internalType": "bool", "name": "mode", "type": "bool" }],
+ "name": "setCollectionMintMode",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [{ "internalType": "bool", "name": "enable", "type": "bool" }],
+ "name": "setCollectionNesting",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "bool", "name": "enable", "type": "bool" },
+ {
+ "internalType": "address[]",
+ "name": "collections",
+ "type": "address[]"
+ }
+ ],
+ "name": "setCollectionNesting",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
+ ],
+ "name": "setCollectionProperty",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "sponsor", "type": "address" }
+ ],
+ "name": "setCollectionSponsor",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
+ ],
+ "name": "setProperty",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bool", "name": "isMutable", "type": "bool" },
+ { "internalType": "bool", "name": "collectionAdmin", "type": "bool" },
+ { "internalType": "bool", "name": "tokenOwner", "type": "bool" }
+ ],
+ "name": "setTokenPropertyPermission",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
+ ],
+ "name": "supportsInterface",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "symbol",
+ "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "index", "type": "uint256" }
+ ],
+ "name": "tokenByIndex",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "owner", "type": "address" },
+ { "internalType": "uint256", "name": "index", "type": "uint256" }
+ ],
+ "name": "tokenOfOwnerByIndex",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "tokenURI",
+ "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "totalSupply",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "from", "type": "address" },
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "transferFrom",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ }
+]
tests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -446,25 +446,83 @@
[key: string]: AugmentedError<ApiType>;
};
rmrkCore: {
+ /**
+ * Not the target owner of the sent NFT.
+ **/
CannotAcceptNonOwnedNft: AugmentedError<ApiType>;
+ /**
+ * Not the target owner of the sent NFT.
+ **/
CannotRejectNonOwnedNft: AugmentedError<ApiType>;
+ /**
+ * NFT was not sent and is not pending.
+ **/
CannotRejectNonPendingNft: AugmentedError<ApiType>;
+ /**
+ * If an NFT is sent to a descendant, that would form a nesting loop, an ouroboros.
+ * Sending to self is redundant.
+ **/
CannotSendToDescendentOrSelf: AugmentedError<ApiType>;
+ /**
+ * Too many tokens created in the collection, no new ones are allowed.
+ **/
CollectionFullOrLocked: AugmentedError<ApiType>;
+ /**
+ * Only destroying collections without tokens is allowed.
+ **/
CollectionNotEmpty: AugmentedError<ApiType>;
+ /**
+ * Collection does not exist, has a wrong type, or does not map to a Unique ID.
+ **/
CollectionUnknown: AugmentedError<ApiType>;
+ /**
+ * Property of the type of RMRK collection could not be read successfully.
+ **/
CorruptedCollectionType: AugmentedError<ApiType>;
- NftTypeEncodeError: AugmentedError<ApiType>;
+ /**
+ * Could not find an ID for a collection. It is likely there were too many collections created on the chain, causing an overflow.
+ **/
NoAvailableCollectionId: AugmentedError<ApiType>;
+ /**
+ * Token does not exist, or there is no suitable ID for it, likely too many tokens were created in a collection, causing an overflow.
+ **/
NoAvailableNftId: AugmentedError<ApiType>;
+ /**
+ * Could not find an ID for the resource. It is likely there were too many resources created on an NFT, causing an overflow.
+ **/
NoAvailableResourceId: AugmentedError<ApiType>;
+ /**
+ * Token is marked as non-transferable, and thus cannot be transferred.
+ **/
NonTransferable: AugmentedError<ApiType>;
+ /**
+ * No permission to perform action.
+ **/
NoPermission: AugmentedError<ApiType>;
+ /**
+ * No such resource found.
+ **/
ResourceDoesntExist: AugmentedError<ApiType>;
+ /**
+ * Resource is not pending for the operation.
+ **/
ResourceNotPending: AugmentedError<ApiType>;
+ /**
+ * Could not find a property by the supplied key.
+ **/
RmrkPropertyIsNotFound: AugmentedError<ApiType>;
+ /**
+ * Too many symbols supplied as the property key. The maximum is [256](up_data_structs::MAX_PROPERTY_KEY_LENGTH).
+ **/
RmrkPropertyKeyIsTooLong: AugmentedError<ApiType>;
+ /**
+ * Too many bytes supplied as the property value. The maximum is [32768](up_data_structs::MAX_PROPERTY_VALUE_LENGTH).
+ **/
RmrkPropertyValueIsTooLong: AugmentedError<ApiType>;
+ /**
+ * Something went wrong when decoding encoded data from the storage.
+ * Perhaps, there was a wrong key supplied for the type, or the data was improperly stored.
+ **/
UnableToDecodeRmrkData: AugmentedError<ApiType>;
/**
* Generic error
@@ -472,12 +530,33 @@
[key: string]: AugmentedError<ApiType>;
};
rmrkEquip: {
+ /**
+ * Base collection linked to this ID does not exist.
+ **/
BaseDoesntExist: AugmentedError<ApiType>;
+ /**
+ * No Theme named "default" is associated with the Base.
+ **/
NeedsDefaultThemeFirst: AugmentedError<ApiType>;
+ /**
+ * Could not find an ID for a Base collection. It is likely there were too many collections created on the chain, causing an overflow.
+ **/
NoAvailableBaseId: AugmentedError<ApiType>;
+ /**
+ * Could not find a suitable ID for a Part, likely too many Part tokens were created in the Base, causing an overflow
+ **/
NoAvailablePartId: AugmentedError<ApiType>;
+ /**
+ * Cannot assign equippables to a fixed Part.
+ **/
NoEquippableOnFixedPart: AugmentedError<ApiType>;
+ /**
+ * Part linked to this ID does not exist.
+ **/
PartDoesntExist: AugmentedError<ApiType>;
+ /**
+ * No permission to perform action.
+ **/
PermissionError: AugmentedError<ApiType>;
/**
* Generic error
@@ -508,15 +587,15 @@
};
structure: {
/**
- * While iterating over children, reached the breadth limit.
+ * While nesting, reached the breadth limit of nesting, exceeding the provided budget.
**/
BreadthLimit: AugmentedError<ApiType>;
/**
- * While searching for the owner, reached the depth limit.
+ * While nesting, reached the depth limit of nesting, exceeding the provided budget.
**/
DepthLimit: AugmentedError<ApiType>;
/**
- * While searching for the owner, encountered an already checked account, detecting a loop.
+ * While nesting, encountered an already checked account, detecting a loop.
**/
OuroborosDetected: AugmentedError<ApiType>;
/**
tests/src/interfaces/augment-api-query.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -492,7 +492,13 @@
[key: string]: QueryableStorageEntry<ApiType>;
};
rmrkCore: {
+ /**
+ * Latest yet-unused collection ID.
+ **/
collectionIndex: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
+ /**
+ * Mapping from RMRK collection ID to Unique's.
+ **/
uniqueCollectionId: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<u32>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
/**
* Generic query
@@ -500,7 +506,13 @@
[key: string]: QueryableStorageEntry<ApiType>;
};
rmrkEquip: {
+ /**
+ * Checkmark that a Base has a Theme NFT named "default".
+ **/
baseHasDefaultTheme: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<bool>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
+ /**
+ * Map of a Base ID and a Part ID to an NFT in the Base collection serving as the Part.
+ **/
inernalPartId: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<Option<u32>>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>;
/**
* Generic query
tests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -348,103 +348,259 @@
};
rmrkCore: {
/**
- * Accepts an NFT sent from another account to self or owned NFT
+ * Accept an NFT sent from another account to self or an owned NFT.
+ *
+ * The NFT in question must be pending, and, thus, be [sent](`Pallet::send`) first.
*
- * Parameters:
- * - `origin`: sender of the transaction
- * - `rmrk_collection_id`: collection id of the nft to be accepted
- * - `rmrk_nft_id`: nft id of the nft to be accepted
- * - `new_owner`: either origin's account ID or origin-owned NFT, whichever the NFT was
- * sent to
+ * # Permissions:
+ * - Token-owner-to-be
+ *
+ * # Arguments:
+ * - `rmrk_collection_id`: RMRK collection ID of the NFT to be accepted.
+ * - `rmrk_nft_id`: ID of the NFT to be accepted.
+ * - `new_owner`: Either the sender's account ID or a sender-owned NFT,
+ * whichever the accepted NFT was sent to.
**/
acceptNft: AugmentedSubmittable<(rmrkCollectionId: u32 | AnyNumber | Uint8Array, rmrkNftId: u32 | AnyNumber | Uint8Array, newOwner: RmrkTraitsNftAccountIdOrCollectionNftTuple | { AccountId: any } | { CollectionAndNftTuple: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, RmrkTraitsNftAccountIdOrCollectionNftTuple]>;
/**
- * accept the addition of a new resource to an existing NFT
+ * Accept the addition of a newly created pending resource to an existing NFT.
+ *
+ * This transaction is needed when a resource is created and assigned to an NFT
+ * by a non-owner, i.e. the collection issuer, with one of the
+ * [`add_...` transactions](Pallet::add_basic_resource).
+ *
+ * # Permissions:
+ * - Token owner
+ *
+ * # Arguments:
+ * - `rmrk_collection_id`: RMRK collection ID of the NFT.
+ * - `rmrk_nft_id`: ID of the NFT with a pending resource to be accepted.
+ * - `resource_id`: ID of the newly created pending resource.
**/
acceptResource: AugmentedSubmittable<(rmrkCollectionId: u32 | AnyNumber | Uint8Array, rmrkNftId: u32 | AnyNumber | Uint8Array, resourceId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, u32]>;
/**
- * accept the removal of a resource of an existing NFT
+ * Accept the removal of a removal-pending resource from an NFT.
+ *
+ * This transaction is needed when a non-owner, i.e. the collection issuer,
+ * requests a [removal](`Pallet::remove_resource`) of a resource from an NFT.
+ *
+ * # Permissions:
+ * - Token owner
+ *
+ * # Arguments:
+ * - `rmrk_collection_id`: RMRK collection ID of the NFT.
+ * - `rmrk_nft_id`: ID of the NFT with a resource to be removed.
+ * - `resource_id`: ID of the removal-pending resource.
**/
acceptResourceRemoval: AugmentedSubmittable<(rmrkCollectionId: u32 | AnyNumber | Uint8Array, rmrkNftId: u32 | AnyNumber | Uint8Array, resourceId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, u32]>;
/**
- * Create basic resource
+ * Create and set/propose a basic resource for an NFT.
+ *
+ * A basic resource is the simplest, lacking a Base and anything that comes with it.
+ * See RMRK docs for more information and examples.
+ *
+ * # Permissions:
+ * - Collection issuer - if not the token owner, adding the resource will warrant
+ * the owner's [acceptance](Pallet::accept_resource).
+ *
+ * # Arguments:
+ * - `rmrk_collection_id`: RMRK collection ID of the NFT.
+ * - `nft_id`: ID of the NFT to assign a resource to.
+ * - `resource`: Data of the resource to be created.
**/
addBasicResource: AugmentedSubmittable<(rmrkCollectionId: u32 | AnyNumber | Uint8Array, nftId: u32 | AnyNumber | Uint8Array, resource: RmrkTraitsResourceBasicResource | { src?: any; metadata?: any; license?: any; thumb?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, RmrkTraitsResourceBasicResource]>;
/**
- * Create composable resource
+ * Create and set/propose a composable resource for an NFT.
+ *
+ * A composable resource links to a Base and has a subset of its Parts it is composed of.
+ * See RMRK docs for more information and examples.
+ *
+ * # Permissions:
+ * - Collection issuer - if not the token owner, adding the resource will warrant
+ * the owner's [acceptance](Pallet::accept_resource).
+ *
+ * # Arguments:
+ * - `rmrk_collection_id`: RMRK collection ID of the NFT.
+ * - `nft_id`: ID of the NFT to assign a resource to.
+ * - `resource`: Data of the resource to be created.
**/
addComposableResource: AugmentedSubmittable<(rmrkCollectionId: u32 | AnyNumber | Uint8Array, nftId: u32 | AnyNumber | Uint8Array, resource: RmrkTraitsResourceComposableResource | { parts?: any; base?: any; src?: any; metadata?: any; license?: any; thumb?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, RmrkTraitsResourceComposableResource]>;
/**
- * Create slot resource
+ * Create and set/propose a slot resource for an NFT.
+ *
+ * A slot resource links to a Base and a slot ID in it which it can fit into.
+ * See RMRK docs for more information and examples.
+ *
+ * # Permissions:
+ * - Collection issuer - if not the token owner, adding the resource will warrant
+ * the owner's [acceptance](Pallet::accept_resource).
+ *
+ * # Arguments:
+ * - `rmrk_collection_id`: RMRK collection ID of the NFT.
+ * - `nft_id`: ID of the NFT to assign a resource to.
+ * - `resource`: Data of the resource to be created.
**/
addSlotResource: AugmentedSubmittable<(rmrkCollectionId: u32 | AnyNumber | Uint8Array, nftId: u32 | AnyNumber | Uint8Array, resource: RmrkTraitsResourceSlotResource | { base?: any; src?: any; metadata?: any; slot?: any; license?: any; thumb?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, RmrkTraitsResourceSlotResource]>;
/**
- * burn nft
+ * Burn an NFT, destroying it and its nested tokens up to the specified limit.
+ * If the burning budget is exceeded, the transaction is reverted.
+ *
+ * This is the way to burn a nested token as well.
+ *
+ * For more information, see [`burn_recursively`](pallet_nonfungible::pallet::Pallet::burn_recursively).
+ *
+ * # Permissions:
+ * * Token owner
+ *
+ * # Arguments:
+ * - `collection_id`: RMRK ID of the collection in which the NFT to burn belongs to.
+ * - `nft_id`: ID of the NFT to be destroyed.
+ * - `max_burns`: Maximum number of tokens to burn, assuming nesting. The transaction
+ * is reverted if there are more tokens to burn in the nesting tree than this number.
+ * This is primarily a mechanism of transaction weight control.
**/
burnNft: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, nftId: u32 | AnyNumber | Uint8Array, maxBurns: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, u32]>;
/**
- * Change the issuer of a collection
+ * Change the issuer of a collection. Analogous to Unique's collection's [`owner`](up_data_structs::Collection).
*
- * Parameters:
- * - `origin`: sender of the transaction
- * - `collection_id`: collection id of the nft to change issuer of
- * - `new_issuer`: Collection's new issuer
+ * # Permissions:
+ * * Collection issuer
+ *
+ * # Arguments:
+ * - `collection_id`: RMRK collection ID to change the issuer of.
+ * - `new_issuer`: Collection's new issuer.
**/
changeCollectionIssuer: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, newIssuer: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, MultiAddress]>;
/**
- * Create a collection
+ * Create a new collection of NFTs.
+ *
+ * # Permissions:
+ * * Anyone - will be assigned as the issuer of the collection.
+ *
+ * # Arguments:
+ * - `metadata`: Metadata describing the collection, e.g. IPFS hash. Cannot be changed.
+ * - `max`: Optional maximum number of tokens.
+ * - `symbol`: UTF-8 string with token prefix, by which to represent the token in wallets and UIs.
+ * Analogous to Unique's [`token_prefix`](up_data_structs::Collection). Cannot be changed.
**/
createCollection: AugmentedSubmittable<(metadata: Bytes | string | Uint8Array, max: Option<u32> | null | object | string | Uint8Array, symbol: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Bytes, Option<u32>, Bytes]>;
/**
- * destroy collection
+ * Destroy a collection.
+ *
+ * Only empty collections can be destroyed. If it has any tokens, they must be burned first.
+ *
+ * # Permissions:
+ * * Collection issuer
+ *
+ * # Arguments:
+ * - `collection_id`: RMRK ID of the collection to destroy.
**/
destroyCollection: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32]>;
/**
- * lock collection
+ * "Lock" the collection and prevent new token creation. Cannot be undone.
+ *
+ * # Permissions:
+ * * Collection issuer
+ *
+ * # Arguments:
+ * - `collection_id`: RMRK ID of the collection to lock.
**/
lockCollection: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32]>;
/**
- * Mints an NFT in the specified collection
- * Sets metadata and the royalty attribute
+ * Mint an NFT in a specified collection.
+ *
+ * # Permissions:
+ * * Collection issuer
*
- * Parameters:
- * - `collection_id`: The class of the asset to be minted.
- * - `nft_id`: The nft value of the asset to be minted.
- * - `recipient`: Receiver of the royalty
- * - `royalty`: Permillage reward from each trade for the Recipient
- * - `metadata`: Arbitrary data about an nft, e.g. IPFS hash
- * - `transferable`: Ability to transfer this NFT
+ * # Arguments:
+ * - `owner`: Owner account of the NFT. If set to None, defaults to the sender (collection issuer).
+ * - `collection_id`: RMRK collection ID for the NFT to be minted within. Cannot be changed.
+ * - `recipient`: Receiver account of the royalty. Has no effect if the `royalty_amount` is not set. Cannot be changed.
+ * - `royalty_amount`: Optional permillage reward from each trade for the `recipient`. Cannot be changed.
+ * - `metadata`: Arbitrary data about an NFT, e.g. IPFS hash. Cannot be changed.
+ * - `transferable`: Can this NFT be transferred? Cannot be changed.
+ * - `resources`: Resource data to be added to the NFT immediately after minting.
**/
mintNft: AugmentedSubmittable<(owner: Option<AccountId32> | null | object | string | Uint8Array, collectionId: u32 | AnyNumber | Uint8Array, recipient: Option<AccountId32> | null | object | string | Uint8Array, royaltyAmount: Option<Permill> | null | object | string | Uint8Array, metadata: Bytes | string | Uint8Array, transferable: bool | boolean | Uint8Array, resources: Option<Vec<RmrkTraitsResourceResourceTypes>> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Option<AccountId32>, u32, Option<AccountId32>, Option<Permill>, Bytes, bool, Option<Vec<RmrkTraitsResourceResourceTypes>>]>;
/**
- * Rejects an NFT sent from another account to self or owned NFT
+ * Reject an NFT sent from another account to self or owned NFT.
+ * The NFT in question will not be sent back and burnt instead.
+ *
+ * The NFT in question must be pending, and, thus, be [sent](`Pallet::send`) first.
+ *
+ * # Permissions:
+ * - Token-owner-to-be-not
*
- * Parameters:
- * - `origin`: sender of the transaction
- * - `rmrk_collection_id`: collection id of the nft to be accepted
- * - `rmrk_nft_id`: nft id of the nft to be accepted
+ * # Arguments:
+ * - `rmrk_collection_id`: RMRK ID of the NFT to be rejected.
+ * - `rmrk_nft_id`: ID of the NFT to be rejected.
**/
rejectNft: AugmentedSubmittable<(rmrkCollectionId: u32 | AnyNumber | Uint8Array, rmrkNftId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32]>;
/**
- * remove resource
+ * Remove and erase a resource from an NFT.
+ *
+ * If the sender does not own the NFT, then it will be pending confirmation,
+ * and will have to be [accepted](Pallet::accept_resource_removal) by the token owner.
+ *
+ * # Permissions
+ * - Collection issuer
+ *
+ * # Arguments
+ * - `collection_id`: RMRK ID of a collection to which the NFT making use of the resource belongs to.
+ * - `nft_id`: ID of the NFT with a resource to be removed.
+ * - `resource_id`: ID of the resource to be removed.
**/
removeResource: AugmentedSubmittable<(rmrkCollectionId: u32 | AnyNumber | Uint8Array, nftId: u32 | AnyNumber | Uint8Array, resourceId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, u32]>;
/**
- * Transfers a NFT from an Account or NFT A to another Account or NFT B
+ * Transfer an NFT from an account/NFT A to another account/NFT B.
+ * The token must be transferable. Nesting cannot occur deeper than the [`NESTING_BUDGET`].
*
- * Parameters:
- * - `origin`: sender of the transaction
- * - `rmrk_collection_id`: collection id of the nft to be transferred
- * - `rmrk_nft_id`: nft id of the nft to be transferred
- * - `new_owner`: new owner of the nft which can be either an account or a NFT
+ * If the target owner is an NFT owned by another account, then the NFT will enter
+ * the pending state and will have to be accepted by the other account.
+ *
+ * # Permissions:
+ * - Token owner
+ *
+ * # Arguments:
+ * - `collection_id`: RMRK ID of the collection of the NFT to be transferred.
+ * - `nft_id`: ID of the NFT to be transferred.
+ * - `new_owner`: New owner of the nft which can be either an account or a NFT.
**/
send: AugmentedSubmittable<(rmrkCollectionId: u32 | AnyNumber | Uint8Array, rmrkNftId: u32 | AnyNumber | Uint8Array, newOwner: RmrkTraitsNftAccountIdOrCollectionNftTuple | { AccountId: any } | { CollectionAndNftTuple: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, RmrkTraitsNftAccountIdOrCollectionNftTuple]>;
/**
- * set a different order of resource priority
+ * Set a different order of resource priorities for an NFT. Priorities can be used,
+ * for example, for order of rendering.
+ *
+ * Note that the priorities are not updated automatically, and are an empty vector
+ * by default. There is no pre-set definition for the order to be particular,
+ * it can be interpreted arbitrarily use-case by use-case.
+ *
+ * # Permissions:
+ * - Token owner
+ *
+ * # Arguments:
+ * - `rmrk_collection_id`: RMRK collection ID of the NFT.
+ * - `rmrk_nft_id`: ID of the NFT to rearrange resource priorities for.
+ * - `priorities`: Ordered vector of resource IDs.
**/
setPriority: AugmentedSubmittable<(rmrkCollectionId: u32 | AnyNumber | Uint8Array, rmrkNftId: u32 | AnyNumber | Uint8Array, priorities: Vec<u32> | (u32 | AnyNumber | Uint8Array)[]) => SubmittableExtrinsic<ApiType>, [u32, u32, Vec<u32>]>;
/**
- * set a custom value on an NFT
+ * Add or edit a custom user property, a key-value pair, describing the metadata
+ * of a token or a collection, on either one of these.
+ *
+ * Note that in this proxy implementation many details regarding RMRK are stored
+ * as scoped properties prefixed with "rmrk:", normally inaccessible
+ * to external transactions and RPCs.
+ *
+ * # Permissions:
+ * - Collection issuer - in case of collection property
+ * - Token owner - in case of NFT property
+ *
+ * # Arguments:
+ * - `rmrk_collection_id`: RMRK collection ID.
+ * - `maybe_nft_id`: Optional ID of the NFT. If left empty, then the property is set for the collection.
+ * - `key`: Key of the custom property to be referenced by.
+ * - `value`: Value of the custom property to be stored.
**/
setProperty: AugmentedSubmittable<(rmrkCollectionId: Compact<u32> | AnyNumber | Uint8Array, maybeNftId: Option<u32> | null | object | string | Uint8Array, key: Bytes | string | Uint8Array, value: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Compact<u32>, Option<u32>, Bytes, Bytes]>;
/**
@@ -454,32 +610,50 @@
};
rmrkEquip: {
/**
- * Creates a new Base.
- * Modeled after [base interaction](https://github.com/rmrk-team/rmrk-spec/blob/master/standards/rmrk2.0.0/interactions/base.md)
+ * Create a new Base.
+ *
+ * Modeled after the [Base interaction](https://github.com/rmrk-team/rmrk-spec/blob/master/standards/rmrk2.0.0/interactions/base.md)
+ *
+ * # Permissions
+ * - Anyone - will be assigned as the issuer of the Base.
*
- * Parameters:
- * - origin: Caller, will be assigned as the issuer of the Base
- * - base_type: media type, e.g. "svg"
- * - symbol: arbitrary client-chosen symbol
- * - parts: array of Fixed and Slot parts composing the base, confined in length by
- * RmrkPartsLimit
+ * # Arguments:
+ * - `base_type`: Arbitrary media type, e.g. "svg".
+ * - `symbol`: Arbitrary client-chosen symbol.
+ * - `parts`: Array of Fixed and Slot Parts composing the Base,
+ * confined in length by [`RmrkPartsLimit`](up_data_structs::RmrkPartsLimit).
**/
createBase: AugmentedSubmittable<(baseType: Bytes | string | Uint8Array, symbol: Bytes | string | Uint8Array, parts: Vec<RmrkTraitsPartPartType> | (RmrkTraitsPartPartType | { FixedPart: any } | { SlotPart: any } | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>, [Bytes, Bytes, Vec<RmrkTraitsPartPartType>]>;
+ /**
+ * Update the array of Collections allowed to be equipped to a Base's specified Slot Part.
+ *
+ * Modeled after [equippable interaction](https://github.com/rmrk-team/rmrk-spec/blob/master/standards/rmrk2.0.0/interactions/equippable.md).
+ *
+ * # Permissions:
+ * - Base issuer
+ *
+ * # Arguments:
+ * - `base_id`: Base containing the Slot Part to be updated.
+ * - `part_id`: Slot Part whose Equippable List is being updated.
+ * - `equippables`: List of equippables that will override the current Equippables list.
+ **/
equippable: AugmentedSubmittable<(baseId: u32 | AnyNumber | Uint8Array, slotId: u32 | AnyNumber | Uint8Array, equippables: RmrkTraitsPartEquippableList | { All: any } | { Empty: any } | { Custom: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, RmrkTraitsPartEquippableList]>;
/**
- * Adds a Theme to a Base.
- * Modeled after [themeadd interaction](https://github.com/rmrk-team/rmrk-spec/blob/master/standards/rmrk2.0.0/interactions/themeadd.md)
- * Themes are stored in the Themes storage
+ * Add a Theme to a Base.
* A Theme named "default" is required prior to adding other Themes.
*
- * Parameters:
- * - origin: The caller of the function, must be issuer of the base
- * - base_id: The Base containing the Theme to be updated
- * - theme: The Theme to add to the Base. A Theme has a name and properties, which are an
+ * Modeled after [Themeadd interaction](https://github.com/rmrk-team/rmrk-spec/blob/master/standards/rmrk2.0.0/interactions/themeadd.md).
+ *
+ * # Permissions:
+ * - Base issuer
+ *
+ * # Arguments:
+ * - `base_id`: Base ID containing the Theme to be updated.
+ * - `theme`: Theme to add to the Base. A Theme has a name and properties, which are an
* array of [key, value, inherit].
- * - key: arbitrary BoundedString, defined by client
- * - value: arbitrary BoundedString, defined by client
- * - inherit: optional bool
+ * - `key`: Arbitrary BoundedString, defined by client.
+ * - `value`: Arbitrary BoundedString, defined by client.
+ * - `inherit`: Optional bool.
**/
themeAdd: AugmentedSubmittable<(baseId: u32 | AnyNumber | Uint8Array, theme: RmrkTraitsTheme | { name?: any; properties?: any; inherit?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, RmrkTraitsTheme]>;
/**
tests/src/interfaces/default/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -1314,7 +1314,6 @@
/** @name PalletRmrkCoreError */
export interface PalletRmrkCoreError extends Enum {
readonly isCorruptedCollectionType: boolean;
- readonly isNftTypeEncodeError: boolean;
readonly isRmrkPropertyKeyIsTooLong: boolean;
readonly isRmrkPropertyValueIsTooLong: boolean;
readonly isRmrkPropertyIsNotFound: boolean;
@@ -1333,7 +1332,7 @@
readonly isCannotRejectNonPendingNft: boolean;
readonly isResourceNotPending: boolean;
readonly isNoAvailableResourceId: boolean;
- readonly type: 'CorruptedCollectionType' | 'NftTypeEncodeError' | 'RmrkPropertyKeyIsTooLong' | 'RmrkPropertyValueIsTooLong' | 'RmrkPropertyIsNotFound' | 'UnableToDecodeRmrkData' | 'CollectionNotEmpty' | 'NoAvailableCollectionId' | 'NoAvailableNftId' | 'CollectionUnknown' | 'NoPermission' | 'NonTransferable' | 'CollectionFullOrLocked' | 'ResourceDoesntExist' | 'CannotSendToDescendentOrSelf' | 'CannotAcceptNonOwnedNft' | 'CannotRejectNonOwnedNft' | 'CannotRejectNonPendingNft' | 'ResourceNotPending' | 'NoAvailableResourceId';
+ readonly type: 'CorruptedCollectionType' | 'RmrkPropertyKeyIsTooLong' | 'RmrkPropertyValueIsTooLong' | 'RmrkPropertyIsNotFound' | 'UnableToDecodeRmrkData' | 'CollectionNotEmpty' | 'NoAvailableCollectionId' | 'NoAvailableNftId' | 'CollectionUnknown' | 'NoPermission' | 'NonTransferable' | 'CollectionFullOrLocked' | 'ResourceDoesntExist' | 'CannotSendToDescendentOrSelf' | 'CannotAcceptNonOwnedNft' | 'CannotRejectNonOwnedNft' | 'CannotRejectNonPendingNft' | 'ResourceNotPending' | 'NoAvailableResourceId';
}
/** @name PalletRmrkCoreEvent */
tests/src/interfaces/lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -2990,7 +2990,7 @@
* Lookup400: pallet_rmrk_core::pallet::Error<T>
**/
PalletRmrkCoreError: {
- _enum: ['CorruptedCollectionType', 'NftTypeEncodeError', 'RmrkPropertyKeyIsTooLong', 'RmrkPropertyValueIsTooLong', 'RmrkPropertyIsNotFound', 'UnableToDecodeRmrkData', 'CollectionNotEmpty', 'NoAvailableCollectionId', 'NoAvailableNftId', 'CollectionUnknown', 'NoPermission', 'NonTransferable', 'CollectionFullOrLocked', 'ResourceDoesntExist', 'CannotSendToDescendentOrSelf', 'CannotAcceptNonOwnedNft', 'CannotRejectNonOwnedNft', 'CannotRejectNonPendingNft', 'ResourceNotPending', 'NoAvailableResourceId']
+ _enum: ['CorruptedCollectionType', 'RmrkPropertyKeyIsTooLong', 'RmrkPropertyValueIsTooLong', 'RmrkPropertyIsNotFound', 'UnableToDecodeRmrkData', 'CollectionNotEmpty', 'NoAvailableCollectionId', 'NoAvailableNftId', 'CollectionUnknown', 'NoPermission', 'NonTransferable', 'CollectionFullOrLocked', 'ResourceDoesntExist', 'CannotSendToDescendentOrSelf', 'CannotAcceptNonOwnedNft', 'CannotRejectNonOwnedNft', 'CannotRejectNonPendingNft', 'ResourceNotPending', 'NoAvailableResourceId']
},
/**
* Lookup402: pallet_rmrk_equip::pallet::Error<T>
tests/src/interfaces/types-lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -3144,7 +3144,6 @@
/** @name PalletRmrkCoreError (400) */
export interface PalletRmrkCoreError extends Enum {
readonly isCorruptedCollectionType: boolean;
- readonly isNftTypeEncodeError: boolean;
readonly isRmrkPropertyKeyIsTooLong: boolean;
readonly isRmrkPropertyValueIsTooLong: boolean;
readonly isRmrkPropertyIsNotFound: boolean;
@@ -3163,7 +3162,7 @@
readonly isCannotRejectNonPendingNft: boolean;
readonly isResourceNotPending: boolean;
readonly isNoAvailableResourceId: boolean;
- readonly type: 'CorruptedCollectionType' | 'NftTypeEncodeError' | 'RmrkPropertyKeyIsTooLong' | 'RmrkPropertyValueIsTooLong' | 'RmrkPropertyIsNotFound' | 'UnableToDecodeRmrkData' | 'CollectionNotEmpty' | 'NoAvailableCollectionId' | 'NoAvailableNftId' | 'CollectionUnknown' | 'NoPermission' | 'NonTransferable' | 'CollectionFullOrLocked' | 'ResourceDoesntExist' | 'CannotSendToDescendentOrSelf' | 'CannotAcceptNonOwnedNft' | 'CannotRejectNonOwnedNft' | 'CannotRejectNonPendingNft' | 'ResourceNotPending' | 'NoAvailableResourceId';
+ readonly type: 'CorruptedCollectionType' | 'RmrkPropertyKeyIsTooLong' | 'RmrkPropertyValueIsTooLong' | 'RmrkPropertyIsNotFound' | 'UnableToDecodeRmrkData' | 'CollectionNotEmpty' | 'NoAvailableCollectionId' | 'NoAvailableNftId' | 'CollectionUnknown' | 'NoPermission' | 'NonTransferable' | 'CollectionFullOrLocked' | 'ResourceDoesntExist' | 'CannotSendToDescendentOrSelf' | 'CannotAcceptNonOwnedNft' | 'CannotRejectNonOwnedNft' | 'CannotRejectNonPendingNft' | 'ResourceNotPending' | 'NoAvailableResourceId';
}
/** @name PalletRmrkEquipError (402) */