difftreelog
Merge branch 'develop' into tests/eth-helpers
in: master
59 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2274,7 +2274,7 @@
"hash256-std-hasher",
"rlp",
"rlp-derive",
- "sha3",
+ "sha3 0.10.6",
"triehash",
]
@@ -2292,7 +2292,7 @@
"rlp",
"scale-info",
"serde",
- "sha3",
+ "sha3 0.10.6",
"triehash",
]
@@ -2350,7 +2350,7 @@
"rlp",
"scale-info",
"serde",
- "sha3",
+ "sha3 0.10.6",
]
[[package]]
@@ -2380,7 +2380,7 @@
"hex",
"proc-macro2",
"quote",
- "sha3",
+ "sha3 0.10.6",
"syn",
]
@@ -2415,7 +2415,7 @@
"environmental",
"evm-core",
"primitive-types 0.12.1",
- "sha3",
+ "sha3 0.10.6",
]
[[package]]
@@ -4958,7 +4958,7 @@
"digest 0.10.6",
"multihash-derive",
"sha2 0.10.6",
- "sha3",
+ "sha3 0.10.6",
"unsigned-varint",
]
@@ -5280,6 +5280,7 @@
"cumulus-primitives-utility",
"derivative",
"evm-coder",
+ "fp-evm",
"fp-evm-mapping",
"fp-rpc",
"fp-self-contained",
@@ -5294,6 +5295,7 @@
"impl-trait-for-tuples",
"log",
"logtest",
+ "num_enum",
"orml-tokens",
"orml-traits",
"orml-vesting",
@@ -5309,6 +5311,7 @@
"pallet-evm-coder-substrate",
"pallet-evm-contract-helpers",
"pallet-evm-migration",
+ "pallet-evm-precompile-simple",
"pallet-evm-transaction-payment",
"pallet-foreign-assets",
"pallet-fungible",
@@ -5333,6 +5336,7 @@
"parachain-info",
"parity-scale-codec 3.2.1",
"polkadot-parachain",
+ "precompile-utils-macro",
"rmrk-rpc",
"scale-info",
"serde",
@@ -6005,6 +6009,16 @@
]
[[package]]
+name = "pallet-evm-precompile-simple"
+version = "2.0.0-dev"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.33#c37ced433a29baad45899d6ab364fe437f97570e"
+dependencies = [
+ "fp-evm",
+ "ripemd",
+ "sp-io",
+]
+
+[[package]]
name = "pallet-evm-transaction-payment"
version = "0.1.1"
dependencies = [
@@ -6328,7 +6342,7 @@
[[package]]
name = "pallet-nonfungible"
-version = "0.1.9"
+version = "0.1.11"
dependencies = [
"ethereum 0.14.0",
"evm-coder",
@@ -6487,7 +6501,7 @@
[[package]]
name = "pallet-refungible"
-version = "0.2.8"
+version = "0.2.10"
dependencies = [
"derivative",
"ethereum 0.14.0",
@@ -8595,6 +8609,17 @@
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
+name = "precompile-utils-macro"
+version = "0.1.0"
+dependencies = [
+ "num_enum",
+ "proc-macro2",
+ "quote",
+ "sha3 0.8.2",
+ "syn",
+]
+
+[[package]]
name = "predicates"
version = "2.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -8850,6 +8875,7 @@
"cumulus-primitives-utility",
"derivative",
"evm-coder",
+ "fp-evm",
"fp-evm-mapping",
"fp-rpc",
"fp-self-contained",
@@ -8864,6 +8890,7 @@
"impl-trait-for-tuples",
"log",
"logtest",
+ "num_enum",
"orml-tokens",
"orml-traits",
"orml-vesting",
@@ -8879,6 +8906,7 @@
"pallet-evm-coder-substrate",
"pallet-evm-contract-helpers",
"pallet-evm-migration",
+ "pallet-evm-precompile-simple",
"pallet-evm-transaction-payment",
"pallet-foreign-assets",
"pallet-fungible",
@@ -8901,6 +8929,7 @@
"parachain-info",
"parity-scale-codec 3.2.1",
"polkadot-parachain",
+ "precompile-utils-macro",
"rmrk-rpc",
"scale-info",
"serde",
@@ -9249,6 +9278,15 @@
]
[[package]]
+name = "ripemd"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f"
+dependencies = [
+ "digest 0.10.6",
+]
+
+[[package]]
name = "rlp"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -10961,6 +10999,19 @@
[[package]]
name = "sha3"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd26bc0e7a2e3a7c959bc494caf58b72ee0c71d67704e9520f736ca7e4853ecf"
+dependencies = [
+ "block-buffer 0.7.3",
+ "byte-tools",
+ "digest 0.8.1",
+ "keccak",
+ "opaque-debug 0.2.3",
+]
+
+[[package]]
+name = "sha3"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdf0c33fae925bdc080598b84bc15c55e7b9a4a43b3c704da051f977469691c9"
@@ -11396,7 +11447,7 @@
"byteorder",
"digest 0.10.6",
"sha2 0.10.6",
- "sha3",
+ "sha3 0.10.6",
"sp-std",
"twox-hash",
]
@@ -13026,6 +13077,7 @@
"cumulus-primitives-utility",
"derivative",
"evm-coder",
+ "fp-evm",
"fp-evm-mapping",
"fp-rpc",
"fp-self-contained",
@@ -13040,6 +13092,7 @@
"impl-trait-for-tuples",
"log",
"logtest",
+ "num_enum",
"orml-tokens",
"orml-traits",
"orml-vesting",
@@ -13055,6 +13108,7 @@
"pallet-evm-coder-substrate",
"pallet-evm-contract-helpers",
"pallet-evm-migration",
+ "pallet-evm-precompile-simple",
"pallet-evm-transaction-payment",
"pallet-foreign-assets",
"pallet-fungible",
@@ -13077,6 +13131,7 @@
"parachain-info",
"parity-scale-codec 3.2.1",
"polkadot-parachain",
+ "precompile-utils-macro",
"rmrk-rpc",
"scale-info",
"serde",
crates/evm-coder/tests/abi_derive_generation.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/abi_derive_generation.rs
+++ b/crates/evm-coder/tests/abi_derive_generation.rs
@@ -740,7 +740,7 @@
/// Some docs
/// At multi
/// line
- #[derive(AbiCoder, Debug, PartialEq, Default)]
+ #[derive(AbiCoder, Debug, PartialEq, Default, Clone, Copy)]
#[repr(u8)]
enum Color {
/// Docs for Red
pallets/app-promotion/src/lib.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -564,7 +564,7 @@
/// # Arguments
///
/// * `stakers_number`: the number of stakers for which recalculation will be performed
- #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(20) as u32))]
+ #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]
pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {
let admin_id = ensure_signed(admin)?;
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -162,3 +162,18 @@
CollectionAdmin,
TokenOwner,
}
+
+/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.
+#[derive(AbiCoder, Copy, Clone, Default, Debug)]
+#[repr(u8)]
+pub enum EthTokenPermissions {
+ /// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]
+ #[default]
+ Mutable,
+
+ /// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]
+ TokenOwner,
+
+ /// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]
+ CollectionAdmin,
+}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1222,7 +1222,8 @@
Ok(())
}
- /// Set scouped collection property.
+ /// Set a scoped collection property, where the scope is a special prefix
+ /// prohibiting a user to change the property.
///
/// * `collection_id` - ID of the collection for which the property is being set.
/// * `scope` - Property scope.
@@ -1240,7 +1241,8 @@
Ok(())
}
- /// Set scouped collection properties.
+ /// Set scoped collection properties, where the scope is a special prefix
+ /// prohibiting a user to change the properties.
///
/// * `collection_id` - ID of the collection for which the properties is being set.
/// * `scope` - Property scope.
pallets/configuration/src/lib.rsdiffbeforeafterboth--- a/pallets/configuration/src/lib.rs
+++ b/pallets/configuration/src/lib.rs
@@ -52,7 +52,7 @@
type DefaultMinGasPrice: Get<u64>;
#[pallet::constant]
- type MaxOverridedAllowedLocations: Get<u32>;
+ type MaxXcmAllowedLocations: Get<u32>;
#[pallet::constant]
type AppPromotionDailyRate: Get<Perbill>;
#[pallet::constant]
@@ -77,7 +77,7 @@
#[pallet::storage]
pub type XcmAllowedLocationsOverride<T: Config> = StorageValue<
- Value = BoundedVec<MultiLocation, T::MaxOverridedAllowedLocations>,
+ Value = BoundedVec<MultiLocation, T::MaxXcmAllowedLocations>,
QueryKind = OptionQuery,
>;
@@ -118,7 +118,7 @@
#[pallet::weight(T::DbWeight::get().writes(1))]
pub fn set_xcm_allowed_locations(
origin: OriginFor<T>,
- locations: Option<BoundedVec<MultiLocation, T::MaxOverridedAllowedLocations>>,
+ locations: Option<BoundedVec<MultiLocation, T::MaxXcmAllowedLocations>>,
) -> DispatchResult {
ensure_root(origin)?;
<XcmAllowedLocationsOverride<T>>::set(locations);
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -18,7 +18,10 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};
use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData};
-use pallet_common::{CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight};
+use pallet_common::{
+ CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
+ weights::WeightInfo as _,
+};
use pallet_structure::Error as StructureError;
use sp_runtime::ArithmeticError;
use sp_std::{vec::Vec, vec};
@@ -53,14 +56,12 @@
<SelfWeightOf<T>>::burn_item()
}
- fn set_collection_properties(_amount: u32) -> Weight {
- // Error
- Weight::zero()
+ fn set_collection_properties(amount: u32) -> Weight {
+ <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)
}
- fn delete_collection_properties(_amount: u32) -> Weight {
- // Error
- Weight::zero()
+ fn delete_collection_properties(amount: u32) -> Weight {
+ <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)
}
fn set_token_properties(_amount: u32) -> Weight {
@@ -294,18 +295,28 @@
fn set_collection_properties(
&self,
- _sender: T::CrossAccountId,
- _property: Vec<Property>,
+ sender: T::CrossAccountId,
+ properties: Vec<Property>,
) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::SettingPropertiesNotAllowed)
+ let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);
+
+ with_weight(
+ <Pallet<T>>::set_collection_properties(self, &sender, properties),
+ weight,
+ )
}
fn delete_collection_properties(
&self,
- _sender: &T::CrossAccountId,
- _property_keys: Vec<PropertyKey>,
+ sender: &T::CrossAccountId,
+ property_keys: Vec<PropertyKey>,
) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::SettingPropertiesNotAllowed)
+ let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);
+
+ with_weight(
+ <Pallet<T>>::delete_collection_properties(self, sender, property_keys),
+ weight,
+ )
}
fn set_token_properties(
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -80,11 +80,11 @@
use core::ops::Deref;
use evm_coder::ToLog;
-use frame_support::{ensure};
+use frame_support::ensure;
use pallet_evm::account::CrossAccountId;
use up_data_structs::{
AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,
- mapping::TokenAddressMapping, budget::Budget,
+ mapping::TokenAddressMapping, budget::Budget, PropertyKey, Property,
};
use pallet_common::{
Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
@@ -260,7 +260,25 @@
Ok(())
}
- ///Checks if collection has tokens. Return `true` if it has.
+ /// Add properties to the collection.
+ pub fn set_collection_properties(
+ collection: &FungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ properties: Vec<Property>,
+ ) -> DispatchResult {
+ <PalletCommon<T>>::set_collection_properties(collection, sender, properties)
+ }
+
+ /// Delete properties of the collection, associated with the provided keys.
+ pub fn delete_collection_properties(
+ collection: &FungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ property_keys: Vec<PropertyKey>,
+ ) -> DispatchResult {
+ <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)
+ }
+
+ /// Checks if collection has tokens. Return `true` if it has.
fn collection_has_tokens(collection_id: CollectionId) -> bool {
<TotalSupply<T>>::get(collection_id) != 0
}
pallets/nonfungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/nonfungible/CHANGELOG.md
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -4,6 +4,16 @@
<!-- bureaucrate goes here -->
+## [0.1.11] - 2022-12-16
+
+### Added
+
+- The function `tokenPropertyPermissions` and `setTokenPropertyPermissions` to `TokenProperties` interface.
+
+### Changed
+
+- Hide `setTokenPropertyPermission` function in `TokenProperties` interface.
+
## [0.1.10] - 2022-11-18
### Added
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-nonfungible"
-version = "0.1.9"
+version = "0.1.11"
license = "GPLv3"
edition = "2021"
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -34,11 +34,11 @@
CollectionPropertiesVec,
};
use pallet_evm_coder_substrate::dispatch_to_evm;
-use sp_std::vec::Vec;
+use sp_std::{vec::Vec, vec};
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
- eth::EthCrossAccount,
+ eth::{EthCrossAccount, EthTokenPermissions},
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::call;
@@ -60,6 +60,7 @@
/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
/// @param tokenOwner Permission to mutate property by token owner if property is mutable.
#[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]
+ #[solidity(hide)]
fn set_token_property_permission(
&mut self,
caller: caller,
@@ -69,10 +70,10 @@
token_owner: bool,
) -> Result<()> {
let caller = T::CrossAccountId::from_eth(caller);
- <Pallet<T>>::set_property_permission(
+ <Pallet<T>>::set_token_property_permissions(
self,
&caller,
- PropertyKeyPermission {
+ vec![PropertyKeyPermission {
key: <Vec<u8>>::from(key)
.try_into()
.map_err(|_| "too long key")?,
@@ -81,11 +82,78 @@
collection_admin,
token_owner,
},
- },
+ }],
)
.map_err(dispatch_to_evm::<T>)
}
+ /// @notice Set permissions for token property.
+ /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+ /// @param permissions Permissions for keys.
+ #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]
+ fn set_token_property_permissions(
+ &mut self,
+ caller: caller,
+ permissions: Vec<(string, Vec<(EthTokenPermissions, bool)>)>,
+ ) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ const PERMISSIONS_FIELDS_COUNT: usize = 3;
+
+ let mut perms = Vec::new();
+
+ for (key, pp) in permissions {
+ if pp.len() > PERMISSIONS_FIELDS_COUNT {
+ return Err(alloc::format!(
+ "Actual number of fields {} for {}, which exceeds the maximum value of {}",
+ pp.len(),
+ stringify!(EthTokenPermissions),
+ PERMISSIONS_FIELDS_COUNT
+ )
+ .as_str()
+ .into());
+ }
+
+ let mut token_permission = PropertyPermission::default();
+
+ for (perm, value) in pp {
+ match perm {
+ EthTokenPermissions::Mutable => token_permission.mutable = value,
+ EthTokenPermissions::TokenOwner => token_permission.token_owner = value,
+ EthTokenPermissions::CollectionAdmin => {
+ token_permission.collection_admin = value
+ }
+ }
+ }
+
+ perms.push(PropertyKeyPermission {
+ key: key.into_bytes().try_into().map_err(|_| "too long key")?,
+ permission: token_permission,
+ });
+ }
+
+ <Pallet<T>>::set_token_property_permissions(self, &caller, perms)
+ .map_err(dispatch_to_evm::<T>)
+ }
+
+ /// @notice Get permissions for token properties.
+ fn token_property_permissions(
+ &self,
+ ) -> Result<Vec<(string, Vec<(EthTokenPermissions, bool)>)>> {
+ let perms = <Pallet<T>>::token_property_permission(self.id);
+ Ok(perms
+ .into_iter()
+ .map(|(key, pp)| {
+ let key = string::from_utf8(key.into_inner()).expect("Stored key must be valid");
+ let pp = vec![
+ (EthTokenPermissions::Mutable, pp.mutable),
+ (EthTokenPermissions::TokenOwner, pp.token_owner),
+ (EthTokenPermissions::CollectionAdmin, pp.collection_admin),
+ ];
+ (key, pp)
+ })
+ .collect())
+ }
+
/// @notice Set token property value.
/// @dev Throws error if `msg.sender` has no permission to edit the property.
/// @param tokenId ID of the token.
pallets/nonfungible/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//! # Nonfungible Pallet18//!19//! The Nonfungible pallet provides functionality for handling nonfungible collections and tokens.20//!21//! - [`Config`]22//! - [`NonfungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Nonfungible pallet provides functions for:29//!30//! - NFT collection creation and removal31//! - Minting and burning of NFT tokens32//! - Retrieving account balances33//! - Transfering NFT tokens34//! - Setting and checking allowance for NFT tokens35//! - Setting properties and permissions for NFT collections and tokens36//! - Nesting and unnesting tokens37//!38//! ### Terminology39//!40//! - **NFT token:** Non fungible token.41//!42//! - **NFT Collection:** A collection of NFT tokens. All NFT tokens are part of a collection.43//! Each collection can define it's own properties, properties for it's tokens and set of permissions.44//!45//! - **Balance:** Number of NFT tokens owned by an account46//!47//! - **Allowance:** NFT tokens owned by one account that another account is allowed to make operations on48//!49//! - **Burning:** The process of “deleting” a token from a collection and from50//! an account balance of the owner.51//!52//! - **Nesting:** Setting up parent-child relationship between tokens. Nested tokens are inhereting53//! owner from their parent. There could be multiple levels of nesting. Token couldn't be nested in54//! it's child token i.e. parent-child relationship graph shouldn't have cycles.55//!56//! - **Properties:** Key-Values pairs. Token properties are attached to a token. Collection properties are57//! attached to a collection. Set of permissions could be defined for each property.58//!59//! ### Implementations60//!61//! The Nonfungible pallet provides implementations for the following traits. If these traits provide62//! the functionality that you need, then you can avoid coupling with the Nonfungible pallet.63//!64//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight65//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing66//! with collections67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create NFT collection. NFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising NFT collection. There should be no tokens in the collection.75//! - `burn` - Burn NFT token owned by account.76//! - `transfer` - Transfer NFT token. Transfers should be enabled for NFT collection.77//! Nests the NFT token if it is sent to another token.78//! - `create_item` - Mint NFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account.80//! - `set_token_property` - Set token property value.81//! - `delete_token_property` - Remove property from the token.82//! - `set_collection_properties` - Set collection properties.83//! - `delete_collection_properties` - Remove properties from the collection.84//! - `set_property_permission` - Set collection property permission.85//! - `set_token_property_permissions` - Set token property permissions.86//!87//! ## Assumptions88//!89//! * To perform operations on tokens sender should be in collection's allow list if collection access mode is `AllowList`.9091#![cfg_attr(not(feature = "std"), no_std)]9293use erc::ERC721Events;94use evm_coder::ToLog;95use frame_support::{96 BoundedVec, ensure, fail, transactional,97 storage::with_transaction,98 pallet_prelude::DispatchResultWithPostInfo,99 pallet_prelude::Weight,100 dispatch::{PostDispatchInfo, Pays},101};102use up_data_structs::{103 AccessMode, CollectionId, CollectionFlags, CustomDataLimit, TokenId, CreateCollectionData,104 CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyPermission,105 PropertyKey, PropertyValue, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,106 TokenChild, AuxPropertyValue,107};108use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};109use pallet_common::{110 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,111 eth::collection_id_to_address, erc::CollectionHelpersEvents,112};113use pallet_structure::{Pallet as PalletStructure, Error as StructureError};114use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};115use sp_core::{H160, Get};116use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};117use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};118use core::ops::Deref;119use codec::{Encode, Decode, MaxEncodedLen};120use scale_info::TypeInfo;121122pub use pallet::*;123use weights::WeightInfo;124#[cfg(feature = "runtime-benchmarks")]125pub mod benchmarking;126pub mod common;127pub mod erc;128pub mod weights;129130pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::Config>::CrossAccountId>;131pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;132133/// Token data, stored independently from other data used to describe it134/// for the convenience of database access. Notably contains the owner account address.135#[struct_versioning::versioned(version = 2, upper)]136#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]137pub struct ItemData<CrossAccountId> {138 #[version(..2)]139 pub const_data: BoundedVec<u8, CustomDataLimit>,140141 #[version(..2)]142 pub variable_data: BoundedVec<u8, CustomDataLimit>,143144 pub owner: CrossAccountId,145}146147#[frame_support::pallet]148pub mod pallet {149 use super::*;150 use frame_support::{151 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,152 };153 use frame_system::pallet_prelude::*;154 use up_data_structs::{CollectionId, TokenId};155 use super::weights::WeightInfo;156157 #[pallet::error]158 pub enum Error<T> {159 /// Not Nonfungible item data used to mint in Nonfungible collection.160 NotNonfungibleDataUsedToMintFungibleCollectionToken,161 /// Used amount > 1 with NFT162 NonfungibleItemsHaveNoAmount,163 /// Unable to burn NFT with children164 CantBurnNftWithChildren,165 }166167 #[pallet::config]168 pub trait Config:169 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config170 {171 type WeightInfo: WeightInfo;172 }173174 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);175176 #[pallet::pallet]177 #[pallet::storage_version(STORAGE_VERSION)]178 #[pallet::generate_store(pub(super) trait Store)]179 pub struct Pallet<T>(_);180181 /// Total amount of minted tokens in a collection.182 #[pallet::storage]183 pub type TokensMinted<T: Config> =184 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;185186 /// Amount of burnt tokens in a collection.187 #[pallet::storage]188 pub type TokensBurnt<T: Config> =189 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;190191 /// Token data, used to partially describe a token.192 #[pallet::storage]193 pub type TokenData<T: Config> = StorageNMap<194 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),195 Value = ItemData<T::CrossAccountId>,196 QueryKind = OptionQuery,197 >;198199 /// Map of key-value pairs, describing the metadata of a token.200 #[pallet::storage]201 #[pallet::getter(fn token_properties)]202 pub type TokenProperties<T: Config> = StorageNMap<203 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),204 Value = Properties,205 QueryKind = ValueQuery,206 OnEmpty = up_data_structs::TokenProperties,207 >;208209 /// Custom data of a token that is serialized to bytes,210 /// primarily reserved for on-chain operations,211 /// normally obscured from the external users.212 ///213 /// Auxiliary properties are slightly different from214 /// usual [`TokenProperties`] due to an unlimited number215 /// and separately stored and written-to key-value pairs.216 ///217 /// Currently used to store RMRK data.218 #[pallet::storage]219 #[pallet::getter(fn token_aux_property)]220 pub type TokenAuxProperties<T: Config> = StorageNMap<221 Key = (222 Key<Twox64Concat, CollectionId>,223 Key<Twox64Concat, TokenId>,224 Key<Twox64Concat, PropertyScope>,225 Key<Twox64Concat, PropertyKey>,226 ),227 Value = AuxPropertyValue,228 QueryKind = OptionQuery,229 >;230231 /// Used to enumerate tokens owned by account.232 #[pallet::storage]233 pub type Owned<T: Config> = StorageNMap<234 Key = (235 Key<Twox64Concat, CollectionId>,236 Key<Blake2_128Concat, T::CrossAccountId>,237 Key<Twox64Concat, TokenId>,238 ),239 Value = bool,240 QueryKind = ValueQuery,241 >;242243 /// Used to enumerate token's children.244 #[pallet::storage]245 #[pallet::getter(fn token_children)]246 pub type TokenChildren<T: Config> = StorageNMap<247 Key = (248 Key<Twox64Concat, CollectionId>,249 Key<Twox64Concat, TokenId>,250 Key<Twox64Concat, (CollectionId, TokenId)>,251 ),252 Value = bool,253 QueryKind = ValueQuery,254 >;255256 /// Amount of tokens owned by an account in a collection.257 #[pallet::storage]258 pub type AccountBalance<T: Config> = StorageNMap<259 Key = (260 Key<Twox64Concat, CollectionId>,261 Key<Blake2_128Concat, T::CrossAccountId>,262 ),263 Value = u32,264 QueryKind = ValueQuery,265 >;266267 /// Allowance set by a token owner for another user to perform one of certain transactions on a token.268 #[pallet::storage]269 pub type Allowance<T: Config> = StorageNMap<270 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),271 Value = T::CrossAccountId,272 QueryKind = OptionQuery,273 >;274275 /// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.276 #[pallet::storage]277 pub type CollectionAllowance<T: Config> = StorageNMap<278 Key = (279 Key<Twox64Concat, CollectionId>,280 Key<Blake2_128Concat, T::CrossAccountId>,281 Key<Blake2_128Concat, T::CrossAccountId>,282 ),283 Value = bool,284 QueryKind = ValueQuery,285 >;286287 /// Upgrade from the old schema to properties.288 #[pallet::hooks]289 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {290 fn on_runtime_upgrade() -> Weight {291 StorageVersion::new(1).put::<Pallet<T>>();292293 Weight::zero()294 }295 }296}297298pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);299impl<T: Config> NonfungibleHandle<T> {300 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {301 Self(inner)302 }303 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {304 self.0305 }306 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {307 &mut self.0308 }309}310311impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {312 fn recorder(&self) -> &SubstrateRecorder<T> {313 self.0.recorder()314 }315 fn into_recorder(self) -> SubstrateRecorder<T> {316 self.0.into_recorder()317 }318}319impl<T: Config> Deref for NonfungibleHandle<T> {320 type Target = pallet_common::CollectionHandle<T>;321322 fn deref(&self) -> &Self::Target {323 &self.0324 }325}326327impl<T: Config> Pallet<T> {328 /// Get number of NFT tokens in collection.329 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {330 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)331 }332333 /// Check that NFT token exists.334 ///335 /// - `token`: Token ID.336 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {337 <TokenData<T>>::contains_key((collection.id, token))338 }339340 /// Set the token property with the scope.341 ///342 /// - `property`: Contains key-value pair.343 pub fn set_scoped_token_property(344 collection_id: CollectionId,345 token_id: TokenId,346 scope: PropertyScope,347 property: Property,348 ) -> DispatchResult {349 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {350 properties.try_scoped_set(scope, property.key, property.value)351 })352 .map_err(<CommonError<T>>::from)?;353354 Ok(())355 }356357 /// Batch operation to set multiple properties with the same scope.358 pub fn set_scoped_token_properties(359 collection_id: CollectionId,360 token_id: TokenId,361 scope: PropertyScope,362 properties: impl Iterator<Item = Property>,363 ) -> DispatchResult {364 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {365 stored_properties.try_scoped_set_from_iter(scope, properties)366 })367 .map_err(<CommonError<T>>::from)?;368369 Ok(())370 }371372 /// Add or edit auxiliary data for the property.373 ///374 /// - `f`: function that adds or edits auxiliary data.375 pub fn try_mutate_token_aux_property<R, E>(376 collection_id: CollectionId,377 token_id: TokenId,378 scope: PropertyScope,379 key: PropertyKey,380 f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,381 ) -> Result<R, E> {382 <TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)383 }384385 /// Remove auxiliary data for the property.386 pub fn remove_token_aux_property(387 collection_id: CollectionId,388 token_id: TokenId,389 scope: PropertyScope,390 key: PropertyKey,391 ) {392 <TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));393 }394395 /// Get all auxiliary data in a given scope.396 ///397 /// Returns iterator over Property Key - Data pairs.398 pub fn iterate_token_aux_properties(399 collection_id: CollectionId,400 token_id: TokenId,401 scope: PropertyScope,402 ) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {403 <TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))404 }405406 /// Get ID of the last minted token407 pub fn current_token_id(collection_id: CollectionId) -> TokenId {408 TokenId(<TokensMinted<T>>::get(collection_id))409 }410}411412// unchecked calls skips any permission checks413impl<T: Config> Pallet<T> {414 /// Create NFT collection415 ///416 /// `init_collection` will take non-refundable deposit for collection creation.417 ///418 /// - `data`: Contains settings for collection limits and permissions.419 pub fn init_collection(420 owner: T::CrossAccountId,421 payer: T::CrossAccountId,422 data: CreateCollectionData<T::AccountId>,423 flags: CollectionFlags,424 ) -> Result<CollectionId, DispatchError> {425 <PalletCommon<T>>::init_collection(owner, payer, data, flags)426 }427428 /// Destroy NFT collection429 ///430 /// `destroy_collection` will throw error if collection contains any tokens.431 /// Only owner can destroy collection.432 pub fn destroy_collection(433 collection: NonfungibleHandle<T>,434 sender: &T::CrossAccountId,435 ) -> DispatchResult {436 let id = collection.id;437438 if Self::collection_has_tokens(id) {439 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());440 }441442 // =========443444 PalletCommon::destroy_collection(collection.0, sender)?;445446 let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);447 let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);448 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);449 <TokensMinted<T>>::remove(id);450 <TokensBurnt<T>>::remove(id);451 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);452 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);453 let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);454 Ok(())455 }456457 /// Burn NFT token458 ///459 /// `burn` removes `token` from the `collection`, from it's owner and from the parent token460 /// if the token is nested.461 /// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.462 /// Also removes all corresponding properties and auxiliary properties.463 ///464 /// - `token`: Token that should be burned465 /// - `collection`: Collection that contains the token466 pub fn burn(467 collection: &NonfungibleHandle<T>,468 sender: &T::CrossAccountId,469 token: TokenId,470 ) -> DispatchResult {471 let token_data =472 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;473 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);474475 if collection.permissions.access() == AccessMode::AllowList {476 collection.check_allowlist(sender)?;477 }478479 if Self::token_has_children(collection.id, token) {480 return Err(<Error<T>>::CantBurnNftWithChildren.into());481 }482483 let burnt = <TokensBurnt<T>>::get(collection.id)484 .checked_add(1)485 .ok_or(ArithmeticError::Overflow)?;486487 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))488 .checked_sub(1)489 .ok_or(ArithmeticError::Overflow)?;490491 // =========492493 if balance == 0 {494 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));495 } else {496 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);497 }498499 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);500501 <Owned<T>>::remove((collection.id, &token_data.owner, token));502 <TokensBurnt<T>>::insert(collection.id, burnt);503 <TokenData<T>>::remove((collection.id, token));504 <TokenProperties<T>>::remove((collection.id, token));505 let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);506 let old_spender = <Allowance<T>>::take((collection.id, token));507508 if let Some(old_spender) = old_spender {509 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(510 collection.id,511 token,512 token_data.owner.clone(),513 old_spender,514 0,515 ));516 }517518 <PalletEvm<T>>::deposit_log(519 ERC721Events::Transfer {520 from: *token_data.owner.as_eth(),521 to: H160::default(),522 token_id: token.into(),523 }524 .to_log(collection_id_to_address(collection.id)),525 );526 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(527 collection.id,528 token,529 token_data.owner,530 1,531 ));532 Ok(())533 }534535 /// Same as [`burn`] but burns all the tokens that are nested in the token first536 ///537 /// - `self_budget`: Limit for searching children in depth.538 /// - `breadth_budget`: Limit of breadth of searching children.539 ///540 /// [`burn`]: struct.Pallet.html#method.burn541 #[transactional]542 pub fn burn_recursively(543 collection: &NonfungibleHandle<T>,544 sender: &T::CrossAccountId,545 token: TokenId,546 self_budget: &dyn Budget,547 breadth_budget: &dyn Budget,548 ) -> DispatchResultWithPostInfo {549 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);550551 let current_token_account =552 T::CrossTokenAddressMapping::token_to_address(collection.id, token);553554 let mut weight = Weight::zero();555556 // This method is transactional, if user in fact doesn't have permissions to remove token -557 // tokens removed here will be restored after rejected transaction558 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {559 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);560 let PostDispatchInfo { actual_weight, .. } =561 <PalletStructure<T>>::burn_item_recursively(562 current_token_account.clone(),563 collection,564 token,565 self_budget,566 breadth_budget,567 )?;568 if let Some(actual_weight) = actual_weight {569 weight = weight.saturating_add(actual_weight);570 }571 }572573 Self::burn(collection, sender, token)?;574 DispatchResultWithPostInfo::Ok(PostDispatchInfo {575 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),576 pays_fee: Pays::Yes,577 })578 }579580 /// Batch operation to add, edit or remove properties for the token581 ///582 /// All affected properties should have mutable permission and sender should have583 /// permission to edit those properties.584 ///585 /// - `nesting_budget`: Limit for searching parents in depth to check ownership.586 /// - `is_token_create`: Indicates that method is called during token initialization.587 /// Allows to bypass ownership check.588 #[transactional]589 fn modify_token_properties(590 collection: &NonfungibleHandle<T>,591 sender: &T::CrossAccountId,592 token_id: TokenId,593 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,594 is_token_create: bool,595 nesting_budget: &dyn Budget,596 ) -> DispatchResult {597 let mut collection_admin_status = None;598 let mut token_owner_result = None;599600 let mut is_collection_admin =601 || *collection_admin_status.get_or_insert_with(|| collection.is_owner_or_admin(sender));602603 let mut is_token_owner = || {604 *token_owner_result.get_or_insert_with(|| -> Result<bool, DispatchError> {605 let is_owned = <PalletStructure<T>>::check_indirectly_owned(606 sender.clone(),607 collection.id,608 token_id,609 None,610 nesting_budget,611 )?;612613 Ok(is_owned)614 })615 };616617 for (key, value) in properties {618 let permission = <PalletCommon<T>>::property_permissions(collection.id)619 .get(&key)620 .cloned()621 .unwrap_or_else(PropertyPermission::none);622623 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))624 .get(&key)625 .is_some();626627 match permission {628 PropertyPermission { mutable: false, .. } if is_property_exists => {629 return Err(<CommonError<T>>::NoPermission.into());630 }631632 PropertyPermission {633 collection_admin,634 token_owner,635 ..636 } => {637 //TODO: investigate threats during public minting.638 if is_token_create && (collection_admin || token_owner) && value.is_some() {639 // Pass640 } else if collection_admin && is_collection_admin() {641 // Pass642 } else if token_owner && is_token_owner()? {643 // Pass644 } else {645 fail!(<CommonError<T>>::NoPermission);646 }647 }648 }649650 match value {651 Some(value) => {652 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {653 properties.try_set(key.clone(), value)654 })655 .map_err(<CommonError<T>>::from)?;656657 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(658 collection.id,659 token_id,660 key,661 ));662 }663 None => {664 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {665 properties.remove(&key)666 })667 .map_err(<CommonError<T>>::from)?;668669 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(670 collection.id,671 token_id,672 key,673 ));674 }675 }676677 <PalletEvm<T>>::deposit_log(678 CollectionHelpersEvents::TokenChanged {679 collection_id: collection_id_to_address(collection.id),680 token_id: token_id.into(),681 }682 .to_log(T::ContractAddress::get()),683 );684 }685686 Ok(())687 }688689 /// Batch operation to add or edit properties for the token690 ///691 /// Same as [`modify_token_properties`] but doesn't allow to remove properties692 ///693 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties694 pub fn set_token_properties(695 collection: &NonfungibleHandle<T>,696 sender: &T::CrossAccountId,697 token_id: TokenId,698 properties: impl Iterator<Item = Property>,699 is_token_create: bool,700 nesting_budget: &dyn Budget,701 ) -> DispatchResult {702 Self::modify_token_properties(703 collection,704 sender,705 token_id,706 properties.map(|p| (p.key, Some(p.value))),707 is_token_create,708 nesting_budget,709 )710 }711712 /// Add or edit single property for the token713 ///714 /// Calls [`set_token_properties`] internally715 ///716 /// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties717 pub fn set_token_property(718 collection: &NonfungibleHandle<T>,719 sender: &T::CrossAccountId,720 token_id: TokenId,721 property: Property,722 nesting_budget: &dyn Budget,723 ) -> DispatchResult {724 let is_token_create = false;725726 Self::set_token_properties(727 collection,728 sender,729 token_id,730 [property].into_iter(),731 is_token_create,732 nesting_budget,733 )734 }735736 /// Batch operation to remove properties from the token737 ///738 /// Same as [`modify_token_properties`] but doesn't allow to add or edit properties739 ///740 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties741 pub fn delete_token_properties(742 collection: &NonfungibleHandle<T>,743 sender: &T::CrossAccountId,744 token_id: TokenId,745 property_keys: impl Iterator<Item = PropertyKey>,746 nesting_budget: &dyn Budget,747 ) -> DispatchResult {748 let is_token_create = false;749750 Self::modify_token_properties(751 collection,752 sender,753 token_id,754 property_keys.into_iter().map(|key| (key, None)),755 is_token_create,756 nesting_budget,757 )758 }759760 /// Remove single property from the token761 ///762 /// Calls [`delete_token_properties`] internally763 ///764 /// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties765 pub fn delete_token_property(766 collection: &NonfungibleHandle<T>,767 sender: &T::CrossAccountId,768 token_id: TokenId,769 property_key: PropertyKey,770 nesting_budget: &dyn Budget,771 ) -> DispatchResult {772 Self::delete_token_properties(773 collection,774 sender,775 token_id,776 [property_key].into_iter(),777 nesting_budget,778 )779 }780781 /// Add or edit properties for the collection782 pub fn set_collection_properties(783 collection: &NonfungibleHandle<T>,784 sender: &T::CrossAccountId,785 properties: Vec<Property>,786 ) -> DispatchResult {787 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)788 }789790 /// Remove properties from the collection791 pub fn delete_collection_properties(792 collection: &CollectionHandle<T>,793 sender: &T::CrossAccountId,794 property_keys: Vec<PropertyKey>,795 ) -> DispatchResult {796 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)797 }798799 /// Set property permissions for the token.800 ///801 /// Sender should be the owner or admin of token's collection.802 pub fn set_token_property_permissions(803 collection: &CollectionHandle<T>,804 sender: &T::CrossAccountId,805 property_permissions: Vec<PropertyKeyPermission>,806 ) -> DispatchResult {807 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)808 }809810 /// Set property permissions for the token with scope.811 ///812 /// Sender should be the owner or admin of token's collection.813 pub fn set_scoped_token_property_permissions(814 collection: &CollectionHandle<T>,815 sender: &T::CrossAccountId,816 scope: PropertyScope,817 property_permissions: Vec<PropertyKeyPermission>,818 ) -> DispatchResult {819 <PalletCommon<T>>::set_scoped_token_property_permissions(820 collection,821 sender,822 scope,823 property_permissions,824 )825 }826827 /// Set property permissions for the collection.828 ///829 /// Sender should be the owner or admin of the collection.830 pub fn set_property_permission(831 collection: &CollectionHandle<T>,832 sender: &T::CrossAccountId,833 permission: PropertyKeyPermission,834 ) -> DispatchResult {835 <PalletCommon<T>>::set_property_permission(collection, sender, permission)836 }837838 pub fn check_token_immediate_ownership(839 collection: &NonfungibleHandle<T>,840 token: TokenId,841 possible_owner: &T::CrossAccountId,842 ) -> DispatchResult {843 let token_data =844 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;845 ensure!(846 &token_data.owner == possible_owner,847 <CommonError<T>>::NoPermission848 );849 Ok(())850 }851852 /// Transfer NFT token from one account to another.853 ///854 /// `from` account stops being the owner and `to` account becomes the owner of the token.855 /// If `to` is token than `to` becomes owner of the token and the token become nested.856 /// Unnests token from previous parent if it was nested before.857 /// Removes allowance for the token if there was any.858 /// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.859 ///860 /// - `nesting_budget`: Limit for token nesting depth861 pub fn transfer(862 collection: &NonfungibleHandle<T>,863 from: &T::CrossAccountId,864 to: &T::CrossAccountId,865 token: TokenId,866 nesting_budget: &dyn Budget,867 ) -> DispatchResult {868 ensure!(869 collection.limits.transfers_enabled(),870 <CommonError<T>>::TransferNotAllowed871 );872873 let token_data =874 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;875 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);876877 if collection.permissions.access() == AccessMode::AllowList {878 collection.check_allowlist(from)?;879 collection.check_allowlist(to)?;880 }881 <PalletCommon<T>>::ensure_correct_receiver(to)?;882883 let balance_from = <AccountBalance<T>>::get((collection.id, from))884 .checked_sub(1)885 .ok_or(<CommonError<T>>::TokenValueTooLow)?;886 let balance_to = if from != to {887 let balance_to = <AccountBalance<T>>::get((collection.id, to))888 .checked_add(1)889 .ok_or(ArithmeticError::Overflow)?;890891 ensure!(892 balance_to < collection.limits.account_token_ownership_limit(),893 <CommonError<T>>::AccountTokenLimitExceeded,894 );895896 Some(balance_to)897 } else {898 None899 };900901 <PalletStructure<T>>::nest_if_sent_to_token(902 from.clone(),903 to,904 collection.id,905 token,906 nesting_budget,907 )?;908909 // =========910911 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);912913 <TokenData<T>>::insert(914 (collection.id, token),915 ItemData {916 owner: to.clone(),917 ..token_data918 },919 );920921 if let Some(balance_to) = balance_to {922 // from != to923 if balance_from == 0 {924 <AccountBalance<T>>::remove((collection.id, from));925 } else {926 <AccountBalance<T>>::insert((collection.id, from), balance_from);927 }928 <AccountBalance<T>>::insert((collection.id, to), balance_to);929 <Owned<T>>::remove((collection.id, from, token));930 <Owned<T>>::insert((collection.id, to, token), true);931 }932 Self::set_allowance_unchecked(collection, from, token, None, true);933934 <PalletEvm<T>>::deposit_log(935 ERC721Events::Transfer {936 from: *from.as_eth(),937 to: *to.as_eth(),938 token_id: token.into(),939 }940 .to_log(collection_id_to_address(collection.id)),941 );942 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(943 collection.id,944 token,945 from.clone(),946 to.clone(),947 1,948 ));949 Ok(())950 }951952 /// Batch operation to mint multiple NFT tokens.953 ///954 /// The sender should be the owner/admin of the collection or collection should be configured955 /// to allow public minting.956 /// Throws if amount of tokens reached it's limit for the collection or if caller reached957 /// token ownership limit.958 ///959 /// - `data`: Contains list of token properties and users who will become the owners of the960 /// corresponging tokens.961 /// - `nesting_budget`: Limit for token nesting depth962 pub fn create_multiple_items(963 collection: &NonfungibleHandle<T>,964 sender: &T::CrossAccountId,965 data: Vec<CreateItemData<T>>,966 nesting_budget: &dyn Budget,967 ) -> DispatchResult {968 if !collection.is_owner_or_admin(sender) {969 ensure!(970 collection.permissions.mint_mode(),971 <CommonError<T>>::PublicMintingNotAllowed972 );973 collection.check_allowlist(sender)?;974975 for item in data.iter() {976 collection.check_allowlist(&item.owner)?;977 }978 }979980 for data in data.iter() {981 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;982 }983984 let first_token = <TokensMinted<T>>::get(collection.id);985 let tokens_minted = first_token986 .checked_add(data.len() as u32)987 .ok_or(ArithmeticError::Overflow)?;988 ensure!(989 tokens_minted <= collection.limits.token_limit(),990 <CommonError<T>>::CollectionTokenLimitExceeded991 );992993 let mut balances = BTreeMap::new();994 for data in &data {995 let balance = balances996 .entry(&data.owner)997 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));998 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;9991000 ensure!(1001 *balance <= collection.limits.account_token_ownership_limit(),1002 <CommonError<T>>::AccountTokenLimitExceeded,1003 );1004 }10051006 for (i, data) in data.iter().enumerate() {1007 let token = TokenId(first_token + i as u32 + 1);10081009 <PalletStructure<T>>::check_nesting(1010 sender.clone(),1011 &data.owner,1012 collection.id,1013 token,1014 nesting_budget,1015 )?;1016 }10171018 // =========10191020 with_transaction(|| {1021 for (i, data) in data.iter().enumerate() {1022 let token = first_token + i as u32 + 1;10231024 <TokenData<T>>::insert(1025 (collection.id, token),1026 ItemData {1027 // const_data: data.const_data.clone(),1028 owner: data.owner.clone(),1029 },1030 );10311032 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(1033 &data.owner,1034 collection.id,1035 TokenId(token),1036 );10371038 if let Err(e) = Self::set_token_properties(1039 collection,1040 sender,1041 TokenId(token),1042 data.properties.clone().into_iter(),1043 true,1044 nesting_budget,1045 ) {1046 return TransactionOutcome::Rollback(Err(e));1047 }1048 }1049 TransactionOutcome::Commit(Ok(()))1050 })?;10511052 <TokensMinted<T>>::insert(collection.id, tokens_minted);1053 for (account, balance) in balances {1054 <AccountBalance<T>>::insert((collection.id, account), balance);1055 }1056 for (i, data) in data.into_iter().enumerate() {1057 let token = first_token + i as u32 + 1;1058 <Owned<T>>::insert((collection.id, &data.owner, token), true);10591060 <PalletEvm<T>>::deposit_log(1061 ERC721Events::Transfer {1062 from: H160::default(),1063 to: *data.owner.as_eth(),1064 token_id: token.into(),1065 }1066 .to_log(collection_id_to_address(collection.id)),1067 );1068 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1069 collection.id,1070 TokenId(token),1071 data.owner.clone(),1072 1,1073 ));1074 }1075 Ok(())1076 }10771078 pub fn set_allowance_unchecked(1079 collection: &NonfungibleHandle<T>,1080 sender: &T::CrossAccountId,1081 token: TokenId,1082 spender: Option<&T::CrossAccountId>,1083 assume_implicit_eth: bool,1084 ) {1085 if let Some(spender) = spender {1086 let old_spender = <Allowance<T>>::get((collection.id, token));1087 <Allowance<T>>::insert((collection.id, token), spender);1088 // In ERC721 there is only one possible approved user of token, so we set1089 // approved user to spender1090 <PalletEvm<T>>::deposit_log(1091 ERC721Events::Approval {1092 owner: *sender.as_eth(),1093 approved: *spender.as_eth(),1094 token_id: token.into(),1095 }1096 .to_log(collection_id_to_address(collection.id)),1097 );1098 // In Unique chain, any token can have any amount of approved users, so we need to1099 // set allowance of old owner to 0, and allowance of new owner to 11100 if old_spender.as_ref() != Some(spender) {1101 if let Some(old_owner) = old_spender {1102 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1103 collection.id,1104 token,1105 sender.clone(),1106 old_owner,1107 0,1108 ));1109 }1110 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1111 collection.id,1112 token,1113 sender.clone(),1114 spender.clone(),1115 1,1116 ));1117 }1118 } else {1119 let old_spender = <Allowance<T>>::take((collection.id, token));1120 if !assume_implicit_eth {1121 // In ERC721 there is only one possible approved user of token, so we set1122 // approved user to zero address1123 <PalletEvm<T>>::deposit_log(1124 ERC721Events::Approval {1125 owner: *sender.as_eth(),1126 approved: H160::default(),1127 token_id: token.into(),1128 }1129 .to_log(collection_id_to_address(collection.id)),1130 );1131 }1132 // In Unique chain, any token can have any amount of approved users, so we need to1133 // set allowance of old owner to 01134 if let Some(old_spender) = old_spender {1135 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1136 collection.id,1137 token,1138 sender.clone(),1139 old_spender,1140 0,1141 ));1142 }1143 }1144 }11451146 /// Set allowance for the spender to `transfer` or `burn` sender's token.1147 ///1148 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1149 pub fn set_allowance(1150 collection: &NonfungibleHandle<T>,1151 sender: &T::CrossAccountId,1152 token: TokenId,1153 spender: Option<&T::CrossAccountId>,1154 ) -> DispatchResult {1155 if collection.permissions.access() == AccessMode::AllowList {1156 collection.check_allowlist(sender)?;1157 if let Some(spender) = spender {1158 collection.check_allowlist(spender)?;1159 }1160 }11611162 if let Some(spender) = spender {1163 <PalletCommon<T>>::ensure_correct_receiver(spender)?;1164 }11651166 let token_data =1167 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1168 if &token_data.owner != sender {1169 ensure!(1170 collection.ignores_owned_amount(sender),1171 <CommonError<T>>::CantApproveMoreThanOwned1172 );1173 }11741175 // =========11761177 Self::set_allowance_unchecked(collection, sender, token, spender, false);1178 Ok(())1179 }11801181 /// Checks allowance for the spender to use the token.1182 fn check_allowed(1183 collection: &NonfungibleHandle<T>,1184 spender: &T::CrossAccountId,1185 from: &T::CrossAccountId,1186 token: TokenId,1187 nesting_budget: &dyn Budget,1188 ) -> DispatchResult {1189 if spender.conv_eq(from) {1190 return Ok(());1191 }1192 if collection.permissions.access() == AccessMode::AllowList {1193 // `from`, `to` checked in [`transfer`]1194 collection.check_allowlist(spender)?;1195 }11961197 if collection.limits.owner_can_transfer() && collection.is_owner_or_admin(spender) {1198 return Ok(());1199 }12001201 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1202 ensure!(1203 <PalletStructure<T>>::check_indirectly_owned(1204 spender.clone(),1205 source.0,1206 source.1,1207 None,1208 nesting_budget1209 )?,1210 <CommonError<T>>::ApprovedValueTooLow,1211 );1212 return Ok(());1213 }1214 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1215 return Ok(());1216 }1217 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1218 return Ok(());1219 }1220 ensure!(1221 collection.ignores_allowance(spender),1222 <CommonError<T>>::ApprovedValueTooLow1223 );1224 Ok(())1225 }12261227 /// Transfer NFT token from one account to another.1228 ///1229 /// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1230 /// The owner should set allowance for the spender to transfer token.1231 ///1232 /// [`transfer`]: struct.Pallet.html#method.transfer1233 pub fn transfer_from(1234 collection: &NonfungibleHandle<T>,1235 spender: &T::CrossAccountId,1236 from: &T::CrossAccountId,1237 to: &T::CrossAccountId,1238 token: TokenId,1239 nesting_budget: &dyn Budget,1240 ) -> DispatchResult {1241 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12421243 // =========12441245 // Allowance is reset in [`transfer`]1246 Self::transfer(collection, from, to, token, nesting_budget)1247 }12481249 /// Burn NFT token for `from` account.1250 ///1251 /// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1252 /// set allowance for the spender to burn token.1253 ///1254 /// [`burn`]: struct.Pallet.html#method.burn1255 pub fn burn_from(1256 collection: &NonfungibleHandle<T>,1257 spender: &T::CrossAccountId,1258 from: &T::CrossAccountId,1259 token: TokenId,1260 nesting_budget: &dyn Budget,1261 ) -> DispatchResult {1262 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12631264 // =========12651266 Self::burn(collection, from, token)1267 }12681269 /// Check that `from` token could be nested in `under` token.1270 ///1271 pub fn check_nesting(1272 handle: &NonfungibleHandle<T>,1273 sender: T::CrossAccountId,1274 from: (CollectionId, TokenId),1275 under: TokenId,1276 nesting_budget: &dyn Budget,1277 ) -> DispatchResult {1278 let nesting = handle.permissions.nesting();12791280 #[cfg(not(feature = "runtime-benchmarks"))]1281 let permissive = false;1282 #[cfg(feature = "runtime-benchmarks")]1283 let permissive = nesting.permissive;12841285 if permissive {1286 // Pass1287 } else if nesting.token_owner1288 && <PalletStructure<T>>::check_indirectly_owned(1289 sender.clone(),1290 handle.id,1291 under,1292 Some(from),1293 nesting_budget,1294 )? {1295 // Pass1296 } else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1297 // Pass1298 } else {1299 fail!(<CommonError<T>>::UserIsNotAllowedToNest);1300 }13011302 if let Some(whitelist) = &nesting.restricted {1303 ensure!(1304 whitelist.contains(&from.0),1305 <CommonError<T>>::SourceCollectionIsNotAllowedToNest1306 );1307 }1308 Ok(())1309 }13101311 fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1312 <TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);1313 }13141315 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1316 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1317 }13181319 fn collection_has_tokens(collection_id: CollectionId) -> bool {1320 <TokenData<T>>::iter_prefix((collection_id,))1321 .next()1322 .is_some()1323 }13241325 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1326 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1327 .next()1328 .is_some()1329 }13301331 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1332 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1333 .map(|((child_collection_id, child_id), _)| TokenChild {1334 collection: child_collection_id,1335 token: child_id,1336 })1337 .collect()1338 }13391340 /// Mint single NFT token.1341 ///1342 /// Delegated to [`create_multiple_items`]1343 ///1344 /// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1345 pub fn create_item(1346 collection: &NonfungibleHandle<T>,1347 sender: &T::CrossAccountId,1348 data: CreateItemData<T>,1349 nesting_budget: &dyn Budget,1350 ) -> DispatchResult {1351 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1352 }13531354 /// Sets or unsets the approval of a given operator.1355 ///1356 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1357 /// - `owner`: Token owner1358 /// - `operator`: Operator1359 /// - `approve`: Should operator status be granted or revoked?1360 pub fn set_allowance_for_all(1361 collection: &NonfungibleHandle<T>,1362 owner: &T::CrossAccountId,1363 operator: &T::CrossAccountId,1364 approve: bool,1365 ) -> DispatchResult {1366 if collection.permissions.access() == AccessMode::AllowList {1367 collection.check_allowlist(owner)?;1368 collection.check_allowlist(operator)?;1369 }13701371 <PalletCommon<T>>::ensure_correct_receiver(operator)?;13721373 // =========13741375 <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve);1376 <PalletEvm<T>>::deposit_log(1377 ERC721Events::ApprovalForAll {1378 owner: *owner.as_eth(),1379 operator: *operator.as_eth(),1380 approved: approve,1381 }1382 .to_log(collection_id_to_address(collection.id)),1383 );1384 <PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(1385 collection.id,1386 owner.clone(),1387 operator.clone(),1388 approve,1389 ));1390 Ok(())1391 }13921393 /// Tells whether the given `owner` approves the `operator`.1394 pub fn allowance_for_all(1395 collection: &NonfungibleHandle<T>,1396 owner: &T::CrossAccountId,1397 operator: &T::CrossAccountId,1398 ) -> bool {1399 <CollectionAllowance<T>>::get((collection.id, owner, operator))1400 }14011402 pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1403 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1404 properties.recompute_consumed_space();1405 });14061407 Ok(())1408 }1409}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Nonfungible Pallet18//!19//! The Nonfungible pallet provides functionality for handling nonfungible collections and tokens.20//!21//! - [`Config`]22//! - [`NonfungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Nonfungible pallet provides functions for:29//!30//! - NFT collection creation and removal31//! - Minting and burning of NFT tokens32//! - Retrieving account balances33//! - Transfering NFT tokens34//! - Setting and checking allowance for NFT tokens35//! - Setting properties and permissions for NFT collections and tokens36//! - Nesting and unnesting tokens37//!38//! ### Terminology39//!40//! - **NFT token:** Non fungible token.41//!42//! - **NFT Collection:** A collection of NFT tokens. All NFT tokens are part of a collection.43//! Each collection can define it's own properties, properties for it's tokens and set of permissions.44//!45//! - **Balance:** Number of NFT tokens owned by an account46//!47//! - **Allowance:** NFT tokens owned by one account that another account is allowed to make operations on48//!49//! - **Burning:** The process of “deleting” a token from a collection and from50//! an account balance of the owner.51//!52//! - **Nesting:** Setting up parent-child relationship between tokens. Nested tokens are inhereting53//! owner from their parent. There could be multiple levels of nesting. Token couldn't be nested in54//! it's child token i.e. parent-child relationship graph shouldn't have cycles.55//!56//! - **Properties:** Key-Values pairs. Token properties are attached to a token. Collection properties are57//! attached to a collection. Set of permissions could be defined for each property.58//!59//! ### Implementations60//!61//! The Nonfungible pallet provides implementations for the following traits. If these traits provide62//! the functionality that you need, then you can avoid coupling with the Nonfungible pallet.63//!64//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight65//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing66//! with collections67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create NFT collection. NFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising NFT collection. There should be no tokens in the collection.75//! - `burn` - Burn NFT token owned by account.76//! - `transfer` - Transfer NFT token. Transfers should be enabled for NFT collection.77//! Nests the NFT token if it is sent to another token.78//! - `create_item` - Mint NFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account.80//! - `set_token_property` - Set token property value.81//! - `delete_token_property` - Remove property from the token.82//! - `set_collection_properties` - Set collection properties.83//! - `delete_collection_properties` - Remove properties from the collection.84//! - `set_property_permission` - Set collection property permission.85//! - `set_token_property_permissions` - Set token property permissions.86//!87//! ## Assumptions88//!89//! * To perform operations on tokens sender should be in collection's allow list if collection access mode is `AllowList`.9091#![cfg_attr(not(feature = "std"), no_std)]9293use erc::ERC721Events;94use evm_coder::ToLog;95use frame_support::{96 BoundedVec, ensure, fail, transactional,97 storage::with_transaction,98 pallet_prelude::DispatchResultWithPostInfo,99 pallet_prelude::Weight,100 dispatch::{PostDispatchInfo, Pays},101};102use up_data_structs::{103 AccessMode, CollectionId, CollectionFlags, CustomDataLimit, TokenId, CreateCollectionData,104 CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyPermission,105 PropertyKey, PropertyValue, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,106 TokenChild, AuxPropertyValue, PropertiesPermissionMap,107};108use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};109use pallet_common::{110 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,111 eth::collection_id_to_address, erc::CollectionHelpersEvents,112};113use pallet_structure::{Pallet as PalletStructure, Error as StructureError};114use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};115use sp_core::{H160, Get};116use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};117use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};118use core::ops::Deref;119use codec::{Encode, Decode, MaxEncodedLen};120use scale_info::TypeInfo;121122pub use pallet::*;123use weights::WeightInfo;124#[cfg(feature = "runtime-benchmarks")]125pub mod benchmarking;126pub mod common;127pub mod erc;128pub mod weights;129130pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::Config>::CrossAccountId>;131pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;132133/// Token data, stored independently from other data used to describe it134/// for the convenience of database access. Notably contains the owner account address.135#[struct_versioning::versioned(version = 2, upper)]136#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]137pub struct ItemData<CrossAccountId> {138 #[version(..2)]139 pub const_data: BoundedVec<u8, CustomDataLimit>,140141 #[version(..2)]142 pub variable_data: BoundedVec<u8, CustomDataLimit>,143144 pub owner: CrossAccountId,145}146147#[frame_support::pallet]148pub mod pallet {149 use super::*;150 use frame_support::{151 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,152 };153 use frame_system::pallet_prelude::*;154 use up_data_structs::{CollectionId, TokenId};155 use super::weights::WeightInfo;156157 #[pallet::error]158 pub enum Error<T> {159 /// Not Nonfungible item data used to mint in Nonfungible collection.160 NotNonfungibleDataUsedToMintFungibleCollectionToken,161 /// Used amount > 1 with NFT162 NonfungibleItemsHaveNoAmount,163 /// Unable to burn NFT with children164 CantBurnNftWithChildren,165 }166167 #[pallet::config]168 pub trait Config:169 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config170 {171 type WeightInfo: WeightInfo;172 }173174 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);175176 #[pallet::pallet]177 #[pallet::storage_version(STORAGE_VERSION)]178 #[pallet::generate_store(pub(super) trait Store)]179 pub struct Pallet<T>(_);180181 /// Total amount of minted tokens in a collection.182 #[pallet::storage]183 pub type TokensMinted<T: Config> =184 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;185186 /// Amount of burnt tokens in a collection.187 #[pallet::storage]188 pub type TokensBurnt<T: Config> =189 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;190191 /// Token data, used to partially describe a token.192 #[pallet::storage]193 pub type TokenData<T: Config> = StorageNMap<194 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),195 Value = ItemData<T::CrossAccountId>,196 QueryKind = OptionQuery,197 >;198199 /// Map of key-value pairs, describing the metadata of a token.200 #[pallet::storage]201 #[pallet::getter(fn token_properties)]202 pub type TokenProperties<T: Config> = StorageNMap<203 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),204 Value = Properties,205 QueryKind = ValueQuery,206 OnEmpty = up_data_structs::TokenProperties,207 >;208209 /// Custom data of a token that is serialized to bytes,210 /// primarily reserved for on-chain operations,211 /// normally obscured from the external users.212 ///213 /// Auxiliary properties are slightly different from214 /// usual [`TokenProperties`] due to an unlimited number215 /// and separately stored and written-to key-value pairs.216 ///217 /// Currently used to store RMRK data.218 #[pallet::storage]219 #[pallet::getter(fn token_aux_property)]220 pub type TokenAuxProperties<T: Config> = StorageNMap<221 Key = (222 Key<Twox64Concat, CollectionId>,223 Key<Twox64Concat, TokenId>,224 Key<Twox64Concat, PropertyScope>,225 Key<Twox64Concat, PropertyKey>,226 ),227 Value = AuxPropertyValue,228 QueryKind = OptionQuery,229 >;230231 /// Used to enumerate tokens owned by account.232 #[pallet::storage]233 pub type Owned<T: Config> = StorageNMap<234 Key = (235 Key<Twox64Concat, CollectionId>,236 Key<Blake2_128Concat, T::CrossAccountId>,237 Key<Twox64Concat, TokenId>,238 ),239 Value = bool,240 QueryKind = ValueQuery,241 >;242243 /// Used to enumerate token's children.244 #[pallet::storage]245 #[pallet::getter(fn token_children)]246 pub type TokenChildren<T: Config> = StorageNMap<247 Key = (248 Key<Twox64Concat, CollectionId>,249 Key<Twox64Concat, TokenId>,250 Key<Twox64Concat, (CollectionId, TokenId)>,251 ),252 Value = bool,253 QueryKind = ValueQuery,254 >;255256 /// Amount of tokens owned by an account in a collection.257 #[pallet::storage]258 pub type AccountBalance<T: Config> = StorageNMap<259 Key = (260 Key<Twox64Concat, CollectionId>,261 Key<Blake2_128Concat, T::CrossAccountId>,262 ),263 Value = u32,264 QueryKind = ValueQuery,265 >;266267 /// Allowance set by a token owner for another user to perform one of certain transactions on a token.268 #[pallet::storage]269 pub type Allowance<T: Config> = StorageNMap<270 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),271 Value = T::CrossAccountId,272 QueryKind = OptionQuery,273 >;274275 /// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.276 #[pallet::storage]277 pub type CollectionAllowance<T: Config> = StorageNMap<278 Key = (279 Key<Twox64Concat, CollectionId>,280 Key<Blake2_128Concat, T::CrossAccountId>,281 Key<Blake2_128Concat, T::CrossAccountId>,282 ),283 Value = bool,284 QueryKind = ValueQuery,285 >;286287 /// Upgrade from the old schema to properties.288 #[pallet::hooks]289 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {290 fn on_runtime_upgrade() -> Weight {291 StorageVersion::new(1).put::<Pallet<T>>();292293 Weight::zero()294 }295 }296}297298pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);299impl<T: Config> NonfungibleHandle<T> {300 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {301 Self(inner)302 }303 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {304 self.0305 }306 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {307 &mut self.0308 }309}310311impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {312 fn recorder(&self) -> &SubstrateRecorder<T> {313 self.0.recorder()314 }315 fn into_recorder(self) -> SubstrateRecorder<T> {316 self.0.into_recorder()317 }318}319impl<T: Config> Deref for NonfungibleHandle<T> {320 type Target = pallet_common::CollectionHandle<T>;321322 fn deref(&self) -> &Self::Target {323 &self.0324 }325}326327impl<T: Config> Pallet<T> {328 /// Get number of NFT tokens in collection.329 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {330 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)331 }332333 /// Check that NFT token exists.334 ///335 /// - `token`: Token ID.336 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {337 <TokenData<T>>::contains_key((collection.id, token))338 }339340 /// Set the token property with the scope.341 ///342 /// - `property`: Contains key-value pair.343 pub fn set_scoped_token_property(344 collection_id: CollectionId,345 token_id: TokenId,346 scope: PropertyScope,347 property: Property,348 ) -> DispatchResult {349 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {350 properties.try_scoped_set(scope, property.key, property.value)351 })352 .map_err(<CommonError<T>>::from)?;353354 Ok(())355 }356357 /// Batch operation to set multiple properties with the same scope.358 pub fn set_scoped_token_properties(359 collection_id: CollectionId,360 token_id: TokenId,361 scope: PropertyScope,362 properties: impl Iterator<Item = Property>,363 ) -> DispatchResult {364 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {365 stored_properties.try_scoped_set_from_iter(scope, properties)366 })367 .map_err(<CommonError<T>>::from)?;368369 Ok(())370 }371372 /// Add or edit auxiliary data for the property.373 ///374 /// - `f`: function that adds or edits auxiliary data.375 pub fn try_mutate_token_aux_property<R, E>(376 collection_id: CollectionId,377 token_id: TokenId,378 scope: PropertyScope,379 key: PropertyKey,380 f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,381 ) -> Result<R, E> {382 <TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)383 }384385 /// Remove auxiliary data for the property.386 pub fn remove_token_aux_property(387 collection_id: CollectionId,388 token_id: TokenId,389 scope: PropertyScope,390 key: PropertyKey,391 ) {392 <TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));393 }394395 /// Get all auxiliary data in a given scope.396 ///397 /// Returns iterator over Property Key - Data pairs.398 pub fn iterate_token_aux_properties(399 collection_id: CollectionId,400 token_id: TokenId,401 scope: PropertyScope,402 ) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {403 <TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))404 }405406 /// Get ID of the last minted token407 pub fn current_token_id(collection_id: CollectionId) -> TokenId {408 TokenId(<TokensMinted<T>>::get(collection_id))409 }410}411412// unchecked calls skips any permission checks413impl<T: Config> Pallet<T> {414 /// Create NFT collection415 ///416 /// `init_collection` will take non-refundable deposit for collection creation.417 ///418 /// - `data`: Contains settings for collection limits and permissions.419 pub fn init_collection(420 owner: T::CrossAccountId,421 payer: T::CrossAccountId,422 data: CreateCollectionData<T::AccountId>,423 flags: CollectionFlags,424 ) -> Result<CollectionId, DispatchError> {425 <PalletCommon<T>>::init_collection(owner, payer, data, flags)426 }427428 /// Destroy NFT collection429 ///430 /// `destroy_collection` will throw error if collection contains any tokens.431 /// Only owner can destroy collection.432 pub fn destroy_collection(433 collection: NonfungibleHandle<T>,434 sender: &T::CrossAccountId,435 ) -> DispatchResult {436 let id = collection.id;437438 if Self::collection_has_tokens(id) {439 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());440 }441442 // =========443444 PalletCommon::destroy_collection(collection.0, sender)?;445446 let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);447 let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);448 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);449 <TokensMinted<T>>::remove(id);450 <TokensBurnt<T>>::remove(id);451 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);452 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);453 let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);454 Ok(())455 }456457 /// Burn NFT token458 ///459 /// `burn` removes `token` from the `collection`, from it's owner and from the parent token460 /// if the token is nested.461 /// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.462 /// Also removes all corresponding properties and auxiliary properties.463 ///464 /// - `token`: Token that should be burned465 /// - `collection`: Collection that contains the token466 pub fn burn(467 collection: &NonfungibleHandle<T>,468 sender: &T::CrossAccountId,469 token: TokenId,470 ) -> DispatchResult {471 let token_data =472 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;473 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);474475 if collection.permissions.access() == AccessMode::AllowList {476 collection.check_allowlist(sender)?;477 }478479 if Self::token_has_children(collection.id, token) {480 return Err(<Error<T>>::CantBurnNftWithChildren.into());481 }482483 let burnt = <TokensBurnt<T>>::get(collection.id)484 .checked_add(1)485 .ok_or(ArithmeticError::Overflow)?;486487 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))488 .checked_sub(1)489 .ok_or(ArithmeticError::Overflow)?;490491 // =========492493 if balance == 0 {494 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));495 } else {496 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);497 }498499 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);500501 <Owned<T>>::remove((collection.id, &token_data.owner, token));502 <TokensBurnt<T>>::insert(collection.id, burnt);503 <TokenData<T>>::remove((collection.id, token));504 <TokenProperties<T>>::remove((collection.id, token));505 let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);506 let old_spender = <Allowance<T>>::take((collection.id, token));507508 if let Some(old_spender) = old_spender {509 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(510 collection.id,511 token,512 token_data.owner.clone(),513 old_spender,514 0,515 ));516 }517518 <PalletEvm<T>>::deposit_log(519 ERC721Events::Transfer {520 from: *token_data.owner.as_eth(),521 to: H160::default(),522 token_id: token.into(),523 }524 .to_log(collection_id_to_address(collection.id)),525 );526 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(527 collection.id,528 token,529 token_data.owner,530 1,531 ));532 Ok(())533 }534535 /// Same as [`burn`] but burns all the tokens that are nested in the token first536 ///537 /// - `self_budget`: Limit for searching children in depth.538 /// - `breadth_budget`: Limit of breadth of searching children.539 ///540 /// [`burn`]: struct.Pallet.html#method.burn541 #[transactional]542 pub fn burn_recursively(543 collection: &NonfungibleHandle<T>,544 sender: &T::CrossAccountId,545 token: TokenId,546 self_budget: &dyn Budget,547 breadth_budget: &dyn Budget,548 ) -> DispatchResultWithPostInfo {549 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);550551 let current_token_account =552 T::CrossTokenAddressMapping::token_to_address(collection.id, token);553554 let mut weight = Weight::zero();555556 // This method is transactional, if user in fact doesn't have permissions to remove token -557 // tokens removed here will be restored after rejected transaction558 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {559 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);560 let PostDispatchInfo { actual_weight, .. } =561 <PalletStructure<T>>::burn_item_recursively(562 current_token_account.clone(),563 collection,564 token,565 self_budget,566 breadth_budget,567 )?;568 if let Some(actual_weight) = actual_weight {569 weight = weight.saturating_add(actual_weight);570 }571 }572573 Self::burn(collection, sender, token)?;574 DispatchResultWithPostInfo::Ok(PostDispatchInfo {575 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),576 pays_fee: Pays::Yes,577 })578 }579580 /// Batch operation to add, edit or remove properties for the token581 ///582 /// All affected properties should have mutable permission and sender should have583 /// permission to edit those properties.584 ///585 /// - `nesting_budget`: Limit for searching parents in depth to check ownership.586 /// - `is_token_create`: Indicates that method is called during token initialization.587 /// Allows to bypass ownership check.588 #[transactional]589 fn modify_token_properties(590 collection: &NonfungibleHandle<T>,591 sender: &T::CrossAccountId,592 token_id: TokenId,593 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,594 is_token_create: bool,595 nesting_budget: &dyn Budget,596 ) -> DispatchResult {597 let mut collection_admin_status = None;598 let mut token_owner_result = None;599600 let mut is_collection_admin =601 || *collection_admin_status.get_or_insert_with(|| collection.is_owner_or_admin(sender));602603 let mut is_token_owner = || {604 *token_owner_result.get_or_insert_with(|| -> Result<bool, DispatchError> {605 let is_owned = <PalletStructure<T>>::check_indirectly_owned(606 sender.clone(),607 collection.id,608 token_id,609 None,610 nesting_budget,611 )?;612613 Ok(is_owned)614 })615 };616617 for (key, value) in properties {618 let permission = <PalletCommon<T>>::property_permissions(collection.id)619 .get(&key)620 .cloned()621 .unwrap_or_else(PropertyPermission::none);622623 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))624 .get(&key)625 .is_some();626627 match permission {628 PropertyPermission { mutable: false, .. } if is_property_exists => {629 return Err(<CommonError<T>>::NoPermission.into());630 }631632 PropertyPermission {633 collection_admin,634 token_owner,635 ..636 } => {637 //TODO: investigate threats during public minting.638 if is_token_create && (collection_admin || token_owner) && value.is_some() {639 // Pass640 } else if collection_admin && is_collection_admin() {641 // Pass642 } else if token_owner && is_token_owner()? {643 // Pass644 } else {645 fail!(<CommonError<T>>::NoPermission);646 }647 }648 }649650 match value {651 Some(value) => {652 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {653 properties.try_set(key.clone(), value)654 })655 .map_err(<CommonError<T>>::from)?;656657 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(658 collection.id,659 token_id,660 key,661 ));662 }663 None => {664 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {665 properties.remove(&key)666 })667 .map_err(<CommonError<T>>::from)?;668669 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(670 collection.id,671 token_id,672 key,673 ));674 }675 }676677 <PalletEvm<T>>::deposit_log(678 CollectionHelpersEvents::TokenChanged {679 collection_id: collection_id_to_address(collection.id),680 token_id: token_id.into(),681 }682 .to_log(T::ContractAddress::get()),683 );684 }685686 Ok(())687 }688689 /// Batch operation to add or edit properties for the token690 ///691 /// Same as [`modify_token_properties`] but doesn't allow to remove properties692 ///693 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties694 pub fn set_token_properties(695 collection: &NonfungibleHandle<T>,696 sender: &T::CrossAccountId,697 token_id: TokenId,698 properties: impl Iterator<Item = Property>,699 is_token_create: bool,700 nesting_budget: &dyn Budget,701 ) -> DispatchResult {702 Self::modify_token_properties(703 collection,704 sender,705 token_id,706 properties.map(|p| (p.key, Some(p.value))),707 is_token_create,708 nesting_budget,709 )710 }711712 /// Add or edit single property for the token713 ///714 /// Calls [`set_token_properties`] internally715 ///716 /// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties717 pub fn set_token_property(718 collection: &NonfungibleHandle<T>,719 sender: &T::CrossAccountId,720 token_id: TokenId,721 property: Property,722 nesting_budget: &dyn Budget,723 ) -> DispatchResult {724 let is_token_create = false;725726 Self::set_token_properties(727 collection,728 sender,729 token_id,730 [property].into_iter(),731 is_token_create,732 nesting_budget,733 )734 }735736 /// Batch operation to remove properties from the token737 ///738 /// Same as [`modify_token_properties`] but doesn't allow to add or edit properties739 ///740 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties741 pub fn delete_token_properties(742 collection: &NonfungibleHandle<T>,743 sender: &T::CrossAccountId,744 token_id: TokenId,745 property_keys: impl Iterator<Item = PropertyKey>,746 nesting_budget: &dyn Budget,747 ) -> DispatchResult {748 let is_token_create = false;749750 Self::modify_token_properties(751 collection,752 sender,753 token_id,754 property_keys.into_iter().map(|key| (key, None)),755 is_token_create,756 nesting_budget,757 )758 }759760 /// Remove single property from the token761 ///762 /// Calls [`delete_token_properties`] internally763 ///764 /// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties765 pub fn delete_token_property(766 collection: &NonfungibleHandle<T>,767 sender: &T::CrossAccountId,768 token_id: TokenId,769 property_key: PropertyKey,770 nesting_budget: &dyn Budget,771 ) -> DispatchResult {772 Self::delete_token_properties(773 collection,774 sender,775 token_id,776 [property_key].into_iter(),777 nesting_budget,778 )779 }780781 /// Add or edit properties for the collection782 pub fn set_collection_properties(783 collection: &NonfungibleHandle<T>,784 sender: &T::CrossAccountId,785 properties: Vec<Property>,786 ) -> DispatchResult {787 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)788 }789790 /// Remove properties from the collection791 pub fn delete_collection_properties(792 collection: &CollectionHandle<T>,793 sender: &T::CrossAccountId,794 property_keys: Vec<PropertyKey>,795 ) -> DispatchResult {796 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)797 }798799 /// Set property permissions for the token.800 ///801 /// Sender should be the owner or admin of token's collection.802 pub fn set_token_property_permissions(803 collection: &CollectionHandle<T>,804 sender: &T::CrossAccountId,805 property_permissions: Vec<PropertyKeyPermission>,806 ) -> DispatchResult {807 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)808 }809810 /// Set property permissions for the token with scope.811 ///812 /// Sender should be the owner or admin of token's collection.813 pub fn set_scoped_token_property_permissions(814 collection: &CollectionHandle<T>,815 sender: &T::CrossAccountId,816 scope: PropertyScope,817 property_permissions: Vec<PropertyKeyPermission>,818 ) -> DispatchResult {819 <PalletCommon<T>>::set_scoped_token_property_permissions(820 collection,821 sender,822 scope,823 property_permissions,824 )825 }826827 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {828 <PalletCommon<T>>::property_permissions(collection_id)829 }830831 pub fn check_token_immediate_ownership(832 collection: &NonfungibleHandle<T>,833 token: TokenId,834 possible_owner: &T::CrossAccountId,835 ) -> DispatchResult {836 let token_data =837 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;838 ensure!(839 &token_data.owner == possible_owner,840 <CommonError<T>>::NoPermission841 );842 Ok(())843 }844845 /// Transfer NFT token from one account to another.846 ///847 /// `from` account stops being the owner and `to` account becomes the owner of the token.848 /// If `to` is token than `to` becomes owner of the token and the token become nested.849 /// Unnests token from previous parent if it was nested before.850 /// Removes allowance for the token if there was any.851 /// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.852 ///853 /// - `nesting_budget`: Limit for token nesting depth854 pub fn transfer(855 collection: &NonfungibleHandle<T>,856 from: &T::CrossAccountId,857 to: &T::CrossAccountId,858 token: TokenId,859 nesting_budget: &dyn Budget,860 ) -> DispatchResult {861 ensure!(862 collection.limits.transfers_enabled(),863 <CommonError<T>>::TransferNotAllowed864 );865866 let token_data =867 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;868 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);869870 if collection.permissions.access() == AccessMode::AllowList {871 collection.check_allowlist(from)?;872 collection.check_allowlist(to)?;873 }874 <PalletCommon<T>>::ensure_correct_receiver(to)?;875876 let balance_from = <AccountBalance<T>>::get((collection.id, from))877 .checked_sub(1)878 .ok_or(<CommonError<T>>::TokenValueTooLow)?;879 let balance_to = if from != to {880 let balance_to = <AccountBalance<T>>::get((collection.id, to))881 .checked_add(1)882 .ok_or(ArithmeticError::Overflow)?;883884 ensure!(885 balance_to < collection.limits.account_token_ownership_limit(),886 <CommonError<T>>::AccountTokenLimitExceeded,887 );888889 Some(balance_to)890 } else {891 None892 };893894 <PalletStructure<T>>::nest_if_sent_to_token(895 from.clone(),896 to,897 collection.id,898 token,899 nesting_budget,900 )?;901902 // =========903904 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);905906 <TokenData<T>>::insert(907 (collection.id, token),908 ItemData {909 owner: to.clone(),910 ..token_data911 },912 );913914 if let Some(balance_to) = balance_to {915 // from != to916 if balance_from == 0 {917 <AccountBalance<T>>::remove((collection.id, from));918 } else {919 <AccountBalance<T>>::insert((collection.id, from), balance_from);920 }921 <AccountBalance<T>>::insert((collection.id, to), balance_to);922 <Owned<T>>::remove((collection.id, from, token));923 <Owned<T>>::insert((collection.id, to, token), true);924 }925 Self::set_allowance_unchecked(collection, from, token, None, true);926927 <PalletEvm<T>>::deposit_log(928 ERC721Events::Transfer {929 from: *from.as_eth(),930 to: *to.as_eth(),931 token_id: token.into(),932 }933 .to_log(collection_id_to_address(collection.id)),934 );935 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(936 collection.id,937 token,938 from.clone(),939 to.clone(),940 1,941 ));942 Ok(())943 }944945 /// Batch operation to mint multiple NFT tokens.946 ///947 /// The sender should be the owner/admin of the collection or collection should be configured948 /// to allow public minting.949 /// Throws if amount of tokens reached it's limit for the collection or if caller reached950 /// token ownership limit.951 ///952 /// - `data`: Contains list of token properties and users who will become the owners of the953 /// corresponging tokens.954 /// - `nesting_budget`: Limit for token nesting depth955 pub fn create_multiple_items(956 collection: &NonfungibleHandle<T>,957 sender: &T::CrossAccountId,958 data: Vec<CreateItemData<T>>,959 nesting_budget: &dyn Budget,960 ) -> DispatchResult {961 if !collection.is_owner_or_admin(sender) {962 ensure!(963 collection.permissions.mint_mode(),964 <CommonError<T>>::PublicMintingNotAllowed965 );966 collection.check_allowlist(sender)?;967968 for item in data.iter() {969 collection.check_allowlist(&item.owner)?;970 }971 }972973 for data in data.iter() {974 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;975 }976977 let first_token = <TokensMinted<T>>::get(collection.id);978 let tokens_minted = first_token979 .checked_add(data.len() as u32)980 .ok_or(ArithmeticError::Overflow)?;981 ensure!(982 tokens_minted <= collection.limits.token_limit(),983 <CommonError<T>>::CollectionTokenLimitExceeded984 );985986 let mut balances = BTreeMap::new();987 for data in &data {988 let balance = balances989 .entry(&data.owner)990 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));991 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;992993 ensure!(994 *balance <= collection.limits.account_token_ownership_limit(),995 <CommonError<T>>::AccountTokenLimitExceeded,996 );997 }998999 for (i, data) in data.iter().enumerate() {1000 let token = TokenId(first_token + i as u32 + 1);10011002 <PalletStructure<T>>::check_nesting(1003 sender.clone(),1004 &data.owner,1005 collection.id,1006 token,1007 nesting_budget,1008 )?;1009 }10101011 // =========10121013 with_transaction(|| {1014 for (i, data) in data.iter().enumerate() {1015 let token = first_token + i as u32 + 1;10161017 <TokenData<T>>::insert(1018 (collection.id, token),1019 ItemData {1020 // const_data: data.const_data.clone(),1021 owner: data.owner.clone(),1022 },1023 );10241025 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(1026 &data.owner,1027 collection.id,1028 TokenId(token),1029 );10301031 if let Err(e) = Self::set_token_properties(1032 collection,1033 sender,1034 TokenId(token),1035 data.properties.clone().into_iter(),1036 true,1037 nesting_budget,1038 ) {1039 return TransactionOutcome::Rollback(Err(e));1040 }1041 }1042 TransactionOutcome::Commit(Ok(()))1043 })?;10441045 <TokensMinted<T>>::insert(collection.id, tokens_minted);1046 for (account, balance) in balances {1047 <AccountBalance<T>>::insert((collection.id, account), balance);1048 }1049 for (i, data) in data.into_iter().enumerate() {1050 let token = first_token + i as u32 + 1;1051 <Owned<T>>::insert((collection.id, &data.owner, token), true);10521053 <PalletEvm<T>>::deposit_log(1054 ERC721Events::Transfer {1055 from: H160::default(),1056 to: *data.owner.as_eth(),1057 token_id: token.into(),1058 }1059 .to_log(collection_id_to_address(collection.id)),1060 );1061 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1062 collection.id,1063 TokenId(token),1064 data.owner.clone(),1065 1,1066 ));1067 }1068 Ok(())1069 }10701071 pub fn set_allowance_unchecked(1072 collection: &NonfungibleHandle<T>,1073 sender: &T::CrossAccountId,1074 token: TokenId,1075 spender: Option<&T::CrossAccountId>,1076 assume_implicit_eth: bool,1077 ) {1078 if let Some(spender) = spender {1079 let old_spender = <Allowance<T>>::get((collection.id, token));1080 <Allowance<T>>::insert((collection.id, token), spender);1081 // In ERC721 there is only one possible approved user of token, so we set1082 // approved user to spender1083 <PalletEvm<T>>::deposit_log(1084 ERC721Events::Approval {1085 owner: *sender.as_eth(),1086 approved: *spender.as_eth(),1087 token_id: token.into(),1088 }1089 .to_log(collection_id_to_address(collection.id)),1090 );1091 // In Unique chain, any token can have any amount of approved users, so we need to1092 // set allowance of old owner to 0, and allowance of new owner to 11093 if old_spender.as_ref() != Some(spender) {1094 if let Some(old_owner) = old_spender {1095 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1096 collection.id,1097 token,1098 sender.clone(),1099 old_owner,1100 0,1101 ));1102 }1103 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1104 collection.id,1105 token,1106 sender.clone(),1107 spender.clone(),1108 1,1109 ));1110 }1111 } else {1112 let old_spender = <Allowance<T>>::take((collection.id, token));1113 if !assume_implicit_eth {1114 // In ERC721 there is only one possible approved user of token, so we set1115 // approved user to zero address1116 <PalletEvm<T>>::deposit_log(1117 ERC721Events::Approval {1118 owner: *sender.as_eth(),1119 approved: H160::default(),1120 token_id: token.into(),1121 }1122 .to_log(collection_id_to_address(collection.id)),1123 );1124 }1125 // In Unique chain, any token can have any amount of approved users, so we need to1126 // set allowance of old owner to 01127 if let Some(old_spender) = old_spender {1128 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1129 collection.id,1130 token,1131 sender.clone(),1132 old_spender,1133 0,1134 ));1135 }1136 }1137 }11381139 /// Set allowance for the spender to `transfer` or `burn` sender's token.1140 ///1141 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1142 pub fn set_allowance(1143 collection: &NonfungibleHandle<T>,1144 sender: &T::CrossAccountId,1145 token: TokenId,1146 spender: Option<&T::CrossAccountId>,1147 ) -> DispatchResult {1148 if collection.permissions.access() == AccessMode::AllowList {1149 collection.check_allowlist(sender)?;1150 if let Some(spender) = spender {1151 collection.check_allowlist(spender)?;1152 }1153 }11541155 if let Some(spender) = spender {1156 <PalletCommon<T>>::ensure_correct_receiver(spender)?;1157 }11581159 let token_data =1160 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1161 if &token_data.owner != sender {1162 ensure!(1163 collection.ignores_owned_amount(sender),1164 <CommonError<T>>::CantApproveMoreThanOwned1165 );1166 }11671168 // =========11691170 Self::set_allowance_unchecked(collection, sender, token, spender, false);1171 Ok(())1172 }11731174 /// Checks allowance for the spender to use the token.1175 fn check_allowed(1176 collection: &NonfungibleHandle<T>,1177 spender: &T::CrossAccountId,1178 from: &T::CrossAccountId,1179 token: TokenId,1180 nesting_budget: &dyn Budget,1181 ) -> DispatchResult {1182 if spender.conv_eq(from) {1183 return Ok(());1184 }1185 if collection.permissions.access() == AccessMode::AllowList {1186 // `from`, `to` checked in [`transfer`]1187 collection.check_allowlist(spender)?;1188 }11891190 if collection.limits.owner_can_transfer() && collection.is_owner_or_admin(spender) {1191 return Ok(());1192 }11931194 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1195 ensure!(1196 <PalletStructure<T>>::check_indirectly_owned(1197 spender.clone(),1198 source.0,1199 source.1,1200 None,1201 nesting_budget1202 )?,1203 <CommonError<T>>::ApprovedValueTooLow,1204 );1205 return Ok(());1206 }1207 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1208 return Ok(());1209 }1210 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1211 return Ok(());1212 }1213 ensure!(1214 collection.ignores_allowance(spender),1215 <CommonError<T>>::ApprovedValueTooLow1216 );1217 Ok(())1218 }12191220 /// Transfer NFT token from one account to another.1221 ///1222 /// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1223 /// The owner should set allowance for the spender to transfer token.1224 ///1225 /// [`transfer`]: struct.Pallet.html#method.transfer1226 pub fn transfer_from(1227 collection: &NonfungibleHandle<T>,1228 spender: &T::CrossAccountId,1229 from: &T::CrossAccountId,1230 to: &T::CrossAccountId,1231 token: TokenId,1232 nesting_budget: &dyn Budget,1233 ) -> DispatchResult {1234 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12351236 // =========12371238 // Allowance is reset in [`transfer`]1239 Self::transfer(collection, from, to, token, nesting_budget)1240 }12411242 /// Burn NFT token for `from` account.1243 ///1244 /// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1245 /// set allowance for the spender to burn token.1246 ///1247 /// [`burn`]: struct.Pallet.html#method.burn1248 pub fn burn_from(1249 collection: &NonfungibleHandle<T>,1250 spender: &T::CrossAccountId,1251 from: &T::CrossAccountId,1252 token: TokenId,1253 nesting_budget: &dyn Budget,1254 ) -> DispatchResult {1255 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12561257 // =========12581259 Self::burn(collection, from, token)1260 }12611262 /// Check that `from` token could be nested in `under` token.1263 ///1264 pub fn check_nesting(1265 handle: &NonfungibleHandle<T>,1266 sender: T::CrossAccountId,1267 from: (CollectionId, TokenId),1268 under: TokenId,1269 nesting_budget: &dyn Budget,1270 ) -> DispatchResult {1271 let nesting = handle.permissions.nesting();12721273 #[cfg(not(feature = "runtime-benchmarks"))]1274 let permissive = false;1275 #[cfg(feature = "runtime-benchmarks")]1276 let permissive = nesting.permissive;12771278 if permissive {1279 // Pass1280 } else if nesting.token_owner1281 && <PalletStructure<T>>::check_indirectly_owned(1282 sender.clone(),1283 handle.id,1284 under,1285 Some(from),1286 nesting_budget,1287 )? {1288 // Pass1289 } else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1290 // Pass1291 } else {1292 fail!(<CommonError<T>>::UserIsNotAllowedToNest);1293 }12941295 if let Some(whitelist) = &nesting.restricted {1296 ensure!(1297 whitelist.contains(&from.0),1298 <CommonError<T>>::SourceCollectionIsNotAllowedToNest1299 );1300 }1301 Ok(())1302 }13031304 fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1305 <TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);1306 }13071308 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1309 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1310 }13111312 fn collection_has_tokens(collection_id: CollectionId) -> bool {1313 <TokenData<T>>::iter_prefix((collection_id,))1314 .next()1315 .is_some()1316 }13171318 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1319 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1320 .next()1321 .is_some()1322 }13231324 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1325 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1326 .map(|((child_collection_id, child_id), _)| TokenChild {1327 collection: child_collection_id,1328 token: child_id,1329 })1330 .collect()1331 }13321333 /// Mint single NFT token.1334 ///1335 /// Delegated to [`create_multiple_items`]1336 ///1337 /// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1338 pub fn create_item(1339 collection: &NonfungibleHandle<T>,1340 sender: &T::CrossAccountId,1341 data: CreateItemData<T>,1342 nesting_budget: &dyn Budget,1343 ) -> DispatchResult {1344 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1345 }13461347 /// Sets or unsets the approval of a given operator.1348 ///1349 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1350 /// - `owner`: Token owner1351 /// - `operator`: Operator1352 /// - `approve`: Should operator status be granted or revoked?1353 pub fn set_allowance_for_all(1354 collection: &NonfungibleHandle<T>,1355 owner: &T::CrossAccountId,1356 operator: &T::CrossAccountId,1357 approve: bool,1358 ) -> DispatchResult {1359 if collection.permissions.access() == AccessMode::AllowList {1360 collection.check_allowlist(owner)?;1361 collection.check_allowlist(operator)?;1362 }13631364 <PalletCommon<T>>::ensure_correct_receiver(operator)?;13651366 // =========13671368 <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve);1369 <PalletEvm<T>>::deposit_log(1370 ERC721Events::ApprovalForAll {1371 owner: *owner.as_eth(),1372 operator: *operator.as_eth(),1373 approved: approve,1374 }1375 .to_log(collection_id_to_address(collection.id)),1376 );1377 <PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(1378 collection.id,1379 owner.clone(),1380 operator.clone(),1381 approve,1382 ));1383 Ok(())1384 }13851386 /// Tells whether the given `owner` approves the `operator`.1387 pub fn allowance_for_all(1388 collection: &NonfungibleHandle<T>,1389 owner: &T::CrossAccountId,1390 operator: &T::CrossAccountId,1391 ) -> bool {1392 <CollectionAllowance<T>>::get((collection.id, owner, operator))1393 }13941395 pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1396 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1397 properties.recompute_consumed_space();1398 });13991400 Ok(())1401 }1402}pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -18,30 +18,44 @@
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x91a97a68
+/// @dev the ERC-165 identifier for this interface is 0xde0695c2
contract TokenProperties is Dummy, ERC165 {
+ // /// @notice Set permissions for token property.
+ // /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+ // /// @param key Property key.
+ // /// @param isMutable Permission to mutate property.
+ // /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
+ // /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
+ // /// @dev EVM selector for this function is: 0x222d97fa,
+ // /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
+ // function setTokenPropertyPermission(string memory key, bool isMutable, bool collectionAdmin, bool tokenOwner) public {
+ // require(false, stub_error);
+ // key;
+ // isMutable;
+ // collectionAdmin;
+ // tokenOwner;
+ // dummy = 0;
+ // }
+
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
- /// @param key Property key.
- /// @param isMutable Permission to mutate property.
- /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
- /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
- /// @dev EVM selector for this function is: 0x222d97fa,
- /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
- function setTokenPropertyPermission(
- string memory key,
- bool isMutable,
- bool collectionAdmin,
- bool tokenOwner
- ) public {
+ /// @param permissions Permissions for keys.
+ /// @dev EVM selector for this function is: 0xbd92983a,
+ /// or in textual repr: setTokenPropertyPermissions((string,(uint8,bool)[])[])
+ function setTokenPropertyPermissions(Tuple48[] memory permissions) public {
require(false, stub_error);
- key;
- isMutable;
- collectionAdmin;
- tokenOwner;
+ permissions;
dummy = 0;
}
+ /// @dev EVM selector for this function is: 0xf23d7790,
+ /// or in textual repr: tokenPropertyPermissions()
+ function tokenPropertyPermissions() public view returns (Tuple48[] memory) {
+ require(false, stub_error);
+ dummy;
+ return new Tuple48[](0);
+ }
+
// /// @notice Set token property value.
// /// @dev Throws error if `msg.sender` has no permission to edit the property.
// /// @param tokenId ID of the token.
@@ -118,6 +132,24 @@
bytes value;
}
+enum EthTokenPermissions {
+ Mutable,
+ TokenOwner,
+ CollectionAdmin
+}
+
+/// @dev anonymous struct
+struct Tuple48 {
+ string field_0;
+ Tuple46[] field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple46 {
+ EthTokenPermissions field_0;
+ bool field_1;
+}
+
/// @title A contract that allows you to work with collections.
/// @dev the ERC-165 identifier for this interface is 0xb5e1747f
contract Collection is Dummy, ERC165 {
pallets/refungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/refungible/CHANGELOG.md
+++ b/pallets/refungible/CHANGELOG.md
@@ -4,6 +4,16 @@
<!-- bureaucrate goes here -->
+## [0.2.10] - 2022-12-16
+
+### Added
+
+- The function `tokenPropertyPermissions` and `setTokenPropertyPermissions` to `TokenProperties` interface.
+
+### Changed
+
+- Hide `setTokenPropertyPermission` function in `TokenProperties` interface.
+
## [0.2.9] - 2022-11-18
### Added
pallets/refungible/Cargo.tomldiffbeforeafterboth--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-refungible"
-version = "0.2.8"
+version = "0.2.10"
license = "GPLv3"
edition = "2021"
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -33,7 +33,7 @@
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
erc::{CommonEvmHandler, CollectionCall, static_property::key},
- eth::EthCrossAccount,
+ eth::{EthCrossAccount, EthTokenPermissions},
Error as CommonError,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
@@ -63,6 +63,7 @@
/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
/// @param tokenOwner Permission to mutate property by token owner if property is mutable.
#[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]
+ #[solidity(hide)]
fn set_token_property_permission(
&mut self,
caller: caller,
@@ -89,6 +90,77 @@
.map_err(dispatch_to_evm::<T>)
}
+ /// @notice Set permissions for token property.
+ /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+ /// @param permissions Permissions for keys.
+ #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]
+ fn set_token_property_permissions(
+ &mut self,
+ caller: caller,
+ permissions: Vec<(string, Vec<(EthTokenPermissions, bool)>)>,
+ ) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ const PERMISSIONS_FIELDS_COUNT: usize = 3;
+
+ let mut perms = Vec::new();
+
+ for (key, pp) in permissions {
+ if pp.len() > PERMISSIONS_FIELDS_COUNT {
+ return Err(alloc::format!(
+ "Actual number of fields {} for {}, which exceeds the maximum value of {}",
+ pp.len(),
+ stringify!(EthTokenPermissions),
+ PERMISSIONS_FIELDS_COUNT
+ )
+ .as_str()
+ .into());
+ }
+
+ let mut token_permission = PropertyPermission {
+ mutable: false,
+ collection_admin: false,
+ token_owner: false,
+ };
+
+ for (perm, value) in pp {
+ match perm {
+ EthTokenPermissions::Mutable => token_permission.mutable = value,
+ EthTokenPermissions::TokenOwner => token_permission.token_owner = value,
+ EthTokenPermissions::CollectionAdmin => {
+ token_permission.collection_admin = value
+ }
+ }
+ }
+
+ perms.push(PropertyKeyPermission {
+ key: key.into_bytes().try_into().map_err(|_| "too long key")?,
+ permission: token_permission,
+ });
+ }
+
+ <Pallet<T>>::set_token_property_permissions(self, &caller, perms)
+ .map_err(dispatch_to_evm::<T>)
+ }
+
+ /// @notice Get permissions for token properties.
+ fn token_property_permissions(
+ &self,
+ ) -> Result<Vec<(string, Vec<(EthTokenPermissions, bool)>)>> {
+ let perms = <Pallet<T>>::token_property_permission(self.id);
+ Ok(perms
+ .into_iter()
+ .map(|(key, pp)| {
+ let key = string::from_utf8(key.into_inner()).expect("Stored key must be valid");
+ let pp = vec![
+ (EthTokenPermissions::Mutable, pp.mutable),
+ (EthTokenPermissions::TokenOwner, pp.token_owner),
+ (EthTokenPermissions::CollectionAdmin, pp.collection_admin),
+ ];
+ (key, pp)
+ })
+ .collect())
+ }
+
/// @notice Set token property value.
/// @dev Throws error if `msg.sender` has no permission to edit the property.
/// @param tokenId ID of the token.
pallets/refungible/src/erc_token.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -19,11 +19,6 @@
//! Provides ERC-20 standart support implementation and EVM API for unique extensions for Refungible Pallet.
//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.
-extern crate alloc;
-
-#[cfg(not(feature = "std"))]
-use alloc::format;
-
use core::{
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
@@ -35,7 +30,7 @@
use pallet_common::{
CommonWeightInfo,
erc::{CommonEvmHandler, PrecompileResult},
- eth::collection_id_to_address,
+ eth::{collection_id_to_address, EthCrossAccount},
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};
@@ -199,7 +194,10 @@
}
#[solidity_interface(name = ERC20UniqueExtensions)]
-impl<T: Config> RefungibleTokenHandle<T> {
+impl<T: Config> RefungibleTokenHandle<T>
+where
+ T::AccountId: From<[u8; 32]>,
+{
/// @dev Function that burns an amount of the token of a given account,
/// deducting from the sender's allowance for said account.
/// @param from The account whose tokens will be burnt.
@@ -218,6 +216,51 @@
Ok(true)
}
+ /// @dev Function that burns an amount of the token of a given account,
+ /// deducting from the sender's allowance for said account.
+ /// @param from The account whose tokens will be burnt.
+ /// @param amount The amount that will be burnt.
+ #[weight(<SelfWeightOf<T>>::burn_from())]
+ fn burn_from_cross(
+ &mut self,
+ caller: caller,
+ from: EthCrossAccount,
+ amount: uint256,
+ ) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let from = from.into_sub_cross_account::<T>()?;
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ <Pallet<T>>::burn_from(self, &caller, &from, self.1, amount, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+
+ /// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.
+ /// Beware that changing an allowance with this method brings the risk that someone may use both the old
+ /// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
+ /// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
+ /// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
+ /// @param spender The crossaccount which will spend the funds.
+ /// @param amount The amount of tokens to be spent.
+ #[weight(<SelfWeightOf<T>>::approve())]
+ fn approve_cross(
+ &mut self,
+ caller: caller,
+ spender: EthCrossAccount,
+ amount: uint256,
+ ) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let spender = spender.into_sub_cross_account::<T>()?;
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+
+ <Pallet<T>>::set_allowance(self, &caller, &spender, self.1, amount)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
/// @dev Function that changes total amount of the tokens.
/// Throws if `msg.sender` doesn't owns all of the tokens.
/// @param amount New total amount of the tokens.
@@ -229,6 +272,53 @@
<Pallet<T>>::repartition(self, &caller, self.1, amount).map_err(dispatch_to_evm::<T>)?;
Ok(true)
}
+
+ /// @dev Transfer token for a specified address
+ /// @param to The crossaccount to transfer to.
+ /// @param amount The amount to be transferred.
+ #[weight(<CommonWeights<T>>::transfer())]
+ fn transfer_cross(
+ &mut self,
+ caller: caller,
+ to: EthCrossAccount,
+ amount: uint256,
+ ) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let to = to.into_sub_cross_account::<T>()?;
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ <Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+
+ /// @dev Transfer tokens from one address to another
+ /// @param from The address which you want to send tokens from
+ /// @param to The address which you want to transfer to
+ /// @param amount the amount of tokens to be transferred
+ #[weight(<CommonWeights<T>>::transfer_from())]
+ fn transfer_from_cross(
+ &mut self,
+ caller: caller,
+ from: EthCrossAccount,
+ to: EthCrossAccount,
+ amount: uint256,
+ ) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let from = from.into_sub_cross_account::<T>()?;
+ let to = to.into_sub_cross_account::<T>()?;
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ <Pallet<T>>::transfer_from(self, &caller, &from, &to, self.1, amount, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
}
impl<T: Config> RefungibleTokenHandle<T> {
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -113,7 +113,7 @@
AccessMode, budget::Budget, CollectionId, CollectionFlags, CollectionPropertiesVec,
CreateCollectionData, CustomDataLimit, mapping::TokenAddressMapping, MAX_ITEMS_PER_BATCH,
MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,
- PropertyScope, PropertyValue, TokenId, TrySetProperty,
+ PropertyScope, PropertyValue, TokenId, TrySetProperty, PropertiesPermissionMap,
};
pub use pallet::*;
@@ -1378,6 +1378,10 @@
<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)
}
+ pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {
+ <PalletCommon<T>>::property_permissions(collection_id)
+ }
+
pub fn set_scoped_token_property_permissions(
collection: &RefungibleHandle<T>,
sender: &T::CrossAccountId,
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -18,30 +18,45 @@
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x91a97a68
+/// @dev the ERC-165 identifier for this interface is 0xde0695c2
contract TokenProperties is Dummy, ERC165 {
+ // /// @notice Set permissions for token property.
+ // /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+ // /// @param key Property key.
+ // /// @param isMutable Permission to mutate property.
+ // /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
+ // /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
+ // /// @dev EVM selector for this function is: 0x222d97fa,
+ // /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
+ // function setTokenPropertyPermission(string memory key, bool isMutable, bool collectionAdmin, bool tokenOwner) public {
+ // require(false, stub_error);
+ // key;
+ // isMutable;
+ // collectionAdmin;
+ // tokenOwner;
+ // dummy = 0;
+ // }
+
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
- /// @param key Property key.
- /// @param isMutable Permission to mutate property.
- /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
- /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
- /// @dev EVM selector for this function is: 0x222d97fa,
- /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
- function setTokenPropertyPermission(
- string memory key,
- bool isMutable,
- bool collectionAdmin,
- bool tokenOwner
- ) public {
+ /// @param permissions Permissions for keys.
+ /// @dev EVM selector for this function is: 0xbd92983a,
+ /// or in textual repr: setTokenPropertyPermissions((string,(uint8,bool)[])[])
+ function setTokenPropertyPermissions(Tuple53[] memory permissions) public {
require(false, stub_error);
- key;
- isMutable;
- collectionAdmin;
- tokenOwner;
+ permissions;
dummy = 0;
}
+ /// @notice Get permissions for token properties.
+ /// @dev EVM selector for this function is: 0xf23d7790,
+ /// or in textual repr: tokenPropertyPermissions()
+ function tokenPropertyPermissions() public view returns (Tuple53[] memory) {
+ require(false, stub_error);
+ dummy;
+ return new Tuple53[](0);
+ }
+
// /// @notice Set token property value.
// /// @dev Throws error if `msg.sender` has no permission to edit the property.
// /// @param tokenId ID of the token.
@@ -118,6 +133,24 @@
bytes value;
}
+enum EthTokenPermissions {
+ Mutable,
+ TokenOwner,
+ CollectionAdmin
+}
+
+/// @dev anonymous struct
+struct Tuple53 {
+ string field_0;
+ Tuple51[] field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple51 {
+ EthTokenPermissions field_0;
+ bool field_1;
+}
+
/// @title A contract that allows you to work with collections.
/// @dev the ERC-165 identifier for this interface is 0xb5e1747f
contract Collection is Dummy, ERC165 {
pallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungibleToken.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
@@ -36,7 +36,7 @@
}
}
-/// @dev the ERC-165 identifier for this interface is 0xab8deb37
+/// @dev the ERC-165 identifier for this interface is 0xe17a7d2b
contract ERC20UniqueExtensions is Dummy, ERC165 {
/// @dev Function that burns an amount of the token of a given account,
/// deducting from the sender's allowance for said account.
@@ -52,6 +52,37 @@
return false;
}
+ /// @dev Function that burns an amount of the token of a given account,
+ /// deducting from the sender's allowance for said account.
+ /// @param from The account whose tokens will be burnt.
+ /// @param amount The amount that will be burnt.
+ /// @dev EVM selector for this function is: 0xbb2f5a58,
+ /// or in textual repr: burnFromCross((address,uint256),uint256)
+ function burnFromCross(EthCrossAccount memory from, uint256 amount) public returns (bool) {
+ require(false, stub_error);
+ from;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
+ /// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.
+ /// Beware that changing an allowance with this method brings the risk that someone may use both the old
+ /// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
+ /// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
+ /// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
+ /// @param spender The crossaccount which will spend the funds.
+ /// @param amount The amount of tokens to be spent.
+ /// @dev EVM selector for this function is: 0x0ecd0ab0,
+ /// or in textual repr: approveCross((address,uint256),uint256)
+ function approveCross(EthCrossAccount memory spender, uint256 amount) public returns (bool) {
+ require(false, stub_error);
+ spender;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
/// @dev Function that changes total amount of the tokens.
/// Throws if `msg.sender` doesn't owns all of the tokens.
/// @param amount New total amount of the tokens.
@@ -63,6 +94,44 @@
dummy = 0;
return false;
}
+
+ /// @dev Transfer token for a specified address
+ /// @param to The crossaccount to transfer to.
+ /// @param amount The amount to be transferred.
+ /// @dev EVM selector for this function is: 0x2ada85ff,
+ /// or in textual repr: transferCross((address,uint256),uint256)
+ function transferCross(EthCrossAccount memory to, uint256 amount) public returns (bool) {
+ require(false, stub_error);
+ to;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
+ /// @dev Transfer tokens from one address to another
+ /// @param from The address which you want to send tokens from
+ /// @param to The address which you want to transfer to
+ /// @param amount the amount of tokens to be transferred
+ /// @dev EVM selector for this function is: 0xd5cf430b,
+ /// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
+ function transferFromCross(
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
+ uint256 amount
+ ) public returns (bool) {
+ require(false, stub_error);
+ from;
+ to;
+ amount;
+ dummy = 0;
+ return false;
+ }
+}
+
+/// @dev Cross account struct
+struct EthCrossAccount {
+ address eth;
+ uint256 sub;
}
/// @dev inlined interface
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1010,7 +1010,7 @@
pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;
/// Property permission.
-#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
+#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone, Default)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct PropertyPermission {
/// Permission to change the property and property permission.
runtime/common/config/ethereum.rsdiffbeforeafterboth--- a/runtime/common/config/ethereum.rs
+++ b/runtime/common/config/ethereum.rs
@@ -7,8 +7,10 @@
use sp_runtime::{RuntimeAppPublic, Perbill};
use crate::{
runtime_common::{
- dispatch::CollectionDispatchT, ethereum::sponsoring::EvmSponsorshipHandler,
- config::sponsoring::DefaultSponsoringRateLimit, DealWithFees,
+ config::sponsoring::DefaultSponsoringRateLimit,
+ DealWithFees,
+ dispatch::CollectionDispatchT,
+ ethereum::{precompiles::UniquePrecompiles, sponsoring::EvmSponsorshipHandler},
},
Runtime, Aura, Balances, RuntimeEvent, ChainId,
};
@@ -34,6 +36,7 @@
const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);
parameter_types! {
pub BlockGasLimit: U256 = U256::from((NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightTimePerGas::get()).ref_time());
+ pub PrecompilesValue: UniquePrecompiles<Runtime> = UniquePrecompiles::<_>::new();
}
pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);
@@ -62,8 +65,8 @@
type CallOrigin = EnsureAddressTruncated<Self>;
type WithdrawOrigin = EnsureAddressTruncated<Self>;
type AddressMapping = HashedAddressMapping<Self::Hashing>;
- type PrecompilesType = ();
- type PrecompilesValue = ();
+ type PrecompilesType = UniquePrecompiles<Self>;
+ type PrecompilesValue = PrecompilesValue;
type Currency = Balances;
type RuntimeEvent = RuntimeEvent;
type OnMethodCall = (
runtime/common/config/pallets/mod.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -106,7 +106,7 @@
impl pallet_configuration::Config for Runtime {
type DefaultWeightToFeeCoefficient = ConstU32<{ up_common::constants::WEIGHT_TO_FEE_COEFF }>;
type DefaultMinGasPrice = ConstU64<{ up_common::constants::MIN_GAS_PRICE }>;
- type MaxOverridedAllowedLocations = ConstU32<16>;
+ type MaxXcmAllowedLocations = ConstU32<16>;
type AppPromotionDailyRate = AppPromotionDailyRate;
type DayRelayBlocks = DayRelayBlocks;
}
runtime/common/construct_runtime/mod.rsdiffbeforeafterboth--- a/runtime/common/construct_runtime/mod.rs
+++ b/runtime/common/construct_runtime/mod.rs
@@ -82,7 +82,7 @@
#[runtimes(opal, quartz)]
AppPromotion: pallet_app_promotion::{Pallet, Call, Storage, Event<T>} = 73,
- #[runtimes(opal)]
+ #[runtimes(opal, quartz, unique)]
ForeignAssets: pallet_foreign_assets::{Pallet, Call, Storage, Event<T>} = 80,
// Frontier
runtime/common/ethereum/mod.rsdiffbeforeafterboth--- a/runtime/common/ethereum/mod.rs
+++ b/runtime/common/ethereum/mod.rs
@@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+pub mod precompiles;
pub mod self_contained_call;
pub mod sponsoring;
pub mod transaction_converter;
runtime/common/ethereum/precompiles/mod.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/ethereum/precompiles/mod.rs
@@ -0,0 +1,60 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+use pallet_evm::{Precompile, PrecompileHandle, PrecompileResult, PrecompileSet};
+use sp_core::H160;
+use sp_std::marker::PhantomData;
+
+use pallet_evm_precompile_simple::{ECRecover};
+use sr25519::Sr25519Precompile;
+
+mod sr25519;
+mod utils;
+
+pub struct UniquePrecompiles<R>(PhantomData<R>);
+
+impl<R> UniquePrecompiles<R>
+where
+ R: pallet_evm::Config,
+{
+ pub fn new() -> Self {
+ Self(Default::default())
+ }
+ pub fn used_addresses() -> [H160; 2] {
+ [hash(1), hash(20482)]
+ }
+}
+impl<R> PrecompileSet for UniquePrecompiles<R>
+where
+ R: pallet_evm::Config,
+{
+ fn execute(&self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {
+ match handle.code_address() {
+ a if a == hash(1) => Some(ECRecover::execute(handle)),
+ // Sr25519 0x5002
+ a if a == hash(20482) => Some(Sr25519Precompile::<R>::execute(handle)),
+ _ => None,
+ }
+ }
+
+ fn is_precompile(&self, address: H160) -> bool {
+ Self::used_addresses().contains(&address)
+ }
+}
+
+fn hash(a: u64) -> H160 {
+ H160::from_low_u64_be(a)
+}
runtime/common/ethereum/precompiles/sr25519.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/ethereum/precompiles/sr25519.rs
@@ -0,0 +1,103 @@
+// Copyright 2019-2022 PureStake Inc.
+// Copyright 2022 Stake Technologies
+
+// Astar Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Astar Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Astar Network. If not, see <http://www.gnu.org/licenses/>.
+
+use fp_evm::{Context, ExitSucceed, PrecompileHandle, PrecompileOutput};
+use pallet_evm::Precompile;
+use sp_core::{crypto::UncheckedFrom, sr25519, H256};
+use sp_std::marker::PhantomData;
+use sp_std::prelude::*;
+
+use super::utils::{Bytes, EvmDataReader, EvmDataWriter, EvmResult, FunctionModifier, Gasometer};
+
+#[precompile_utils_macro::generate_function_selector]
+#[derive(Debug, PartialEq)]
+pub enum Action {
+ Verify = "verify(bytes32,bytes,bytes)",
+}
+
+/// A precompile to wrap substrate sr25519 functions.
+pub struct Sr25519Precompile<Runtime>(PhantomData<Runtime>);
+
+impl<Runtime: pallet_evm::Config> Precompile for Sr25519Precompile<Runtime> {
+ fn execute(handle: &mut impl PrecompileHandle) -> EvmResult<PrecompileOutput> {
+ log::trace!(target: "sr25519-precompile", "In sr25519 precompile");
+
+ let gasometer = Gasometer::new();
+
+ let (mut input, selector) = EvmDataReader::new_with_selector(&gasometer, handle.input())?;
+ let input = &mut input;
+
+ gasometer.check_function_modifier(
+ handle.context(),
+ handle.is_static(),
+ FunctionModifier::View,
+ )?;
+
+ match selector {
+ // Dispatchables
+ Action::Verify => Self::verify(input, &gasometer, handle.context()),
+ }
+ }
+}
+
+impl<Runtime: pallet_evm::Config> Sr25519Precompile<Runtime> {
+ fn verify(
+ input: &mut EvmDataReader,
+ gasometer: &Gasometer,
+ _: &Context,
+ ) -> EvmResult<PrecompileOutput> {
+ // Bound check
+ input.expect_arguments(gasometer, 3)?;
+
+ // Parse arguments
+ let public: sr25519::Public =
+ sr25519::Public::unchecked_from(input.read::<H256>(gasometer)?).into();
+ let signature_bytes: Vec<u8> = input.read::<Bytes>(gasometer)?.into();
+ let message: Vec<u8> = input.read::<Bytes>(gasometer)?.into();
+
+ // Parse signature
+ let signature_opt = sr25519::Signature::from_slice(&signature_bytes[..]);
+
+ let signature = if let Some(sig) = signature_opt {
+ sig
+ } else {
+ // Return `false` if signature length is wrong
+ return Ok(PrecompileOutput {
+ exit_status: ExitSucceed::Returned,
+ output: EvmDataWriter::new().write(false).build(),
+ });
+ };
+
+ log::trace!(
+ target: "sr25519-precompile",
+ "Verify signature {:?} for public {:?} and message {:?}",
+ signature, public, message,
+ );
+
+ let is_confirmed = sp_io::crypto::sr25519_verify(&signature, &message[..], &public);
+
+ log::trace!(
+ target: "sr25519-precompile",
+ "Verified signature {:?} is {:?}",
+ signature, is_confirmed,
+ );
+
+ Ok(PrecompileOutput {
+ exit_status: ExitSucceed::Returned,
+ output: EvmDataWriter::new().write(is_confirmed).build(),
+ })
+ }
+}
runtime/common/ethereum/precompiles/utils/data.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/ethereum/precompiles/utils/data.rs
@@ -0,0 +1,486 @@
+// Copyright 2019-2022 PureStake Inc.
+// Copyright 2022 Stake Technologies
+// This file is part of Utils package, originally developed by Purestake Inc.
+// Utils package used in Astar Network in terms of GPLv3.
+//
+// Utils is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Utils is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Utils. If not, see <http://www.gnu.org/licenses/>.
+
+use super::{EvmResult, Gasometer};
+
+use sp_std::borrow::ToOwned;
+use core::{any::type_name, ops::Range};
+use sp_core::{H160, H256, U256};
+use sp_std::{convert::TryInto, vec, vec::Vec};
+
+/// The `address` type of Solidity.
+/// H160 could represent 2 types of data (bytes20 and address) that are not encoded the same way.
+/// To avoid issues writing H160 is thus not supported.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct Address(pub H160);
+
+impl From<H160> for Address {
+ fn from(a: H160) -> Address {
+ Address(a)
+ }
+}
+
+impl From<Address> for H160 {
+ fn from(a: Address) -> H160 {
+ a.0
+ }
+}
+
+/// The `bytes`/`string` type of Solidity.
+/// It is different from `Vec<u8>` which will be serialized with padding for each `u8` element
+/// of the array, while `Bytes` is tightly packed.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct Bytes(pub Vec<u8>);
+
+impl From<&[u8]> for Bytes {
+ fn from(a: &[u8]) -> Self {
+ Self(a.to_owned())
+ }
+}
+
+impl From<&str> for Bytes {
+ fn from(a: &str) -> Self {
+ a.as_bytes().into()
+ }
+}
+
+impl Into<Vec<u8>> for Bytes {
+ fn into(self: Self) -> Vec<u8> {
+ self.0
+ }
+}
+
+/// Wrapper around an EVM input slice, helping to parse it.
+/// Provide functions to parse common types.
+#[derive(Clone, Copy, Debug)]
+pub struct EvmDataReader<'a> {
+ input: &'a [u8],
+ cursor: usize,
+}
+
+impl<'a> EvmDataReader<'a> {
+ /// Create a new input parser.
+ pub fn new(input: &'a [u8]) -> Self {
+ Self { input, cursor: 0 }
+ }
+
+ /// Create a new input parser from a selector-initial input.
+ pub fn new_with_selector<T>(gasometer: &Gasometer, input: &'a [u8]) -> EvmResult<(Self, T)>
+ where
+ T: num_enum::TryFromPrimitive<Primitive = u32>,
+ {
+ if input.len() < 4 {
+ return Err(gasometer.revert("tried to parse selector out of bounds"));
+ }
+
+ let mut buffer = [0u8; 4];
+ buffer.copy_from_slice(&input[0..4]);
+ let selector = T::try_from_primitive(u32::from_be_bytes(buffer)).map_err(|_| {
+ log::trace!(
+ target: "precompile-utils",
+ "Failed to match function selector for {}",
+ type_name::<T>()
+ );
+ gasometer.revert("unknown selector")
+ })?;
+
+ Ok((Self::new(&input[4..]), selector))
+ }
+
+ /// Check the input has at least the correct amount of arguments before the end (32 bytes values).
+ pub fn expect_arguments(&self, gasometer: &Gasometer, args: usize) -> EvmResult {
+ if self.input.len() >= self.cursor + args * 32 {
+ Ok(())
+ } else {
+ Err(gasometer.revert("input doesn't match expected length"))
+ }
+ }
+
+ /// Read data from the input.
+ /// Must be provided a gasometer to generate correct Revert errors.
+ /// TODO : Benchmark and add cost of parsing to gasometer ?
+ pub fn read<T: EvmData>(&mut self, gasometer: &Gasometer) -> EvmResult<T> {
+ T::read(self, gasometer)
+ }
+
+ /// Reads a pointer, returning a reader targetting the pointed location.
+ pub fn read_pointer(&mut self, gasometer: &Gasometer) -> EvmResult<Self> {
+ let offset: usize = self
+ .read::<U256>(gasometer)
+ .map_err(|_| gasometer.revert("tried to parse array offset out of bounds"))?
+ .try_into()
+ .map_err(|_| gasometer.revert("array offset is too large"))?;
+
+ if offset >= self.input.len() {
+ return Err(gasometer.revert("pointer points out of bounds"));
+ }
+
+ Ok(Self {
+ input: &self.input[offset..],
+ cursor: 0,
+ })
+ }
+
+ /// Move the reading cursor with provided length, and return a range from the previous cursor
+ /// location to the new one.
+ /// Checks cursor overflows.
+ fn move_cursor(&mut self, gasometer: &Gasometer, len: usize) -> EvmResult<Range<usize>> {
+ let start = self.cursor;
+ let end = self
+ .cursor
+ .checked_add(len)
+ .ok_or_else(|| gasometer.revert("data reading cursor overflow"))?;
+
+ self.cursor = end;
+
+ Ok(start..end)
+ }
+}
+
+/// Help build an EVM input/output data.
+///
+/// Functions takes `self` to allow chaining all calls like
+/// `EvmDataWriter::new().write(...).write(...).build()`.
+/// While it could be more ergonomic to take &mut self, this would
+/// prevent to have a `build` function that don't clone the output.
+#[derive(Clone, Debug)]
+pub struct EvmDataWriter {
+ pub(crate) data: Vec<u8>,
+ offset_data: Vec<OffsetDatum>,
+ selector: Option<u32>,
+}
+
+#[derive(Clone, Debug)]
+struct OffsetDatum {
+ // Offset location in the container data.
+ offset_position: usize,
+ // Data pointed by the offset that must be inserted at the end of container data.
+ data: Vec<u8>,
+ // Inside of arrays, the offset is not from the start of array data (length), but from the start
+ // of the item. This shift allow to correct this.
+ offset_shift: usize,
+}
+
+impl EvmDataWriter {
+ /// Creates a new empty output builder (without selector).
+ pub fn new() -> Self {
+ Self {
+ data: vec![],
+ offset_data: vec![],
+ selector: None,
+ }
+ }
+
+ /// Return the built data.
+ pub fn build(mut self) -> Vec<u8> {
+ Self::bake_offsets(&mut self.data, self.offset_data);
+
+ if let Some(selector) = self.selector {
+ let mut output = selector.to_be_bytes().to_vec();
+ output.append(&mut self.data);
+ output
+ } else {
+ self.data
+ }
+ }
+
+ /// Add offseted data at the end of this writer's data, updating the offsets.
+ fn bake_offsets(output: &mut Vec<u8>, offsets: Vec<OffsetDatum>) {
+ for mut offset_datum in offsets {
+ let offset_position = offset_datum.offset_position;
+ let offset_position_end = offset_position + 32;
+
+ // The offset is the distance between the start of the data and the
+ // start of the pointed data (start of a struct, length of an array).
+ // Offsets in inner data are relative to the start of their respective "container".
+ // However in arrays the "container" is actually the item itself instead of the whole
+ // array, which is corrected by `offset_shift`.
+ let free_space_offset = output.len() - offset_datum.offset_shift;
+
+ // Override dummy offset to the offset it will be in the final output.
+ U256::from(free_space_offset)
+ .to_big_endian(&mut output[offset_position..offset_position_end]);
+
+ // Append this data at the end of the current output.
+ output.append(&mut offset_datum.data);
+ }
+ }
+
+ /// Write arbitrary bytes.
+ /// Doesn't handle any alignement checks, prefer using `write` instead if possible.
+ fn write_raw_bytes(mut self, value: &[u8]) -> Self {
+ self.data.extend_from_slice(value);
+ self
+ }
+
+ /// Write data of requested type.
+ pub fn write<T: EvmData>(mut self, value: T) -> Self {
+ T::write(&mut self, value);
+ self
+ }
+
+ /// Writes a pointer to given data.
+ /// The data will be appended when calling `build`.
+ /// Initially write a dummy value as offset in this writer's data, which will be replaced by
+ /// the correct offset once the pointed data is appended.
+ ///
+ /// Takes `&mut self` since its goal is to be used inside `EvmData` impl and not in chains.
+ pub fn write_pointer(&mut self, data: Vec<u8>) {
+ let offset_position = self.data.len();
+ H256::write(self, H256::repeat_byte(0xff));
+
+ self.offset_data.push(OffsetDatum {
+ offset_position,
+ data,
+ offset_shift: 0,
+ });
+ }
+}
+
+impl Default for EvmDataWriter {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Data that can be converted from and to EVM data types.
+pub trait EvmData: Sized {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self>;
+ fn write(writer: &mut EvmDataWriter, value: Self);
+}
+
+impl EvmData for H256 {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let range = reader.move_cursor(gasometer, 32)?;
+
+ let data = reader
+ .input
+ .get(range)
+ .ok_or_else(|| gasometer.revert("tried to parse H256 out of bounds"))?;
+
+ Ok(H256::from_slice(data))
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ writer.data.extend_from_slice(value.as_bytes());
+ }
+}
+
+impl EvmData for Address {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let range = reader.move_cursor(gasometer, 32)?;
+
+ let data = reader
+ .input
+ .get(range)
+ .ok_or_else(|| gasometer.revert("tried to parse H160 out of bounds"))?;
+
+ Ok(H160::from_slice(&data[12..32]).into())
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ H256::write(writer, value.0.into());
+ }
+}
+
+impl EvmData for U256 {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let range = reader.move_cursor(gasometer, 32)?;
+
+ let data = reader
+ .input
+ .get(range)
+ .ok_or_else(|| gasometer.revert("tried to parse U256 out of bounds"))?;
+
+ Ok(U256::from_big_endian(data))
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ let mut buffer = [0u8; 32];
+ value.to_big_endian(&mut buffer);
+ writer.data.extend_from_slice(&buffer);
+ }
+}
+
+macro_rules! impl_evmdata_for_uints {
+ ($($uint:ty, )*) => {
+ $(
+ impl EvmData for $uint {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let range = reader.move_cursor(gasometer, 32)?;
+
+ let data = reader
+ .input
+ .get(range)
+ .ok_or_else(|| gasometer.revert(alloc::format!(
+ "tried to parse {} out of bounds", core::any::type_name::<Self>()
+ )))?;
+
+ let mut buffer = [0u8; core::mem::size_of::<Self>()];
+ buffer.copy_from_slice(&data[32 - core::mem::size_of::<Self>()..]);
+ Ok(Self::from_be_bytes(buffer))
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ let mut buffer = [0u8; 32];
+ buffer[32 - core::mem::size_of::<Self>()..].copy_from_slice(&value.to_be_bytes());
+ writer.data.extend_from_slice(&buffer);
+ }
+ }
+ )*
+ };
+}
+
+impl_evmdata_for_uints!(u16, u32, u64, u128,);
+
+// The implementation for u8 is specific, for performance reasons.
+impl EvmData for u8 {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let range = reader.move_cursor(gasometer, 32)?;
+
+ let data = reader
+ .input
+ .get(range)
+ .ok_or_else(|| gasometer.revert("tried to parse u64 out of bounds"))?;
+
+ Ok(data[31])
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ let mut buffer = [0u8; 32];
+ buffer[31] = value;
+
+ writer.data.extend_from_slice(&buffer);
+ }
+}
+
+impl EvmData for bool {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let h256 = H256::read(reader, gasometer)
+ .map_err(|_| gasometer.revert("tried to parse bool out of bounds"))?;
+
+ Ok(!h256.is_zero())
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ let mut buffer = [0u8; 32];
+ if value {
+ buffer[31] = 1;
+ }
+
+ writer.data.extend_from_slice(&buffer);
+ }
+}
+
+impl<T: EvmData> EvmData for Vec<T> {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let mut inner_reader = reader.read_pointer(gasometer)?;
+
+ let array_size: usize = inner_reader
+ .read::<U256>(gasometer)
+ .map_err(|_| gasometer.revert("tried to parse array length out of bounds"))?
+ .try_into()
+ .map_err(|_| gasometer.revert("array length is too large"))?;
+
+ let mut array = vec![];
+
+ let mut item_reader = EvmDataReader {
+ input: inner_reader
+ .input
+ .get(32..)
+ .ok_or_else(|| gasometer.revert("try to read array items out of bound"))?,
+ cursor: 0,
+ };
+
+ for _ in 0..array_size {
+ array.push(item_reader.read(gasometer)?);
+ }
+
+ Ok(array)
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ let mut inner_writer = EvmDataWriter::new().write(U256::from(value.len()));
+
+ for inner in value {
+ // Any offset in items are relative to the start of the item instead of the
+ // start of the array. However if there is offseted data it must but appended after
+ // all items (offsets) are written. We thus need to rely on `compute_offsets` to do
+ // that, and must store a "shift" to correct the offsets.
+ let shift = inner_writer.data.len();
+ let item_writer = EvmDataWriter::new().write(inner);
+
+ inner_writer = inner_writer.write_raw_bytes(&item_writer.data);
+ for mut offset_datum in item_writer.offset_data {
+ offset_datum.offset_shift += 32;
+ offset_datum.offset_position += shift;
+ inner_writer.offset_data.push(offset_datum);
+ }
+ }
+
+ writer.write_pointer(inner_writer.build());
+ }
+}
+
+impl EvmData for Bytes {
+ fn read(reader: &mut EvmDataReader, gasometer: &Gasometer) -> EvmResult<Self> {
+ let mut inner_reader = reader.read_pointer(gasometer)?;
+
+ // Read bytes/string size.
+ let array_size: usize = inner_reader
+ .read::<U256>(gasometer)
+ .map_err(|_| gasometer.revert("tried to parse bytes/string length out of bounds"))?
+ .try_into()
+ .map_err(|_| gasometer.revert("bytes/string length is too large"))?;
+
+ // Get valid range over the bytes data.
+ let range = inner_reader.move_cursor(gasometer, array_size)?;
+
+ let data = inner_reader
+ .input
+ .get(range)
+ .ok_or_else(|| gasometer.revert("tried to parse bytes/string out of bounds"))?;
+
+ let bytes = Self(data.to_owned());
+
+ Ok(bytes)
+ }
+
+ fn write(writer: &mut EvmDataWriter, value: Self) {
+ let length = value.0.len();
+
+ // Pad the data.
+ // Leave it as is if a multiple of 32, otherwise pad to next
+ // multiple or 32.
+ let chunks = length / 32;
+ let padded_size = match length % 32 {
+ 0 => chunks * 32,
+ _ => (chunks + 1) * 32,
+ };
+
+ let mut value = value.0.to_vec();
+ value.resize(padded_size, 0);
+
+ writer.write_pointer(
+ EvmDataWriter::new()
+ .write(U256::from(length))
+ .write_raw_bytes(&value)
+ .build(),
+ );
+ }
+}
runtime/common/ethereum/precompiles/utils/macro/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/runtime/common/ethereum/precompiles/utils/macro/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "precompile-utils-macro"
+authors = [ "StakeTechnologies", "PureStake" ]
+description = ""
+edition = "2018"
+version = "0.1.0"
+
+[lib]
+proc-macro = true
+
+[dependencies]
+num_enum = { version = "0.5.3", default-features = false }
+proc-macro2 = "1.0"
+quote = "1.0"
+sha3 = "0.8"
+syn = { version = "1.0", features = [ "extra-traits", "fold", "full", "visit" ] }
runtime/common/ethereum/precompiles/utils/macro/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/ethereum/precompiles/utils/macro/src/lib.rs
@@ -0,0 +1,115 @@
+// Copyright 2019-2022 PureStake Inc.
+// Copyright 2022 Stake Technologies
+// This file is part of Utils package, originally developed by Purestake Inc.
+// Utils package used in Astar Network in terms of GPLv3.
+//
+// Utils is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Utils is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Utils. If not, see <http://www.gnu.org/licenses/>.
+
+#![crate_type = "proc-macro"]
+extern crate proc_macro;
+
+use proc_macro::TokenStream;
+use proc_macro2::Literal;
+use quote::{quote, quote_spanned};
+use sha3::{Digest, Keccak256};
+use std::convert::TryInto;
+use syn::{parse_macro_input, spanned::Spanned, Expr, ExprLit, Ident, ItemEnum, Lit};
+
+/// This macro allows to associate to each variant of an enumeration a discriminant (of type u32
+/// whose value corresponds to the first 4 bytes of the Hash Keccak256 of the character string
+///indicated by the user of this macro.
+///
+/// Usage:
+///
+/// ```ignore
+/// #[generate_function_selector]
+/// enum Action {
+/// Toto = "toto()",
+/// Tata = "tata()",
+/// }
+/// ```
+///
+/// Extanded to:
+///
+/// ```rust
+/// #[repr(u32)]
+/// enum Action {
+/// Toto = 119097542u32,
+/// Tata = 1414311903u32,
+/// }
+/// ```
+///
+#[proc_macro_attribute]
+pub fn generate_function_selector(_: TokenStream, input: TokenStream) -> TokenStream {
+ let item = parse_macro_input!(input as ItemEnum);
+
+ let ItemEnum {
+ attrs,
+ vis,
+ enum_token,
+ ident,
+ variants,
+ ..
+ } = item;
+
+ let mut ident_expressions: Vec<Ident> = vec![];
+ let mut variant_expressions: Vec<Expr> = vec![];
+ for variant in variants {
+ match variant.discriminant {
+ Some((_, Expr::Lit(ExprLit { lit, .. }))) => {
+ if let Lit::Str(lit_str) = lit {
+ let selector = u32::from_be_bytes(
+ Keccak256::digest(lit_str.value().as_ref())[..4]
+ .try_into()
+ .unwrap(),
+ );
+ ident_expressions.push(variant.ident);
+ variant_expressions.push(Expr::Lit(ExprLit {
+ lit: Lit::Verbatim(Literal::u32_suffixed(selector)),
+ attrs: Default::default(),
+ }));
+ } else {
+ return quote_spanned! {
+ lit.span() => compile_error("Expected literal string");
+ }
+ .into();
+ }
+ }
+ Some((_eg, expr)) => {
+ return quote_spanned! {
+ expr.span() => compile_error("Expected literal");
+ }
+ .into()
+ }
+ None => {
+ return quote_spanned! {
+ variant.span() => compile_error("Each variant must have a discriminant");
+ }
+ .into()
+ }
+ }
+ }
+
+ (quote! {
+ #(#attrs)*
+ #[derive(num_enum::TryFromPrimitive, num_enum::IntoPrimitive)]
+ #[repr(u32)]
+ #vis #enum_token #ident {
+ #(
+ #ident_expressions = #variant_expressions,
+ )*
+ }
+ })
+ .into()
+}
runtime/common/ethereum/precompiles/utils/mod.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/ethereum/precompiles/utils/mod.rs
@@ -0,0 +1,95 @@
+// Copyright 2019-2022 PureStake Inc.
+// Copyright 2022 Stake Technologies
+// This file is part of Utils package, originally developed by Purestake Inc.
+// Utils package used in Astar Network in terms of GPLv3.
+//
+// Utils is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Utils is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Utils. If not, see <http://www.gnu.org/licenses/>.
+
+use sp_std::borrow::ToOwned;
+use fp_evm::{Context, ExitRevert, PrecompileFailure};
+use sp_core::U256;
+use sp_std::marker::PhantomData;
+
+mod data;
+
+pub use data::{Bytes, EvmData, EvmDataReader, EvmDataWriter};
+
+/// Alias for Result returning an EVM precompile error.
+pub type EvmResult<T = ()> = Result<T, PrecompileFailure>;
+
+/// Helper functions requiring a Runtime.
+/// This runtime must of course implement `pallet_evm::Config`.
+#[derive(Clone, Copy, Debug)]
+pub struct RuntimeHelper<Runtime>(PhantomData<Runtime>);
+
+/// Represents modifiers a Solidity function can be annotated with.
+#[derive(Copy, Clone, PartialEq, Eq)]
+pub enum FunctionModifier {
+ /// Function that doesn't modify the state.
+ View,
+ /// Function that modifies the state and accept funds.
+ Payable,
+}
+
+/// Custom Gasometer to record costs in precompiles.
+/// It is advised to record known costs as early as possible to
+/// avoid unecessary computations if there is an Out of Gas.
+///
+/// Provides functions related to reverts, as reverts takes the recorded amount
+/// of gas into account.
+#[derive(Clone, Copy, Debug)]
+pub struct Gasometer();
+
+impl Gasometer {
+ /// Create a new Gasometer with provided gas limit.
+ /// None is no limit.
+ pub fn new() -> Self {
+ Self()
+ }
+
+ /// Revert the execution, making the user pay for the the currently
+ /// recorded cost. It is better to **revert** instead of **error** as
+ /// erroring consumes the entire gas limit, and **revert** returns an error
+ /// message to the calling contract.
+ ///
+ /// TODO : Record cost of the input based on its size and handle Out of Gas ?
+ /// This might be required if we format revert messages using user data.
+ #[must_use]
+ pub fn revert(&self, output: impl AsRef<[u8]>) -> PrecompileFailure {
+ PrecompileFailure::Revert {
+ exit_status: ExitRevert::Reverted,
+ output: output.as_ref().to_owned(),
+ }
+ }
+
+ #[must_use]
+ /// Check that a function call is compatible with the context it is
+ /// called into.
+ pub fn check_function_modifier(
+ &self,
+ context: &Context,
+ is_static: bool,
+ modifier: FunctionModifier,
+ ) -> EvmResult {
+ if is_static && modifier != FunctionModifier::View {
+ return Err(self.revert("can't call non-static function in static context"));
+ }
+
+ if modifier != FunctionModifier::Payable && context.apparent_value > U256::zero() {
+ return Err(self.revert("function is not payable"));
+ }
+
+ Ok(())
+ }
+}
runtime/opal/Cargo.tomldiffbeforeafterboth--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -471,6 +471,7 @@
up-rpc = { path = "../../primitives/rpc", default-features = false }
app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false }
rmrk-rpc = { path = "../../primitives/rmrk-rpc", default-features = false }
+fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
pallet-inflation = { path = '../../pallets/inflation', default-features = false }
pallet-app-promotion = { path = '../../pallets/app-promotion', default-features = false }
@@ -494,10 +495,13 @@
pallet-base-fee = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-rpc = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-self-contained = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
+pallet-evm-precompile-simple = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
up-sponsorship = { default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = 'polkadot-v0.9.33' }
pallet-foreign-assets = { default-features = false, path = "../../pallets/foreign-assets" }
pallet-maintenance = { default-features = false, path = "../../pallets/maintenance" }
+precompile-utils-macro = { path = "../common/ethereum/precompiles/utils/macro" }
+num_enum = { version = "0.5.3", default-features = false }
################################################################################
# Test dependencies
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -25,6 +25,8 @@
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
+extern crate alloc;
+
use frame_support::parameter_types;
use sp_version::RuntimeVersion;
runtime/quartz/Cargo.tomldiffbeforeafterboth--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -169,7 +169,7 @@
"pallet-maintenance/std",
]
limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
-quartz-runtime = ['refungible', 'app-promotion']
+quartz-runtime = ['refungible', 'app-promotion', 'foreign-assets']
refungible = []
scheduler = []
@@ -463,6 +463,7 @@
pallet-unique = { path = '../../pallets/unique', default-features = false }
up-rpc = { path = "../../primitives/rpc", default-features = false }
app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false }
+fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
pallet-inflation = { path = '../../pallets/inflation', default-features = false }
pallet-app-promotion = { path = '../../pallets/app-promotion', default-features = false }
@@ -486,10 +487,13 @@
pallet-base-fee = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-rpc = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-self-contained = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
+pallet-evm-precompile-simple = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
up-sponsorship = { default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = 'polkadot-v0.9.33' }
pallet-foreign-assets = { default-features = false, path = "../../pallets/foreign-assets" }
pallet-maintenance = { default-features = false, path = "../../pallets/maintenance" }
+precompile-utils-macro = { path = "../common/ethereum/precompiles/utils/macro" }
+num_enum = { version = "0.5.3", default-features = false }
################################################################################
# Other Dependencies
runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -25,6 +25,8 @@
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
+extern crate alloc;
+
use frame_support::parameter_types;
use sp_version::RuntimeVersion;
runtime/quartz/src/xcm_barrier.rsdiffbeforeafterboth--- a/runtime/quartz/src/xcm_barrier.rs
+++ b/runtime/quartz/src/xcm_barrier.rs
@@ -52,6 +52,11 @@
parents: 1,
interior: Here,
},
+ // Statemint/Statemint location
+ MultiLocation {
+ parents: 1,
+ interior: X1(Parachain(1000)),
+ },
// Karura/Acala location
MultiLocation {
parents: 1,
runtime/unique/Cargo.tomldiffbeforeafterboth--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -170,7 +170,7 @@
"pallet-maintenance/std",
]
limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
-unique-runtime = []
+unique-runtime = ['foreign-assets']
stubgen = ["evm-coder/stubgen"]
refungible = []
@@ -479,11 +479,15 @@
pallet-base-fee = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-rpc = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-self-contained = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
+fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
+pallet-evm-precompile-simple = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.33" }
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
up-sponsorship = { default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = 'polkadot-v0.9.33' }
pallet-foreign-assets = { default-features = false, path = "../../pallets/foreign-assets" }
pallet-maintenance = { default-features = false, path = "../../pallets/maintenance" }
+precompile-utils-macro = { path = "../common/ethereum/precompiles/utils/macro" }
+num_enum = { version = "0.5.3", default-features = false }
################################################################################
# Other Dependencies
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -25,6 +25,8 @@
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
+extern crate alloc;
+
use frame_support::parameter_types;
use sp_version::RuntimeVersion;
runtime/unique/src/xcm_barrier.rsdiffbeforeafterboth--- a/runtime/unique/src/xcm_barrier.rs
+++ b/runtime/unique/src/xcm_barrier.rs
@@ -52,6 +52,11 @@
parents: 1,
interior: Here,
},
+ // Statemint/Statemint location
+ MultiLocation {
+ parents: 1,
+ interior: X1(Parachain(1000)),
+ },
// Karura/Acala location
MultiLocation {
parents: 1,
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -45,6 +45,7 @@
"testNesting": "mocha --timeout 9999999 -r ts-node/register ./**/nest.test.ts",
"testUnnesting": "mocha --timeout 9999999 -r ts-node/register ./**/unnest.test.ts",
"testProperties": "mocha --timeout 9999999 -r ts-node/register ./**/collectionProperties.test.ts ./**/tokenProperties.test.ts ./**/getPropertiesRpc.test.ts",
+ "testCollectionProperties": "mocha --timeout 9999999 -r ts-node/register ./**/collectionProperties.test.ts",
"testMigration": "mocha --timeout 9999999 -r ts-node/register ./**/nesting/migration-check.test.ts",
"testAddCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/addCollectionAdmin.test.ts",
"testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",
tests/src/eth/abi/nonFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -697,12 +697,29 @@
},
{
"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" }
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ {
+ "components": [
+ {
+ "internalType": "enum EthTokenPermissions",
+ "name": "field_0",
+ "type": "uint8"
+ },
+ { "internalType": "bool", "name": "field_1", "type": "bool" }
+ ],
+ "internalType": "struct Tuple46[]",
+ "name": "field_1",
+ "type": "tuple[]"
+ }
+ ],
+ "internalType": "struct Tuple48[]",
+ "name": "permissions",
+ "type": "tuple[]"
+ }
],
- "name": "setTokenPropertyPermission",
+ "name": "setTokenPropertyPermissions",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
@@ -743,6 +760,35 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "tokenPropertyPermissions",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ {
+ "components": [
+ {
+ "internalType": "enum EthTokenPermissions",
+ "name": "field_0",
+ "type": "uint8"
+ },
+ { "internalType": "bool", "name": "field_1", "type": "bool" }
+ ],
+ "internalType": "struct Tuple46[]",
+ "name": "field_1",
+ "type": "tuple[]"
+ }
+ ],
+ "internalType": "struct Tuple48[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
],
tests/src/eth/abi/reFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -679,12 +679,29 @@
},
{
"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" }
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ {
+ "components": [
+ {
+ "internalType": "enum EthTokenPermissions",
+ "name": "field_0",
+ "type": "uint8"
+ },
+ { "internalType": "bool", "name": "field_1", "type": "bool" }
+ ],
+ "internalType": "struct Tuple51[]",
+ "name": "field_1",
+ "type": "tuple[]"
+ }
+ ],
+ "internalType": "struct Tuple53[]",
+ "name": "permissions",
+ "type": "tuple[]"
+ }
],
- "name": "setTokenPropertyPermission",
+ "name": "setTokenPropertyPermissions",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
@@ -734,6 +751,35 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "tokenPropertyPermissions",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ {
+ "components": [
+ {
+ "internalType": "enum EthTokenPermissions",
+ "name": "field_0",
+ "type": "uint8"
+ },
+ { "internalType": "bool", "name": "field_1", "type": "bool" }
+ ],
+ "internalType": "struct Tuple51[]",
+ "name": "field_1",
+ "type": "tuple[]"
+ }
+ ],
+ "internalType": "struct Tuple53[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
],
tests/src/eth/abi/reFungibleToken.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungibleToken.json
+++ b/tests/src/eth/abi/reFungibleToken.json
@@ -71,6 +71,24 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct EthCrossAccount",
+ "name": "spender",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "approveCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "owner", "type": "address" }
],
"name": "balanceOf",
@@ -89,6 +107,24 @@
"type": "function"
},
{
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct EthCrossAccount",
+ "name": "from",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "burnFromCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "decimals",
"outputs": [{ "internalType": "uint8", "name": "", "type": "uint8" }],
@@ -160,6 +196,24 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct EthCrossAccount",
+ "name": "to",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "transferCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "from", "type": "address" },
{ "internalType": "address", "name": "to", "type": "address" },
{ "internalType": "uint256", "name": "amount", "type": "uint256" }
@@ -168,5 +222,32 @@
"outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
"stateMutability": "nonpayable",
"type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct EthCrossAccount",
+ "name": "from",
+ "type": "tuple"
+ },
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct EthCrossAccount",
+ "name": "to",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "transferFromCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
}
]
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -13,22 +13,28 @@
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x91a97a68
+/// @dev the ERC-165 identifier for this interface is 0xde0695c2
interface TokenProperties is Dummy, ERC165 {
+ // /// @notice Set permissions for token property.
+ // /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+ // /// @param key Property key.
+ // /// @param isMutable Permission to mutate property.
+ // /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
+ // /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
+ // /// @dev EVM selector for this function is: 0x222d97fa,
+ // /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
+ // function setTokenPropertyPermission(string memory key, bool isMutable, bool collectionAdmin, bool tokenOwner) external;
+
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
- /// @param key Property key.
- /// @param isMutable Permission to mutate property.
- /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
- /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
- /// @dev EVM selector for this function is: 0x222d97fa,
- /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
- function setTokenPropertyPermission(
- string memory key,
- bool isMutable,
- bool collectionAdmin,
- bool tokenOwner
- ) external;
+ /// @param permissions Permissions for keys.
+ /// @dev EVM selector for this function is: 0xbd92983a,
+ /// or in textual repr: setTokenPropertyPermissions((string,(uint8,bool)[])[])
+ function setTokenPropertyPermissions(Tuple43[] memory permissions) external;
+
+ /// @dev EVM selector for this function is: 0xf23d7790,
+ /// or in textual repr: tokenPropertyPermissions()
+ function tokenPropertyPermissions() external view returns (Tuple43[] memory);
// /// @notice Set token property value.
// /// @dev Throws error if `msg.sender` has no permission to edit the property.
@@ -79,6 +85,24 @@
bytes value;
}
+enum EthTokenPermissions {
+ Mutable,
+ TokenOwner,
+ CollectionAdmin
+}
+
+/// @dev anonymous struct
+struct Tuple43 {
+ string field_0;
+ Tuple41[] field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple41 {
+ EthTokenPermissions field_0;
+ bool field_1;
+}
+
/// @title A contract that allows you to work with collections.
/// @dev the ERC-165 identifier for this interface is 0xb5e1747f
interface Collection is Dummy, ERC165 {
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -13,22 +13,29 @@
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x91a97a68
+/// @dev the ERC-165 identifier for this interface is 0xde0695c2
interface TokenProperties is Dummy, ERC165 {
+ // /// @notice Set permissions for token property.
+ // /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+ // /// @param key Property key.
+ // /// @param isMutable Permission to mutate property.
+ // /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
+ // /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
+ // /// @dev EVM selector for this function is: 0x222d97fa,
+ // /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
+ // function setTokenPropertyPermission(string memory key, bool isMutable, bool collectionAdmin, bool tokenOwner) external;
+
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
- /// @param key Property key.
- /// @param isMutable Permission to mutate property.
- /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
- /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
- /// @dev EVM selector for this function is: 0x222d97fa,
- /// or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
- function setTokenPropertyPermission(
- string memory key,
- bool isMutable,
- bool collectionAdmin,
- bool tokenOwner
- ) external;
+ /// @param permissions Permissions for keys.
+ /// @dev EVM selector for this function is: 0xbd92983a,
+ /// or in textual repr: setTokenPropertyPermissions((string,(uint8,bool)[])[])
+ function setTokenPropertyPermissions(Tuple47[] memory permissions) external;
+
+ /// @notice Get permissions for token properties.
+ /// @dev EVM selector for this function is: 0xf23d7790,
+ /// or in textual repr: tokenPropertyPermissions()
+ function tokenPropertyPermissions() external view returns (Tuple47[] memory);
// /// @notice Set token property value.
// /// @dev Throws error if `msg.sender` has no permission to edit the property.
@@ -79,6 +86,24 @@
bytes value;
}
+enum EthTokenPermissions {
+ Mutable,
+ TokenOwner,
+ CollectionAdmin
+}
+
+/// @dev anonymous struct
+struct Tuple47 {
+ string field_0;
+ Tuple45[] field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple45 {
+ EthTokenPermissions field_0;
+ bool field_1;
+}
+
/// @title A contract that allows you to work with collections.
/// @dev the ERC-165 identifier for this interface is 0xb5e1747f
interface Collection is Dummy, ERC165 {
tests/src/eth/api/UniqueRefungibleToken.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungibleToken.sol
+++ b/tests/src/eth/api/UniqueRefungibleToken.sol
@@ -23,7 +23,7 @@
function parentTokenId() external view returns (uint256);
}
-/// @dev the ERC-165 identifier for this interface is 0xab8deb37
+/// @dev the ERC-165 identifier for this interface is 0xe17a7d2b
interface ERC20UniqueExtensions is Dummy, ERC165 {
/// @dev Function that burns an amount of the token of a given account,
/// deducting from the sender's allowance for said account.
@@ -33,12 +33,56 @@
/// or in textual repr: burnFrom(address,uint256)
function burnFrom(address from, uint256 amount) external returns (bool);
+ /// @dev Function that burns an amount of the token of a given account,
+ /// deducting from the sender's allowance for said account.
+ /// @param from The account whose tokens will be burnt.
+ /// @param amount The amount that will be burnt.
+ /// @dev EVM selector for this function is: 0xbb2f5a58,
+ /// or in textual repr: burnFromCross((address,uint256),uint256)
+ function burnFromCross(EthCrossAccount memory from, uint256 amount) external returns (bool);
+
+ /// @dev Approve the passed address to spend the specified amount of tokens on behalf of `msg.sender`.
+ /// Beware that changing an allowance with this method brings the risk that someone may use both the old
+ /// and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
+ /// race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
+ /// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
+ /// @param spender The crossaccount which will spend the funds.
+ /// @param amount The amount of tokens to be spent.
+ /// @dev EVM selector for this function is: 0x0ecd0ab0,
+ /// or in textual repr: approveCross((address,uint256),uint256)
+ function approveCross(EthCrossAccount memory spender, uint256 amount) external returns (bool);
+
/// @dev Function that changes total amount of the tokens.
/// Throws if `msg.sender` doesn't owns all of the tokens.
/// @param amount New total amount of the tokens.
/// @dev EVM selector for this function is: 0xd2418ca7,
/// or in textual repr: repartition(uint256)
function repartition(uint256 amount) external returns (bool);
+
+ /// @dev Transfer token for a specified address
+ /// @param to The crossaccount to transfer to.
+ /// @param amount The amount to be transferred.
+ /// @dev EVM selector for this function is: 0x2ada85ff,
+ /// or in textual repr: transferCross((address,uint256),uint256)
+ function transferCross(EthCrossAccount memory to, uint256 amount) external returns (bool);
+
+ /// @dev Transfer tokens from one address to another
+ /// @param from The address which you want to send tokens from
+ /// @param to The address which you want to transfer to
+ /// @param amount the amount of tokens to be transferred
+ /// @dev EVM selector for this function is: 0xd5cf430b,
+ /// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
+ function transferFromCross(
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
+ uint256 amount
+ ) external returns (bool);
+}
+
+/// @dev Cross account struct
+struct EthCrossAccount {
+ address eth;
+ uint256 sub;
}
/// @dev inlined interface
tests/src/eth/events.test.tsdiffbeforeafterboth--- a/tests/src/eth/events.test.ts
+++ b/tests/src/eth/events.test.ts
@@ -19,7 +19,7 @@
import {EthUniqueHelper, itEth, usingEthPlaygrounds} from './util';
import {IEvent, TCollectionMode} from '../util/playgrounds/types';
import {Pallets, requirePalletsOrSkip} from '../util';
-import {NormalizedEvent} from './util/playgrounds/types';
+import {EthTokenPermissions, NormalizedEvent} from './util/playgrounds/types';
let donor: IKeyringPair;
@@ -119,7 +119,13 @@
ethEvents.push(event);
});
const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['PropertyPermissionSet']}]);
- await collection.methods.setTokenPropertyPermission('testKey', true, true, true).send({from: owner});
+ await collection.methods.setTokenPropertyPermissions([
+ ['A', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ]).send({from: owner});
await helper.wait.newBlocks(1);
expect(ethEvents).to.be.like([
{
@@ -374,7 +380,13 @@
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
const result = await collection.methods.mint(owner).send({from: owner});
const tokenId = result.events.Transfer.returnValues.tokenId;
- await collection.methods.setTokenPropertyPermission('A', true, true, true).send({from: owner});
+ await collection.methods.setTokenPropertyPermissions([
+ ['A', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ]).send({from: owner});
const ethEvents: any = [];
tests/src/eth/precompile.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/precompile.test.ts
@@ -0,0 +1,112 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+
+import {expect, itEth, usingEthPlaygrounds} from './util';
+
+describe('Precompiles', () => {
+ let donor: IKeyringPair;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (_, privateKey) => {
+ donor = await privateKey({filename: __filename});
+ });
+ });
+
+ itEth('ecrecover is supported', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const ecrecoverCompiledСontract = await helper.ethContract.compile(
+ 'ECRECOVER',
+ `
+ // SPDX-License-Identifier: MIT
+ pragma solidity ^0.8.17;
+
+ contract ECRECOVER{
+ address addressTest = 0x12Cb274aAD8251C875c0bf6872b67d9983E53fDd;
+ bytes32 msgHash1 = 0xc51dac836bc7841a01c4b631fa620904fc8724d7f9f1d3c420f0e02adf229d50;
+ bytes32 msgHash2 = 0xc51dac836bc7841a01c4b631fa620904fc8724d7f9f1d3c420f0e02adf229d51;
+ uint8 v = 0x1b;
+ bytes32 r = 0x44287513919034a471a7dc2b2ed121f95984ae23b20f9637ba8dff471b6719ef;
+ bytes32 s = 0x7d7dc30309a3baffbfd9342b97d0e804092c0aeb5821319aa732bc09146eafb4;
+
+
+ function verifyValid() public view returns(bool) {
+ // Use ECRECOVER to verify address
+ return ecrecover(msgHash1, v, r, s) == (addressTest);
+ }
+
+ function verifyInvalid() public view returns(bool) {
+ // Use ECRECOVER to verify address
+ return ecrecover(msgHash2, v, r, s) == (addressTest);
+ }
+ }
+ `,
+ );
+
+ const ecrecoverСontract = await helper.ethContract.deployByAbi(owner, ecrecoverCompiledСontract.abi, ecrecoverCompiledСontract.object);
+ expect(await ecrecoverСontract.methods.verifyValid().call({from: owner})).to.be.true;
+ expect(await ecrecoverСontract.methods.verifyInvalid().call({from: owner})).to.be.false;
+ });
+
+ itEth('sr25519 is supported', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sr25519CompiledСontract = await helper.ethContract.compile(
+ 'SR25519Contract',
+ `
+ // SPDX-License-Identifier: MIT
+ pragma solidity ^0.8.17;
+
+ /**
+ * @title SR25519 signature interface.
+ */
+ interface SR25519 {
+ /**
+ * @dev Verify signed message using SR25519 crypto.
+ * @return A boolean confirming whether the public key is signer for the message.
+ */
+ function verify(
+ bytes32 public_key,
+ bytes calldata signature,
+ bytes calldata message
+ ) external view returns (bool);
+ }
+
+ contract SR25519Contract{
+ SR25519 public constant sr25519 = SR25519(0x0000000000000000000000000000000000005002);
+
+ bytes32 public_key = 0x96b2f9237ed0890fbeed891ebb81b91ac0d5d5b6e3afcdbc95df1b68d9f14036;
+ bytes signature = hex"4a5d733d7c568f2e88abf0467fd497f87c1be3e940ed897efdf9da72eaad394ef9918cb574ee99c54485775b17a0deaf46ff7a1f10346cea39fff0e4ede97689";
+ bytes message1 = hex"7372323535313920697320737570706f72746564";
+ bytes message2 = hex"7372323535313920697320737570706f7274656401";
+
+
+ function verifyValid() public view returns(bool) {
+ return sr25519.verify(public_key, signature, message1);
+ }
+
+ function verifyInvalid() public view returns(bool) {
+ return sr25519.verify(public_key, signature, message2);
+ }
+ }
+ `,
+ );
+
+ const sr25519Сontract = await helper.ethContract.deployByAbi(owner, sr25519CompiledСontract.abi, sr25519CompiledСontract.object);
+ expect(await sr25519Сontract.methods.verifyValid().call({from: owner})).to.be.true;
+ expect(await sr25519Сontract.methods.verifyInvalid().call({from: owner})).to.be.false;
+ });
+});
\ No newline at end of file
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -159,7 +159,55 @@
expect(+allowance).to.equal(100);
}
});
+
+ itEth('Can perform approveCross()', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const spender = helper.eth.createAccount();
+ const spenderSub = (await helper.arrange.createAccounts([1n], donor))[0];
+ const spenderCrossEth = helper.ethCrossAccount.fromAddress(spender);
+ const spenderCrossSub = helper.ethCrossAccount.fromKeyringPair(spenderSub);
+
+
+ const collection = await helper.rft.mintCollection(alice);
+ const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});
+
+ const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+ const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
+ {
+ const result = await contract.methods.approveCross(spenderCrossEth, 100).send({from: owner});
+ const event = result.events.Approval;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.owner).to.be.equal(owner);
+ expect(event.returnValues.spender).to.be.equal(spender);
+ expect(event.returnValues.value).to.be.equal('100');
+ }
+
+ {
+ const allowance = await contract.methods.allowance(owner, spender).call();
+ expect(+allowance).to.equal(100);
+ }
+
+
+ {
+ const result = await contract.methods.approveCross(spenderCrossSub, 100).send({from: owner});
+ const event = result.events.Approval;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.owner).to.be.equal(owner);
+ expect(event.returnValues.spender).to.be.equal(helper.address.substrateToEth(spenderSub.address));
+ expect(event.returnValues.value).to.be.equal('100');
+ }
+
+ {
+ const allowance = await collection.getTokenApprovedPieces(tokenId, {Ethereum: owner}, {Substrate: spenderSub.address});
+ expect(allowance).to.equal(100n);
+ }
+
+ {
+ //TO-DO expect with future allowanceCross(owner, spenderCrossEth).call()
+ }
+ });
+
itEth('Can perform transferFrom()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const spender = await helper.eth.createAccountWithBalance(donor);
@@ -197,7 +245,75 @@
expect(+balance).to.equal(151);
}
});
+
+ itEth('Can perform transferFromCross()', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+ const spender = await helper.eth.createAccountWithBalance(donor);
+ const receiver = helper.eth.createAccount();
+ const receiverSub = (await helper.arrange.createAccounts([1n], donor))[0];
+ const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiver);
+ const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(receiverSub);
+
+ const collection = await helper.rft.mintCollection(alice);
+ const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});
+
+ const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+ const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
+
+ await contract.methods.approve(spender, 100).send({from: owner});
+
+ {
+ const result = await contract.methods.transferFromCross(ownerCross, receiverCrossEth, 49).send({from: spender});
+ let event = result.events.Transfer;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.from).to.be.equal(owner);
+ expect(event.returnValues.to).to.be.equal(receiver);
+ expect(event.returnValues.value).to.be.equal('49');
+ event = result.events.Approval;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.owner).to.be.equal(owner);
+ expect(event.returnValues.spender).to.be.equal(spender);
+ expect(event.returnValues.value).to.be.equal('51');
+ }
+
+ {
+ const balance = await contract.methods.balanceOf(receiver).call();
+ expect(+balance).to.equal(49);
+ }
+
+ {
+ const balance = await contract.methods.balanceOf(owner).call();
+ expect(+balance).to.equal(151);
+ }
+
+ {
+ const result = await contract.methods.transferFromCross(ownerCross, receiverCrossSub, 51).send({from: spender});
+ let event = result.events.Transfer;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.from).to.be.equal(owner);
+ expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(receiverSub.address));
+ expect(event.returnValues.value).to.be.equal('51');
+
+ event = result.events.Approval;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.owner).to.be.equal(owner);
+ expect(event.returnValues.spender).to.be.equal(spender);
+ expect(event.returnValues.value).to.be.equal('0');
+ }
+
+ {
+ const balance = await collection.getTokenBalance(tokenId, {Substrate: receiverSub.address});
+ expect(balance).to.equal(51n);
+ }
+
+ {
+ const balance = await contract.methods.balanceOf(owner).call();
+ expect(+balance).to.equal(100);
+ }
+ });
+
itEth('Can perform transfer()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
@@ -226,7 +342,7 @@
expect(+balance).to.equal(50);
}
});
-
+
[
'transfer',
// 'transferCross', // TODO
@@ -267,6 +383,56 @@
expect(await rftReceiver.getTop10Owners()).to.deep.eq([{Ethereum: owner.toLowerCase()}]);
}));
+ itEth('Can perform transferCross()', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const receiver = helper.eth.createAccount();
+ const receiverSub = (await helper.arrange.createAccounts([1n], donor))[0];
+ const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiver);
+ const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(receiverSub);
+ const collection = await helper.rft.mintCollection(alice);
+ const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});
+
+ const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+ const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
+
+ {
+ const result = await contract.methods.transferCross(receiverCrossEth, 50).send({from: owner});
+ const event = result.events.Transfer;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.from).to.be.equal(owner);
+ expect(event.returnValues.to).to.be.equal(receiver);
+ expect(event.returnValues.value).to.be.equal('50');
+ }
+
+ {
+ const balance = await contract.methods.balanceOf(owner).call();
+ expect(+balance).to.equal(150);
+ }
+
+ {
+ const balance = await contract.methods.balanceOf(receiver).call();
+ expect(+balance).to.equal(50);
+ }
+
+ {
+ const result = await contract.methods.transferCross(receiverCrossSub, 50).send({from: owner});
+ const event = result.events.Transfer;
+ expect(event.address).to.be.equal(tokenAddress);
+ expect(event.returnValues.from).to.be.equal(owner);
+ expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(receiverSub.address));
+ expect(event.returnValues.value).to.be.equal('50');
+ }
+
+ {
+ const balance = await contract.methods.balanceOf(owner).call();
+ expect(+balance).to.equal(100);
+ }
+
+ {
+ const balance = await collection.getTokenBalance(tokenId, {Substrate: receiverSub.address});
+ expect(balance).to.equal(50n);
+ }
+ });
itEth('Can perform repartition()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = await helper.eth.createAccountWithBalance(donor);
@@ -353,6 +519,41 @@
expect(event.returnValues.to).to.be.equal(receiver);
expect(event.returnValues.tokenId).to.be.equal(tokenId);
});
+
+ itEth('Can perform burnFromCross()', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const ownerSub = (await helper.arrange.createAccounts([10n], donor))[0];
+ const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+ const spender = await helper.eth.createAccountWithBalance(donor);
+
+ const spenderCrossEth = helper.ethCrossAccount.fromAddress(spender);
+ const ownerSubCross = helper.ethCrossAccount.fromKeyringPair(ownerSub);
+
+ const collection = await helper.rft.mintCollection(alice);
+ const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});
+
+
+ const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+ const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
+
+ {
+ await contract.methods.approveCross(spenderCrossEth, 100).send({from: owner});
+
+ await expect(contract.methods.burnFromCross(ownerCross, 50).send({from: spender})).to.be.fulfilled;
+ await expect(contract.methods.burnFromCross(ownerCross, 100).send({from: spender})).to.be.rejected;
+ expect(await contract.methods.balanceOf(owner).call({from: owner})).to.be.equal('150');
+ }
+ {
+ const {tokenId} = await collection.mintToken(alice, 200n, {Substrate: ownerSub.address});
+ await collection.approveToken(ownerSub, tokenId, {Ethereum: spender}, 100n);
+ const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+ const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
+
+ await expect(contract.methods.burnFromCross(ownerSubCross, 50).send({from: spender})).to.be.fulfilled;
+ await expect(contract.methods.burnFromCross(ownerSubCross, 100).send({from: spender})).to.be.rejected;
+ expect(await collection.getTokenBalance(tokenId, {Substrate: ownerSub.address})).to.be.equal(150n);
+ }
+ });
});
describe('Refungible: Fees', () => {
tests/src/eth/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -20,6 +20,7 @@
import {ITokenPropertyPermission} from '../util/playgrounds/types';
import {Pallets} from '../util';
import {UniqueNFTCollection, UniqueNFToken, UniqueRFTCollection} from '../util/playgrounds/unique';
+import {EthTokenPermissions} from './util/playgrounds/types';
describe('EVM token properties', () => {
let donor: IKeyringPair;
@@ -32,25 +33,170 @@
});
});
- itEth('Can be reconfigured', async({helper}) => {
- const caller = await helper.eth.createAccountWithBalance(donor);
- for(const [mutable,collectionAdmin, tokenOwner] of cartesian([], [false, true], [false, true], [false, true])) {
- const collection = await helper.nft.mintCollection(alice);
- await collection.addAdmin(alice, {Ethereum: caller});
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Set and get token property permissions`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.ethCrossAccount.createAccountWithBalance(donor);
+ for(const [mutable,collectionAdmin, tokenOwner] of cartesian([], [false, true], [false, true], [false, true])) {
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+ await collection.methods.addCollectionAdminCross(caller).send({from: owner});
+
+ await collection.methods.setTokenPropertyPermissions([
+ ['testKey', [
+ [EthTokenPermissions.Mutable, mutable],
+ [EthTokenPermissions.TokenOwner, tokenOwner],
+ [EthTokenPermissions.CollectionAdmin, collectionAdmin]],
+ ],
+ ]).send({from: caller.eth});
- const address = helper.ethAddress.fromCollectionId(collection.collectionId);
- const contract = helper.ethNativeContract.collection(address, 'nft', caller);
-
- await contract.methods.setTokenPropertyPermission('testKey', mutable, collectionAdmin, tokenOwner).send({from: caller});
-
- expect(await collection.getPropertyPermissions()).to.be.deep.equal([{
- key: 'testKey',
- permission: {mutable, collectionAdmin, tokenOwner},
- }]);
- }
- });
+ expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([{
+ key: 'testKey',
+ permission: {mutable, collectionAdmin, tokenOwner},
+ }]);
+ expect(await collection.methods.tokenPropertyPermissions().call({from: caller.eth})).to.be.like([
+ ['testKey', [
+ [EthTokenPermissions.Mutable.toString(), mutable],
+ [EthTokenPermissions.TokenOwner.toString(), tokenOwner],
+ [EthTokenPermissions.CollectionAdmin.toString(), collectionAdmin]],
+ ],
+ ]);
+ }
+ }));
+
[
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Set and get multiple token property permissions as owner`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+ await collection.methods.setTokenPropertyPermissions([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ['testKey_1', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, false],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ['testKey_2', [
+ [EthTokenPermissions.Mutable, false],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, false]],
+ ],
+ ]).send({from: owner});
+
+ expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([
+ {
+ key: 'testKey_0',
+ permission: {mutable: true, tokenOwner: true, collectionAdmin: true},
+ },
+ {
+ key: 'testKey_1',
+ permission: {mutable: true, tokenOwner: false, collectionAdmin: true},
+ },
+ {
+ key: 'testKey_2',
+ permission: {mutable: false, tokenOwner: true, collectionAdmin: false},
+ },
+ ]);
+
+ expect(await collection.methods.tokenPropertyPermissions().call({from: owner})).to.be.like([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable.toString(), true],
+ [EthTokenPermissions.TokenOwner.toString(), true],
+ [EthTokenPermissions.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_1', [
+ [EthTokenPermissions.Mutable.toString(), true],
+ [EthTokenPermissions.TokenOwner.toString(), false],
+ [EthTokenPermissions.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_2', [
+ [EthTokenPermissions.Mutable.toString(), false],
+ [EthTokenPermissions.TokenOwner.toString(), true],
+ [EthTokenPermissions.CollectionAdmin.toString(), false]],
+ ],
+ ]);
+
+ }));
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Set and get multiple token property permissions as admin`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.ethCrossAccount.createAccountWithBalance(donor);
+
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+ await collection.methods.addCollectionAdminCross(caller).send({from: owner});
+
+ await collection.methods.setTokenPropertyPermissions([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ['testKey_1', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, false],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ['testKey_2', [
+ [EthTokenPermissions.Mutable, false],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, false]],
+ ],
+ ]).send({from: caller.eth});
+
+ expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([
+ {
+ key: 'testKey_0',
+ permission: {mutable: true, tokenOwner: true, collectionAdmin: true},
+ },
+ {
+ key: 'testKey_1',
+ permission: {mutable: true, tokenOwner: false, collectionAdmin: true},
+ },
+ {
+ key: 'testKey_2',
+ permission: {mutable: false, tokenOwner: true, collectionAdmin: false},
+ },
+ ]);
+
+ expect(await collection.methods.tokenPropertyPermissions().call({from: caller.eth})).to.be.like([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable.toString(), true],
+ [EthTokenPermissions.TokenOwner.toString(), true],
+ [EthTokenPermissions.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_1', [
+ [EthTokenPermissions.Mutable.toString(), true],
+ [EthTokenPermissions.TokenOwner.toString(), false],
+ [EthTokenPermissions.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_2', [
+ [EthTokenPermissions.Mutable.toString(), false],
+ [EthTokenPermissions.TokenOwner.toString(), true],
+ [EthTokenPermissions.CollectionAdmin.toString(), false]],
+ ],
+ ]);
+
+ }));
+
+ [
{
method: 'setProperties',
methodParams: [[{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}]],
@@ -301,6 +447,47 @@
const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();
expect(actualProps).to.deep.eq(expectedProps);
}));
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Cant set token property permissions as non owner or admin`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+ await expect(collection.methods.setTokenPropertyPermissions([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ]).call({from: caller})).to.be.rejectedWith('NoPermission');
+ }));
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Cant set token property permissions with invalid character`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+ await expect(collection.methods.setTokenPropertyPermissions([
+ // "Space" is invalid character
+ ['testKey 0', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ]).call({from: owner})).to.be.rejectedWith('InvalidCharacterInPropertyKey');
+ }));
+
});
tests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -20,3 +20,8 @@
export type EthProperty = string[];
+export enum EthTokenPermissions {
+ Mutable,
+ TokenOwner,
+ CollectionAdmin
+}
\ No newline at end of file
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -60,7 +60,7 @@
}
async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {
- const out = JSON.parse(solc.compile(JSON.stringify({
+ const compiled = JSON.parse(solc.compile(JSON.stringify({
language: 'Solidity',
sources: {
[`${name}.sol`]: {
@@ -74,7 +74,18 @@
},
},
},
- }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];
+ }), {import: await this.findImports(imports)}));
+
+ const hasErrors = compiled['errors']
+ && compiled['errors'].length > 0
+ && compiled.errors.some(function(err: any) {
+ return err.severity == 'error';
+ });
+
+ if (hasErrors) {
+ throw compiled.errors;
+ }
+ const out = compiled.contracts[`${name}.sol`][name];
return {
abi: out.abi,
tests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-rpc.ts
+++ b/tests/src/interfaces/augment-api-rpc.ts
@@ -16,7 +16,7 @@
import type { BlockHash } from '@polkadot/types/interfaces/chain';
import type { PrefixedStorageKey } from '@polkadot/types/interfaces/childstate';
import type { AuthorityId } from '@polkadot/types/interfaces/consensus';
-import type { CodeUploadRequest, CodeUploadResult, ContractCallRequest, ContractExecResult, ContractInstantiateResult, InstantiateRequestV1 } from '@polkadot/types/interfaces/contracts';
+import type { CodeUploadRequest, CodeUploadResult, ContractCallRequest, ContractExecResult, ContractInstantiateResult, InstantiateRequest } from '@polkadot/types/interfaces/contracts';
import type { BlockStats } from '@polkadot/types/interfaces/dev';
import type { CreatedBlock } from '@polkadot/types/interfaces/engine';
import type { EthAccount, EthCallRequest, EthFeeHistory, EthFilter, EthFilterChanges, EthLog, EthReceipt, EthRichBlock, EthSubKind, EthSubParams, EthSyncStatus, EthTransaction, EthTransactionRequest, EthWork } from '@polkadot/types/interfaces/eth';
@@ -24,7 +24,7 @@
import type { EncodedFinalityProofs, JustificationNotification, ReportedRoundStates } from '@polkadot/types/interfaces/grandpa';
import type { MmrLeafBatchProof, MmrLeafProof } from '@polkadot/types/interfaces/mmr';
import type { StorageKind } from '@polkadot/types/interfaces/offchain';
-import type { FeeDetails, RuntimeDispatchInfoV1 } from '@polkadot/types/interfaces/payment';
+import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { RpcMethods } from '@polkadot/types/interfaces/rpc';
import type { AccountId, AccountId32, BlockNumber, H160, H256, H64, Hash, Header, Index, Justification, KeyValue, SignedBlock, StorageData } from '@polkadot/types/interfaces/runtime';
import type { MigrationStatusResult, ReadProof, RuntimeVersion, TraceBlockResponse } from '@polkadot/types/interfaces/state';
@@ -174,7 +174,7 @@
* @deprecated Use the runtime interface `api.call.contractsApi.instantiate` instead
* Instantiate a new contract
**/
- instantiate: AugmentedRpc<(request: InstantiateRequestV1 | { origin?: any; value?: any; gasLimit?: any; code?: any; data?: any; salt?: any } | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<ContractInstantiateResult>>;
+ instantiate: AugmentedRpc<(request: InstantiateRequest | { origin?: any; value?: any; gasLimit?: any; storageDepositLimit?: any; code?: any; data?: any; salt?: any } | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<ContractInstantiateResult>>;
/**
* @deprecated Not available in newer versions of the contracts interfaces
* Returns the projected time a given contract will be able to sustain paying its rent
@@ -426,15 +426,13 @@
};
payment: {
/**
- * @deprecated Use `api.call.transactionPaymentApi.queryFeeDetails` instead
* Query the detailed fee of a given encoded extrinsic
**/
queryFeeDetails: AugmentedRpc<(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<FeeDetails>>;
/**
- * @deprecated Use `api.call.transactionPaymentApi.queryInfo` instead
* Retrieves the fee information for an encoded extrinsic
**/
- queryInfo: AugmentedRpc<(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<RuntimeDispatchInfoV1>>;
+ queryInfo: AugmentedRpc<(extrinsic: Bytes | string | Uint8Array, at?: BlockHash | string | Uint8Array) => Observable<RuntimeDispatchInfo>>;
};
rmrk: {
/**
tests/src/interfaces/augment-api-runtime.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-runtime.ts
+++ b/tests/src/interfaces/augment-api-runtime.ts
@@ -6,7 +6,7 @@
import '@polkadot/api-base/types/calls';
import type { ApiTypes, AugmentedCall, DecoratedCallBase } from '@polkadot/api-base/types';
-import type { Bytes, Null, Option, Result, U256, Vec, bool, u256, u32, u64 } from '@polkadot/types-codec';
+import type { Bytes, Null, Option, Result, U256, Vec, bool, u256, u64 } from '@polkadot/types-codec';
import type { AnyNumber, ITuple } from '@polkadot/types-codec/types';
import type { CheckInherentsResult, InherentData } from '@polkadot/types/interfaces/blockbuilder';
import type { BlockHash } from '@polkadot/types/interfaces/chain';
@@ -16,7 +16,6 @@
import type { EvmAccount, EvmCallInfo, EvmCreateInfo } from '@polkadot/types/interfaces/evm';
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
import type { OpaqueMetadata } from '@polkadot/types/interfaces/metadata';
-import type { FeeDetails, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { AccountId, Block, H160, H256, Header, Index, KeyTypeId, Permill, SlotDuration } from '@polkadot/types/interfaces/runtime';
import type { RuntimeVersion } from '@polkadot/types/interfaces/state';
import type { ApplyExtrinsicResult, DispatchError } from '@polkadot/types/interfaces/system';
@@ -224,21 +223,6 @@
* Validate the transaction.
**/
validateTransaction: AugmentedCall<ApiType, (source: TransactionSource | 'InBlock' | 'Local' | 'External' | number | Uint8Array, tx: Extrinsic | IExtrinsic | string | Uint8Array, blockHash: BlockHash | string | Uint8Array) => Observable<TransactionValidity>>;
- /**
- * Generic call
- **/
- [key: string]: DecoratedCallBase<ApiType>;
- };
- /** 0x37c8bb1350a9a2a8/2 */
- transactionPaymentApi: {
- /**
- * The transaction fee details
- **/
- queryFeeDetails: AugmentedCall<ApiType, (uxt: Extrinsic | IExtrinsic | string | Uint8Array, len: u32 | AnyNumber | Uint8Array) => Observable<FeeDetails>>;
- /**
- * The transaction info
- **/
- queryInfo: AugmentedCall<ApiType, (uxt: Extrinsic | IExtrinsic | string | Uint8Array, len: u32 | AnyNumber | Uint8Array) => Observable<RuntimeDispatchInfo>>;
/**
* Generic call
**/
tests/src/interfaces/augment-types.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -24,7 +24,7 @@
import type { StatementKind } from '@polkadot/types/interfaces/claims';
import type { CollectiveOrigin, MemberCount, ProposalIndex, Votes, VotesTo230 } from '@polkadot/types/interfaces/collective';
import type { AuthorityId, RawVRFOutput } from '@polkadot/types/interfaces/consensus';
-import type { AliveContractInfo, CodeHash, CodeSource, CodeUploadRequest, CodeUploadResult, CodeUploadResultValue, ContractCallFlags, ContractCallRequest, ContractExecResult, ContractExecResultOk, ContractExecResultResult, ContractExecResultSuccessTo255, ContractExecResultSuccessTo260, ContractExecResultTo255, ContractExecResultTo260, ContractExecResultTo267, ContractExecResultU64, ContractInfo, ContractInstantiateResult, ContractInstantiateResultTo267, ContractInstantiateResultTo299, ContractInstantiateResultU64, ContractReturnFlags, ContractStorageKey, DeletedContract, ExecReturnValue, Gas, HostFnWeights, HostFnWeightsTo264, InstantiateRequest, InstantiateRequestV1, InstantiateRequestV2, InstantiateReturnValue, InstantiateReturnValueOk, InstantiateReturnValueTo267, InstructionWeights, Limits, LimitsTo264, PrefabWasmModule, RentProjection, Schedule, ScheduleTo212, ScheduleTo258, ScheduleTo264, SeedOf, StorageDeposit, TombstoneContractInfo, TrieId } from '@polkadot/types/interfaces/contracts';
+import type { AliveContractInfo, CodeHash, CodeSource, CodeUploadRequest, CodeUploadResult, CodeUploadResultValue, ContractCallFlags, ContractCallRequest, ContractExecResult, ContractExecResultOk, ContractExecResultResult, ContractExecResultSuccessTo255, ContractExecResultSuccessTo260, ContractExecResultTo255, ContractExecResultTo260, ContractExecResultTo267, ContractInfo, ContractInstantiateResult, ContractInstantiateResultTo267, ContractInstantiateResultTo299, ContractReturnFlags, ContractStorageKey, DeletedContract, ExecReturnValue, Gas, HostFnWeights, HostFnWeightsTo264, InstantiateRequest, InstantiateRequestV1, InstantiateRequestV2, InstantiateReturnValue, InstantiateReturnValueOk, InstantiateReturnValueTo267, InstructionWeights, Limits, LimitsTo264, PrefabWasmModule, RentProjection, Schedule, ScheduleTo212, ScheduleTo258, ScheduleTo264, SeedOf, StorageDeposit, TombstoneContractInfo, TrieId } from '@polkadot/types/interfaces/contracts';
import type { ContractConstructorSpecLatest, ContractConstructorSpecV0, ContractConstructorSpecV1, ContractConstructorSpecV2, ContractConstructorSpecV3, ContractContractSpecV0, ContractContractSpecV1, ContractContractSpecV2, ContractContractSpecV3, ContractContractSpecV4, ContractCryptoHasher, ContractDiscriminant, ContractDisplayName, ContractEventParamSpecLatest, ContractEventParamSpecV0, ContractEventParamSpecV2, ContractEventSpecLatest, ContractEventSpecV0, ContractEventSpecV1, ContractEventSpecV2, ContractLayoutArray, ContractLayoutCell, ContractLayoutEnum, ContractLayoutHash, ContractLayoutHashingStrategy, ContractLayoutKey, ContractLayoutStruct, ContractLayoutStructField, ContractMessageParamSpecLatest, ContractMessageParamSpecV0, ContractMessageParamSpecV2, ContractMessageSpecLatest, ContractMessageSpecV0, ContractMessageSpecV1, ContractMessageSpecV2, ContractMetadata, ContractMetadataLatest, ContractMetadataV0, ContractMetadataV1, ContractMetadataV2, ContractMetadataV3, ContractMetadataV4, ContractProject, ContractProjectContract, ContractProjectInfo, ContractProjectSource, ContractProjectV0, ContractSelector, ContractStorageLayout, ContractTypeSpec } from '@polkadot/types/interfaces/contractsAbi';
import type { FundIndex, FundInfo, LastContribution, TrieIndex } from '@polkadot/types/interfaces/crowdloan';
import type { CollationInfo, CollationInfoV1, ConfigData, MessageId, OverweightIndex, PageCounter, PageIndexData } from '@polkadot/types/interfaces/cumulus';
@@ -47,7 +47,7 @@
import type { StorageKind } from '@polkadot/types/interfaces/offchain';
import type { DeferredOffenceOf, Kind, OffenceDetails, Offender, OpaqueTimeSlot, ReportIdOf, Reporter } from '@polkadot/types/interfaces/offences';
import type { AbridgedCandidateReceipt, AbridgedHostConfiguration, AbridgedHrmpChannel, AssignmentId, AssignmentKind, AttestedCandidate, AuctionIndex, AuthorityDiscoveryId, AvailabilityBitfield, AvailabilityBitfieldRecord, BackedCandidate, Bidder, BufferedSessionChange, CandidateCommitments, CandidateDescriptor, CandidateEvent, CandidateHash, CandidateInfo, CandidatePendingAvailability, CandidateReceipt, CollatorId, CollatorSignature, CommittedCandidateReceipt, CoreAssignment, CoreIndex, CoreOccupied, CoreState, DisputeLocation, DisputeResult, DisputeState, DisputeStatement, DisputeStatementSet, DoubleVoteReport, DownwardMessage, ExplicitDisputeStatement, GlobalValidationData, GlobalValidationSchedule, GroupIndex, GroupRotationInfo, HeadData, HostConfiguration, HrmpChannel, HrmpChannelId, HrmpOpenChannelRequest, InboundDownwardMessage, InboundHrmpMessage, InboundHrmpMessages, IncomingParachain, IncomingParachainDeploy, IncomingParachainFixed, InvalidDisputeStatementKind, LeasePeriod, LeasePeriodOf, LocalValidationData, MessageIngestionType, MessageQueueChain, MessagingStateSnapshot, MessagingStateSnapshotEgressEntry, MultiDisputeStatementSet, NewBidder, OccupiedCore, OccupiedCoreAssumption, OldV1SessionInfo, OutboundHrmpMessage, ParaGenesisArgs, ParaId, ParaInfo, ParaLifecycle, ParaPastCodeMeta, ParaScheduling, ParaValidatorIndex, ParachainDispatchOrigin, ParachainInherentData, ParachainProposal, ParachainsInherentData, ParathreadClaim, ParathreadClaimQueue, ParathreadEntry, PersistedValidationData, PvfCheckStatement, QueuedParathread, RegisteredParachainInfo, RelayBlockNumber, RelayChainBlockNumber, RelayChainHash, RelayHash, Remark, ReplacementTimes, Retriable, ScheduledCore, Scheduling, ScrapedOnChainVotes, ServiceQuality, SessionInfo, SessionInfoValidatorGroup, SignedAvailabilityBitfield, SignedAvailabilityBitfields, SigningContext, SlotRange, SlotRange10, Statement, SubId, SystemInherentData, TransientValidationData, UpgradeGoAhead, UpgradeRestriction, UpwardMessage, ValidDisputeStatementKind, ValidationCode, ValidationCodeHash, ValidationData, ValidationDataType, ValidationFunctionParams, ValidatorSignature, ValidityAttestation, VecInboundHrmpMessage, WinnersData, WinnersData10, WinnersDataTuple, WinnersDataTuple10, WinningData, WinningData10, WinningDataEntry } from '@polkadot/types/interfaces/parachains';
-import type { FeeDetails, InclusionFee, RuntimeDispatchInfo, RuntimeDispatchInfoV1, RuntimeDispatchInfoV2 } from '@polkadot/types/interfaces/payment';
+import type { FeeDetails, InclusionFee, RuntimeDispatchInfo } from '@polkadot/types/interfaces/payment';
import type { Approvals } from '@polkadot/types/interfaces/poll';
import type { ProxyAnnouncement, ProxyDefinition, ProxyType } from '@polkadot/types/interfaces/proxy';
import type { AccountStatus, AccountValidity } from '@polkadot/types/interfaces/purchase';
@@ -273,12 +273,10 @@
ContractExecResultTo255: ContractExecResultTo255;
ContractExecResultTo260: ContractExecResultTo260;
ContractExecResultTo267: ContractExecResultTo267;
- ContractExecResultU64: ContractExecResultU64;
ContractInfo: ContractInfo;
ContractInstantiateResult: ContractInstantiateResult;
ContractInstantiateResultTo267: ContractInstantiateResultTo267;
ContractInstantiateResultTo299: ContractInstantiateResultTo299;
- ContractInstantiateResultU64: ContractInstantiateResultU64;
ContractLayoutArray: ContractLayoutArray;
ContractLayoutCell: ContractLayoutCell;
ContractLayoutEnum: ContractLayoutEnum;
@@ -1059,8 +1057,6 @@
RpcMethods: RpcMethods;
RuntimeDbWeight: RuntimeDbWeight;
RuntimeDispatchInfo: RuntimeDispatchInfo;
- RuntimeDispatchInfoV1: RuntimeDispatchInfoV1;
- RuntimeDispatchInfoV2: RuntimeDispatchInfoV2;
RuntimeVersion: RuntimeVersion;
RuntimeVersionApi: RuntimeVersionApi;
RuntimeVersionPartial: RuntimeVersionPartial;
tests/src/nesting/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/collectionProperties.test.ts
+++ b/tests/src/nesting/collectionProperties.test.ts
@@ -15,8 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {itSub, Pallets, usingPlaygrounds, expect} from '../util';
-import {UniqueBaseCollection} from '../util/playgrounds/unique';
+import {itSub, Pallets, usingPlaygrounds, expect, requirePalletsOrSkip} from '../util';
describe('Integration Test: Collection Properties', () => {
let alice: IKeyringPair;
@@ -32,116 +31,98 @@
itSub('Properties are initially empty', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice);
expect(await collection.getProperties()).to.be.empty;
- });
-
- async function testSetsPropertiesForCollection(collection: UniqueBaseCollection) {
- // As owner
- await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;
-
- await collection.addAdmin(alice, {Substrate: bob.address});
-
- // As administrator
- await expect(collection.setProperties(bob, [{key: 'black_hole'}])).to.be.fulfilled;
-
- const properties = await collection.getProperties();
- expect(properties).to.include.deep.members([
- {key: 'electron', value: 'come bond'},
- {key: 'black_hole', value: ''},
- ]);
- }
-
- itSub('Sets properties for a NFT collection', async ({helper}) => {
- await testSetsPropertiesForCollection(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Sets properties for a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
- await testSetsPropertiesForCollection(await helper.rft.mintCollection(alice));
});
-
- async function testCheckValidNames(collection: UniqueBaseCollection) {
- // alpha symbols
- await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;
-
- // numeric symbols
- await expect(collection.setProperties(alice, [{key: '451'}])).to.be.fulfilled;
-
- // underscore symbol
- await expect(collection.setProperties(alice, [{key: 'black_hole'}])).to.be.fulfilled;
-
- // dash symbol
- await expect(collection.setProperties(alice, [{key: '-'}])).to.be.fulfilled;
-
- // dot symbol
- await expect(collection.setProperties(alice, [{key: 'once.in.a.long.long.while...', value: 'you get a little lost'}])).to.be.fulfilled;
-
- const properties = await collection.getProperties();
- expect(properties).to.include.deep.members([
- {key: 'answer', value: ''},
- {key: '451', value: ''},
- {key: 'black_hole', value: ''},
- {key: '-', value: ''},
- {key: 'once.in.a.long.long.while...', value: 'you get a little lost'},
- ]);
- }
-
- itSub('Check valid names for NFT collection properties keys', async ({helper}) => {
- await testCheckValidNames(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Check valid names for ReFungible collection properties keys', [Pallets.ReFungible], async ({helper}) => {
- await testCheckValidNames(await helper.rft.mintCollection(alice));
- });
-
- async function testChangesProperties(collection: UniqueBaseCollection) {
- await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;
-
- // Mutate the properties
- await expect(collection.setProperties(alice, [{key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
-
- const properties = await collection.getProperties();
- expect(properties).to.include.deep.members([
- {key: 'electron', value: 'come bond'},
- {key: 'black_hole', value: 'LIGO'},
- ]);
- }
-
- itSub('Changes properties of a NFT collection', async ({helper}) => {
- await testChangesProperties(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Changes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
- await testChangesProperties(await helper.rft.mintCollection(alice));
- });
-
- async function testDeleteProperties(collection: UniqueBaseCollection) {
- await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
-
- await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;
-
- const properties = await collection.getProperties(['black_hole', 'electron']);
- expect(properties).to.be.deep.equal([
- {key: 'black_hole', value: 'LIGO'},
- ]);
- }
-
- itSub('Deletes properties of a NFT collection', async ({helper}) => {
- await testDeleteProperties(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Deletes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
- await testDeleteProperties(await helper.rft.mintCollection(alice));
- });
[
- // TODO enable properties for FT collection in Substrate (release 040)
- // {mode: 'ft' as const, requiredPallets: []},
{mode: 'nft' as const, requiredPallets: []},
+ {mode: 'ft' as const, requiredPallets: []},
{mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
- ].map(testCase =>
- itSub.ifWithPallets(`Allows modifying a collection property multiple times with the same size (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ ].map(testSuite => describe(`${testSuite.mode.toUpperCase()}`, () => {
+ before(async function() {
+ // eslint-disable-next-line require-await
+ await usingPlaygrounds(async helper => {
+ requirePalletsOrSkip(this, helper, testSuite.requiredPallets);
+ });
+ });
+
+ itSub('Sets properties for a collection', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ // As owner
+ await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;
+
+ await collection.addAdmin(alice, {Substrate: bob.address});
+
+ // As administrator
+ await expect(collection.setProperties(bob, [{key: 'black_hole'}])).to.be.fulfilled;
+
+ const properties = await collection.getProperties();
+ expect(properties).to.include.deep.members([
+ {key: 'electron', value: 'come bond'},
+ {key: 'black_hole', value: ''},
+ ]);
+ });
+
+ itSub('Check valid names for collection properties keys', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ // alpha symbols
+ await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;
+
+ // numeric symbols
+ await expect(collection.setProperties(alice, [{key: '451'}])).to.be.fulfilled;
+
+ // underscore symbol
+ await expect(collection.setProperties(alice, [{key: 'black_hole'}])).to.be.fulfilled;
+
+ // dash symbol
+ await expect(collection.setProperties(alice, [{key: '-'}])).to.be.fulfilled;
+
+ // dot symbol
+ await expect(collection.setProperties(alice, [{key: 'once.in.a.long.long.while...', value: 'you get a little lost'}])).to.be.fulfilled;
+
+ const properties = await collection.getProperties();
+ expect(properties).to.include.deep.members([
+ {key: 'answer', value: ''},
+ {key: '451', value: ''},
+ {key: 'black_hole', value: ''},
+ {key: '-', value: ''},
+ {key: 'once.in.a.long.long.while...', value: 'you get a little lost'},
+ ]);
+ });
+
+ itSub('Changes properties of a collection', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;
+
+ // Mutate the properties
+ await expect(collection.setProperties(alice, [{key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
+
+ const properties = await collection.getProperties();
+ expect(properties).to.include.deep.members([
+ {key: 'electron', value: 'come bond'},
+ {key: 'black_hole', value: 'LIGO'},
+ ]);
+ });
+
+ itSub('Deletes properties of a collection', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
+
+ await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;
+
+ const properties = await collection.getProperties(['black_hole', 'electron']);
+ expect(properties).to.be.deep.equal([
+ {key: 'black_hole', value: 'LIGO'},
+ ]);
+ });
+
+ itSub('Allows modifying a collection property multiple times with the same size', async({helper}) => {
const propKey = 'tok-prop';
- const collection = await helper[testCase.mode].mintCollection(alice);
+ const collection = await helper[testSuite.mode].mintCollection(alice);
const maxCollectionPropertiesSize = 40960;
@@ -166,18 +147,12 @@
const consumedSpace = await collection.getPropertiesConsumedSpace();
expect(consumedSpace).to.be.equal(originalSpace);
}
- }));
+ });
- [
- // TODO enable properties for FT collection in Substrate (release 040)
- // {mode: 'ft' as const, requiredPallets: []},
- {mode: 'nft' as const, requiredPallets: []},
- {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
- ].map(testCase =>
- itSub.ifWithPallets(`Adding then removing a collection property doesn't change the consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ itSub('Adding then removing a collection property doesn\'t change the consumed space', async({helper}) => {
const propKey = 'tok-prop';
- const collection = await helper[testCase.mode].mintCollection(alice);
+ const collection = await helper[testSuite.mode].mintCollection(alice);
const originalSpace = await collection.getPropertiesConsumedSpace();
const propDataSize = 4096;
@@ -190,18 +165,12 @@
await collection.deleteProperties(alice, [propKey]);
consumedSpace = await collection.getPropertiesConsumedSpace();
expect(consumedSpace).to.be.equal(originalSpace);
- }));
+ });
- [
- // TODO enable properties for FT collection in Substrate (release 040)
- // {mode: 'ft' as const, requiredPallets: []},
- {mode: 'nft' as const, requiredPallets: []},
- {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
- ].map(testCase =>
- itSub.ifWithPallets(`Modifying a collection property with different sizes correctly changes the consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ itSub('Modifying a collection property with different sizes correctly changes the consumed space', async({helper}) => {
const propKey = 'tok-prop';
- const collection = await helper[testCase.mode].mintCollection(alice);
+ const collection = await helper[testSuite.mode].mintCollection(alice);
const originalSpace = await collection.getPropertiesConsumedSpace();
const initPropDataSize = 4096;
@@ -229,7 +198,8 @@
consumedSpace = await collection.getPropertiesConsumedSpace();
expectedConsumedSpaceDiff = biggerPropDataSize - smallerPropDataSize;
expect(consumedSpace).to.be.equal(biggerPropDataSize - expectedConsumedSpaceDiff);
- }));
+ });
+ }));
});
describe('Negative Integration Test: Collection Properties', () => {
@@ -242,119 +212,108 @@
[alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
});
});
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'ft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testSuite => describe(`${testSuite.mode.toUpperCase()}`, () => {
+ before(async function() {
+ // eslint-disable-next-line require-await
+ await usingPlaygrounds(async helper => {
+ requirePalletsOrSkip(this, helper, testSuite.requiredPallets);
+ });
+ });
- async function testFailsSetPropertiesIfNotOwnerOrAdmin(collection: UniqueBaseCollection) {
- await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))
- .to.be.rejectedWith(/common\.NoPermission/);
-
- expect(await collection.getProperties()).to.be.empty;
- }
-
- itSub('Fails to set properties in a NFT collection if not its onwer/administrator', async ({helper}) => {
- await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Fails to set properties in a ReFungible collection if not its onwer/administrator', [Pallets.ReFungible], async ({helper}) => {
- await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.rft.mintCollection(alice));
- });
+ itSub('Fails to set properties in a collection if not its onwer/administrator', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))
+ .to.be.rejectedWith(/common\.NoPermission/);
- async function testFailsSetPropertiesThatExeedLimits(collection: UniqueBaseCollection) {
- const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();
+ expect(await collection.getProperties()).to.be.empty;
+ });
- // Mute the general tx parsing error, too many bytes to process
- {
- console.error = () => {};
+ itSub('Fails to set properties that exceed the limits', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();
+
+ // Mute the general tx parsing error, too many bytes to process
+ {
+ console.error = () => {};
+ await expect(collection.setProperties(alice, [
+ {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))},
+ ])).to.be.rejected;
+ }
+
+ expect(await collection.getProperties(['electron'])).to.be.empty;
+
await expect(collection.setProperties(alice, [
- {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))},
- ])).to.be.rejected;
- }
-
- expect(await collection.getProperties(['electron'])).to.be.empty;
-
- await expect(collection.setProperties(alice, [
- {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))},
- {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))},
- ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);
-
- expect(await collection.getProperties(['electron', 'black_hole'])).to.be.empty;
- }
-
- itSub('Fails to set properties that exceed the limits (NFT)', async ({helper}) => {
- await testFailsSetPropertiesThatExeedLimits(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Fails to set properties that exceed the limits (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
- await testFailsSetPropertiesThatExeedLimits(await helper.rft.mintCollection(alice));
- });
+ {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))},
+ {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))},
+ ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);
- async function testFailsSetMorePropertiesThanAllowed(collection: UniqueBaseCollection) {
- const propertiesToBeSet = [];
- for (let i = 0; i < 65; i++) {
- propertiesToBeSet.push({
- key: 'electron_' + i,
- value: Math.random() > 0.5 ? 'high' : 'low',
- });
- }
-
- await expect(collection.setProperties(alice, propertiesToBeSet)).
- to.be.rejectedWith(/common\.PropertyLimitReached/);
-
- expect(await collection.getProperties()).to.be.empty;
- }
-
- itSub('Fails to set more properties than it is allowed (NFT)', async ({helper}) => {
- await testFailsSetMorePropertiesThanAllowed(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Fails to set more properties than it is allowed (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
- await testFailsSetMorePropertiesThanAllowed(await helper.rft.mintCollection(alice));
- });
+ expect(await collection.getProperties(['electron', 'black_hole'])).to.be.empty;
+ });
+
+ itSub('Fails to set more properties than it is allowed', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ const propertiesToBeSet = [];
+ for (let i = 0; i < 65; i++) {
+ propertiesToBeSet.push({
+ key: 'electron_' + i,
+ value: Math.random() > 0.5 ? 'high' : 'low',
+ });
+ }
+
+ await expect(collection.setProperties(alice, propertiesToBeSet)).
+ to.be.rejectedWith(/common\.PropertyLimitReached/);
+
+ expect(await collection.getProperties()).to.be.empty;
+ });
+
+ itSub('Fails to set properties with invalid names', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ const invalidProperties = [
+ [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],
+ [{key: 'Mr/Sandman', value: 'Bring me a gene'}],
+ [{key: 'déjà vu', value: 'hmm...'}],
+ ];
- async function testFailsSetPropertiesWithInvalidNames(collection: UniqueBaseCollection) {
- const invalidProperties = [
- [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],
- [{key: 'Mr/Sandman', value: 'Bring me a gene'}],
- [{key: 'déjà vu', value: 'hmm...'}],
- ];
-
- for (let i = 0; i < invalidProperties.length; i++) {
+ for (let i = 0; i < invalidProperties.length; i++) {
+ await expect(
+ collection.setProperties(alice, invalidProperties[i]),
+ `on rejecting the new badly-named property #${i}`,
+ ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
+ }
+
await expect(
- collection.setProperties(alice, invalidProperties[i]),
- `on rejecting the new badly-named property #${i}`,
- ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
- }
-
- await expect(
- collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]),
- 'on rejecting an unnamed property',
- ).to.be.rejectedWith(/common\.EmptyPropertyKey/);
-
- await expect(
- collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]),
- 'on setting the correctly-but-still-badly-named property',
- ).to.be.fulfilled;
-
- const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');
-
- const properties = await collection.getProperties(keys);
- expect(properties).to.be.deep.equal([
- {key: 'CRISPR-Cas9', value: 'rewriting nature!'},
- ]);
-
- for (let i = 0; i < invalidProperties.length; i++) {
+ collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]),
+ 'on rejecting an unnamed property',
+ ).to.be.rejectedWith(/common\.EmptyPropertyKey/);
+
await expect(
- collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)),
- `on trying to delete the non-existent badly-named property #${i}`,
- ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
- }
- }
-
- itSub('Fails to set properties with invalid names (NFT)', async ({helper}) => {
- await testFailsSetPropertiesWithInvalidNames(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Fails to set properties with invalid names (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
- await testFailsSetPropertiesWithInvalidNames(await helper.rft.mintCollection(alice));
- });
+ collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]),
+ 'on setting the correctly-but-still-badly-named property',
+ ).to.be.fulfilled;
+
+ const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');
+
+ const properties = await collection.getProperties(keys);
+ expect(properties).to.be.deep.equal([
+ {key: 'CRISPR-Cas9', value: 'rewriting nature!'},
+ ]);
+
+ for (let i = 0; i < invalidProperties.length; i++) {
+ await expect(
+ collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)),
+ `on trying to delete the non-existent badly-named property #${i}`,
+ ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
+ }
+ });
+ }));
});
\ No newline at end of file
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -80,6 +80,7 @@
requiredPallets.push(
refungible,
appPromotion,
+ foreignAssets,
);
} else if (chain.eq('UNIQUE')) {
// Insert Unique additional pallets here