difftreelog
feat eth all-in-one create_collection (#971)
in: master
* feat: setNesting api change * fix: change restricted collections to addresses instead of ids * feat: all in one create collection method * fix: code review requests * feat: use struct for create_collection flags * fix: update evm-coder dependency * fix: code review requests * fix: change pending_sponsor to optional cross address * feat: forbid user from using flags * refactor: deduplicate CollectionFlags struct * fix: eth CollectionMode should be NFT * style: fix clippy warning * fix: disable eth create_collection ---------
67 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2646,8 +2646,8 @@
[[package]]
name = "evm-coder"
-version = "0.3.1"
-source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.1#21e61c627f71337d6b8a03899fe8de14bfbf67aa"
+version = "0.3.6"
+source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.6#be59ae41a5d2ec9389bae22d54f81122b6ba55a4"
dependencies = [
"ethereum",
"evm-coder-procedural",
@@ -2658,8 +2658,8 @@
[[package]]
name = "evm-coder-procedural"
-version = "0.3.1"
-source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.1#21e61c627f71337d6b8a03899fe8de14bfbf67aa"
+version = "0.3.6"
+source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.6#be59ae41a5d2ec9389bae22d54f81122b6ba55a4"
dependencies = [
"Inflector",
"hex",
@@ -6489,6 +6489,7 @@
name = "pallet-common"
version = "0.1.14"
dependencies = [
+ "bondrewd",
"ethereum",
"evm-coder",
"frame-benchmarking",
@@ -7530,6 +7531,7 @@
"frame-benchmarking",
"frame-support",
"frame-system",
+ "log",
"pallet-balances-adapter",
"pallet-common",
"pallet-evm",
@@ -14097,6 +14099,7 @@
dependencies = [
"bondrewd",
"derivative",
+ "evm-coder",
"frame-support",
"pallet-evm",
"parity-scale-codec",
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -27,7 +27,7 @@
[workspace.dependencies]
# Unique
app-promotion-rpc = { path = "primitives/app_promotion_rpc", default-features = false }
-evm-coder = { git = "https://github.com/uniquenetwork/evm-coder", tag = "v0.3.1", default-features = false }
+evm-coder = { git = "https://github.com/uniquenetwork/evm-coder", tag = "v0.3.6", default-features = false, features = ['bondrewd'] }
pallet-app-promotion = { path = "pallets/app-promotion", default-features = false }
pallet-balances-adapter = { default-features = false, path = "pallets/balances-adapter" }
pallet-charge-transaction = { package = "pallet-template-transaction-payment", default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.43" }
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -10,6 +10,7 @@
scale-info = { workspace = true }
+bondrewd = { version = "0.1.14", features = ["derive"], default-features = false }
ethereum = { workspace = true }
evm-coder = { workspace = true }
frame-benchmarking = { workspace = true, optional = true }
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -21,10 +21,9 @@
use pallet_evm::account::CrossAccountId;
use frame_benchmarking::{benchmarks, account};
use up_data_structs::{
- CollectionMode, CollectionFlags, CreateCollectionData, CollectionId, Property, PropertyKey,
- PropertyValue, CollectionPermissions, NestingPermissions, AccessMode,
- MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
- MAX_PROPERTIES_PER_ITEM,
+ CollectionMode, CreateCollectionData, CollectionId, Property, PropertyKey, PropertyValue,
+ CollectionPermissions, NestingPermissions, AccessMode, MAX_COLLECTION_NAME_LENGTH,
+ MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, MAX_PROPERTIES_PER_ITEM,
};
use frame_support::{
traits::{Get, fungible::Balanced, Imbalance, tokens::Precision},
@@ -47,12 +46,7 @@
.unwrap()
}
pub fn create_var_data<const S: u32>(size: u32) -> BoundedVec<u8, ConstU32<S>> {
- assert!(
- size <= S,
- "size ({}) should be less within bound ({})",
- size,
- S
- );
+ assert!(size <= S, "size ({size}) should be less within bound ({S})",);
(0..size)
.map(|v| (v & 0xff) as u8)
.collect::<Vec<_>>()
@@ -81,7 +75,7 @@
mode: CollectionMode,
handler: impl FnOnce(
T::CrossAccountId,
- CreateCollectionData<T::AccountId>,
+ CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError>,
cast: impl FnOnce(CollectionHandle<T>) -> R,
) -> Result<R, DispatchError> {
@@ -124,9 +118,7 @@
create_collection_raw(
owner,
CollectionMode::NFT,
- |owner: T::CrossAccountId, data| {
- <Pallet<T>>::init_collection(owner.clone(), owner, data, CollectionFlags::default())
- },
+ |owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
|h| h,
)
}
pallets/common/src/dispatch.rsdiffbeforeafterboth--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -9,7 +9,7 @@
traits::Get,
};
use sp_runtime::DispatchError;
-use up_data_structs::{CollectionId, CreateCollectionData, CollectionFlags};
+use up_data_structs::{CollectionId, CreateCollectionData};
use crate::{pallet::Config, CommonCollectionOperations};
@@ -76,8 +76,7 @@
fn create(
sender: T::CrossAccountId,
payer: T::CrossAccountId,
- data: CreateCollectionData<T::AccountId>,
- flags: CollectionFlags,
+ data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError>;
/// Delete the collection.
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -402,10 +402,44 @@
Ok(())
}
+ #[solidity(rename_selector = "setCollectionNesting")]
+ fn set_nesting(
+ &mut self,
+ caller: Caller,
+ collection_nesting_and_permissions: eth::CollectionNestingAndPermission,
+ ) -> Result<()> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
+ let caller = T::CrossAccountId::from_eth(caller);
+
+ let mut permissions = self.collection.permissions.clone();
+ let mut nesting = permissions.nesting().clone();
+
+ let bv = if !collection_nesting_and_permissions.restricted.is_empty() {
+ let mut bv = OwnerRestrictedSet::new();
+ for address in collection_nesting_and_permissions.restricted.iter() {
+ bv.try_insert(crate::eth::map_eth_to_id(address).ok_or_else(|| {
+ Error::Revert("Can't convert address into collection id".into())
+ })?)
+ .map_err(|_| "too many collections")?;
+ }
+ Some(bv)
+ } else {
+ None
+ };
+
+ nesting.token_owner = collection_nesting_and_permissions.token_owner;
+ nesting.collection_admin = collection_nesting_and_permissions.collection_admin;
+ nesting.restricted = bv;
+ permissions.nesting = Some(nesting);
+
+ <Pallet<T>>::update_permissions(&caller, self, permissions).map_err(dispatch_to_evm::<T>)
+ }
+
/// Toggle accessibility of collection nesting.
///
/// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
- #[solidity(rename_selector = "setCollectionNesting")]
+ #[solidity(hide, rename_selector = "setCollectionNesting")]
fn set_nesting_bool(&mut self, caller: Caller, enable: bool) -> Result<()> {
self.consume_store_reads_and_writes(1, 1)?;
@@ -424,8 +458,8 @@
///
/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
/// @param collections Addresses of collections that will be available for nesting.
- #[solidity(rename_selector = "setCollectionNesting")]
- fn set_nesting(
+ #[solidity(hide, rename_selector = "setCollectionNesting")]
+ fn set_nesting_collection_ids(
&mut self,
caller: Caller,
enable: bool,
@@ -464,8 +498,28 @@
<Pallet<T>>::update_permissions(&caller, self, permissions).map_err(dispatch_to_evm::<T>)
}
+ #[solidity(rename_selector = "collectionNesting")]
+ fn collection_nesting(&self) -> Result<eth::CollectionNestingAndPermission> {
+ let nesting = self.collection.permissions.nesting();
+
+ Ok(eth::CollectionNestingAndPermission::new(
+ nesting.token_owner,
+ nesting.collection_admin,
+ nesting
+ .restricted
+ .clone()
+ .map(|b| {
+ b.0.into_inner()
+ .iter()
+ .map(|id| crate::eth::collection_id_to_address(id.0.into()))
+ .collect()
+ })
+ .unwrap_or_default(),
+ ))
+ }
+
/// Returns nesting for a collection
- #[solidity(rename_selector = "collectionNestingRestrictedCollectionIds")]
+ #[solidity(hide, rename_selector = "collectionNestingRestrictedCollectionIds")]
fn collection_nesting_restricted_ids(&self) -> Result<eth::CollectionNesting> {
let nesting = self.collection.permissions.nesting();
@@ -480,6 +534,7 @@
}
/// Returns permissions for a collection
+ #[solidity(hide)]
fn collection_nesting_permissions(&self) -> Result<Vec<eth::CollectionNestingPermission>> {
let nesting = self.collection.permissions.nesting();
Ok(vec![
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -24,7 +24,8 @@
};
pub use pallet_evm::{Config, account::CrossAccountId};
use sp_core::{H160, U256};
-use up_data_structs::CollectionId;
+use up_data_structs::{CollectionId, CollectionFlags};
+use pallet_evm_coder_substrate::execution::Error;
// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 1
// TODO: Unhardcode prefix
@@ -104,10 +105,26 @@
sub: Default::default(),
}
}
+
+ /// Converts [`CrossAddress`] to `Option<CrossAccountId>`.
+ pub fn into_option_sub_cross_account<T>(&self) -> Result<Option<T::CrossAccountId>, Error>
+ where
+ T: pallet_evm::Config,
+ T::AccountId: From<[u8; 32]>,
+ {
+ if self.eth == Default::default() && self.sub == Default::default() {
+ Ok(None)
+ } else if self.eth == Default::default() {
+ Ok(Some(convert_uint256_to_cross_account::<T>(self.sub)))
+ } else if self.sub == Default::default() {
+ Ok(Some(T::CrossAccountId::from_eth(self.eth)))
+ } else {
+ Err(format!("All fields of cross account is non zeroed {:?}", self).into())
+ }
+ }
+
/// Converts [`CrossAddress`] to `CrossAccountId`.
- pub fn into_sub_cross_account<T>(
- &self,
- ) -> pallet_evm_coder_substrate::execution::Result<T::CrossAccountId>
+ pub fn into_sub_cross_account<T>(&self) -> Result<T::CrossAccountId, Error>
where
T: pallet_evm::Config,
T::AccountId: From<[u8; 32]>,
@@ -124,6 +141,19 @@
}
}
+/// Type of tokens in collection
+#[derive(AbiCoder, Copy, Clone, Default, Debug, PartialEq)]
+#[repr(u8)]
+pub enum CollectionMode {
+ /// Nonfungible
+ #[default]
+ Nonfungible,
+ /// Fungible
+ Fungible,
+ /// Refungible
+ Refungible,
+}
+
/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).
#[derive(Debug, Default, AbiCoder)]
pub struct Property {
@@ -144,7 +174,7 @@
}
impl TryFrom<up_data_structs::Property> for Property {
- type Error = pallet_evm_coder_substrate::execution::Error;
+ type Error = Error;
fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {
let key = evm_coder::types::String::from_utf8(from.key.into())
@@ -155,7 +185,7 @@
}
impl TryInto<up_data_structs::Property> for Property {
- type Error = pallet_evm_coder_substrate::execution::Error;
+ type Error = Error;
fn try_into(self) -> Result<up_data_structs::Property, Self::Error> {
let key = <Vec<u8>>::from(self.key)
@@ -220,17 +250,14 @@
pub fn has_value(&self) -> bool {
self.value.is_some()
}
-}
-impl TryInto<up_data_structs::CollectionLimits> for CollectionLimit {
- type Error = pallet_evm_coder_substrate::execution::Error;
-
- fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {
+ /// Set corresponding property in CollectionLimits struct
+ pub fn apply_limit(&self, limits: &mut up_data_structs::CollectionLimits) -> Result<(), Error> {
let value = self
.value
- .ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;
+ .ok_or::<Error>("can't convert `None` value to boolean".into())?;
let value = Some(value.try_into().map_err(|error| {
- Self::Error::Revert(format!(
+ Error::Revert(format!(
"can't convert value to u32 \"{value}\" because: \"{error}\""
))
})?);
@@ -239,14 +266,13 @@
Some(value) => match value {
0 => Ok(Some(false)),
1 => Ok(Some(true)),
- _ => Err(Self::Error::Revert(format!(
+ _ => Err(Error::Revert(format!(
"can't convert value to boolean \"{value}\""
))),
},
None => Ok(None),
};
- let mut limits = up_data_structs::CollectionLimits::default();
match self.field {
CollectionLimitField::AccountTokenOwnership => {
limits.account_token_ownership_limit = value;
@@ -277,10 +303,99 @@
limits.transfers_enabled = convert_value_to_bool()?;
}
};
+ Ok(())
+ }
+}
+
+/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
+#[derive(Debug, Default, AbiCoder)]
+pub struct CollectionLimitValue {
+ field: CollectionLimitField,
+ value: U256,
+}
+
+impl CollectionLimitValue {
+ /// Create [`CollectionLimitValue`] from field and value.
+ pub fn new(field: CollectionLimitField, value: u32) -> Self {
+ Self {
+ field,
+ value: value.into(),
+ }
+ }
+
+ /// Set corresponding property in CollectionLimits struct
+ pub fn apply_limit(&self, limits: &mut up_data_structs::CollectionLimits) -> Result<(), Error> {
+ let value = self.value;
+ let value: u32 = value.try_into().map_err(|error| {
+ Error::Revert(format!(
+ "can't convert value to u32 \"{value}\" because: \"{error}\""
+ ))
+ })?;
+
+ let convert_value_to_bool = || match value {
+ 0 => Ok(Some(false)),
+ 1 => Ok(Some(true)),
+ _ => Err(Error::Revert(format!(
+ "can't convert value to boolean \"{value}\""
+ ))),
+ };
+
+ match self.field {
+ CollectionLimitField::AccountTokenOwnership => {
+ limits.account_token_ownership_limit = Some(value);
+ }
+ CollectionLimitField::SponsoredDataSize => {
+ limits.sponsored_data_size = Some(value);
+ }
+ CollectionLimitField::SponsoredDataRateLimit => {
+ limits.sponsored_data_rate_limit =
+ Some(up_data_structs::SponsoringRateLimit::Blocks(value));
+ }
+ CollectionLimitField::TokenLimit => {
+ limits.token_limit = Some(value);
+ }
+ CollectionLimitField::SponsorTransferTimeout => {
+ limits.sponsor_transfer_timeout = Some(value);
+ }
+ CollectionLimitField::SponsorApproveTimeout => {
+ limits.sponsor_approve_timeout = Some(value);
+ }
+ CollectionLimitField::OwnerCanTransfer => {
+ limits.owner_can_transfer = convert_value_to_bool()?;
+ }
+ CollectionLimitField::OwnerCanDestroy => {
+ limits.owner_can_destroy = convert_value_to_bool()?;
+ }
+ CollectionLimitField::TransferEnabled => {
+ limits.transfers_enabled = convert_value_to_bool()?;
+ }
+ };
+ Ok(())
+ }
+}
+
+impl TryInto<up_data_structs::CollectionLimits> for CollectionLimit {
+ type Error = Error;
+
+ fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {
+ let mut limits = up_data_structs::CollectionLimits::default();
+ self.apply_limit(&mut limits)?;
Ok(limits)
}
}
+impl FromIterator<CollectionLimitValue> for Result<up_data_structs::CollectionLimits, Error> {
+ fn from_iter<T: IntoIterator<Item = CollectionLimitValue>>(
+ iter: T,
+ ) -> Result<up_data_structs::CollectionLimits, Error> {
+ let mut limits = up_data_structs::CollectionLimits::default();
+ for value in iter.into_iter() {
+ value.apply_limit(&mut limits)?;
+ }
+ Ok(limits)
+ }
+}
+
/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) fields as an enumeration.
#[derive(Default, Debug, Clone, Copy, AbiCoder)]
#[repr(u8)]
@@ -384,8 +499,7 @@
/// Convert vector of [`TokenPropertyPermission`] into vector of [`up_data_structs::PropertyKeyPermission`].
pub fn into_property_key_permissions(
permissions: Vec<TokenPropertyPermission>,
- ) -> pallet_evm_coder_substrate::execution::Result<Vec<up_data_structs::PropertyKeyPermission>>
- {
+ ) -> Result<Vec<up_data_structs::PropertyKeyPermission>, Error> {
let mut perms = Vec::new();
for TokenPropertyPermission { key, permissions } in permissions {
@@ -410,6 +524,57 @@
pub uri: String,
}
+/// Nested collections and permissions
+#[derive(Debug, Default, AbiCoder)]
+pub struct CollectionNestingAndPermission {
+ /// Owner of token can nest tokens under it.
+ pub token_owner: bool,
+ /// Admin of token collection can nest tokens under token.
+ pub collection_admin: bool,
+ /// If set - only tokens from specified collections can be nested.
+ pub restricted: Vec<Address>,
+}
+
+impl CollectionNestingAndPermission {
+ /// Create [`CollectionNesting`].
+ pub fn new(token_owner: bool, collection_admin: bool, restricted: Vec<Address>) -> Self {
+ Self {
+ token_owner,
+ collection_admin,
+ restricted,
+ }
+ }
+}
+
+/// Collection properties
+#[derive(Debug, Default, AbiCoder)]
+pub struct CreateCollectionData {
+ /// Collection sponsor
+ pub pending_sponsor: CrossAddress,
+ /// Collection name
+ pub name: String,
+ /// Collection description
+ pub description: String,
+ /// Token prefix
+ pub token_prefix: String,
+ /// Token type (NFT, FT or RFT)
+ pub mode: CollectionMode,
+ /// Fungible token precision
+ pub decimals: u8,
+ /// Custom Properties
+ pub properties: Vec<Property>,
+ /// Permissions for token properties
+ pub token_property_permissions: Vec<TokenPropertyPermission>,
+ /// Collection admins
+ pub admin_list: Vec<CrossAddress>,
+ /// Nesting settings
+ pub nesting_settings: CollectionNestingAndPermission,
+ /// Collection limits
+ pub limits: Vec<CollectionLimitValue>,
+ /// Extra collection flags
+ pub flags: CollectionFlags,
+}
+
/// Nested collections.
#[derive(Debug, Default, AbiCoder)]
pub struct CollectionNesting {
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -73,16 +73,15 @@
transactional, fail,
};
use up_data_structs::{
- AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionFlags,
- RpcCollectionFlags, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,
- COLLECTION_ADMINS_LIMIT, TokenId, TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP,
- CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
- REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,
- CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit, budget::Budget,
- PhantomType, Property, CollectionProperties as CollectionPropertiesT, TokenProperties,
- PropertiesPermissionMap, PropertyKey, PropertyValue, PropertyPermission, PropertiesError,
- TokenOwnerError, PropertyKeyPermission, TokenData, TrySetProperty, PropertyScope,
- CollectionPermissions,
+ AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, RpcCollectionFlags,
+ CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, TokenId,
+ TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,
+ FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,
+ CUSTOM_DATA_LIMIT, CollectionLimits, CreateCollectionData, SponsorshipState, CreateItemExData,
+ SponsoringRateLimit, budget::Budget, PhantomType, Property,
+ CollectionProperties as CollectionPropertiesT, TokenProperties, PropertiesPermissionMap,
+ PropertyKey, PropertyValue, PropertyPermission, PropertiesError, TokenOwnerError,
+ PropertyKeyPermission, TokenData, TrySetProperty, PropertyScope, CollectionPermissions,
};
use up_pov_estimate_rpc::PovInfo;
@@ -1094,9 +1093,28 @@
pub fn init_collection(
owner: T::CrossAccountId,
payer: T::CrossAccountId,
- data: CreateCollectionData<T::AccountId>,
- flags: CollectionFlags,
+ data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError> {
+ ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);
+ Self::init_collection_internal(owner, payer, data)
+ }
+
+ /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.
+ pub fn init_foreign_collection(
+ owner: T::CrossAccountId,
+ payer: T::CrossAccountId,
+ mut data: CreateCollectionData<T::CrossAccountId>,
+ ) -> Result<CollectionId, DispatchError> {
+ data.flags.foreign = true;
+ let id = Self::init_collection_internal(owner, payer, data)?;
+ Ok(id)
+ }
+
+ fn init_collection_internal(
+ owner: T::CrossAccountId,
+ payer: T::CrossAccountId,
+ data: CreateCollectionData<T::CrossAccountId>,
+ ) -> Result<CollectionId, DispatchError> {
{
ensure!(
data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,
@@ -1127,7 +1145,7 @@
token_prefix: data.token_prefix,
sponsorship: data
.pending_sponsor
- .map(SponsorshipState::Unconfirmed)
+ .map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))
.unwrap_or_default(),
limits: data
.limits
@@ -1139,7 +1157,7 @@
Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)
})
.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,
- flags,
+ flags: data.flags,
};
let mut collection_properties = CollectionPropertiesT::new();
@@ -1156,6 +1174,21 @@
CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);
+ let mut admin_amount = 0u32;
+ for admin in data.admin_list.iter() {
+ if !<IsAdmin<T>>::get((id, admin)) {
+ <IsAdmin<T>>::insert((id, admin), true);
+ admin_amount = admin_amount
+ .checked_add(1)
+ .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;
+ }
+ }
+ ensure!(
+ admin_amount <= Self::collection_admins_limit(),
+ <Error<T>>::CollectionAdminCountExceeded,
+ );
+ <AdminAmount<T>>::insert(id, admin_amount);
+
// Take a (non-refundable) deposit of collection creation
{
let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();
pallets/foreign-assets/src/lib.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -42,9 +42,9 @@
RuntimeDebug,
};
use frame_system::pallet_prelude::*;
-use up_data_structs::{CollectionMode};
-use pallet_fungible::{Pallet as PalletFungible};
-use scale_info::{TypeInfo};
+use up_data_structs::CollectionMode;
+use pallet_fungible::Pallet as PalletFungible;
+use scale_info::TypeInfo;
use sp_runtime::{
traits::{One, Zero},
ArithmeticError,
@@ -304,7 +304,7 @@
.collect::<Vec<u16>>();
description.append(&mut name.clone());
- let data: CreateCollectionData<T::AccountId> = CreateCollectionData {
+ let data: CreateCollectionData<T::CrossAccountId> = CreateCollectionData {
name: name.try_into().unwrap(),
description: description.try_into().unwrap(),
mode: CollectionMode::Fungible(md.decimals),
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -31,9 +31,7 @@
create_collection_raw(
owner,
CollectionMode::Fungible(0),
- |owner: T::CrossAccountId, data| {
- <Pallet<T>>::init_collection(owner.clone(), owner, data, Default::default())
- },
+ |owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
FungibleHandle::cast,
)
}
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -87,8 +87,8 @@
};
use pallet_evm::account::CrossAccountId;
use up_data_structs::{
- AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,
- mapping::TokenAddressMapping, budget::Budget, PropertyKey, Property,
+ AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,
+ budget::Budget, PropertyKey, Property,
};
use pallet_common::{
Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
@@ -219,28 +219,18 @@
pub fn init_collection(
owner: T::CrossAccountId,
payer: T::CrossAccountId,
- data: CreateCollectionData<T::AccountId>,
- flags: CollectionFlags,
+ data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, payer, data, flags)
+ <PalletCommon<T>>::init_collection(owner, payer, data)
}
/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.
pub fn init_foreign_collection(
owner: T::CrossAccountId,
payer: T::CrossAccountId,
- data: CreateCollectionData<T::AccountId>,
+ data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError> {
- let id = <PalletCommon<T>>::init_collection(
- owner,
- payer,
- data,
- CollectionFlags {
- foreign: true,
- ..Default::default()
- },
- )?;
- Ok(id)
+ <PalletCommon<T>>::init_foreign_collection(owner, payer, data)
}
/// Destroys a collection.
pallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -18,7 +18,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
+/// @dev the ERC-165 identifier for this interface is 0xb34d97e9
contract Collection is Dummy, ERC165 {
// /// Set collection property.
// ///
@@ -230,47 +230,63 @@
// dummy = 0;
// }
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
- /// @dev EVM selector for this function is: 0x112d4586,
- /// or in textual repr: setCollectionNesting(bool)
- function setCollectionNesting(bool enable) public {
+ /// @dev EVM selector for this function is: 0x0b9f3890,
+ /// or in textual repr: setCollectionNesting((bool,bool,address[]))
+ function setCollectionNesting(CollectionNestingAndPermission memory collectionNestingAndPermissions) public {
require(false, stub_error);
- enable;
+ collectionNestingAndPermissions;
dummy = 0;
}
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
- /// @param collections Addresses of collections that will be available for nesting.
- /// @dev EVM selector for this function is: 0x64872396,
- /// or in textual repr: setCollectionNesting(bool,address[])
- function setCollectionNesting(bool enable, address[] memory collections) public {
- require(false, stub_error);
- enable;
- collections;
- dummy = 0;
- }
+ // /// Toggle accessibility of collection nesting.
+ // ///
+ // /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
+ // /// @dev EVM selector for this function is: 0x112d4586,
+ // /// or in textual repr: setCollectionNesting(bool)
+ // function setCollectionNesting(bool enable) public {
+ // require(false, stub_error);
+ // enable;
+ // dummy = 0;
+ // }
+
+ // /// Toggle accessibility of collection nesting.
+ // ///
+ // /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
+ // /// @param collections Addresses of collections that will be available for nesting.
+ // /// @dev EVM selector for this function is: 0x64872396,
+ // /// or in textual repr: setCollectionNesting(bool,address[])
+ // function setCollectionNesting(bool enable, address[] memory collections) public {
+ // require(false, stub_error);
+ // enable;
+ // collections;
+ // dummy = 0;
+ // }
- /// Returns nesting for a collection
- /// @dev EVM selector for this function is: 0x22d25bfe,
- /// or in textual repr: collectionNestingRestrictedCollectionIds()
- function collectionNestingRestrictedCollectionIds() public view returns (CollectionNesting memory) {
+ /// @dev EVM selector for this function is: 0x92c660a8,
+ /// or in textual repr: collectionNesting()
+ function collectionNesting() public view returns (CollectionNestingAndPermission memory) {
require(false, stub_error);
dummy;
- return CollectionNesting(false, new uint256[](0));
+ return CollectionNestingAndPermission(false, false, new address[](0));
}
- /// Returns permissions for a collection
- /// @dev EVM selector for this function is: 0x5b2eaf4b,
- /// or in textual repr: collectionNestingPermissions()
- function collectionNestingPermissions() public view returns (CollectionNestingPermission[] memory) {
- require(false, stub_error);
- dummy;
- return new CollectionNestingPermission[](0);
- }
+ // /// Returns nesting for a collection
+ // /// @dev EVM selector for this function is: 0x22d25bfe,
+ // /// or in textual repr: collectionNestingRestrictedCollectionIds()
+ // function collectionNestingRestrictedCollectionIds() public view returns (CollectionNesting memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return CollectionNesting(false,new uint256[](0));
+ // }
+
+ // /// Returns permissions for a collection
+ // /// @dev EVM selector for this function is: 0x5b2eaf4b,
+ // /// or in textual repr: collectionNestingPermissions()
+ // function collectionNestingPermissions() public view returns (CollectionNestingPermission[] memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return new CollectionNestingPermission[](0);
+ // }
/// Set the collection access method.
/// @param mode Access mode
@@ -469,6 +485,16 @@
uint256[] ids;
}
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+ /// Owner of token can nest tokens under it.
+ bool token_owner;
+ /// Admin of token collection can nest tokens under token.
+ bool collection_admin;
+ /// If set - only tokens from specified collections can be nested.
+ address[] restricted;
+}
+
/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
struct CollectionLimit {
CollectionLimitField field;
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -57,9 +57,7 @@
create_collection_raw(
owner,
CollectionMode::NFT,
- |owner: T::CrossAccountId, data| {
- <Pallet<T>>::init_collection(owner.clone(), owner, data, Default::default())
- },
+ |owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
NonfungibleHandle::cast,
)
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -100,10 +100,10 @@
dispatch::{PostDispatchInfo, Pays},
};
use up_data_structs::{
- AccessMode, CollectionId, CollectionFlags, CustomDataLimit, TokenId, CreateCollectionData,
- CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey,
- PropertyValue, PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild,
- AuxPropertyValue, PropertiesPermissionMap, TokenProperties as TokenPropertiesT,
+ AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
+ mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,
+ PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild, AuxPropertyValue,
+ PropertiesPermissionMap, TokenProperties as TokenPropertiesT,
};
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_common::{
@@ -424,10 +424,9 @@
pub fn init_collection(
owner: T::CrossAccountId,
payer: T::CrossAccountId,
- data: CreateCollectionData<T::AccountId>,
- flags: CollectionFlags,
+ data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, payer, data, flags)
+ <PalletCommon<T>>::init_collection(owner, payer, data)
}
/// Destroy NFT collection
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -165,7 +165,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
+/// @dev the ERC-165 identifier for this interface is 0xb34d97e9
contract Collection is Dummy, ERC165 {
// /// Set collection property.
// ///
@@ -377,47 +377,63 @@
// dummy = 0;
// }
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
- /// @dev EVM selector for this function is: 0x112d4586,
- /// or in textual repr: setCollectionNesting(bool)
- function setCollectionNesting(bool enable) public {
+ /// @dev EVM selector for this function is: 0x0b9f3890,
+ /// or in textual repr: setCollectionNesting((bool,bool,address[]))
+ function setCollectionNesting(CollectionNestingAndPermission memory collectionNestingAndPermissions) public {
require(false, stub_error);
- enable;
+ collectionNestingAndPermissions;
dummy = 0;
}
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
- /// @param collections Addresses of collections that will be available for nesting.
- /// @dev EVM selector for this function is: 0x64872396,
- /// or in textual repr: setCollectionNesting(bool,address[])
- function setCollectionNesting(bool enable, address[] memory collections) public {
- require(false, stub_error);
- enable;
- collections;
- dummy = 0;
- }
+ // /// Toggle accessibility of collection nesting.
+ // ///
+ // /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
+ // /// @dev EVM selector for this function is: 0x112d4586,
+ // /// or in textual repr: setCollectionNesting(bool)
+ // function setCollectionNesting(bool enable) public {
+ // require(false, stub_error);
+ // enable;
+ // dummy = 0;
+ // }
+
+ // /// Toggle accessibility of collection nesting.
+ // ///
+ // /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
+ // /// @param collections Addresses of collections that will be available for nesting.
+ // /// @dev EVM selector for this function is: 0x64872396,
+ // /// or in textual repr: setCollectionNesting(bool,address[])
+ // function setCollectionNesting(bool enable, address[] memory collections) public {
+ // require(false, stub_error);
+ // enable;
+ // collections;
+ // dummy = 0;
+ // }
- /// Returns nesting for a collection
- /// @dev EVM selector for this function is: 0x22d25bfe,
- /// or in textual repr: collectionNestingRestrictedCollectionIds()
- function collectionNestingRestrictedCollectionIds() public view returns (CollectionNesting memory) {
+ /// @dev EVM selector for this function is: 0x92c660a8,
+ /// or in textual repr: collectionNesting()
+ function collectionNesting() public view returns (CollectionNestingAndPermission memory) {
require(false, stub_error);
dummy;
- return CollectionNesting(false, new uint256[](0));
+ return CollectionNestingAndPermission(false, false, new address[](0));
}
- /// Returns permissions for a collection
- /// @dev EVM selector for this function is: 0x5b2eaf4b,
- /// or in textual repr: collectionNestingPermissions()
- function collectionNestingPermissions() public view returns (CollectionNestingPermission[] memory) {
- require(false, stub_error);
- dummy;
- return new CollectionNestingPermission[](0);
- }
+ // /// Returns nesting for a collection
+ // /// @dev EVM selector for this function is: 0x22d25bfe,
+ // /// or in textual repr: collectionNestingRestrictedCollectionIds()
+ // function collectionNestingRestrictedCollectionIds() public view returns (CollectionNesting memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return CollectionNesting(false,new uint256[](0));
+ // }
+
+ // /// Returns permissions for a collection
+ // /// @dev EVM selector for this function is: 0x5b2eaf4b,
+ // /// or in textual repr: collectionNestingPermissions()
+ // function collectionNestingPermissions() public view returns (CollectionNestingPermission[] memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return new CollectionNestingPermission[](0);
+ // }
/// Set the collection access method.
/// @param mode Access mode
@@ -616,6 +632,16 @@
uint256[] ids;
}
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+ /// Owner of token can nest tokens under it.
+ bool token_owner;
+ /// Admin of token collection can nest tokens under token.
+ bool collection_admin;
+ /// If set - only tokens from specified collections can be nested.
+ address[] restricted;
+}
+
/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
struct CollectionLimit {
CollectionLimitField field;
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -61,9 +61,7 @@
create_collection_raw(
owner,
CollectionMode::ReFungible,
- |owner: T::CrossAccountId, data| {
- <Pallet<T>>::init_collection(owner.clone(), owner, data, Default::default())
- },
+ |owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
RefungibleHandle::cast,
)
}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -104,11 +104,10 @@
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
use up_data_structs::{
- AccessMode, budget::Budget, CollectionId, CollectionFlags, CreateCollectionData,
- mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, Property, PropertyKey,
- PropertyKeyPermission, PropertyScope, PropertyValue, TokenId, TrySetProperty,
- PropertiesPermissionMap, CreateRefungibleExMultipleOwners, TokenOwnerError,
- TokenProperties as TokenPropertiesT,
+ AccessMode, budget::Budget, CollectionId, CreateCollectionData, mapping::TokenAddressMapping,
+ MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyScope,
+ PropertyValue, TokenId, TrySetProperty, PropertiesPermissionMap,
+ CreateRefungibleExMultipleOwners, TokenOwnerError, TokenProperties as TokenPropertiesT,
};
pub use pallet::*;
@@ -334,10 +333,9 @@
pub fn init_collection(
owner: T::CrossAccountId,
payer: T::CrossAccountId,
- data: CreateCollectionData<T::AccountId>,
- flags: CollectionFlags,
+ data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, payer, data, flags)
+ <PalletCommon<T>>::init_collection(owner, payer, data)
}
/// Destroy RFT collection
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -165,7 +165,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
+/// @dev the ERC-165 identifier for this interface is 0xb34d97e9
contract Collection is Dummy, ERC165 {
// /// Set collection property.
// ///
@@ -377,47 +377,63 @@
// dummy = 0;
// }
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
- /// @dev EVM selector for this function is: 0x112d4586,
- /// or in textual repr: setCollectionNesting(bool)
- function setCollectionNesting(bool enable) public {
+ /// @dev EVM selector for this function is: 0x0b9f3890,
+ /// or in textual repr: setCollectionNesting((bool,bool,address[]))
+ function setCollectionNesting(CollectionNestingAndPermission memory collectionNestingAndPermissions) public {
require(false, stub_error);
- enable;
+ collectionNestingAndPermissions;
dummy = 0;
}
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
- /// @param collections Addresses of collections that will be available for nesting.
- /// @dev EVM selector for this function is: 0x64872396,
- /// or in textual repr: setCollectionNesting(bool,address[])
- function setCollectionNesting(bool enable, address[] memory collections) public {
- require(false, stub_error);
- enable;
- collections;
- dummy = 0;
- }
+ // /// Toggle accessibility of collection nesting.
+ // ///
+ // /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
+ // /// @dev EVM selector for this function is: 0x112d4586,
+ // /// or in textual repr: setCollectionNesting(bool)
+ // function setCollectionNesting(bool enable) public {
+ // require(false, stub_error);
+ // enable;
+ // dummy = 0;
+ // }
+
+ // /// Toggle accessibility of collection nesting.
+ // ///
+ // /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
+ // /// @param collections Addresses of collections that will be available for nesting.
+ // /// @dev EVM selector for this function is: 0x64872396,
+ // /// or in textual repr: setCollectionNesting(bool,address[])
+ // function setCollectionNesting(bool enable, address[] memory collections) public {
+ // require(false, stub_error);
+ // enable;
+ // collections;
+ // dummy = 0;
+ // }
- /// Returns nesting for a collection
- /// @dev EVM selector for this function is: 0x22d25bfe,
- /// or in textual repr: collectionNestingRestrictedCollectionIds()
- function collectionNestingRestrictedCollectionIds() public view returns (CollectionNesting memory) {
+ /// @dev EVM selector for this function is: 0x92c660a8,
+ /// or in textual repr: collectionNesting()
+ function collectionNesting() public view returns (CollectionNestingAndPermission memory) {
require(false, stub_error);
dummy;
- return CollectionNesting(false, new uint256[](0));
+ return CollectionNestingAndPermission(false, false, new address[](0));
}
- /// Returns permissions for a collection
- /// @dev EVM selector for this function is: 0x5b2eaf4b,
- /// or in textual repr: collectionNestingPermissions()
- function collectionNestingPermissions() public view returns (CollectionNestingPermission[] memory) {
- require(false, stub_error);
- dummy;
- return new CollectionNestingPermission[](0);
- }
+ // /// Returns nesting for a collection
+ // /// @dev EVM selector for this function is: 0x22d25bfe,
+ // /// or in textual repr: collectionNestingRestrictedCollectionIds()
+ // function collectionNestingRestrictedCollectionIds() public view returns (CollectionNesting memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return CollectionNesting(false,new uint256[](0));
+ // }
+
+ // /// Returns permissions for a collection
+ // /// @dev EVM selector for this function is: 0x5b2eaf4b,
+ // /// or in textual repr: collectionNestingPermissions()
+ // function collectionNestingPermissions() public view returns (CollectionNestingPermission[] memory) {
+ // require(false, stub_error);
+ // dummy;
+ // return new CollectionNestingPermission[](0);
+ // }
/// Set the collection access method.
/// @param mode Access mode
@@ -616,6 +632,16 @@
uint256[] ids;
}
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+ /// Owner of token can nest tokens under it.
+ bool token_owner;
+ /// Admin of token collection can nest tokens under token.
+ bool collection_admin;
+ /// If set - only tokens from specified collections can be nested.
+ address[] restricted;
+}
+
/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
struct CollectionLimit {
CollectionLimitField field;
pallets/structure/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/structure/src/benchmarking.rs
+++ b/pallets/structure/src/benchmarking.rs
@@ -40,7 +40,6 @@
mode: CollectionMode::NFT,
..Default::default()
},
- CollectionFlags::default(),
)?;
let dispatch = T::CollectionDispatch::dispatch(CollectionId(1))?;
let dispatch = dispatch.as_dyn();
pallets/unique/Cargo.tomldiffbeforeafterboth--- a/pallets/unique/Cargo.toml
+++ b/pallets/unique/Cargo.toml
@@ -47,6 +47,7 @@
frame-benchmarking = { workspace = true, optional = true }
frame-support = { workspace = true }
frame-system = { workspace = true }
+log = { workspace = true }
pallet-balances-adapter = { workspace = true }
pallet-common = { workspace = true }
pallet-evm = { workspace = true }
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -15,18 +15,16 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
//! Implementation of CollectionHelpers contract.
-
+//!
use core::marker::PhantomData;
use ethereum as _;
use evm_coder::{abi::AbiType, generate_stubgen, solidity_interface, types::*};
-use frame_support::traits::Get;
-use crate::Pallet;
-
+use frame_support::{BoundedVec, traits::Get};
use pallet_common::{
CollectionById,
dispatch::CollectionDispatch,
erc::{CollectionHelpersEvents, static_property::key},
- eth::{map_eth_to_id, collection_id_to_address},
+ eth::{self, map_eth_to_id, collection_id_to_address},
Pallet as PalletCommon, CollectionHandle,
};
use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
@@ -36,13 +34,13 @@
frontier_contract,
};
use up_data_structs::{
- CollectionDescription, CollectionMode, CollectionName, CollectionTokenPrefix,
- CreateCollectionData,
+ CollectionDescription, CollectionMode, CollectionName, CollectionPermissions,
+ CollectionTokenPrefix, CreateCollectionData, NestingPermissions,
};
-use crate::{weights::WeightInfo, Config, SelfWeightOf};
+use crate::{weights::WeightInfo, Config, Pallet, SelfWeightOf};
-use alloc::format;
+use alloc::{format, collections::BTreeSet};
use sp_std::vec::Vec;
frontier_contract! {
@@ -113,9 +111,8 @@
let collection_helpers_address =
T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id =
- T::CollectionDispatch::create(caller, collection_helpers_address, data, Default::default())
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
}
@@ -140,7 +137,119 @@
impl<T> EvmCollectionHelpers<T>
where
T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,
+ T::AccountId: From<[u8; 32]>,
{
+/*
+ /// Create a collection
+ /// @return address Address of the newly created collection
+ #[weight(<SelfWeightOf<T>>::create_collection())]
+ #[solidity(rename_selector = "createCollection")]
+ fn create_collection(
+ &mut self,
+ caller: Caller,
+ value: Value,
+ data: eth::CreateCollectionData,
+ ) -> Result<Address> {
+ let (caller, name, description, token_prefix) =
+ convert_data::<T>(caller, data.name, data.description, data.token_prefix)?;
+ if data.mode != eth::CollectionMode::Fungible && data.decimals != 0 {
+ return Err("decimals are only supported for NFT and RFT collections".into());
+ }
+ let mode = match data.mode {
+ eth::CollectionMode::Fungible => CollectionMode::Fungible(data.decimals),
+ eth::CollectionMode::Nonfungible => CollectionMode::NFT,
+ eth::CollectionMode::Refungible => CollectionMode::ReFungible,
+ };
+
+ let properties: BoundedVec<_, _> = data
+ .properties
+ .into_iter()
+ .map(eth::Property::try_into)
+ .collect::<Result<Vec<_>>>()?
+ .try_into()
+ .map_err(|_| "too many properties")?;
+
+ let token_property_permissions =
+ eth::TokenPropertyPermission::into_property_key_permissions(
+ data.token_property_permissions,
+ )?
+ .try_into()
+ .map_err(|_| "too many property permissions")?;
+
+ let limits = if !data.limits.is_empty() {
+ Some(
+ data.limits
+ .into_iter()
+ .collect::<Result<up_data_structs::CollectionLimits>>()?,
+ )
+ } else {
+ None
+ };
+
+ let pending_sponsor = data.pending_sponsor.into_option_sub_cross_account::<T>()?;
+
+ let restricted = if !data.nesting_settings.restricted.is_empty() {
+ Some(
+ data.nesting_settings
+ .restricted
+ .iter()
+ .map(map_eth_to_id)
+ .collect::<Option<BTreeSet<_>>>()
+ .ok_or("can't convert address into collection id")?
+ .try_into()
+ .map_err(|_| "too many collections")?,
+ )
+ } else {
+ None
+ };
+
+ let admin_list = data
+ .admin_list
+ .into_iter()
+ .map(|admin| admin.into_sub_cross_account::<T>())
+ .collect::<Result<Vec<_>>>()?;
+
+ let flags = data.flags;
+ if !flags.is_allowed_for_user() {
+ return Err("internal flags were used".into());
+ }
+
+ let data = CreateCollectionData {
+ name,
+ mode,
+ description,
+ token_prefix,
+ properties,
+ token_property_permissions,
+ limits,
+ pending_sponsor,
+ access: None,
+ permissions: Some(CollectionPermissions {
+ access: None,
+ mint_mode: None,
+ nesting: Some(NestingPermissions {
+ token_owner: data.nesting_settings.token_owner,
+ collection_admin: data.nesting_settings.collection_admin,
+ restricted,
+ #[cfg(feature = "runtime-benchmarks")]
+ permissive: true,
+ }),
+ }),
+ admin_list,
+ flags,
+ };
+ check_sent_amount_equals_collection_creation_price::<T>(value)?;
+ let collection_helpers_address =
+ T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
+
+ let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
+ .map_err(dispatch_to_evm::<T>)?;
+
+ let address = pallet_common::eth::collection_id_to_address(collection_id);
+ Ok(address)
+ }
+*/
+
/// Create an NFT collection
/// @param name Name of the collection
/// @param description Informative description of the collection
@@ -168,13 +277,8 @@
check_sent_amount_equals_collection_creation_price::<T>(value)?;
let collection_helpers_address =
T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id = T::CollectionDispatch::create(
- caller,
- collection_helpers_address,
- data,
- Default::default(),
- )
- .map_err(dispatch_to_evm::<T>)?;
+ let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
+ .map_err(dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
@@ -387,6 +491,8 @@
pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);
impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>
for CollectionHelpersOnMethodCall<T>
+where
+ T::AccountId: From<[u8; 32]>,
{
fn is_reserved(contract: &sp_core::H160) -> bool {
contract == &T::ContractAddress::get()
pallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -25,8 +25,19 @@
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0xe65011aa
+/// @dev the ERC-165 identifier for this interface is 0x4135fff1
contract CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
+ /// Create a collection
+ /// @return address Address of the newly created collection
+ /// @dev EVM selector for this function is: 0xa765ee5b,
+ /// or in textual repr: createCollection(((address,uint256),string,string,string,uint8,uint8,(string,bytes)[],(string,(uint8,bool)[])[],(address,uint256)[],(bool,bool,address[]),(uint8,uint256)[],uint8))
+ function createCollection(CreateCollectionData memory data) public payable returns (address) {
+ require(false, stub_error);
+ data;
+ dummy = 0;
+ return 0x0000000000000000000000000000000000000000;
+ }
+
/// Create an NFT collection
/// @param name Name of the collection
/// @param description Informative description of the collection
@@ -156,3 +167,135 @@
return 0;
}
}
+
+/// Collection properties
+struct CreateCollectionData {
+ /// Collection sponsor
+ CrossAddress pending_sponsor;
+ /// Collection name
+ string name;
+ /// Collection description
+ string description;
+ /// Token prefix
+ string token_prefix;
+ /// Token type (NFT, FT or RFT)
+ CollectionMode mode;
+ /// Fungible token precision
+ uint8 decimals;
+ /// Custom Properties
+ Property[] properties;
+ /// Permissions for token properties
+ TokenPropertyPermission[] token_property_permissions;
+ /// Collection admins
+ CrossAddress[] admin_list;
+ /// Nesting settings
+ CollectionNestingAndPermission nesting_settings;
+ /// Collection limits
+ CollectionLimitValue[] limits;
+ /// Extra collection flags
+ CollectionFlags flags;
+}
+
+/// Cross account struct
+type CollectionFlags is uint8;
+
+library CollectionFlagsLib {
+ /// Tokens in foreign collections can be transferred, but not burnt
+ CollectionFlags constant foreignField = CollectionFlags.wrap(128);
+ /// Supports ERC721Metadata
+ CollectionFlags constant erc721metadataField = CollectionFlags.wrap(64);
+ /// External collections can't be managed using `unique` api
+ CollectionFlags constant externalField = CollectionFlags.wrap(1);
+
+ /// Reserved bits
+ function reservedField(uint8 value) public pure returns (CollectionFlags) {
+ require(value < 1 << 5, "out of bound value");
+ return CollectionFlags.wrap(value << 1);
+ }
+}
+
+/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
+struct CollectionLimitValue {
+ CollectionLimitField field;
+ uint256 value;
+}
+
+/// [`CollectionLimits`](up_data_structs::CollectionLimits) fields representation for EVM.
+enum CollectionLimitField {
+ /// How many tokens can a user have on one account.
+ AccountTokenOwnership,
+ /// How many bytes of data are available for sponsorship.
+ SponsoredDataSize,
+ /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]
+ SponsoredDataRateLimit,
+ /// How many tokens can be mined into this collection.
+ TokenLimit,
+ /// Timeouts for transfer sponsoring.
+ SponsorTransferTimeout,
+ /// Timeout for sponsoring an approval in passed blocks.
+ SponsorApproveTimeout,
+ /// Whether the collection owner of the collection can send tokens (which belong to other users).
+ OwnerCanTransfer,
+ /// Can the collection owner burn other people's tokens.
+ OwnerCanDestroy,
+ /// Is it possible to send tokens from this collection between users.
+ TransferEnabled
+}
+
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+ /// Owner of token can nest tokens under it.
+ bool token_owner;
+ /// Admin of token collection can nest tokens under token.
+ bool collection_admin;
+ /// If set - only tokens from specified collections can be nested.
+ address[] restricted;
+}
+
+/// Cross account struct
+struct CrossAddress {
+ address eth;
+ uint256 sub;
+}
+
+/// Ethereum representation of Token Property Permissions.
+struct TokenPropertyPermission {
+ /// Token property key.
+ string key;
+ /// Token property permissions.
+ PropertyPermission[] permissions;
+}
+
+/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) as an key and value.
+struct PropertyPermission {
+ /// TokenPermission field.
+ TokenPermissionField code;
+ /// TokenPermission value.
+ bool value;
+}
+
+/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.
+enum TokenPermissionField {
+ /// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]
+ 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
+}
+
+/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).
+struct Property {
+ string key;
+ bytes value;
+}
+
+/// Type of tokens in collection
+enum CollectionMode {
+ /// Fungible
+ Fungible,
+ /// Nonfungible
+ Nonfungible,
+ /// Refungible
+ Refungible
+}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -365,7 +365,7 @@
token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
mode: CollectionMode,
) -> DispatchResult {
- let data: CreateCollectionData<T::AccountId> = CreateCollectionData {
+ let data: CreateCollectionData<T::CrossAccountId> = CreateCollectionData {
name: collection_name,
description: collection_description,
token_prefix,
@@ -390,14 +390,13 @@
#[pallet::weight(<SelfWeightOf<T>>::create_collection())]
pub fn create_collection_ex(
origin: OriginFor<T>,
- data: CreateCollectionData<T::AccountId>,
+ data: CreateCollectionData<T::CrossAccountId>,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
// =========
let sender = T::CrossAccountId::from_sub(sender);
- let _id =
- T::CollectionDispatch::create(sender.clone(), sender, data, Default::default())?;
+ let _id = T::CollectionDispatch::create(sender.clone(), sender, data)?;
Ok(())
}
primitives/data-structs/Cargo.tomldiffbeforeafterboth--- a/primitives/data-structs/Cargo.toml
+++ b/primitives/data-structs/Cargo.toml
@@ -22,6 +22,7 @@
sp-std = { workspace = true }
bondrewd = { version = "0.1.14", features = ["derive"], default-features = false }
struct-versioning = { workspace = true }
+evm-coder = { workspace = true }
[features]
default = ["std"]
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -32,11 +32,13 @@
use sp_core::U256;
use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};
+use sp_std::collections::btree_set::BTreeSet;
use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
-use bondrewd::Bitfields;
use frame_support::{BoundedVec, traits::ConstU32};
use derivative::Derivative;
use scale_info::TypeInfo;
+use evm_coder::AbiCoderFlags;
+use bondrewd::Bitfields;
mod bondrewd_codec;
mod bounded;
@@ -163,6 +165,14 @@
}
}
+impl Deref for CollectionId {
+ type Target = u32;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
/// Token id.
#[derive(
Encode,
@@ -350,7 +360,7 @@
pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;
pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;
-#[derive(Bitfields, Clone, Copy, PartialEq, Eq, Debug, Default)]
+#[derive(AbiCoderFlags, Bitfields, Clone, Copy, PartialEq, Eq, Debug, Default)]
#[bondrewd(enforce_bytes = 1)]
pub struct CollectionFlags {
/// Tokens in foreign collections can be transferred, but not burnt
@@ -362,12 +372,18 @@
/// External collections can't be managed using `unique` api
#[bondrewd(bits = "7..8")]
pub external: bool,
-
- #[bondrewd(reserve, bits = "2..7")]
+ /// Reserved flags
+ #[bondrewd(bits = "2..7")]
pub reserved: u8,
}
bondrewd_codec!(CollectionFlags);
+impl CollectionFlags {
+ pub fn is_allowed_for_user(self) -> bool {
+ !self.foreign && !self.external && self.reserved == 0
+ }
+}
+
/// Base structure for represent collection.
///
/// Used to provide basic functionality for all types of collections.
@@ -545,7 +561,7 @@
/// All fields are wrapped in [`Option`], where `None` means chain default.
#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]
#[derivative(Debug, Default(bound = ""))]
-pub struct CreateCollectionData<AccountId> {
+pub struct CreateCollectionData<CrossAccountId> {
/// Collection mode.
#[derivative(Default(value = "CollectionMode::NFT"))]
pub mode: CollectionMode,
@@ -562,9 +578,6 @@
/// Token prefix.
pub token_prefix: CollectionTokenPrefix,
- /// Pending collection sponsor.
- pub pending_sponsor: Option<AccountId>,
-
/// Collection limits.
pub limits: Option<CollectionLimits>,
@@ -576,6 +589,13 @@
/// Collection properties.
pub properties: CollectionPropertiesVec,
+
+ pub admin_list: Vec<CrossAccountId>,
+
+ /// Pending collection sponsor.
+ pub pending_sponsor: Option<CrossAccountId>,
+
+ pub flags: CollectionFlags,
}
/// Bounded vector of properties permissions. Max length is [`MAX_PROPERTIES_PER_ITEM`].
@@ -833,6 +853,14 @@
}
}
+impl TryFrom<BTreeSet<CollectionId>> for OwnerRestrictedSet {
+ type Error = ();
+
+ fn try_from(value: BTreeSet<CollectionId>) -> Result<Self, Self::Error> {
+ Ok(Self(value.try_into()?))
+ }
+}
+
/// Part of collection permissions, if set, defines who is able to nest tokens into other tokens.
#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
runtime/common/dispatch.rsdiffbeforeafterboth--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -25,14 +25,14 @@
};
pub use pallet_common::dispatch::CollectionDispatch;
use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
-use pallet_balances_adapter::{NativeFungibleHandle};
+use pallet_balances_adapter::NativeFungibleHandle;
use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};
use pallet_refungible::{
Pallet as PalletRefungible, RefungibleHandle, erc_token::RefungibleTokenHandle,
};
use up_data_structs::{
CollectionMode, CreateCollectionData, MAX_DECIMAL_POINTS, mapping::TokenAddressMapping,
- CollectionId, CollectionFlags,
+ CollectionId,
};
#[cfg(not(feature = "refungible"))]
@@ -72,26 +72,21 @@
fn create(
sender: T::CrossAccountId,
payer: T::CrossAccountId,
- data: CreateCollectionData<T::AccountId>,
- flags: CollectionFlags,
+ data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError> {
let id = match data.mode {
- CollectionMode::NFT => {
- <PalletNonfungible<T>>::init_collection(sender, payer, data, flags)?
- }
+ CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, payer, data)?,
CollectionMode::Fungible(decimal_points) => {
// check params
ensure!(
decimal_points <= MAX_DECIMAL_POINTS,
pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded
);
- <PalletFungible<T>>::init_collection(sender, payer, data, flags)?
+ <PalletFungible<T>>::init_collection(sender, payer, data)?
}
#[cfg(feature = "refungible")]
- CollectionMode::ReFungible => {
- <PalletRefungible<T>>::init_collection(sender, payer, data, flags)?
- }
+ CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, payer, data)?,
#[cfg(not(feature = "refungible"))]
CollectionMode::ReFungible => return unsupported!(T),
runtime/common/ethereum/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -234,6 +234,7 @@
| CollectionOwner
| CollectionAdmins
| CollectionLimits
+ | CollectionNesting
| CollectionNestingRestrictedIds
| CollectionNestingPermissions
| UniqueCollectionType => None,
@@ -249,6 +250,7 @@
| RemoveCollectionAdmin { .. }
| SetNestingBool { .. }
| SetNesting { .. }
+ | SetNestingCollectionIds { .. }
| SetCollectionAccess { .. }
| SetCollectionMintMode { .. }
| SetOwner { .. }
tests/src/benchmarks/opsFee/index.tsdiffbeforeafterboth--- a/tests/src/benchmarks/opsFee/index.ts
+++ b/tests/src/benchmarks/opsFee/index.ts
@@ -1,6 +1,6 @@
import {EthUniqueHelper, usingEthPlaygrounds} from '../../eth/util';
import {readFile} from 'fs/promises';
-import {CollectionLimitField, TokenPermissionField} from '../../eth/util/playgrounds/types';
+import {CollectionLimitField, CreateCollectionData, TokenPermissionField} from '../../eth/util/playgrounds/types';
import {IKeyringPair} from '@polkadot/types/types';
import {UniqueFTCollection, UniqueNFTCollection} from '../../util/playgrounds/unique';
import {Contract} from 'web3-eth-contract';
@@ -399,7 +399,7 @@
() => collection.setLimits(donor, {accountTokenOwnershipLimit: 1000}),
)));
- const {collectionAddress} = await helper.eth.createCollection('nft', ethSigner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createCollection(ethSigner, new CreateCollectionData('A', 'B', 'C', 'nft')).send();
const collectionWithEthOwner = await helper.ethNativeContract.collection(collectionAddress, 'nft', ethSigner, true);
@@ -775,7 +775,7 @@
() => collection.setLimits(donor, {accountTokenOwnershipLimit: 1000}),
)));
- const {collectionAddress} = await helper.eth.createCollection('nft', ethSigner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createCollection(ethSigner, new CreateCollectionData('A', 'B', 'C', 'nft')).send();
const collectionWithEthOwner = await helper.ethNativeContract.collection(collectionAddress, 'nft', ethSigner, true);
tests/src/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -16,7 +16,7 @@
import {IKeyringPair} from '@polkadot/types/types';
import {usingPlaygrounds, expect, itSub, Pallets} from './util';
-import {ICollectionCreationOptions, IProperty} from './util/playgrounds/types';
+import {CollectionFlag, ICollectionCreationOptions, IProperty} from './util/playgrounds/types';
import {UniqueHelper} from './util/playgrounds/unique';
async function mintCollectionHelper(helper: UniqueHelper, signer: IKeyringPair, options: ICollectionCreationOptions, type?: 'nft' | 'fungible' | 'refungible') {
@@ -36,6 +36,16 @@
if(options.properties) {
expect(data?.raw.properties).to.be.deep.equal(options.properties);
}
+ if(options.adminList) {
+ expect(data?.admins).to.be.deep.equal(options.adminList);
+ }
+
+ if(options.flags) {
+ if((options.flags[0] & 64) != 0)
+ expect(data?.raw.flags.erc721metadata).to.be.true;
+ if((options.flags[0] & 128) != 0)
+ expect(data?.raw.flags.foreign).to.be.false;
+ }
if(options.tokenPropertyPermissions) {
expect(data?.raw.tokenPropertyPermissions).to.be.deep.equal(options.tokenPropertyPermissions);
@@ -46,11 +56,12 @@
describe('integration test: ext. createCollection():', () => {
let alice: IKeyringPair;
+ let bob: IKeyringPair;
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({url: import.meta.url});
- [alice] = await helper.arrange.createAccounts([100n], donor);
+ [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
});
});
itSub('Create new NFT collection', async ({helper}) => {
@@ -82,6 +93,30 @@
}, 'nft');
});
+ itSub('create new collection with admin', async ({helper}) => {
+ await mintCollectionHelper(helper, alice, {
+ name: 'name', description: 'descr', tokenPrefix: 'COL',
+ adminList: [{Substrate: bob.address}],
+ }, 'nft');
+ });
+
+ itSub('create new collection with flags', async ({helper}) => {
+ await mintCollectionHelper(helper, alice, {
+ name: 'name', description: 'descr', tokenPrefix: 'COL',
+ flags: [CollectionFlag.Erc721metadata],
+ }, 'nft');
+
+ await mintCollectionHelper(helper, alice, {
+ name: 'name', description: 'descr', tokenPrefix: 'COL',
+ flags: [CollectionFlag.Foreign],
+ }, 'nft');
+
+ await mintCollectionHelper(helper, alice, {
+ name: 'name', description: 'descr', tokenPrefix: 'COL',
+ flags: [CollectionFlag.Erc721metadata, CollectionFlag.Foreign],
+ }, 'nft');
+ });
+
itSub('Create new collection with extra fields', async ({helper}) => {
const collection = await mintCollectionHelper(helper, alice, {name: 'name', description: 'descr', tokenPrefix: 'COL'}, 'fungible');
await collection.setPermissions(alice, {access: 'AllowList'});
tests/src/eth/abi/collectionHelpers.jsondiffbeforeafterboth--- a/tests/src/eth/abi/collectionHelpers.json
+++ b/tests/src/eth/abi/collectionHelpers.json
@@ -75,6 +75,118 @@
},
{
"inputs": [
+ {
+ "components": [
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct CrossAddress",
+ "name": "pending_sponsor",
+ "type": "tuple"
+ },
+ { "internalType": "string", "name": "name", "type": "string" },
+ { "internalType": "string", "name": "description", "type": "string" },
+ {
+ "internalType": "string",
+ "name": "token_prefix",
+ "type": "string"
+ },
+ {
+ "internalType": "enum CollectionMode",
+ "name": "mode",
+ "type": "uint8"
+ },
+ { "internalType": "uint8", "name": "decimals", "type": "uint8" },
+ {
+ "components": [
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
+ ],
+ "internalType": "struct Property[]",
+ "name": "properties",
+ "type": "tuple[]"
+ },
+ {
+ "components": [
+ { "internalType": "string", "name": "key", "type": "string" },
+ {
+ "components": [
+ {
+ "internalType": "enum TokenPermissionField",
+ "name": "code",
+ "type": "uint8"
+ },
+ { "internalType": "bool", "name": "value", "type": "bool" }
+ ],
+ "internalType": "struct PropertyPermission[]",
+ "name": "permissions",
+ "type": "tuple[]"
+ }
+ ],
+ "internalType": "struct TokenPropertyPermission[]",
+ "name": "token_property_permissions",
+ "type": "tuple[]"
+ },
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct CrossAddress[]",
+ "name": "admin_list",
+ "type": "tuple[]"
+ },
+ {
+ "components": [
+ { "internalType": "bool", "name": "token_owner", "type": "bool" },
+ {
+ "internalType": "bool",
+ "name": "collection_admin",
+ "type": "bool"
+ },
+ {
+ "internalType": "address[]",
+ "name": "restricted",
+ "type": "address[]"
+ }
+ ],
+ "internalType": "struct CollectionNestingAndPermission",
+ "name": "nesting_settings",
+ "type": "tuple"
+ },
+ {
+ "components": [
+ {
+ "internalType": "enum CollectionLimitField",
+ "name": "field",
+ "type": "uint8"
+ },
+ { "internalType": "uint256", "name": "value", "type": "uint256" }
+ ],
+ "internalType": "struct CollectionLimitValue[]",
+ "name": "limits",
+ "type": "tuple[]"
+ },
+ {
+ "internalType": "CollectionFlags",
+ "name": "flags",
+ "type": "uint8"
+ }
+ ],
+ "internalType": "struct CreateCollectionData",
+ "name": "data",
+ "type": "tuple"
+ }
+ ],
+ "name": "createCollection",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "payable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "string", "name": "name", "type": "string" },
{ "internalType": "uint8", "name": "decimals", "type": "uint8" },
{ "internalType": "string", "name": "description", "type": "string" },
tests/src/eth/abi/fungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/fungible.json
+++ b/tests/src/eth/abi/fungible.json
@@ -280,35 +280,23 @@
},
{
"inputs": [],
- "name": "collectionNestingPermissions",
+ "name": "collectionNesting",
"outputs": [
{
"components": [
+ { "internalType": "bool", "name": "token_owner", "type": "bool" },
{
- "internalType": "enum CollectionPermissionField",
- "name": "field",
- "type": "uint8"
+ "internalType": "bool",
+ "name": "collection_admin",
+ "type": "bool"
},
- { "internalType": "bool", "name": "value", "type": "bool" }
- ],
- "internalType": "struct CollectionNestingPermission[]",
- "name": "",
- "type": "tuple[]"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "collectionNestingRestrictedCollectionIds",
- "outputs": [
- {
- "components": [
- { "internalType": "bool", "name": "token_owner", "type": "bool" },
- { "internalType": "uint256[]", "name": "ids", "type": "uint256[]" }
+ {
+ "internalType": "address[]",
+ "name": "restricted",
+ "type": "address[]"
+ }
],
- "internalType": "struct CollectionNesting",
+ "internalType": "struct CollectionNestingAndPermission",
"name": "",
"type": "tuple"
}
@@ -576,19 +564,24 @@
"type": "function"
},
{
- "inputs": [{ "internalType": "bool", "name": "enable", "type": "bool" }],
- "name": "setCollectionNesting",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
"inputs": [
- { "internalType": "bool", "name": "enable", "type": "bool" },
{
- "internalType": "address[]",
- "name": "collections",
- "type": "address[]"
+ "components": [
+ { "internalType": "bool", "name": "token_owner", "type": "bool" },
+ {
+ "internalType": "bool",
+ "name": "collection_admin",
+ "type": "bool"
+ },
+ {
+ "internalType": "address[]",
+ "name": "restricted",
+ "type": "address[]"
+ }
+ ],
+ "internalType": "struct CollectionNestingAndPermission",
+ "name": "collectionNestingAndPermissions",
+ "type": "tuple"
}
],
"name": "setCollectionNesting",
tests/src/eth/abi/fungibleDeprecated.jsondiffbeforeafterboth--- a/tests/src/eth/abi/fungibleDeprecated.json
+++ b/tests/src/eth/abi/fungibleDeprecated.json
@@ -88,5 +88,64 @@
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "collectionNestingPermissions",
+ "outputs": [
+ {
+ "components": [
+ {
+ "internalType": "enum CollectionPermissionField",
+ "name": "field",
+ "type": "uint8"
+ },
+ { "internalType": "bool", "name": "value", "type": "bool" }
+ ],
+ "internalType": "struct CollectionNestingPermission[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "collectionNestingRestrictedCollectionIds",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "bool", "name": "token_owner", "type": "bool" },
+ { "internalType": "uint256[]", "name": "ids", "type": "uint256[]" }
+ ],
+ "internalType": "struct CollectionNesting",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [{ "internalType": "bool", "name": "enable", "type": "bool" }],
+ "name": "setCollectionNesting",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "bool", "name": "enable", "type": "bool" },
+ {
+ "internalType": "address[]",
+ "name": "collections",
+ "type": "address[]"
+ }
+ ],
+ "name": "setCollectionNesting",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
}
]
tests/src/eth/abi/nonFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -291,35 +291,23 @@
},
{
"inputs": [],
- "name": "collectionNestingPermissions",
+ "name": "collectionNesting",
"outputs": [
{
"components": [
+ { "internalType": "bool", "name": "token_owner", "type": "bool" },
{
- "internalType": "enum CollectionPermissionField",
- "name": "field",
- "type": "uint8"
+ "internalType": "bool",
+ "name": "collection_admin",
+ "type": "bool"
},
- { "internalType": "bool", "name": "value", "type": "bool" }
- ],
- "internalType": "struct CollectionNestingPermission[]",
- "name": "",
- "type": "tuple[]"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "collectionNestingRestrictedCollectionIds",
- "outputs": [
- {
- "components": [
- { "internalType": "bool", "name": "token_owner", "type": "bool" },
- { "internalType": "uint256[]", "name": "ids", "type": "uint256[]" }
+ {
+ "internalType": "address[]",
+ "name": "restricted",
+ "type": "address[]"
+ }
],
- "internalType": "struct CollectionNesting",
+ "internalType": "struct CollectionNestingAndPermission",
"name": "",
"type": "tuple"
}
@@ -705,19 +693,24 @@
"type": "function"
},
{
- "inputs": [{ "internalType": "bool", "name": "enable", "type": "bool" }],
- "name": "setCollectionNesting",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
"inputs": [
- { "internalType": "bool", "name": "enable", "type": "bool" },
{
- "internalType": "address[]",
- "name": "collections",
- "type": "address[]"
+ "components": [
+ { "internalType": "bool", "name": "token_owner", "type": "bool" },
+ {
+ "internalType": "bool",
+ "name": "collection_admin",
+ "type": "bool"
+ },
+ {
+ "internalType": "address[]",
+ "name": "restricted",
+ "type": "address[]"
+ }
+ ],
+ "internalType": "struct CollectionNestingAndPermission",
+ "name": "collectionNestingAndPermissions",
+ "type": "tuple"
}
],
"name": "setCollectionNesting",
tests/src/eth/abi/nonFungibleDeprecated.jsondiffbeforeafterboth--- a/tests/src/eth/abi/nonFungibleDeprecated.json
+++ b/tests/src/eth/abi/nonFungibleDeprecated.json
@@ -109,5 +109,64 @@
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "collectionNestingPermissions",
+ "outputs": [
+ {
+ "components": [
+ {
+ "internalType": "enum CollectionPermissionField",
+ "name": "field",
+ "type": "uint8"
+ },
+ { "internalType": "bool", "name": "value", "type": "bool" }
+ ],
+ "internalType": "struct CollectionNestingPermission[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "collectionNestingRestrictedCollectionIds",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "bool", "name": "token_owner", "type": "bool" },
+ { "internalType": "uint256[]", "name": "ids", "type": "uint256[]" }
+ ],
+ "internalType": "struct CollectionNesting",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [{ "internalType": "bool", "name": "enable", "type": "bool" }],
+ "name": "setCollectionNesting",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "bool", "name": "enable", "type": "bool" },
+ {
+ "internalType": "address[]",
+ "name": "collections",
+ "type": "address[]"
+ }
+ ],
+ "name": "setCollectionNesting",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
}
]
tests/src/eth/abi/reFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -273,35 +273,23 @@
},
{
"inputs": [],
- "name": "collectionNestingPermissions",
+ "name": "collectionNesting",
"outputs": [
{
"components": [
+ { "internalType": "bool", "name": "token_owner", "type": "bool" },
{
- "internalType": "enum CollectionPermissionField",
- "name": "field",
- "type": "uint8"
+ "internalType": "bool",
+ "name": "collection_admin",
+ "type": "bool"
},
- { "internalType": "bool", "name": "value", "type": "bool" }
- ],
- "internalType": "struct CollectionNestingPermission[]",
- "name": "",
- "type": "tuple[]"
- }
- ],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "collectionNestingRestrictedCollectionIds",
- "outputs": [
- {
- "components": [
- { "internalType": "bool", "name": "token_owner", "type": "bool" },
- { "internalType": "uint256[]", "name": "ids", "type": "uint256[]" }
+ {
+ "internalType": "address[]",
+ "name": "restricted",
+ "type": "address[]"
+ }
],
- "internalType": "struct CollectionNesting",
+ "internalType": "struct CollectionNestingAndPermission",
"name": "",
"type": "tuple"
}
@@ -687,19 +675,24 @@
"type": "function"
},
{
- "inputs": [{ "internalType": "bool", "name": "enable", "type": "bool" }],
- "name": "setCollectionNesting",
- "outputs": [],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
"inputs": [
- { "internalType": "bool", "name": "enable", "type": "bool" },
{
- "internalType": "address[]",
- "name": "collections",
- "type": "address[]"
+ "components": [
+ { "internalType": "bool", "name": "token_owner", "type": "bool" },
+ {
+ "internalType": "bool",
+ "name": "collection_admin",
+ "type": "bool"
+ },
+ {
+ "internalType": "address[]",
+ "name": "restricted",
+ "type": "address[]"
+ }
+ ],
+ "internalType": "struct CollectionNestingAndPermission",
+ "name": "collectionNestingAndPermissions",
+ "type": "tuple"
}
],
"name": "setCollectionNesting",
tests/src/eth/abi/reFungibleDeprecated.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungibleDeprecated.json
+++ b/tests/src/eth/abi/reFungibleDeprecated.json
@@ -137,5 +137,64 @@
"outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
"stateMutability": "nonpayable",
"type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "collectionNestingPermissions",
+ "outputs": [
+ {
+ "components": [
+ {
+ "internalType": "enum CollectionPermissionField",
+ "name": "field",
+ "type": "uint8"
+ },
+ { "internalType": "bool", "name": "value", "type": "bool" }
+ ],
+ "internalType": "struct CollectionNestingPermission[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "collectionNestingRestrictedCollectionIds",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "bool", "name": "token_owner", "type": "bool" },
+ { "internalType": "uint256[]", "name": "ids", "type": "uint256[]" }
+ ],
+ "internalType": "struct CollectionNesting",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [{ "internalType": "bool", "name": "enable", "type": "bool" }],
+ "name": "setCollectionNesting",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "bool", "name": "enable", "type": "bool" },
+ {
+ "internalType": "address[]",
+ "name": "collections",
+ "type": "address[]"
+ }
+ ],
+ "name": "setCollectionNesting",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
}
]
tests/src/eth/allowlist.test.tsdiffbeforeafterboth--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -17,6 +17,7 @@
import {IKeyringPair} from '@polkadot/types/types';
import {Pallets} from '../util';
import {itEth, usingEthPlaygrounds, expect, SponsoringMode} from './util';
+import {CreateCollectionData} from './util/playgrounds/types';
describe('EVM contract allowlist', () => {
let donor: IKeyringPair;
@@ -104,7 +105,7 @@
const userEth = await helper.eth.createAccountWithBalance(donor);
const mintParams = testCase.mode === 'ft' ? [userEth, 100] : [userEth];
- const {collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
const userCrossSub = helper.ethCrossAccount.fromKeyringPair(userSub);
const userCrossEth = helper.ethCrossAccount.fromAddress(userEth);
@@ -178,7 +179,7 @@
const userEth = helper.eth.createAccount();
const userCrossEth = helper.ethCrossAccount.fromAddress(userEth);
- const {collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner, !testCase.cross);
expect(await helper.collection.allowed(collectionId, {Substrate: userSub.address})).to.be.false;
tests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -20,8 +20,14 @@
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0xe65011aa
+/// @dev the ERC-165 identifier for this interface is 0x4135fff1
interface CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
+ /// Create a collection
+ /// @return address Address of the newly created collection
+ /// @dev EVM selector for this function is: 0xa765ee5b,
+ /// or in textual repr: createCollection(((address,uint256),string,string,string,uint8,uint8,(string,bytes)[],(string,(uint8,bool)[])[],(address,uint256)[],(bool,bool,address[]),(uint8,uint256)[],uint8))
+ function createCollection(CreateCollectionData memory data) external payable returns (address);
+
/// Create an NFT collection
/// @param name Name of the collection
/// @param description Informative description of the collection
@@ -94,3 +100,135 @@
/// or in textual repr: collectionId(address)
function collectionId(address collectionAddress) external view returns (uint32);
}
+
+/// Collection properties
+struct CreateCollectionData {
+ /// Collection sponsor
+ CrossAddress pending_sponsor;
+ /// Collection name
+ string name;
+ /// Collection description
+ string description;
+ /// Token prefix
+ string token_prefix;
+ /// Token type (NFT, FT or RFT)
+ CollectionMode mode;
+ /// Fungible token precision
+ uint8 decimals;
+ /// Custom Properties
+ Property[] properties;
+ /// Permissions for token properties
+ TokenPropertyPermission[] token_property_permissions;
+ /// Collection admins
+ CrossAddress[] admin_list;
+ /// Nesting settings
+ CollectionNestingAndPermission nesting_settings;
+ /// Collection limits
+ CollectionLimitValue[] limits;
+ /// Extra collection flags
+ CollectionFlags flags;
+}
+
+/// Cross account struct
+type CollectionFlags is uint8;
+
+library CollectionFlagsLib {
+ /// Tokens in foreign collections can be transferred, but not burnt
+ CollectionFlags constant foreignField = CollectionFlags.wrap(128);
+ /// Supports ERC721Metadata
+ CollectionFlags constant erc721metadataField = CollectionFlags.wrap(64);
+ /// External collections can't be managed using `unique` api
+ CollectionFlags constant externalField = CollectionFlags.wrap(1);
+
+ /// Reserved bits
+ function reservedField(uint8 value) public pure returns (CollectionFlags) {
+ require(value < 1 << 5, "out of bound value");
+ return CollectionFlags.wrap(value << 1);
+ }
+}
+
+/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
+struct CollectionLimitValue {
+ CollectionLimitField field;
+ uint256 value;
+}
+
+/// [`CollectionLimits`](up_data_structs::CollectionLimits) fields representation for EVM.
+enum CollectionLimitField {
+ /// How many tokens can a user have on one account.
+ AccountTokenOwnership,
+ /// How many bytes of data are available for sponsorship.
+ SponsoredDataSize,
+ /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]
+ SponsoredDataRateLimit,
+ /// How many tokens can be mined into this collection.
+ TokenLimit,
+ /// Timeouts for transfer sponsoring.
+ SponsorTransferTimeout,
+ /// Timeout for sponsoring an approval in passed blocks.
+ SponsorApproveTimeout,
+ /// Whether the collection owner of the collection can send tokens (which belong to other users).
+ OwnerCanTransfer,
+ /// Can the collection owner burn other people's tokens.
+ OwnerCanDestroy,
+ /// Is it possible to send tokens from this collection between users.
+ TransferEnabled
+}
+
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+ /// Owner of token can nest tokens under it.
+ bool token_owner;
+ /// Admin of token collection can nest tokens under token.
+ bool collection_admin;
+ /// If set - only tokens from specified collections can be nested.
+ address[] restricted;
+}
+
+/// Cross account struct
+struct CrossAddress {
+ address eth;
+ uint256 sub;
+}
+
+/// Ethereum representation of Token Property Permissions.
+struct TokenPropertyPermission {
+ /// Token property key.
+ string key;
+ /// Token property permissions.
+ PropertyPermission[] permissions;
+}
+
+/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) as an key and value.
+struct PropertyPermission {
+ /// TokenPermission field.
+ TokenPermissionField code;
+ /// TokenPermission value.
+ bool value;
+}
+
+/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.
+enum TokenPermissionField {
+ /// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]
+ 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
+}
+
+/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).
+struct Property {
+ string key;
+ bytes value;
+}
+
+/// Type of tokens in collection
+enum CollectionMode {
+ /// Fungible
+ Fungible,
+ /// Nonfungible
+ Nonfungible,
+ /// Refungible
+ Refungible
+}
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -13,7 +13,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
+/// @dev the ERC-165 identifier for this interface is 0xb34d97e9
interface Collection is Dummy, ERC165 {
// /// Set collection property.
// ///
@@ -148,30 +148,38 @@
// /// or in textual repr: removeCollectionAdmin(address)
// function removeCollectionAdmin(address admin) external;
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
- /// @dev EVM selector for this function is: 0x112d4586,
- /// or in textual repr: setCollectionNesting(bool)
- function setCollectionNesting(bool enable) external;
+ /// @dev EVM selector for this function is: 0x0b9f3890,
+ /// or in textual repr: setCollectionNesting((bool,bool,address[]))
+ function setCollectionNesting(CollectionNestingAndPermission memory collectionNestingAndPermissions) external;
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
- /// @param collections Addresses of collections that will be available for nesting.
- /// @dev EVM selector for this function is: 0x64872396,
- /// or in textual repr: setCollectionNesting(bool,address[])
- function setCollectionNesting(bool enable, address[] memory collections) external;
+ // /// Toggle accessibility of collection nesting.
+ // ///
+ // /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
+ // /// @dev EVM selector for this function is: 0x112d4586,
+ // /// or in textual repr: setCollectionNesting(bool)
+ // function setCollectionNesting(bool enable) external;
+
+ // /// Toggle accessibility of collection nesting.
+ // ///
+ // /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
+ // /// @param collections Addresses of collections that will be available for nesting.
+ // /// @dev EVM selector for this function is: 0x64872396,
+ // /// or in textual repr: setCollectionNesting(bool,address[])
+ // function setCollectionNesting(bool enable, address[] memory collections) external;
+
+ /// @dev EVM selector for this function is: 0x92c660a8,
+ /// or in textual repr: collectionNesting()
+ function collectionNesting() external view returns (CollectionNestingAndPermission memory);
- /// Returns nesting for a collection
- /// @dev EVM selector for this function is: 0x22d25bfe,
- /// or in textual repr: collectionNestingRestrictedCollectionIds()
- function collectionNestingRestrictedCollectionIds() external view returns (CollectionNesting memory);
+ // /// Returns nesting for a collection
+ // /// @dev EVM selector for this function is: 0x22d25bfe,
+ // /// or in textual repr: collectionNestingRestrictedCollectionIds()
+ // function collectionNestingRestrictedCollectionIds() external view returns (CollectionNesting memory);
- /// Returns permissions for a collection
- /// @dev EVM selector for this function is: 0x5b2eaf4b,
- /// or in textual repr: collectionNestingPermissions()
- function collectionNestingPermissions() external view returns (CollectionNestingPermission[] memory);
+ // /// Returns permissions for a collection
+ // /// @dev EVM selector for this function is: 0x5b2eaf4b,
+ // /// or in textual repr: collectionNestingPermissions()
+ // function collectionNestingPermissions() external view returns (CollectionNestingPermission[] memory);
/// Set the collection access method.
/// @param mode Access mode
@@ -311,6 +319,16 @@
uint256[] ids;
}
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+ /// Owner of token can nest tokens under it.
+ bool token_owner;
+ /// Admin of token collection can nest tokens under token.
+ bool collection_admin;
+ /// If set - only tokens from specified collections can be nested.
+ address[] restricted;
+}
+
/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
struct CollectionLimit {
CollectionLimitField field;
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -118,7 +118,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
+/// @dev the ERC-165 identifier for this interface is 0xb34d97e9
interface Collection is Dummy, ERC165 {
// /// Set collection property.
// ///
@@ -253,30 +253,38 @@
// /// or in textual repr: removeCollectionAdmin(address)
// function removeCollectionAdmin(address admin) external;
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
- /// @dev EVM selector for this function is: 0x112d4586,
- /// or in textual repr: setCollectionNesting(bool)
- function setCollectionNesting(bool enable) external;
+ /// @dev EVM selector for this function is: 0x0b9f3890,
+ /// or in textual repr: setCollectionNesting((bool,bool,address[]))
+ function setCollectionNesting(CollectionNestingAndPermission memory collectionNestingAndPermissions) external;
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
- /// @param collections Addresses of collections that will be available for nesting.
- /// @dev EVM selector for this function is: 0x64872396,
- /// or in textual repr: setCollectionNesting(bool,address[])
- function setCollectionNesting(bool enable, address[] memory collections) external;
+ // /// Toggle accessibility of collection nesting.
+ // ///
+ // /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
+ // /// @dev EVM selector for this function is: 0x112d4586,
+ // /// or in textual repr: setCollectionNesting(bool)
+ // function setCollectionNesting(bool enable) external;
+
+ // /// Toggle accessibility of collection nesting.
+ // ///
+ // /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
+ // /// @param collections Addresses of collections that will be available for nesting.
+ // /// @dev EVM selector for this function is: 0x64872396,
+ // /// or in textual repr: setCollectionNesting(bool,address[])
+ // function setCollectionNesting(bool enable, address[] memory collections) external;
+
+ /// @dev EVM selector for this function is: 0x92c660a8,
+ /// or in textual repr: collectionNesting()
+ function collectionNesting() external view returns (CollectionNestingAndPermission memory);
- /// Returns nesting for a collection
- /// @dev EVM selector for this function is: 0x22d25bfe,
- /// or in textual repr: collectionNestingRestrictedCollectionIds()
- function collectionNestingRestrictedCollectionIds() external view returns (CollectionNesting memory);
+ // /// Returns nesting for a collection
+ // /// @dev EVM selector for this function is: 0x22d25bfe,
+ // /// or in textual repr: collectionNestingRestrictedCollectionIds()
+ // function collectionNestingRestrictedCollectionIds() external view returns (CollectionNesting memory);
- /// Returns permissions for a collection
- /// @dev EVM selector for this function is: 0x5b2eaf4b,
- /// or in textual repr: collectionNestingPermissions()
- function collectionNestingPermissions() external view returns (CollectionNestingPermission[] memory);
+ // /// Returns permissions for a collection
+ // /// @dev EVM selector for this function is: 0x5b2eaf4b,
+ // /// or in textual repr: collectionNestingPermissions()
+ // function collectionNestingPermissions() external view returns (CollectionNestingPermission[] memory);
/// Set the collection access method.
/// @param mode Access mode
@@ -416,6 +424,16 @@
uint256[] ids;
}
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+ /// Owner of token can nest tokens under it.
+ bool token_owner;
+ /// Admin of token collection can nest tokens under token.
+ bool collection_admin;
+ /// If set - only tokens from specified collections can be nested.
+ address[] restricted;
+}
+
/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
struct CollectionLimit {
CollectionLimitField field;
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -118,7 +118,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
+/// @dev the ERC-165 identifier for this interface is 0xb34d97e9
interface Collection is Dummy, ERC165 {
// /// Set collection property.
// ///
@@ -253,30 +253,38 @@
// /// or in textual repr: removeCollectionAdmin(address)
// function removeCollectionAdmin(address admin) external;
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
- /// @dev EVM selector for this function is: 0x112d4586,
- /// or in textual repr: setCollectionNesting(bool)
- function setCollectionNesting(bool enable) external;
+ /// @dev EVM selector for this function is: 0x0b9f3890,
+ /// or in textual repr: setCollectionNesting((bool,bool,address[]))
+ function setCollectionNesting(CollectionNestingAndPermission memory collectionNestingAndPermissions) external;
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
- /// @param collections Addresses of collections that will be available for nesting.
- /// @dev EVM selector for this function is: 0x64872396,
- /// or in textual repr: setCollectionNesting(bool,address[])
- function setCollectionNesting(bool enable, address[] memory collections) external;
+ // /// Toggle accessibility of collection nesting.
+ // ///
+ // /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
+ // /// @dev EVM selector for this function is: 0x112d4586,
+ // /// or in textual repr: setCollectionNesting(bool)
+ // function setCollectionNesting(bool enable) external;
+
+ // /// Toggle accessibility of collection nesting.
+ // ///
+ // /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
+ // /// @param collections Addresses of collections that will be available for nesting.
+ // /// @dev EVM selector for this function is: 0x64872396,
+ // /// or in textual repr: setCollectionNesting(bool,address[])
+ // function setCollectionNesting(bool enable, address[] memory collections) external;
+
+ /// @dev EVM selector for this function is: 0x92c660a8,
+ /// or in textual repr: collectionNesting()
+ function collectionNesting() external view returns (CollectionNestingAndPermission memory);
- /// Returns nesting for a collection
- /// @dev EVM selector for this function is: 0x22d25bfe,
- /// or in textual repr: collectionNestingRestrictedCollectionIds()
- function collectionNestingRestrictedCollectionIds() external view returns (CollectionNesting memory);
+ // /// Returns nesting for a collection
+ // /// @dev EVM selector for this function is: 0x22d25bfe,
+ // /// or in textual repr: collectionNestingRestrictedCollectionIds()
+ // function collectionNestingRestrictedCollectionIds() external view returns (CollectionNesting memory);
- /// Returns permissions for a collection
- /// @dev EVM selector for this function is: 0x5b2eaf4b,
- /// or in textual repr: collectionNestingPermissions()
- function collectionNestingPermissions() external view returns (CollectionNestingPermission[] memory);
+ // /// Returns permissions for a collection
+ // /// @dev EVM selector for this function is: 0x5b2eaf4b,
+ // /// or in textual repr: collectionNestingPermissions()
+ // function collectionNestingPermissions() external view returns (CollectionNestingPermission[] memory);
/// Set the collection access method.
/// @param mode Access mode
@@ -416,6 +424,16 @@
uint256[] ids;
}
+/// Nested collections and permissions
+struct CollectionNestingAndPermission {
+ /// Owner of token can nest tokens under it.
+ bool token_owner;
+ /// Admin of token collection can nest tokens under token.
+ bool collection_admin;
+ /// If set - only tokens from specified collections can be nested.
+ address[] restricted;
+}
+
/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
struct CollectionLimit {
CollectionLimitField field;
tests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -19,6 +19,7 @@
import {IEthCrossAccountId} from '../util/playgrounds/types';
import {usingEthPlaygrounds, itEth} from './util';
import {EthUniqueHelper} from './util/playgrounds/unique.dev';
+import {CreateCollectionData} from './util/playgrounds/types';
async function recordEthFee(helper: EthUniqueHelper, userAddress: string, call: () => Promise<any>) {
const before = await helper.balance.getSubstrate(helper.address.ethToSubstrate(userAddress));
@@ -55,7 +56,7 @@
const adminCrossSub = helper.ethCrossAccount.fromKeyringPair(adminSub);
const adminCrossEth = helper.ethCrossAccount.fromAddress(adminEth);
- const {collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner, true);
// Check isOwnerOrAdminCross returns false:
tests/src/eth/collectionLimits.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionLimits.test.ts
+++ b/tests/src/eth/collectionLimits.test.ts
@@ -1,7 +1,7 @@
import {IKeyringPair} from '@polkadot/types/types';
import {Pallets} from '../util';
import {expect, itEth, usingEthPlaygrounds} from './util';
-import {CollectionLimitField} from './util/playgrounds/types';
+import {CollectionLimitField, CreateCollectionData} from './util/playgrounds/types';
describe('Can set collection limits', () => {
@@ -20,7 +20,7 @@
].map(testCase =>
itEth.ifWithPallets(`for ${testCase.case}`, testCase.requiredPallets || [], async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.case, owner, 'Limits', 'absolutely anything', 'FLO', 18);
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('Limits', 'absolutely anything', 'FLO', testCase.case, 18)).send();
const limits = {
accountTokenOwnershipLimit: 1000,
sponsoredDataSize: 1024,
@@ -96,13 +96,13 @@
};
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createCollection(testCase.case, owner, 'Limits', 'absolutely anything', 'ISNI', 18);
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('Limits', 'absolutely anything', 'ISNI', testCase.case, 18)).send();
const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.case, owner);
// Cannot set non-existing limit
await expect(collectionEvm.methods
.setCollectionLimit({field: 9, value: {status: true, value: 1}})
- .call()).to.be.rejectedWith('Returned error: VM Exception while processing transaction: revert Value not convertible into enum "CollectionLimitField"');
+ .call()).to.be.rejectedWith('Returned error: VM Exception while processing transaction: revert value not convertible into enum "CollectionLimitField"');
// Cannot disable limits
await expect(collectionEvm.methods
@@ -129,7 +129,7 @@
itEth.ifWithPallets(`Non-owner and non-admin cannot set collection limits for ${testCase.case}`, testCase.requiredPallets || [], async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const nonOwner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createCollection(testCase.case, owner, 'Limits', 'absolutely anything', 'FLO', 18);
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('Limits', 'absolutely anything', 'FLO', testCase.case, 18)).send();
const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.case, owner);
await expect(collectionEvm.methods
tests/src/eth/createCollection.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/createCollection.test.ts
@@ -0,0 +1,1459 @@
+// 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 {evmToAddress} from '@polkadot/util-crypto';
+import {Pallets, requirePalletsOrSkip} from '../util';
+import {expect, itEth, usingEthPlaygrounds} from './util';
+import {CREATE_COLLECTION_DATA_DEFAULTS, CollectionLimitField, CollectionMode, CreateCollectionData, TokenPermissionField, emptyAddress} from './util/playgrounds/types';
+import {CollectionFlag, IEthCrossAccountId, TCollectionMode} from '../util/playgrounds/types';
+
+const DECIMALS = 18;
+const CREATE_COLLECTION_DATA_DEFAULTS_ARRAY = [
+ [],
+ [],
+ [],
+ [false, false, []],
+ [],
+ [0],
+];
+
+type ElementOf<A> = A extends readonly (infer T)[] ? T : never;
+function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {
+ if(args.length === 0) {
+ yield internalRest as any;
+ return;
+ }
+ for(const value of args[0]) {
+ yield* cartesian([...internalRest, value], ...args.slice(1)) as any;
+ }
+}
+
+describe('Create collection from EVM', () => {
+ let donor: IKeyringPair;
+ let nominal: bigint;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (helper, privateKey) => {
+ donor = await privateKey({url: import.meta.url});
+ nominal = helper.balance.getOneTokenNominal();
+ });
+ });
+
+ describe('Fungible collection', () => {
+ before(async function() {
+ await usingEthPlaygrounds((helper) => {
+ requirePalletsOrSkip(this, helper, [Pallets.Fungible]);
+ return Promise.resolve();
+ });
+ });
+
+ itEth('Collection address exist', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const collectionAddressForNonexistentCollection = '0x17C4E6453CC49AAAAEACA894E6D9683E00112233';
+ const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);
+
+ expect(await collectionHelpers
+ .methods.isCollectionExist(collectionAddressForNonexistentCollection).call())
+ .to.be.false;
+
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('Exister', 'absolutely anything', 'WIWT', 'ft', DECIMALS)).send();
+ expect(await collectionHelpers
+ .methods.isCollectionExist(collectionAddress).call())
+ .to.be.true;
+
+ // check collectionOwner:
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner, true);
+ const collectionOwner = await collectionEvm.methods.collectionOwner().call();
+ expect(helper.address.restoreCrossAccountFromBigInt(BigInt(collectionOwner.sub))).to.eq(helper.address.ethToSubstrate(owner, true));
+ });
+
+ itEth('destroyCollection', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('Exister', 'absolutely anything', 'WIWT', 'ft', DECIMALS)).send();
+ const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
+
+ const result = await collectionHelper.methods
+ .destroyCollection(collectionAddress)
+ .send({from: owner});
+
+ const events = helper.eth.normalizeEvents(result.events);
+
+ expect(events).to.be.deep.equal([
+ {
+ address: collectionHelper.options.address,
+ event: 'CollectionDestroyed',
+ args: {
+ collectionId: collectionAddress,
+ },
+ },
+ ]);
+
+ expect(await collectionHelper.methods
+ .isCollectionExist(collectionAddress)
+ .call()).to.be.false;
+ expect(await helper.collection.getData(collectionId)).to.be.null;
+ });
+
+ itEth('(!negative test!) Create collection (bad lengths)', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
+ {
+ const MAX_NAME_LENGTH = 64;
+ const collectionName = 'A'.repeat(MAX_NAME_LENGTH + 1);
+ const description = 'A';
+ const tokenPrefix = 'A';
+
+ await expect(collectionHelper.methods
+ .createCollection([
+ emptyAddress,
+ collectionName,
+ description,
+ tokenPrefix,
+ CollectionMode.Fungible,
+ DECIMALS,
+ ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+ ])
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
+ }
+ {
+ const MAX_DESCRIPTION_LENGTH = 256;
+ const collectionName = 'A';
+ const description = 'A'.repeat(MAX_DESCRIPTION_LENGTH + 1);
+ const tokenPrefix = 'A';
+ await expect(collectionHelper.methods
+ .createCollection([
+ emptyAddress,
+ collectionName,
+ description,
+ tokenPrefix,
+ CollectionMode.Fungible,
+ DECIMALS,
+ ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+ ])
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
+ }
+ {
+ const MAX_TOKEN_PREFIX_LENGTH = 16;
+ const collectionName = 'A';
+ const description = 'A';
+ const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGTH + 1);
+ await expect(collectionHelper.methods
+ .createCollection([
+ emptyAddress,
+ collectionName,
+ description,
+ tokenPrefix,
+ CollectionMode.Fungible,
+ DECIMALS,
+ ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+ ])
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
+ }
+ });
+
+ itEth('(!negative test!) cannot create collection if value !== 2', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
+ const expects = [0n, 1n, 30n].map(async value => {
+ await expect(collectionHelper.methods
+ .createCollection([
+ emptyAddress,
+ 'Peasantry',
+ 'absolutely anything',
+ 'TWIW',
+ CollectionMode.Fungible,
+ DECIMALS,
+ ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+ ])
+ .call({value: Number(value * nominal)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+ });
+ await Promise.all(expects);
+ });
+ });
+
+ describe('Nonfungible collection', () => {
+ before(async function() {
+ await usingEthPlaygrounds((helper) => {
+ requirePalletsOrSkip(this, helper, [Pallets.NFT]);
+ return Promise.resolve();
+ });
+ });
+
+ itEth('Create collection', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const name = 'CollectionEVM';
+ const description = 'Some description';
+ const prefix = 'token prefix';
+
+ // todo:playgrounds this might fail when in async environment.
+ const collectionCountBefore = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
+ const {collectionId, collectionAddress, events} = await helper.eth.createCollection(owner, new CreateCollectionData(name, description, prefix, 'nft')).send();
+
+ expect(events).to.be.deep.equal([
+ {
+ address: '0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F',
+ event: 'CollectionCreated',
+ args: {
+ owner: owner,
+ collectionId: collectionAddress,
+ },
+ },
+ ]);
+
+ const collectionCountAfter = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
+
+ const collection = helper.nft.getCollectionObject(collectionId);
+ const data = (await collection.getData())!;
+
+ expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
+ expect(collectionId).to.be.eq(collectionCountAfter);
+ expect(data.name).to.be.eq(name);
+ expect(data.description).to.be.eq(description);
+ expect(data.raw.tokenPrefix).to.be.eq(prefix);
+ expect(data.raw.mode).to.be.eq('NFT');
+
+ const options = await collection.getOptions();
+
+ expect(options.tokenPropertyPermissions).to.be.empty;
+ });
+
+ // this test will occasionally fail when in async environment.
+ itEth('Check collection address exist', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const expectedCollectionId = +(await helper.callRpc('api.rpc.unique.collectionStats')).created + 1;
+ const expectedCollectionAddress = helper.ethAddress.fromCollectionId(expectedCollectionId);
+ const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);
+
+ expect(await collectionHelpers.methods
+ .isCollectionExist(expectedCollectionAddress)
+ .call()).to.be.false;
+
+ await collectionHelpers.methods
+ .createCollection([
+ emptyAddress,
+ 'A',
+ 'A',
+ 'A',
+ CollectionMode.Nonfungible,
+ 0,
+ ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+ ])
+ .send({value: Number(2n * helper.balance.getOneTokenNominal())});
+
+ expect(await collectionHelpers.methods
+ .isCollectionExist(expectedCollectionAddress)
+ .call()).to.be.true;
+ });
+ });
+
+ describe('Create RFT collection from EVM', () => {
+ before(async function() {
+ await usingEthPlaygrounds((helper) => {
+ requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+ return Promise.resolve();
+ });
+ });
+
+ itEth('Create collection', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const name = 'CollectionEVM';
+ const description = 'Some description';
+ const prefix = 'token prefix';
+
+ const {collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData(name, description, prefix, 'rft')).send();
+ const data = (await helper.rft.getData(collectionId))!;
+ const collection = helper.rft.getCollectionObject(collectionId);
+
+ expect(data.name).to.be.eq(name);
+ expect(data.description).to.be.eq(description);
+ expect(data.raw.tokenPrefix).to.be.eq(prefix);
+ expect(data.raw.mode).to.be.eq('ReFungible');
+
+ const options = await collection.getOptions();
+
+ expect(options.tokenPropertyPermissions).to.be.empty;
+ });
+
+ itEth('Create collection with properties & get description', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const name = 'CollectionEVM';
+ const description = 'Some description';
+ const prefix = 'token prefix';
+ const baseUri = 'BaseURI';
+
+ const {collectionId, collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, name, description, prefix, baseUri);
+ const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
+
+ const collection = helper.rft.getCollectionObject(collectionId);
+ const data = (await collection.getData())!;
+
+ expect(data.name).to.be.eq(name);
+ expect(data.description).to.be.eq(description);
+ expect(data.raw.tokenPrefix).to.be.eq(prefix);
+ expect(data.raw.mode).to.be.eq('ReFungible');
+
+ expect(await contract.methods.description().call()).to.deep.equal(description);
+
+ const options = await collection.getOptions();
+ expect(options.tokenPropertyPermissions).to.be.deep.equal([
+ {
+ key: 'URI',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ {
+ key: 'URISuffix',
+ permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+ },
+ ]);
+ });
+
+ itEth('Set sponsorship', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const ss58Format = helper.chain.getChainProperties().ss58Format;
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('Sponsor', 'absolutely anything', 'ENVY', 'rft')).send();
+
+ const collection = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+ const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);
+ await collection.methods.setCollectionSponsorCross(sponsorCross).send();
+
+ let data = (await helper.rft.getData(collectionId))!;
+ expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
+
+ await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');
+
+ const sponsorCollection = await helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor);
+ await sponsorCollection.methods.confirmCollectionSponsorship().send();
+
+ data = (await helper.rft.getData(collectionId))!;
+ expect(data.raw.sponsorship.Confirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
+ });
+
+ itEth('Collection address exist', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const collectionAddressForNonexistentCollection = '0x17C4E6453CC49AAAAEACA894E6D9683E00112233';
+ const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);
+
+ expect(await collectionHelpers
+ .methods.isCollectionExist(collectionAddressForNonexistentCollection).call())
+ .to.be.false;
+
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('Exister', 'absolutely anything', 'WIWT', 'rft')).send();
+ expect(await collectionHelpers
+ .methods.isCollectionExist(collectionAddress).call())
+ .to.be.true;
+
+ // check collectionOwner:
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner, true);
+ const collectionOwner = await collectionEvm.methods.collectionOwner().call();
+ expect(helper.address.restoreCrossAccountFromBigInt(BigInt(collectionOwner.sub))).to.eq(helper.address.ethToSubstrate(owner, true));
+ });
+
+ itEth('destroyCollection', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('Limits', 'absolutely anything', 'OLF', 'rft')).send();
+ const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
+
+ await expect(collectionHelper.methods
+ .destroyCollection(collectionAddress)
+ .send({from: owner})).to.be.fulfilled;
+
+ expect(await collectionHelper.methods
+ .isCollectionExist(collectionAddress)
+ .call()).to.be.false;
+ expect(await helper.collection.getData(collectionId)).to.be.null;
+ });
+
+ itEth('(!negative test!) Create collection (bad lengths)', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
+ {
+ const MAX_NAME_LENGTH = 64;
+ const collectionName = 'A'.repeat(MAX_NAME_LENGTH + 1);
+ const description = 'A';
+ const tokenPrefix = 'A';
+
+ await expect(collectionHelper.methods
+ .createCollection([
+ emptyAddress,
+ collectionName,
+ description,
+ tokenPrefix,
+ CollectionMode.Refungible,
+ DECIMALS,
+ ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+ ])
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
+ }
+ {
+ const MAX_DESCRIPTION_LENGTH = 256;
+ const collectionName = 'A';
+ const description = 'A'.repeat(MAX_DESCRIPTION_LENGTH + 1);
+ const tokenPrefix = 'A';
+ await expect(collectionHelper.methods
+ .createCollection([
+ emptyAddress,
+ collectionName,
+ description,
+ tokenPrefix,
+ CollectionMode.Refungible,
+ DECIMALS,
+ ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+ ])
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
+ }
+ {
+ const MAX_TOKEN_PREFIX_LENGTH = 16;
+ const collectionName = 'A';
+ const description = 'A';
+ const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGTH + 1);
+ await expect(collectionHelper.methods
+ .createCollection([
+ emptyAddress,
+ collectionName,
+ description,
+ tokenPrefix,
+ CollectionMode.Refungible,
+ DECIMALS,
+ ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+ ])
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
+ }
+ });
+
+ itEth('(!negative test!) Create collection (no funds)', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
+ await expect(collectionHelper.methods
+ .createCollection([
+ emptyAddress,
+ 'Peasantry',
+ 'absolutely anything',
+ 'TWIW',
+ CollectionMode.Refungible,
+ 0,
+ ...CREATE_COLLECTION_DATA_DEFAULTS_ARRAY,
+ ])
+ .call({value: Number(1n * nominal)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+ });
+ });
+
+ describe('Sponsoring', () => {
+ itEth('Сan remove collection sponsor', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const sponsorCross = helper.ethCrossAccount.fromAddr(sponsor);
+
+ const {collectionAddress} = await helper.eth.createCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'Sponsor collection',
+ description: '1',
+ tokenPrefix: '1',
+ collectionMode: 'nft',
+ pendingSponsor: sponsorCross,
+ },
+ ).send();
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
+
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
+ let sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});
+ expect(helper.address.restoreCrossAccountFromBigInt(BigInt(sponsorStruct.sub))).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
+
+ await collectionEvm.methods.removeCollectionSponsor().send({from: owner});
+
+ sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});
+ expect(sponsorStruct.eth).to.be.eq('0x0000000000000000000000000000000000000000');
+ });
+
+ itEth('Can sponsor from evm address via access list', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsorEth = await helper.eth.createAccountWithBalance(donor);
+ const sponsorCross = helper.ethCrossAccount.fromAddr(sponsorEth);
+
+ const {collectionId, collectionAddress} = await helper.eth.createERC721MetadataCompatibleCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'Sponsor collection',
+ description: '1',
+ tokenPrefix: '1',
+ collectionMode: 'nft',
+ pendingSponsor: sponsorCross,
+ limits: [{field: CollectionLimitField.SponsoredDataRateLimit, value: 30n}],
+ tokenPropertyPermissions: [{key: 'key', permissions: [{code: TokenPermissionField.TokenOwner, value: true}]}],
+ },
+ '',
+ );
+
+ const collectionSub = helper.nft.getCollectionObject(collectionId);
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ let sponsorship = (await collectionSub.getData())!.raw.sponsorship;
+ expect(sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));
+ // Account cannot confirm sponsorship if it is not set as a sponsor
+ await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');
+
+ // Sponsor can confirm sponsorship:
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});
+ sponsorship = (await collectionSub.getData())!.raw.sponsorship;
+ expect(sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));
+
+ // Create user with no balance:
+ const user = helper.ethCrossAccount.createAccount();
+ const nextTokenId = await collectionEvm.methods.nextTokenId().call();
+ expect(nextTokenId).to.be.equal('1');
+
+ // Set collection permissions:
+ const oldPermissions = (await collectionSub.getData())!.raw.permissions;
+ expect(oldPermissions.mintMode).to.be.false;
+ expect(oldPermissions.access).to.be.equal('Normal');
+
+ await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});
+ await collectionEvm.methods.addToCollectionAllowListCross(user).send({from: owner});
+ await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
+
+ const newPermissions = (await collectionSub.getData())!.raw.permissions;
+ expect(newPermissions.mintMode).to.be.true;
+ expect(newPermissions.access).to.be.equal('AllowList');
+
+ const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
+ const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));
+
+ // User can mint token without balance:
+ {
+ const result = await collectionEvm.methods.mintCross(user, [{key: 'key', value: Buffer.from('Value')}]).send({from: user.eth});
+ const event = helper.eth.normalizeEvents(result.events)
+ .find(event => event.event === 'Transfer');
+
+ expect(event).to.be.deep.equal({
+ address: collectionAddress,
+ event: 'Transfer',
+ args: {
+ from: '0x0000000000000000000000000000000000000000',
+ to: user.eth,
+ tokenId: '1',
+ },
+ });
+
+ // await collectionEvm.methods.setProperties(1, [{key: 'key', value: Buffer.from('Value1')}]).send({from: user.eth});
+
+ const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
+ const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));
+
+ expect(await collectionEvm.methods.properties(nextTokenId, []).call())
+ .to.be.like([
+ [
+ 'key',
+ '0x' + Buffer.from('Value').toString('hex'),
+ ],
+ ]);
+ expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
+ expect(userBalanceAfter).to.be.eq(userBalanceBefore);
+ expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;
+ }
+ });
+
+ itEth('Check that transaction via EVM spend money from sponsor address', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const sponsorCross = helper.ethCrossAccount.fromAddr(sponsor);
+ const user = helper.eth.createAccount();
+ const userCross = helper.ethCrossAccount.fromAddress(user);
+
+ const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'Sponsor collection',
+ description: '1',
+ tokenPrefix: '1',
+ collectionMode: 'nft',
+ pendingSponsor: sponsorCross,
+ adminList: [userCross],
+ },
+ '',
+ );
+
+ const collectionSub = helper.nft.getCollectionObject(collectionId);
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+ // Set collection sponsor:
+ let collectionData = (await collectionSub.getData())!;
+ expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
+ await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');
+
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
+ collectionData = (await collectionSub.getData())!;
+ expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
+
+ const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+
+ const mintingResult = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
+ const tokenId = mintingResult.events.Transfer.returnValues.tokenId;
+
+ const event = helper.eth.normalizeEvents(mintingResult.events)
+ .find(event => event.event === 'Transfer');
+ const address = helper.ethAddress.fromCollectionId(collectionId);
+
+ expect(event).to.be.deep.equal({
+ address,
+ event: 'Transfer',
+ args: {
+ from: '0x0000000000000000000000000000000000000000',
+ to: user,
+ tokenId: '1',
+ },
+ });
+ expect(await collectionEvm.methods.tokenURI(tokenId).call({from: user})).to.be.equal('Test URI');
+
+ const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+ expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
+ });
+
+ itEth('Can reassign collection sponsor', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsorEth = await helper.eth.createAccountWithBalance(donor);
+ const sponsorCrossEth = helper.ethCrossAccount.fromAddr(sponsorEth);
+ const [sponsorSub] = await helper.arrange.createAccounts([100n], donor);
+ const sponsorCrossSub = helper.ethCrossAccount.fromKeyringPair(sponsorSub);
+
+ const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'Sponsor collection',
+ description: '1',
+ tokenPrefix: '1',
+ collectionMode: 'nft',
+ pendingSponsor: sponsorCrossEth,
+ },
+ '',
+ );
+ const collectionSub = helper.nft.getCollectionObject(collectionId);
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ // Set and confirm sponsor:
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});
+
+ // Can reassign sponsor:
+ await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossSub).send({from: owner});
+ const collectionSponsor = (await collectionSub.getData())?.raw.sponsorship;
+ expect(collectionSponsor).to.deep.eq({Unconfirmed: sponsorSub.address});
+ });
+
+ [
+ 'transfer',
+ 'transferCross',
+ 'transferFrom',
+ 'transferFromCross',
+ ].map(testCase =>
+ itEth(`[${testCase}] Check that transfer via EVM spend money from sponsor address`, async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const sponsorCross = helper.ethCrossAccount.fromAddr(sponsor);
+ const user = await helper.eth.createAccountWithBalance(donor);
+ const userCross = helper.ethCrossAccount.fromAddress(user);
+
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'Sponsor collection',
+ description: '1',
+ tokenPrefix: '1',
+ collectionMode: 'rft',
+ pendingSponsor: sponsorCross,
+ adminList: [userCross],
+ },
+ '',
+ );
+ const receiver = await helper.eth.createAccountWithBalance(donor);
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
+
+ const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+
+ const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+ const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+
+ switch (testCase) {
+ case 'transfer':
+ await collectionEvm.methods.transfer(receiver, tokenId).send({from: user});
+ break;
+ case 'transferCross':
+ await collectionEvm.methods.transferCross(helper.ethCrossAccount.fromAddress(receiver), tokenId).send({from: user});
+ break;
+ case 'transferFrom':
+ await collectionEvm.methods.transferFrom(user, receiver, tokenId).send({from: user});
+ break;
+ case 'transferFromCross':
+ await collectionEvm.methods.transferFromCross(helper.ethCrossAccount.fromAddress(user), helper.ethCrossAccount.fromAddress(receiver), tokenId).send({from: user});
+ break;
+ }
+
+ const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+ expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
+ const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+ expect(userBalanceAfter).to.be.eq(userBalanceBefore);
+ }));
+ });
+
+ describe('Collection admins', () => {
+ let donor: IKeyringPair;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (_helper, privateKey) => {
+ donor = await privateKey({url: import.meta.url});
+ });
+ });
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ {mode: 'ft' as const, requiredPallets: []},
+ ].map(testCase => {
+ itEth.ifWithPallets(`can add account admin by owner for ${testCase.mode}`, testCase.requiredPallets, async ({helper, privateKey}) => {
+ // arrange
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const adminSub = await privateKey('//admin2');
+ const adminEth = helper.eth.createAccount().toLowerCase();
+
+ const adminCrossSub = helper.ethCrossAccount.fromKeyringPair(adminSub);
+ const adminCrossEth = helper.ethCrossAccount.fromAddress(adminEth);
+
+ const {collectionAddress, collectionId} = await helper.eth.createCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'Mint collection',
+ description: 'a',
+ tokenPrefix: 'b',
+ collectionMode: testCase.mode,
+ adminList: [adminCrossSub, adminCrossEth],
+ },
+ ).send();
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner, true);
+
+ // 1. Expect api.rpc.unique.adminlist returns admins:
+ const adminListRpc = await helper.collection.getAdmins(collectionId);
+ expect(adminListRpc).to.has.length(2);
+ expect(adminListRpc).to.be.deep.contain.members([{Substrate: adminSub.address}, {Ethereum: adminEth}]);
+
+ // 2. Expect methods.collectionAdmins == api.rpc.unique.adminlist
+ let adminListEth = await collectionEvm.methods.collectionAdmins().call();
+ adminListEth = adminListEth.map((element: IEthCrossAccountId) => helper.address.convertCrossAccountFromEthCrossAccount(element));
+ expect(adminListRpc).to.be.like(adminListEth);
+
+ // 3. check isOwnerOrAdminCross returns true:
+ expect(await collectionEvm.methods.isOwnerOrAdminCross(adminCrossSub).call()).to.be.true;
+ expect(await collectionEvm.methods.isOwnerOrAdminCross(adminCrossEth).call()).to.be.true;
+ });
+ });
+
+ itEth('cross account admin can mint', async ({helper}) => {
+ // arrange: create collection and accounts
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const adminEth = (await helper.eth.createAccountWithBalance(donor)).toLowerCase();
+ const adminCrossEth = helper.ethCrossAccount.fromAddress(adminEth);
+ const [adminSub] = await helper.arrange.createAccounts([100n], donor);
+ const adminCrossSub = helper.ethCrossAccount.fromKeyringPair(adminSub);
+ const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'Mint collection',
+ description: 'a',
+ tokenPrefix: 'b',
+ collectionMode: 'nft',
+ adminList: [adminCrossSub, adminCrossEth],
+ },
+ 'uri',
+ );
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner, true);
+
+ // admin (sub and eth) can mint token:
+ await collectionEvm.methods.mint(owner).send({from: adminEth});
+ await helper.nft.mintToken(adminSub, {collectionId, owner: {Ethereum: owner}});
+
+ expect(await helper.collection.getLastTokenId(collectionId)).to.eq(2);
+ });
+
+ itEth('cannot add invalid cross account admin', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const [admin] = await helper.arrange.createAccounts([100n, 100n], donor);
+
+ const adminCross = {
+ eth: helper.address.substrateToEth(admin.address),
+ sub: admin.addressRaw,
+ };
+
+ await expect(helper.eth.createCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'A',
+ description: 'B',
+ tokenPrefix: 'C',
+ collectionMode: 'nft',
+ adminList: [adminCross],
+ },
+ ).call()).to.be.rejected;
+ });
+
+ itEth('Remove [cross] admin by owner', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const [adminSub] = await helper.arrange.createAccounts([10n], donor);
+ const adminEth = (await helper.eth.createAccountWithBalance(donor)).toLowerCase();
+ const adminCrossSub = helper.ethCrossAccount.fromKeyringPair(adminSub);
+ const adminCrossEth = helper.ethCrossAccount.fromAddress(adminEth);
+
+ const {collectionAddress, collectionId} = await helper.eth.createCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'A',
+ description: 'B',
+ tokenPrefix: 'C',
+ collectionMode: 'nft',
+ adminList: [adminCrossSub, adminCrossEth],
+ },
+ ).send();
+
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ {
+ const adminList = await helper.collection.getAdmins(collectionId);
+ expect(adminList).to.deep.include({Substrate: adminSub.address});
+ expect(adminList).to.deep.include({Ethereum: adminEth});
+ }
+
+ await collectionEvm.methods.removeCollectionAdminCross(adminCrossSub).send();
+ await collectionEvm.methods.removeCollectionAdminCross(adminCrossEth).send();
+ const adminList = await helper.collection.getAdmins(collectionId);
+ expect(adminList.length).to.be.eq(0);
+
+ // Non admin cannot mint:
+ await expect(helper.nft.mintToken(adminSub, {collectionId, owner: {Substrate: adminSub.address}})).to.be.rejectedWith(/common.PublicMintingNotAllowed/);
+ await expect(collectionEvm.methods.mint(adminEth).send({from: adminEth})).to.be.rejected;
+ });
+ });
+
+ describe('Collection limits', () => {
+ describe('Can set collection limits', () => {
+ [
+ {case: 'nft' as const},
+ {case: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ {case: 'ft' as const},
+ ].map(testCase =>
+ itEth.ifWithPallets(`for ${testCase.case}`, testCase.requiredPallets || [], async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const limits = {
+ accountTokenOwnershipLimit: 1000n,
+ sponsoredDataSize: 1024n,
+ sponsoredDataRateLimit: 30n,
+ tokenLimit: 1000000n,
+ sponsorTransferTimeout: 6n,
+ sponsorApproveTimeout: 6n,
+ ownerCanTransfer: 1n,
+ ownerCanDestroy: 0n,
+ transfersEnabled: 0n,
+ };
+
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'Limits',
+ description: 'absolutely anything',
+ tokenPrefix: 'FLO',
+ collectionMode: testCase.case,
+ limits: [
+ {field: CollectionLimitField.AccountTokenOwnership, value: limits.accountTokenOwnershipLimit},
+ {field: CollectionLimitField.SponsoredDataSize, value: limits.sponsoredDataSize},
+ {field: CollectionLimitField.SponsoredDataRateLimit, value: limits.sponsoredDataRateLimit},
+ {field: CollectionLimitField.TokenLimit, value: limits.tokenLimit},
+ {field: CollectionLimitField.SponsorTransferTimeout, value: limits.sponsorTransferTimeout},
+ {field: CollectionLimitField.SponsorApproveTimeout, value: limits.sponsorApproveTimeout},
+ {field: CollectionLimitField.OwnerCanTransfer, value: limits.ownerCanTransfer},
+ {field: CollectionLimitField.OwnerCanDestroy, value: limits.ownerCanDestroy},
+ {field: CollectionLimitField.TransferEnabled, value: limits.transfersEnabled},
+ ],
+ },
+ ).send();
+
+ const expectedLimits = {
+ accountTokenOwnershipLimit: 1000,
+ sponsoredDataSize: 1024,
+ sponsoredDataRateLimit: {blocks: 30},
+ tokenLimit: 1000000,
+ sponsorTransferTimeout: 6,
+ sponsorApproveTimeout: 6,
+ ownerCanTransfer: true,
+ ownerCanDestroy: false,
+ transfersEnabled: false,
+ };
+
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.case, owner);
+
+ // Check limits from sub:
+ const data = (await helper.rft.getData(collectionId))!;
+ expect(data.raw.limits).to.deep.eq(expectedLimits);
+ expect(await helper.collection.getEffectiveLimits(collectionId)).to.deep.eq(expectedLimits);
+ // Check limits from eth:
+ const limitsEvm = await collectionEvm.methods.collectionLimits().call({from: owner});
+ expect(limitsEvm).to.have.length(9);
+ expect(limitsEvm[0]).to.deep.eq([CollectionLimitField.AccountTokenOwnership.toString(), [true, limits.accountTokenOwnershipLimit.toString()]]);
+ expect(limitsEvm[1]).to.deep.eq([CollectionLimitField.SponsoredDataSize.toString(), [true, limits.sponsoredDataSize.toString()]]);
+ expect(limitsEvm[2]).to.deep.eq([CollectionLimitField.SponsoredDataRateLimit.toString(), [true, limits.sponsoredDataRateLimit.toString()]]);
+ expect(limitsEvm[3]).to.deep.eq([CollectionLimitField.TokenLimit.toString(), [true, limits.tokenLimit.toString()]]);
+ expect(limitsEvm[4]).to.deep.eq([CollectionLimitField.SponsorTransferTimeout.toString(), [true, limits.sponsorTransferTimeout.toString()]]);
+ expect(limitsEvm[5]).to.deep.eq([CollectionLimitField.SponsorApproveTimeout.toString(), [true, limits.sponsorApproveTimeout.toString()]]);
+ expect(limitsEvm[6]).to.deep.eq([CollectionLimitField.OwnerCanTransfer.toString(), [true, limits.ownerCanTransfer.toString()]]);
+ expect(limitsEvm[7]).to.deep.eq([CollectionLimitField.OwnerCanDestroy.toString(), [true, limits.ownerCanDestroy.toString()]]);
+ expect(limitsEvm[8]).to.deep.eq([CollectionLimitField.TransferEnabled.toString(), [true, limits.transfersEnabled.toString()]]);
+ }));
+ });
+
+ describe('(!negative test!) Cannot set invalid collection limits', () => {
+ [
+ {case: 'nft' as const},
+ {case: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ {case: 'ft' as const},
+ ].map(testCase =>
+ itEth.ifWithPallets(`for ${testCase.case}`, testCase.requiredPallets || [], async ({helper}) => {
+ const invalidLimits = {
+ accountTokenOwnershipLimit: BigInt(Number.MAX_SAFE_INTEGER),
+ transfersEnabled: 3,
+ };
+
+ const createCollectionData = {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'Limits',
+ description: 'absolutely anything',
+ tokenPrefix: 'ISNI',
+ collectionMode: testCase.case,
+ };
+
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ await expect(helper.eth.createCollection(
+ owner,
+ {
+ ...createCollectionData,
+ limits: [{field: 9 as CollectionLimitField, value: 1n}],
+ },
+ ).call()).to.be.rejectedWith('value not convertible into enum "CollectionLimitField"');
+
+ await expect(helper.eth.createCollection(
+ owner,
+ {
+ ...createCollectionData,
+ limits: [{field: CollectionLimitField.AccountTokenOwnership, value: invalidLimits.accountTokenOwnershipLimit}],
+ },
+ ).call()).to.be.rejectedWith(`can't convert value to u32 "${invalidLimits.accountTokenOwnershipLimit}"`);
+
+ await expect(helper.eth.createCollection(
+ owner,
+ {
+ ...createCollectionData,
+ limits: [{field: CollectionLimitField.TransferEnabled, value: 3n}],
+ },
+ ).call()).to.be.rejectedWith(`can't convert value to boolean "${invalidLimits.transfersEnabled}"`);
+
+ await expect(helper.eth.createCollection(
+ owner,
+ {
+ ...createCollectionData,
+ limits: [{field: CollectionLimitField.SponsoredDataSize, value: -1n}],
+ },
+ ).call()).to.be.rejectedWith('value out-of-bounds');
+ }));
+ });
+ });
+
+ describe('Collection properties', () => {
+
+ [
+ {mode: 'nft' as const, methodParams: [{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}], expectedProps: [{key: 'testKey1', value: 'testValue1'}, {key: 'testKey2', value: 'testValue2'}]},
+ {mode: 'rft' as const, methodParams: [{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}], expectedProps: [{key: 'testKey1', value: 'testValue1'}, {key: 'testKey2', value: 'testValue2'}]},
+ {mode: 'ft' as const, methodParams: [{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}], expectedProps: [{key: 'testKey1', value: 'testValue1'}, {key: 'testKey2', value: 'testValue2'}]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`Collection properties can be set for ${testCase.mode}`, testCase.mode === 'rft' ? [Pallets.ReFungible] : [], async({helper}) => {
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const callerCross = helper.ethCrossAccount.fromAddress(caller);
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'name',
+ description: 'test',
+ tokenPrefix: 'test',
+ collectionMode: testCase.mode,
+ adminList: [callerCross],
+ properties: testCase.methodParams,
+ },
+ ).send();
+
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, caller);
+
+ const raw = (await helper[testCase.mode].getData(collectionId))?.raw;
+ expect(raw.properties).to.deep.equal(testCase.expectedProps);
+
+ // collectionProperties returns properties:
+ expect(await collectionEvm.methods.collectionProperties([]).call()).to.be.like(testCase.expectedProps.map(prop => helper.ethProperty.property(prop.key, prop.value)));
+ }));
+
+ [
+ {mode: 'nft' as const},
+ {mode: 'rft' as const},
+ {mode: 'ft' as const},
+ ].map(testCase =>
+ itEth.ifWithPallets(`Collection properties can be deleted for ${testCase.mode}`, testCase.mode === 'rft' ? [Pallets.ReFungible] : [], async({helper}) => {
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const callerCross = helper.ethCrossAccount.fromAddress(caller);
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'name',
+ description: 'test',
+ tokenPrefix: 'test',
+ collectionMode: testCase.mode,
+ adminList: [callerCross],
+ properties:[
+ {key: 'testKey1', value: Buffer.from('testValue1')},
+ {key: 'testKey2', value: Buffer.from('testValue2')},
+ {key: 'testKey3', value: Buffer.from('testValue3')}],
+ },
+ ).send();
+
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, caller);
+
+ await collectionEvm.methods.deleteCollectionProperties(['testKey1', 'testKey2']).send({from: caller});
+
+ const raw = (await helper[testCase.mode].getData(collectionId))?.raw;
+
+ expect(raw.properties.length).to.equal(1);
+ expect(raw.properties).to.deep.equal([{key: 'testKey3', value: 'testValue3'}]);
+ }));
+
+ itEth('(!negative test!) Cannot set invalid properties', async({helper}) => {
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const callerCross = helper.ethCrossAccount.fromAddress(caller);
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const createCollectionData = {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'name',
+ description: 'test',
+ tokenPrefix: 'test',
+ collectionMode: 'nft' as TCollectionMode,
+ adminList: [callerCross],
+ };
+ await expect(helper.eth.createCollection(
+ owner,
+ {
+ ...createCollectionData,
+ properties: [{key: '', value: Buffer.from('val1')}],
+ },
+ ).call()).to.be.rejected;
+
+ await expect(helper.eth.createCollection(
+ owner,
+ {
+ ...createCollectionData,
+ properties: [{key: 'déjà vu', value: Buffer.from('hmm...')}],
+ },
+ ).call()).to.be.rejected;
+
+ await expect(helper.eth.createCollection(
+ owner,
+ {
+ ...createCollectionData,
+ properties: [{key: 'a'.repeat(257), value: Buffer.from('val3')}],
+ },
+ ).call()).to.be.rejected;
+ });
+
+ itEth('(!negative test!) cannot delete properties of non-owned collections', async ({helper}) => {
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionAddress} = await helper.eth.createCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'name',
+ description: 'test',
+ tokenPrefix: 'test',
+ collectionMode: 'nft',
+ properties:[
+ {key: 'testKey1', value: Buffer.from('testValue1')},
+ {key: 'testKey2', value: Buffer.from('testValue2')}],
+ },
+ ).send();
+
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', caller);
+
+ await expect(collectionEvm.methods.deleteCollectionProperties(['testKey2']).send({from: caller})).to.be.rejected;
+ });
+ });
+
+ describe('Token property permissions', () => {
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Can set all possible 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(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'A',
+ description: 'B',
+ tokenPrefix: 'C',
+ collectionMode: testCase.mode,
+ adminList: [caller],
+ tokenPropertyPermissions: [
+ {
+ key: 'testKey',
+ permissions: [
+ {code: TokenPermissionField.Mutable, value: mutable},
+ {code: TokenPermissionField.TokenOwner, value: tokenOwner},
+ {code: TokenPermissionField.CollectionAdmin, value: collectionAdmin},
+ ],
+ },
+ ],
+ },
+ ).send();
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+ 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', [
+ [TokenPermissionField.Mutable.toString(), mutable],
+ [TokenPermissionField.TokenOwner.toString(), tokenOwner],
+ [TokenPermissionField.CollectionAdmin.toString(), collectionAdmin]],
+ ],
+ ]);
+ }
+ }));
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Can set multiple token property permissions`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'A',
+ description: 'B',
+ tokenPrefix: 'C',
+ collectionMode: testCase.mode,
+ tokenPropertyPermissions: [
+ {
+ key: 'testKey_0',
+ permissions: [
+ {code: TokenPermissionField.Mutable, value: true},
+ {code: TokenPermissionField.TokenOwner, value: true},
+ {code: TokenPermissionField.CollectionAdmin, value: true}],
+ },
+ {
+ key: 'testKey_1',
+ permissions: [
+ {code: TokenPermissionField.Mutable, value: true},
+ {code: TokenPermissionField.TokenOwner, value: false},
+ {code: TokenPermissionField.CollectionAdmin, value: true}],
+ },
+ {
+ key: 'testKey_2',
+ permissions: [
+ {code: TokenPermissionField.Mutable, value: false},
+ {code: TokenPermissionField.TokenOwner, value: true},
+ {code: TokenPermissionField.CollectionAdmin, value: false}],
+ },
+ ],
+ },
+ ).send();
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, 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', [
+ [TokenPermissionField.Mutable.toString(), true],
+ [TokenPermissionField.TokenOwner.toString(), true],
+ [TokenPermissionField.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_1', [
+ [TokenPermissionField.Mutable.toString(), true],
+ [TokenPermissionField.TokenOwner.toString(), false],
+ [TokenPermissionField.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_2', [
+ [TokenPermissionField.Mutable.toString(), false],
+ [TokenPermissionField.TokenOwner.toString(), true],
+ [TokenPermissionField.CollectionAdmin.toString(), false]],
+ ],
+ ]);
+ }));
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`Can be deleted for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const receiver = await helper.ethCrossAccount.createAccountWithBalance(donor);
+ const {collectionAddress} = await helper.eth.createCollection(
+ caller,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'A',
+ description: 'B',
+ tokenPrefix: 'C',
+ collectionMode: testCase.mode,
+ adminList: [receiver],
+ tokenPropertyPermissions: [
+ {
+ key: 'testKey',
+ permissions: [
+ {code: TokenPermissionField.Mutable, value: true},
+ {code: TokenPermissionField.CollectionAdmin, value: true}],
+ },
+ {
+ key: 'testKey_1',
+ permissions: [
+ {code: TokenPermissionField.Mutable, value: true},
+ {code: TokenPermissionField.CollectionAdmin, value: true}],
+ },
+ ],
+ },
+ ).send();
+
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, caller);
+ const tokenId = (await collection.methods.mintCross(receiver, [{key: 'testKey', value: Buffer.from('testValue')}, {key: 'testKey_1', value: Buffer.from('testValue_1')}]).send()).events.Transfer.returnValues.tokenId;
+ expect(await collection.methods.properties(tokenId, ['testKey', 'testKey_1']).call()).to.has.length(2);
+
+ await collection.methods.deleteProperties(tokenId, ['testKey', 'testKey_1']).send({from: caller});
+ expect(await collection.methods.properties(tokenId, ['testKey', 'testKey_1']).call()).to.has.length(0);
+ }));
+ });
+
+ describe('Nesting', () => {
+ itEth('NFT: allows an Owner to nest/unnest their token', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionAddress, collectionId} = await helper.eth.createCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'A',
+ description: 'B',
+ tokenPrefix: 'C',
+ collectionMode: 'nft',
+ nestingSettings: {token_owner: true, collection_admin: false, restricted: []},
+ },
+ ).send();
+
+ const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ // Create a token to be nested to
+ const mintingTargetNFTTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const targetNFTTokenId = mintingTargetNFTTokenIdResult.events.Transfer.returnValues.tokenId;
+ const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNFTTokenId);
+
+ // Create a nested token
+ const mintingFirstTokenIdResult = await contract.methods.mint(targetNftTokenAddress).send({from: owner});
+ const firstTokenId = mintingFirstTokenIdResult.events.Transfer.returnValues.tokenId;
+ expect(await contract.methods.ownerOf(firstTokenId).call()).to.be.equal(targetNftTokenAddress);
+
+ // Create a token to be nested and nest
+ const mintingSecondTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const secondTokenId = mintingSecondTokenIdResult.events.Transfer.returnValues.tokenId;
+
+ await contract.methods.transfer(targetNftTokenAddress, secondTokenId).send({from: owner});
+ expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(targetNftTokenAddress);
+
+ // Unnest token back
+ await contract.methods.transferFrom(targetNftTokenAddress, owner, secondTokenId).send({from: owner});
+ expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(owner);
+ });
+
+ itEth('NFT: collectionNesting()', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionAddress: unnestedCollectionAddress} = await helper.eth.createCollection(
+ owner,
+ new CreateCollectionData('A', 'B', 'C', 'nft'),
+ ).send();
+
+ const unnestedContract = await helper.ethNativeContract.collection(unnestedCollectionAddress, 'nft', owner);
+ expect(await unnestedContract.methods.collectionNesting().call({from: owner})).to.be.like([false, false, []]);
+
+ const {collectionAddress} = await helper.eth.createCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'A',
+ description: 'B',
+ tokenPrefix: 'C',
+ collectionMode: 'nft',
+ nestingSettings: {token_owner: true, collection_admin: false, restricted: [unnestedCollectionAddress.toString()]},
+ },
+ ).send();
+
+ const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+ expect(await contract.methods.collectionNesting().call({from: owner})).to.be.like([true, false, [unnestedCollectionAddress.toString()]]);
+ await contract.methods.setCollectionNesting([false, false, []]).send({from: owner});
+ expect(await contract.methods.collectionNesting().call({from: owner})).to.be.like([false, false, []]);
+ });
+
+ itEth('NFT: disallows to nest token if nesting is disabled', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(
+ owner,
+ {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'A',
+ description: 'B',
+ tokenPrefix: 'C',
+ collectionMode: 'nft',
+ nestingSettings: {token_owner: false, collection_admin: false, restricted: []},
+ },
+ ).send();
+
+ const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ // Create a token to nest into
+ const mintingTargetTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
+ const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetTokenId);
+
+ // Create a token to nest
+ const mintingNftTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+ const nftTokenId = mintingNftTokenIdResult.events.Transfer.returnValues.tokenId;
+
+ // Try to nest
+ await expect(contract.methods
+ .transfer(targetNftTokenAddress, nftTokenId)
+ .call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
+ });
+ });
+
+ describe('Flags', () => {
+ const createCollectionData = {
+ ...CREATE_COLLECTION_DATA_DEFAULTS,
+ name: 'A',
+ description: 'B',
+ tokenPrefix: 'C',
+ collectionMode: 'nft' as TCollectionMode,
+ };
+
+ itEth('NFT: use numbers for flags', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ {
+ const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: 0}).send();
+ expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: false});
+ }
+
+ {
+ const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: 64}).send();
+ expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: true});
+ }
+ });
+
+ itEth('NFT: foreign flag number is ignored', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ {
+ const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: 128}).send();
+ expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: false});
+ }
+
+ {
+ const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: 192}).send();
+ expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: true});
+ }
+ });
+
+ itEth('NFT: use enum for flags', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ {
+ const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: [CollectionFlag.Erc721metadata]}).send();
+ expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: true});
+ }
+ });
+
+ itEth('NFT: foreign flag enum is ignored', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ {
+ const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: [CollectionFlag.Foreign]}).send();
+ expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: false});
+ }
+
+ {
+ const {collectionId} = await helper.eth.createCollection(owner, {...createCollectionData, flags: [CollectionFlag.Erc721metadata | CollectionFlag.Foreign]}).send();
+ expect((await helper.nft.getData(collectionId))?.raw.flags).to.be.deep.equal({foreign: false, erc721metadata: true});
+ }
+ });
+ });
+});
tests/src/eth/destroyCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/destroyCollection.test.ts
+++ b/tests/src/eth/destroyCollection.test.ts
@@ -17,13 +17,15 @@
import {IKeyringPair} from '@polkadot/types/types';
import {Pallets} from '../util';
import {expect, itEth, usingEthPlaygrounds} from './util';
+import {TCollectionMode} from '../util/playgrounds/types';
+import {CreateCollectionData} from './util/playgrounds/types';
describe('Destroy Collection from EVM', function() {
let donor: IKeyringPair;
const testCases = [
- {case: 'rft' as const, params: ['Limits', 'absolutely anything', 'OLF'], requiredPallets: [Pallets.ReFungible]},
- {case: 'nft' as const, params: ['Limits', 'absolutely anything', 'OLF'], requiredPallets: [Pallets.NFT]},
- {case: 'ft' as const, params: ['Limits', 'absolutely anything', 'OLF', 18], requiredPallets: [Pallets.Fungible]},
+ {case: 'rft' as const, params: ['Limits', 'absolutely anything', 'OLF', 'rft'], requiredPallets: [Pallets.ReFungible]},
+ {case: 'nft' as const, params: ['Limits', 'absolutely anything', 'OLF', 'nft'], requiredPallets: [Pallets.NFT]},
+ {case: 'ft' as const, params: ['Limits', 'absolutely anything', 'OLF', 'ft', 18], requiredPallets: [Pallets.Fungible]},
];
before(async function() {
@@ -40,8 +42,7 @@
const unexistedCollection = helper.ethAddress.fromCollectionId(1000000);
const collectionHelpers = await helper.ethNativeContract.collectionHelpers(signer);
- const {collectionAddress} = await helper.eth.createCollection(testCase.case, owner, ...testCase.params as [string, string, string, number?]);
-
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData(...testCase.params as [string, string, string, TCollectionMode, number?])).send();
// cannot burn collec
await expect(collectionHelpers.methods
.destroyCollection(collectionAddress)
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 {CollectionLimitField, TokenPermissionField, NormalizedEvent} from './util/playgrounds/types';
+import {CollectionLimitField, TokenPermissionField, NormalizedEvent, CreateCollectionData} from './util/playgrounds/types';
let donor: IKeyringPair;
@@ -39,7 +39,8 @@
async function testCollectionCreatedAndDestroy(helper: EthUniqueHelper, mode: TCollectionMode) {
const owner = await helper.eth.createAccountWithBalance(donor);
const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionCreated', 'CollectionDestroyed']}]);
- const {collectionAddress, events: ethEvents} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+ const {collectionAddress, events: ethEvents} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
+
await helper.wait.newBlocks(1);
{
expect(ethEvents).to.containSubset([
@@ -72,7 +73,7 @@
async function testCollectionPropertySetAndDeleted(helper: EthUniqueHelper, mode: TCollectionMode) {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
@@ -113,7 +114,7 @@
async function testPropertyPermissionSet(helper: EthUniqueHelper, mode: TCollectionMode) {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
const ethEvents: any = [];
@@ -144,7 +145,7 @@
async function testAllowListAddressAddedAndRemoved(helper: EthUniqueHelper, mode: TCollectionMode) {
const owner = await helper.eth.createAccountWithBalance(donor);
const user = helper.ethCrossAccount.createAccount();
- const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
const ethEvents: any[] = [];
@@ -186,7 +187,7 @@
async function testCollectionAdminAddedAndRemoved(helper: EthUniqueHelper, mode: TCollectionMode) {
const owner = await helper.eth.createAccountWithBalance(donor);
const user = helper.ethCrossAccount.createAccount();
- const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
const ethEvents: any = [];
@@ -226,7 +227,7 @@
async function testCollectionLimitSet(helper: EthUniqueHelper, mode: TCollectionMode) {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
const ethEvents: any = [];
@@ -253,7 +254,7 @@
async function testCollectionOwnerChanged(helper: EthUniqueHelper, mode: TCollectionMode) {
const owner = await helper.eth.createAccountWithBalance(donor);
const newOwner = helper.ethCrossAccount.createAccount();
- const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
const ethEvents: any = [];
@@ -279,7 +280,7 @@
async function testCollectionPermissionSet(helper: EthUniqueHelper, mode: TCollectionMode) {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
const ethEvents: any = [];
@@ -320,7 +321,7 @@
async function testCollectionSponsorSetAndConfirmedAndThenRemoved(helper: EthUniqueHelper, mode: TCollectionMode) {
const owner = await helper.eth.createAccountWithBalance(donor);
const sponsor = await helper.ethCrossAccount.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
const collectionHelper = await helper.ethNativeContract.collectionHelpers(owner);
const ethEvents: any = [];
@@ -374,7 +375,7 @@
async function testTokenPropertySetAndDeleted(helper: EthUniqueHelper, mode: TCollectionMode) {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createCollection(mode, owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', mode, 18)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, mode, owner);
const result = await collection.methods.mint(owner).send({from: owner});
const tokenId = result.events.Transfer.returnValues.tokenId;
tests/src/eth/marketplace-v2/Market.soldiffbeforeafterboth--- a/tests/src/eth/marketplace-v2/Market.sol
+++ b/tests/src/eth/marketplace-v2/Market.sol
@@ -7,7 +7,7 @@
import "@openzeppelin/contracts/access/Ownable.sol";
import { UniqueNFT, CrossAddress } from "@unique-nft/solidity-interfaces/contracts/UniqueNFT.sol";
import { UniqueFungible, CrossAddress as CrossAddressF } from "@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol";
-import "@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol";
+import { CollectionHelpers } from "@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol";
import "./royalty/UniqueRoyaltyHelper.sol";
contract Market is Ownable, ReentrancyGuard {
tests/src/eth/marketplace/marketplace.test.tsdiffbeforeafterboth--- a/tests/src/eth/marketplace/marketplace.test.ts
+++ b/tests/src/eth/marketplace/marketplace.test.ts
@@ -60,7 +60,7 @@
await helpers.methods.setSponsor(matcher.options.address, sponsor).send({from: matcherOwner});
await helpers.methods.confirmSponsorship(matcher.options.address).send({from: sponsor});
- const collection = await helper.nft.mintCollection(alice, {limits: {sponsorApproveTimeout: 1}, pendingSponsor: alice.address});
+ const collection = await helper.nft.mintCollection(alice, {limits: {sponsorApproveTimeout: 1}, pendingSponsor: {Substrate: alice.address}});
await collection.confirmSponsorship(alice);
await collection.addToAllowList(alice, {Substrate: aliceDoubleMirror});
const evmCollection = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(collection.collectionId), 'nft');
@@ -114,7 +114,7 @@
await helpers.methods.setSponsor(matcher.options.address, sponsor).send({from: matcherOwner});
await helpers.methods.confirmSponsorship(matcher.options.address).send({from: sponsor});
- const collection = await helper.nft.mintCollection(alice, {limits: {sponsorApproveTimeout: 1}, pendingSponsor: alice.address});
+ const collection = await helper.nft.mintCollection(alice, {limits: {sponsorApproveTimeout: 1}, pendingSponsor: {Substrate: alice.address}});
await collection.confirmSponsorship(alice);
await collection.addToAllowList(alice, {Substrate: aliceDoubleMirror});
const evmCollection = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(collection.collectionId), 'nft');
tests/src/eth/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/eth/nesting/nest.test.ts
+++ b/tests/src/eth/nesting/nest.test.ts
@@ -6,11 +6,12 @@
const createNestingCollection = async (
helper: EthUniqueHelper,
owner: string,
+ mergeDeprecated = false,
): Promise<{ collectionId: number, collectionAddress: string, contract: Contract }> => {
const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
- const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- await contract.methods.setCollectionNesting(true).send({from: owner});
+ const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner, mergeDeprecated);
+ await contract.methods.setCollectionNesting([true, false, []]).send({from: owner});
return {collectionId, collectionAddress, contract};
};
@@ -52,27 +53,44 @@
expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(owner);
});
+ itEth('NFT: collectionNesting()', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionAddress: unnestedCollectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
+ const unnestedContract = await helper.ethNativeContract.collection(unnestedCollectionAddress, 'nft', owner);
+ expect(await unnestedContract.methods.collectionNesting().call({from: owner})).to.be.like([false, false, []]);
+
+ const {contract} = await createNestingCollection(helper, owner);
+ expect(await contract.methods.collectionNesting().call({from: owner})).to.be.like([true, false, []]);
+ await contract.methods.setCollectionNesting([true, false, [unnestedCollectionAddress]]).send({from: owner});
+ expect(await contract.methods.collectionNesting().call({from: owner})).to.be.like([true, false, [unnestedCollectionAddress]]);
+ await contract.methods.setCollectionNesting([false, true, [unnestedCollectionAddress]]).send({from: owner});
+ expect(await contract.methods.collectionNesting().call({from: owner})).to.be.like([false, true, [unnestedCollectionAddress]]);
+ await contract.methods.setCollectionNesting([false, false, []]).send({from: owner});
+ expect(await contract.methods.collectionNesting().call({from: owner})).to.be.like([false, false, []]);
+ });
+
+ // Sof-deprecated
itEth('NFT: collectionNestingRestrictedCollectionIds() & collectionNestingPermissions', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionId: unnestedCollsectionId, collectionAddress: unnsetedCollectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
- const unnestedContract = await helper.ethNativeContract.collection(unnsetedCollectionAddress, 'nft', owner);
+ const unnestedContract = await helper.ethNativeContract.collection(unnsetedCollectionAddress, 'nft', owner, true);
expect(await unnestedContract.methods.collectionNestingRestrictedCollectionIds().call({from: owner})).to.be.like([false, []]);
- const {contract} = await createNestingCollection(helper, owner);
+ const {contract} = await createNestingCollection(helper, owner, true);
expect(await contract.methods.collectionNestingRestrictedCollectionIds().call({from: owner})).to.be.like([true, []]);
- await contract.methods.setCollectionNesting(true, [unnsetedCollectionAddress]).send({from: owner});
+ await contract.methods['setCollectionNesting(bool,address[])'](true, [unnsetedCollectionAddress]).send({from: owner});
expect(await contract.methods.collectionNestingRestrictedCollectionIds().call({from: owner})).to.be.like([true, [unnestedCollsectionId.toString()]]);
expect(await contract.methods.collectionNestingPermissions().call({from: owner})).to.be.like([['1', false], ['0', true]]);
- await contract.methods.setCollectionNesting(false).send({from: owner});
+ await contract.methods['setCollectionNesting(bool)'](false).send({from: owner});
expect(await contract.methods.collectionNestingPermissions().call({from: owner})).to.be.like([['1', false], ['0', false]]);
});
itEth('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
- const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
- await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
+ const {collectionId: collectionIdA, contract: contractA} = await createNestingCollection(helper, owner);
+ const {contract: contractB} = await createNestingCollection(helper, owner);
+ await contractA.methods.setCollectionNesting([true, false, [contractA.options.address, contractB.options.address]]).send({from: owner});
// Create a token to nest into
const mintingtargetNftTokenIdResult = await contractA.methods.mint(owner).send({from: owner});
@@ -101,7 +119,7 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionId, contract} = await createNestingCollection(helper, owner);
- await contract.methods.setCollectionNesting(false).send({from: owner});
+ await contract.methods.setCollectionNesting([false, false, []]).send({from: owner});
// Create a token to nest into
const mintingTargetTokenIdResult = await contract.methods.mint(owner).send({from: owner});
@@ -143,10 +161,10 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const malignant = await helper.eth.createAccountWithBalance(donor);
- const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
- const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
+ const {collectionId: collectionIdA, contract: contractA} = await createNestingCollection(helper, owner);
+ const {collectionId: collectionIdB, contract: contractB} = await createNestingCollection(helper, owner);
- await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
+ await contractA.methods.setCollectionNesting([true, false, [contractA.options.address, contractB.options.address]]).send({from: owner});
// Create a token in one collection
const mintingTokenIdAResult = await contractA.methods.mint(owner).send({from: owner});
@@ -166,10 +184,10 @@
itEth('NFT: disallows to nest token in an unlisted collection', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
+ const {collectionId: collectionIdA, contract: contractA} = await createNestingCollection(helper, owner);
const {contract: contractB} = await createNestingCollection(helper, owner);
- await contractA.methods.setCollectionNesting(true, [collectionAddressA]).send({from: owner});
+ await contractA.methods.setCollectionNesting([true, false, [contractA.options.address]]).send({from: owner});
// Create a token in one collection
const mintingTokenIdAResult = await contractA.methods.mint(owner).send({from: owner});
@@ -251,7 +269,7 @@
itEth(`Disallow nest into collection without nesting permission [${testCase.mode}] (except for native fungible collection)`, async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionId: targetCollectionId, contract: targetContract} = await createNestingCollection(helper, owner);
- await targetContract.methods.setCollectionNesting(false).send({from: owner});
+ await targetContract.methods.setCollectionNesting([false, false, []]).send({from: owner});
const {contract: ftContract} = await createFungibleCollection(helper, owner, testCase.mode);
tests/src/eth/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -20,7 +20,7 @@
import {ITokenPropertyPermission} from '../util/playgrounds/types';
import {Pallets} from '../util';
import {UniqueNFTCollection, UniqueNFToken, UniqueRFTCollection} from '../util/playgrounds/unique';
-import {TokenPermissionField} from './util/playgrounds/types';
+import {CreateCollectionData, TokenPermissionField} from './util/playgrounds/types';
describe('EVM token properties', () => {
let donor: IKeyringPair;
@@ -41,7 +41,7 @@
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 {collectionId, collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
await collection.methods.addCollectionAdminCross(caller).send({from: owner});
@@ -75,7 +75,7 @@
itEth.ifWithPallets(`[${testCase.mode}] Can set 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 {collectionId, collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
await collection.methods.setTokenPropertyPermissions([
@@ -138,7 +138,7 @@
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 {collectionId, collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
await collection.methods.addCollectionAdminCross(caller).send({from: owner});
@@ -455,7 +455,7 @@
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 {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
await expect(collection.methods.setTokenPropertyPermissions([
@@ -474,7 +474,7 @@
itEth.ifWithPallets(`[${testCase.mode}] Cannot 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 {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
await expect(collection.methods.setTokenPropertyPermissions([
@@ -494,7 +494,7 @@
itEth.ifWithPallets(`[${testCase.mode}] Can reconfigure token property permissions to stricter ones`, testCase.requiredPallets, async({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const {collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
// 1. Owner sets strict property-permissions:
@@ -530,7 +530,7 @@
itEth.ifWithPallets(`[${testCase.mode}] Cannot reconfigure token property permissions to less strict ones`, testCase.requiredPallets, async({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
- const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const {collectionAddress} = await helper.eth.createCollection(owner, new CreateCollectionData('A', 'B', 'C', testCase.mode)).send();
const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
// 1. Owner sets strict property-permissions:
tests/src/eth/tokens/callMethodsERC20.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokens/callMethodsERC20.test.ts
+++ b/tests/src/eth/tokens/callMethodsERC20.test.ts
@@ -17,6 +17,7 @@
import {Pallets, requirePalletsOrSkip} from '../../util';
import {expect, itEth, usingEthPlaygrounds} from '../util';
import {IKeyringPair} from '@polkadot/types/types';
+import {CreateCollectionData} from '../util/playgrounds/types';
[
{mode: 'ft' as const, requiredPallets: []},
@@ -36,7 +37,7 @@
const caller = await helper.eth.createAccountWithBalance(donor);
const mintingParams = testCase.mode === 'ft' ? [caller, 200n] : [caller];
- const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'TotalSupply', '6', '6');
+ const {collection, collectionId} = await helper.eth.createCollection(caller, new CreateCollectionData('TotalSupply', '6', '6', testCase.mode)).send();
if(testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
// Use collection contract for FT or token contract for RFT:
@@ -57,7 +58,7 @@
const caller = await helper.eth.createAccountWithBalance(donor);
const mintingParams = testCase.mode === 'ft' ? [caller, 200n] : [caller];
- const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'BalanceOf', 'Descroption', 'Prefix');
+ const {collection, collectionId} = await helper.eth.createCollection(caller, new CreateCollectionData('BalanceOf', 'Descroption', 'Prefix', testCase.mode)).send();
if(testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
// Use collection contract for FT or token contract for RFT:
@@ -76,7 +77,7 @@
itEth('decimals', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'BalanceOf', 'Descroption', 'Prefix');
+ const {collection, collectionId} = await helper.eth.createCollection(caller, new CreateCollectionData('BalanceOf', 'Descroption', 'Prefix', testCase.mode)).send();
if(testCase.mode === 'rft') await collection.methods.mint(caller).send({from: caller});
// Use collection contract for FT or token contract for RFT:
tests/src/eth/tokens/callMethodsERC721.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokens/callMethodsERC721.test.ts
+++ b/tests/src/eth/tokens/callMethodsERC721.test.ts
@@ -17,6 +17,7 @@
import {Pallets} from '../../util';
import {expect, itEth, usingEthPlaygrounds} from '../util';
import {IKeyringPair} from '@polkadot/types/types';
+import {CreateCollectionData} from '../util/playgrounds/types';
describe('ERC-721 call methods', () => {
@@ -37,7 +38,7 @@
const [callerSub] = await helper.arrange.createAccounts([100n], donor);
const [name, description, tokenPrefix] = ['Name', 'Description', 'Symbol'];
- const {collection: collectionEth} = await helper.eth.createCollection(testCase.mode, callerEth, name, description, tokenPrefix);
+ const {collection: collectionEth} = await helper.eth.createCollection(callerEth, new CreateCollectionData(name, description, tokenPrefix, testCase.mode)).send();
await collectionEth.methods.mint(callerEth).send({from: callerEth});
const {collectionId} = await helper[testCase.mode].mintCollection(callerSub, {name, description, tokenPrefix});
const collectionSub = await helper.ethNativeContract.collectionById(collectionId, testCase.mode, callerEth);
@@ -60,7 +61,7 @@
itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: totalSupply`, testCase.requiredPallets, async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collection} = await helper.eth.createCollection(testCase.mode, caller, 'TotalSupply', '6', '6');
+ const {collection} = await helper.eth.createCollection(caller, new CreateCollectionData('TotalSupply', '6', '6', testCase.mode)).send();
await collection.methods.mint(caller).send({from: caller});
const totalSupply = await collection.methods.totalSupply().call();
@@ -75,7 +76,7 @@
itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: balanceOf`, testCase.requiredPallets, async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collection} = await helper.eth.createCollection(testCase.mode, caller, 'BalanceOf', 'Descroption', 'Prefix');
+ const {collection} = await helper.eth.createCollection(caller, new CreateCollectionData('BalanceOf', 'Descroption', 'Prefix', testCase.mode)).send();
await collection.methods.mint(caller).send({from: caller});
await collection.methods.mint(caller).send({from: caller});
await collection.methods.mint(caller).send({from: caller});
@@ -91,7 +92,7 @@
].map(testCase => {
itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: ownerOf`, testCase.requiredPallets, async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collection} = await helper.eth.createCollection(testCase.mode, caller, 'OwnerOf', '6', '6');
+ const {collection} = await helper.eth.createCollection(caller, new CreateCollectionData('OwnerOf', '6', '6', testCase.mode)).send();
const result = await collection.methods.mint(caller).send();
const tokenId = result.events.Transfer.returnValues.tokenId;
@@ -108,7 +109,7 @@
itEth.ifWithPallets(`${testCase.mode.toUpperCase()}: ownerOf after burn`, testCase.requiredPallets, async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collection, collectionId} = await helper.eth.createCollection(testCase.mode, caller, 'OwnerOf-AfterBurn', '6', '6');
+ const {collection, collectionId} = await helper.eth.createCollection(caller, new CreateCollectionData('OwnerOf-AfterBurn', '6', '6', testCase.mode)).send();
const result = await collection.methods.mint(caller).send();
const tokenId = result.events.Transfer.returnValues.tokenId;
tests/src/eth/tokens/minting.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokens/minting.test.ts
+++ b/tests/src/eth/tokens/minting.test.ts
@@ -17,6 +17,7 @@
import {IKeyringPair} from '@polkadot/types/types';
import {Pallets} from '../../util';
import {expect, itEth, usingEthPlaygrounds} from '../util';
+import {CreateCollectionData} from '../util/playgrounds/types';
describe('Minting tokens', () => {
@@ -78,7 +79,7 @@
const receiver = helper.eth.createAccount();
const mintingParams = testCase.mode === 'ft' ? [receiver, 100] : [receiver];
- const {collection, collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'Name', 'Desc', 'Prefix');
+ const {collection, collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('Name', 'Desc', 'Prefix', testCase.mode)).send();
const result = await collection.methods.mint(...mintingParams).send({from: owner});
@@ -112,7 +113,7 @@
const receiver = helper.eth.createAccount();
const mintingParams = testCase.mode === 'ft' ? [receiver, 100] : [receiver];
- const {collection, collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'Name', 'Desc', 'Prefix');
+ const {collection, collectionAddress, collectionId} = await helper.eth.createCollection(owner, new CreateCollectionData('Name', 'Desc', 'Prefix', testCase.mode)).send();
const result = await collection.methods.mint(...mintingParams).send({from: owner});
tests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -1,3 +1,5 @@
+import {CollectionFlag, TCollectionMode} from '../../../util/playgrounds/types';
+
export interface ContractImports {
solPath: string;
fsPath: string;
@@ -19,8 +21,10 @@
value: bigint,
}
+export type EthAddress = string;
+
export interface CrossAddress {
- readonly eth: string,
+ readonly eth: EthAddress,
readonly sub: string | Uint8Array,
}
@@ -48,3 +52,81 @@
field: CollectionLimitField,
value: OptionUint,
}
+
+export interface CollectionLimitValue {
+ field: CollectionLimitField,
+ value: bigint,
+}
+
+export enum CollectionMode {
+ Fungible,
+ Nonfungible,
+ Refungible,
+}
+
+export interface PropertyPermission {
+ code: TokenPermissionField,
+ value: boolean,
+}
+export interface TokenPropertyPermission {
+ key: string,
+ permissions: PropertyPermission[],
+}
+export interface CollectionNestingAndPermission {
+ token_owner: boolean,
+ collection_admin: boolean,
+ restricted: string[],
+}
+
+export const emptyAddress: [string, string] = [
+ '0x0000000000000000000000000000000000000000',
+ '0',
+];
+
+export const CREATE_COLLECTION_DATA_DEFAULTS = {
+ decimals: 0,
+ properties: [],
+ tokenPropertyPermissions: [],
+ adminList: [],
+ nestingSettings: {token_owner: false, collection_admin: false, restricted: []},
+ limits: [],
+ pendingSponsor: emptyAddress,
+ flags: 0,
+};
+
+export interface Property {
+ key: string;
+ value: Buffer;
+}
+
+export class CreateCollectionData {
+ name: string;
+ description: string;
+ tokenPrefix: string;
+ collectionMode: TCollectionMode;
+ decimals? = 0;
+ properties?: Property[] = [];
+ tokenPropertyPermissions?: TokenPropertyPermission[] = [];
+ adminList?: CrossAddress[] = [];
+ nestingSettings?: CollectionNestingAndPermission = {token_owner: false, collection_admin: false, restricted: []};
+ limits?: CollectionLimitValue[] = [];
+ pendingSponsor?: [string, string] = emptyAddress;
+ flags?: number | CollectionFlag[] = [0];
+
+ constructor(
+ name: string,
+ description: string,
+ tokenPrefix: string,
+ collectionMode: TCollectionMode,
+ decimals = 18,
+ ) {
+ this.name = name;
+ this.description = description;
+ this.tokenPrefix = tokenPrefix;
+ this.collectionMode = collectionMode;
+ if(collectionMode == 'ft')
+ this.decimals = decimals;
+ else
+ this.decimals = 0;
+ }
+}
\ 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
@@ -18,7 +18,7 @@
import {ArrangeGroup, DevUniqueHelper} from '../../../util/playgrounds/unique.dev';
-import {ContractImports, CompiledContract, CrossAddress, NormalizedEvent, EthProperty} from './types';
+import {ContractImports, CompiledContract, CrossAddress, NormalizedEvent, EthProperty, CollectionMode, CreateCollectionData} from './types';
// Native contracts ABI
import collectionHelpersAbi from '../../abi/collectionHelpers.json' assert {type: 'json'};
@@ -50,7 +50,6 @@
}
}
-
class ContractGroup extends EthGroupBase {
async findImports(imports?: ContractImports[]) {
if(!imports) return function(path: string) {
@@ -181,7 +180,84 @@
}
}
+class CreateCollectionTransaction {
+ signer: string;
+ data: CreateCollectionData;
+ mergeDeprecated: boolean;
+ helper: EthUniqueHelper;
+
+ constructor(helper: EthUniqueHelper, signer: string, data: CreateCollectionData, mergeDeprecated = false) {
+ this.helper = helper;
+ this.signer = signer;
+
+ let flags = 0;
+ // convert CollectionFlags to number and join them in one number
+ if(!data.flags || typeof data.flags == 'number') {
+ flags = data.flags ?? 0;
+ } else {
+ for(let i = 0; i < data.flags.length; i++){
+ const flag = data.flags[i];
+ flags = flags | flag;
+ }
+ }
+ data.flags = flags;
+
+ this.data = data;
+ this.mergeDeprecated = mergeDeprecated;
+ }
+
+ private async createTransaction() {
+ const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(this.signer);
+ let collectionMode;
+ switch (this.data.collectionMode) {
+ case 'nft': collectionMode = CollectionMode.Nonfungible; break;
+ case 'rft': collectionMode = CollectionMode.Refungible; break;
+ case 'ft': collectionMode = CollectionMode.Fungible; break;
+ }
+
+ const tx = collectionHelper.methods.createCollection([
+ this.data.pendingSponsor,
+ this.data.name,
+ this.data.description,
+ this.data.tokenPrefix,
+ collectionMode,
+ this.data.decimals,
+ this.data.properties,
+ this.data.tokenPropertyPermissions,
+ this.data.adminList,
+ this.data.nestingSettings,
+ this.data.limits,
+ this.data.flags,
+ ]);
+ return tx;
+ }
+
+ async send(options?: any): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[], collection: Contract }> {
+ const collectionCreationPrice = {
+ value: Number(this.helper.balance.getCollectionCreationPrice()),
+ };
+ const tx = await this.createTransaction();
+ const result = await tx.send({...options, ...collectionCreationPrice});
+ const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);
+ const events = this.helper.eth.normalizeEvents(result.events);
+ const collection = await this.helper.ethNativeContract.collectionById(collectionId, this.data.collectionMode, this.signer, this.mergeDeprecated);
+
+ return {collectionId, collectionAddress, events, collection};
+ }
+
+ async call(options?: any) {
+ const collectionCreationPrice = {
+ value: Number(this.helper.balance.getCollectionCreationPrice()),
+ };
+ const tx = await this.createTransaction();
+
+ return await tx.call({...options, ...collectionCreationPrice});
+ }
+}
+
+
class EthGroup extends EthGroupBase {
DEFAULT_GAS = 2_500_000;
@@ -236,30 +312,28 @@
}
}
- async createCollection(mode: TCollectionMode, signer: string, name: string, description: string, tokenPrefix: string, decimals = 18, mergeDeprecated = false): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[], collection: Contract }> {
- const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
+ createCollection(signer: string, data: CreateCollectionData, mergeDeprecated = false): CreateCollectionTransaction {
+ return new CreateCollectionTransaction(this.helper, signer, data, mergeDeprecated);
+ }
+
+ createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
+ return this.createCollection(signer, new CreateCollectionData(name, description, tokenPrefix, 'nft')).send();
+ }
+
+ async createERC721MetadataCompatibleCollection(signer: string, data: CreateCollectionData, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);
- const functionName: string = this.createCollectionMethodName(mode);
-
- const functionParams = mode === 'ft' ? [name, decimals, description, tokenPrefix] : [name, description, tokenPrefix];
- const result = await collectionHelper.methods[functionName](...functionParams).send({value: Number(collectionCreationPrice)});
- const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
- const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);
- const events = this.helper.eth.normalizeEvents(result.events);
- const collection = await this.helper.ethNativeContract.collectionById(collectionId, mode, signer, mergeDeprecated);
+ const {collectionId, collectionAddress, events} = await this.createCollection(signer, data).send();
- return {collectionId, collectionAddress, events, collection};
- }
+ await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
- createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
- return this.createCollection('nft', signer, name, description, tokenPrefix);
+ return {collectionId, collectionAddress, events};
}
async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);
- const {collectionId, collectionAddress, events} = await this.createCollection('nft', signer, name, description, tokenPrefix);
+ const {collectionId, collectionAddress, events} = await this.createCollection(signer, new CreateCollectionData(name, description, tokenPrefix, 'nft')).send();
await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
@@ -267,17 +341,17 @@
}
createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
- return this.createCollection('rft', signer, name, description, tokenPrefix);
+ return this.createCollection(signer, new CreateCollectionData(name, description, tokenPrefix, 'rft')).send();
}
createFungibleCollection(signer: string, name: string, decimals: number, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
- return this.createCollection('ft', signer, name, description, tokenPrefix, decimals);
+ return this.createCollection(signer, new CreateCollectionData(name, description, tokenPrefix, 'ft')).send();
}
async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);
- const {collectionId, collectionAddress, events} = await this.createCollection('rft', signer, name, description, tokenPrefix);
+ const {collectionId, collectionAddress, events} = await this.createCollection(signer, new CreateCollectionData(name, description, tokenPrefix, 'rft')).send();
await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
@@ -432,6 +506,13 @@
};
}
+ fromAddr(address: TEthereumAccount): [string, string] {
+ return [
+ address,
+ '0',
+ ];
+ }
+
fromKeyringPair(keyring: IKeyringPair): CrossAddress {
return {
eth: '0x0000000000000000000000000000000000000000',
tests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -1499,7 +1499,7 @@
*
* * `data`: Explicit data of a collection used for its creation.
**/
- createCollectionEx: AugmentedSubmittable<(data: UpDataStructsCreateCollectionData | { mode?: any; access?: any; name?: any; description?: any; tokenPrefix?: any; pendingSponsor?: any; limits?: any; permissions?: any; tokenPropertyPermissions?: any; properties?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [UpDataStructsCreateCollectionData]>;
+ createCollectionEx: AugmentedSubmittable<(data: UpDataStructsCreateCollectionData | { mode?: any; access?: any; name?: any; description?: any; tokenPrefix?: any; limits?: any; permissions?: any; tokenPropertyPermissions?: any; properties?: any; adminList?: any; pendingSponsor?: any; flags?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [UpDataStructsCreateCollectionData]>;
/**
* Mint an item within a collection.
*
tests/src/interfaces/augment-types.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -25,7 +25,7 @@
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 { ContractConstructorSpecLatest, ContractConstructorSpecV0, ContractConstructorSpecV1, ContractConstructorSpecV2, ContractConstructorSpecV3, ContractConstructorSpecV4, ContractContractSpecV0, ContractContractSpecV1, ContractContractSpecV2, ContractContractSpecV3, ContractContractSpecV4, ContractCryptoHasher, ContractDiscriminant, ContractDisplayName, ContractEnvironmentV4, ContractEventParamSpecLatest, ContractEventParamSpecV0, ContractEventParamSpecV2, ContractEventSpecLatest, ContractEventSpecV0, ContractEventSpecV1, ContractEventSpecV2, ContractLayoutArray, ContractLayoutCell, ContractLayoutEnum, ContractLayoutHash, ContractLayoutHashingStrategy, ContractLayoutKey, ContractLayoutStruct, ContractLayoutStructField, ContractMessageParamSpecLatest, ContractMessageParamSpecV0, ContractMessageParamSpecV2, ContractMessageSpecLatest, ContractMessageSpecV0, ContractMessageSpecV1, ContractMessageSpecV2, ContractMessageSpecV3, ContractMetadata, ContractMetadataLatest, ContractMetadataV0, ContractMetadataV1, ContractMetadataV2, ContractMetadataV3, ContractMetadataV4, ContractProject, ContractProjectContract, ContractProjectInfo, ContractProjectSource, ContractProjectV0, ContractSelector, ContractStorageLayout, ContractTypeSpec } from '@polkadot/types/interfaces/contractsAbi';
+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';
import type { AccountVote, AccountVoteSplit, AccountVoteStandard, Conviction, Delegations, PreimageStatus, PreimageStatusAvailable, PriorLock, PropIndex, Proposal, ProxyState, ReferendumIndex, ReferendumInfo, ReferendumInfoFinished, ReferendumInfoTo239, ReferendumStatus, Tally, Voting, VotingDelegating, VotingDirect, VotingDirectVote } from '@polkadot/types/interfaces/democracy';
@@ -254,7 +254,6 @@
ContractConstructorSpecV1: ContractConstructorSpecV1;
ContractConstructorSpecV2: ContractConstructorSpecV2;
ContractConstructorSpecV3: ContractConstructorSpecV3;
- ContractConstructorSpecV4: ContractConstructorSpecV4;
ContractContractSpecV0: ContractContractSpecV0;
ContractContractSpecV1: ContractContractSpecV1;
ContractContractSpecV2: ContractContractSpecV2;
@@ -263,7 +262,6 @@
ContractCryptoHasher: ContractCryptoHasher;
ContractDiscriminant: ContractDiscriminant;
ContractDisplayName: ContractDisplayName;
- ContractEnvironmentV4: ContractEnvironmentV4;
ContractEventParamSpecLatest: ContractEventParamSpecLatest;
ContractEventParamSpecV0: ContractEventParamSpecV0;
ContractEventParamSpecV2: ContractEventParamSpecV2;
@@ -300,7 +298,6 @@
ContractMessageSpecV0: ContractMessageSpecV0;
ContractMessageSpecV1: ContractMessageSpecV1;
ContractMessageSpecV2: ContractMessageSpecV2;
- ContractMessageSpecV3: ContractMessageSpecV3;
ContractMetadata: ContractMetadata;
ContractMetadataLatest: ContractMetadataLatest;
ContractMetadataV0: ContractMetadataV0;
tests/src/interfaces/default/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -3221,11 +3221,13 @@
readonly name: Vec<u16>;
readonly description: Vec<u16>;
readonly tokenPrefix: Bytes;
- readonly pendingSponsor: Option<AccountId32>;
readonly limits: Option<UpDataStructsCollectionLimits>;
readonly permissions: Option<UpDataStructsCollectionPermissions>;
readonly tokenPropertyPermissions: Vec<UpDataStructsPropertyKeyPermission>;
readonly properties: Vec<UpDataStructsProperty>;
+ readonly adminList: Vec<PalletEvmAccountBasicCrossAccountIdRepr>;
+ readonly pendingSponsor: Option<PalletEvmAccountBasicCrossAccountIdRepr>;
+ readonly flags: U8aFixed;
}
/** @name UpDataStructsCreateFungibleData */
tests/src/interfaces/lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -2904,7 +2904,7 @@
}
},
/**
- * Lookup335: up_data_structs::CreateCollectionData<sp_core::crypto::AccountId32>
+ * Lookup335: up_data_structs::CreateCollectionData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
**/
UpDataStructsCreateCollectionData: {
mode: 'UpDataStructsCollectionMode',
@@ -2912,11 +2912,13 @@
name: 'Vec<u16>',
description: 'Vec<u16>',
tokenPrefix: 'Bytes',
- pendingSponsor: 'Option<AccountId32>',
limits: 'Option<UpDataStructsCollectionLimits>',
permissions: 'Option<UpDataStructsCollectionPermissions>',
tokenPropertyPermissions: 'Vec<UpDataStructsPropertyKeyPermission>',
- properties: 'Vec<UpDataStructsProperty>'
+ properties: 'Vec<UpDataStructsProperty>',
+ adminList: 'Vec<PalletEvmAccountBasicCrossAccountIdRepr>',
+ pendingSponsor: 'Option<PalletEvmAccountBasicCrossAccountIdRepr>',
+ flags: '[u8;1]'
},
/**
* Lookup337: up_data_structs::AccessMode
@@ -2990,7 +2992,7 @@
value: 'Bytes'
},
/**
- * Lookup360: up_data_structs::CreateItemData
+ * Lookup362: up_data_structs::CreateItemData
**/
UpDataStructsCreateItemData: {
_enum: {
@@ -3000,26 +3002,26 @@
}
},
/**
- * Lookup361: up_data_structs::CreateNftData
+ * Lookup363: up_data_structs::CreateNftData
**/
UpDataStructsCreateNftData: {
properties: 'Vec<UpDataStructsProperty>'
},
/**
- * Lookup362: up_data_structs::CreateFungibleData
+ * Lookup364: up_data_structs::CreateFungibleData
**/
UpDataStructsCreateFungibleData: {
value: 'u128'
},
/**
- * Lookup363: up_data_structs::CreateReFungibleData
+ * Lookup365: up_data_structs::CreateReFungibleData
**/
UpDataStructsCreateReFungibleData: {
pieces: 'u128',
properties: 'Vec<UpDataStructsProperty>'
},
/**
- * Lookup366: up_data_structs::CreateItemExData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+ * Lookup368: up_data_structs::CreateItemExData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
**/
UpDataStructsCreateItemExData: {
_enum: {
@@ -3030,14 +3032,14 @@
}
},
/**
- * Lookup368: up_data_structs::CreateNftExData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+ * Lookup370: up_data_structs::CreateNftExData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
**/
UpDataStructsCreateNftExData: {
properties: 'Vec<UpDataStructsProperty>',
owner: 'PalletEvmAccountBasicCrossAccountIdRepr'
},
/**
- * Lookup375: up_data_structs::CreateRefungibleExSingleOwner<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+ * Lookup377: up_data_structs::CreateRefungibleExSingleOwner<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
**/
UpDataStructsCreateRefungibleExSingleOwner: {
user: 'PalletEvmAccountBasicCrossAccountIdRepr',
@@ -3045,14 +3047,14 @@
properties: 'Vec<UpDataStructsProperty>'
},
/**
- * Lookup377: up_data_structs::CreateRefungibleExMultipleOwners<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+ * Lookup379: up_data_structs::CreateRefungibleExMultipleOwners<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
**/
UpDataStructsCreateRefungibleExMultipleOwners: {
users: 'BTreeMap<PalletEvmAccountBasicCrossAccountIdRepr, u128>',
properties: 'Vec<UpDataStructsProperty>'
},
/**
- * Lookup378: pallet_configuration::pallet::Call<T>
+ * Lookup380: pallet_configuration::pallet::Call<T>
**/
PalletConfigurationCall: {
_enum: {
@@ -3078,7 +3080,7 @@
}
},
/**
- * Lookup380: pallet_configuration::AppPromotionConfiguration<BlockNumber>
+ * Lookup382: pallet_configuration::AppPromotionConfiguration<BlockNumber>
**/
PalletConfigurationAppPromotionConfiguration: {
recalculationInterval: 'Option<u32>',
@@ -3087,11 +3089,11 @@
maxStakersPerCalculation: 'Option<u8>'
},
/**
- * Lookup384: pallet_structure::pallet::Call<T>
+ * Lookup386: pallet_structure::pallet::Call<T>
**/
PalletStructureCall: 'Null',
/**
- * Lookup385: pallet_app_promotion::pallet::Call<T>
+ * Lookup387: pallet_app_promotion::pallet::Call<T>
**/
PalletAppPromotionCall: {
_enum: {
@@ -3126,7 +3128,7 @@
}
},
/**
- * Lookup386: pallet_foreign_assets::module::Call<T>
+ * Lookup388: pallet_foreign_assets::module::Call<T>
**/
PalletForeignAssetsModuleCall: {
_enum: {
@@ -3143,7 +3145,7 @@
}
},
/**
- * Lookup387: pallet_evm::pallet::Call<T>
+ * Lookup389: pallet_evm::pallet::Call<T>
**/
PalletEvmCall: {
_enum: {
@@ -3186,7 +3188,7 @@
}
},
/**
- * Lookup393: pallet_ethereum::pallet::Call<T>
+ * Lookup395: pallet_ethereum::pallet::Call<T>
**/
PalletEthereumCall: {
_enum: {
@@ -3196,7 +3198,7 @@
}
},
/**
- * Lookup394: ethereum::transaction::TransactionV2
+ * Lookup396: ethereum::transaction::TransactionV2
**/
EthereumTransactionTransactionV2: {
_enum: {
@@ -3206,7 +3208,7 @@
}
},
/**
- * Lookup395: ethereum::transaction::LegacyTransaction
+ * Lookup397: ethereum::transaction::LegacyTransaction
**/
EthereumTransactionLegacyTransaction: {
nonce: 'U256',
@@ -3218,7 +3220,7 @@
signature: 'EthereumTransactionTransactionSignature'
},
/**
- * Lookup396: ethereum::transaction::TransactionAction
+ * Lookup398: ethereum::transaction::TransactionAction
**/
EthereumTransactionTransactionAction: {
_enum: {
@@ -3227,7 +3229,7 @@
}
},
/**
- * Lookup397: ethereum::transaction::TransactionSignature
+ * Lookup399: ethereum::transaction::TransactionSignature
**/
EthereumTransactionTransactionSignature: {
v: 'u64',
@@ -3235,7 +3237,7 @@
s: 'H256'
},
/**
- * Lookup399: ethereum::transaction::EIP2930Transaction
+ * Lookup401: ethereum::transaction::EIP2930Transaction
**/
EthereumTransactionEip2930Transaction: {
chainId: 'u64',
@@ -3251,14 +3253,14 @@
s: 'H256'
},
/**
- * Lookup401: ethereum::transaction::AccessListItem
+ * Lookup403: ethereum::transaction::AccessListItem
**/
EthereumTransactionAccessListItem: {
address: 'H160',
storageKeys: 'Vec<H256>'
},
/**
- * Lookup402: ethereum::transaction::EIP1559Transaction
+ * Lookup404: ethereum::transaction::EIP1559Transaction
**/
EthereumTransactionEip1559Transaction: {
chainId: 'u64',
@@ -3275,7 +3277,7 @@
s: 'H256'
},
/**
- * Lookup403: pallet_evm_contract_helpers::pallet::Call<T>
+ * Lookup405: pallet_evm_contract_helpers::pallet::Call<T>
**/
PalletEvmContractHelpersCall: {
_enum: {
@@ -3285,7 +3287,7 @@
}
},
/**
- * Lookup405: pallet_evm_migration::pallet::Call<T>
+ * Lookup407: pallet_evm_migration::pallet::Call<T>
**/
PalletEvmMigrationCall: {
_enum: {
@@ -3310,7 +3312,7 @@
}
},
/**
- * Lookup409: pallet_maintenance::pallet::Call<T>
+ * Lookup411: pallet_maintenance::pallet::Call<T>
**/
PalletMaintenanceCall: {
_enum: {
@@ -3326,7 +3328,7 @@
}
},
/**
- * Lookup410: pallet_test_utils::pallet::Call<T>
+ * Lookup412: pallet_test_utils::pallet::Call<T>
**/
PalletTestUtilsCall: {
_enum: {
@@ -3345,32 +3347,32 @@
}
},
/**
- * Lookup412: pallet_sudo::pallet::Error<T>
+ * Lookup414: pallet_sudo::pallet::Error<T>
**/
PalletSudoError: {
_enum: ['RequireSudo']
},
/**
- * Lookup414: orml_vesting::module::Error<T>
+ * Lookup416: orml_vesting::module::Error<T>
**/
OrmlVestingModuleError: {
_enum: ['ZeroVestingPeriod', 'ZeroVestingPeriodCount', 'InsufficientBalanceToLock', 'TooManyVestingSchedules', 'AmountLow', 'MaxVestingSchedulesExceeded']
},
/**
- * Lookup415: orml_xtokens::module::Error<T>
+ * Lookup417: orml_xtokens::module::Error<T>
**/
OrmlXtokensModuleError: {
_enum: ['AssetHasNoReserve', 'NotCrossChainTransfer', 'InvalidDest', 'NotCrossChainTransferableCurrency', 'UnweighableMessage', 'XcmExecutionFailed', 'CannotReanchor', 'InvalidAncestry', 'InvalidAsset', 'DestinationNotInvertible', 'BadVersion', 'DistinctReserveForAssetAndFee', 'ZeroFee', 'ZeroAmount', 'TooManyAssetsBeingSent', 'AssetIndexNonExistent', 'FeeNotEnough', 'NotSupportedMultiLocation', 'MinXcmFeeNotDefined']
},
/**
- * Lookup418: orml_tokens::BalanceLock<Balance>
+ * Lookup420: orml_tokens::BalanceLock<Balance>
**/
OrmlTokensBalanceLock: {
id: '[u8;8]',
amount: 'u128'
},
/**
- * Lookup420: orml_tokens::AccountData<Balance>
+ * Lookup422: orml_tokens::AccountData<Balance>
**/
OrmlTokensAccountData: {
free: 'u128',
@@ -3378,20 +3380,20 @@
frozen: 'u128'
},
/**
- * Lookup422: orml_tokens::ReserveData<ReserveIdentifier, Balance>
+ * Lookup424: orml_tokens::ReserveData<ReserveIdentifier, Balance>
**/
OrmlTokensReserveData: {
id: 'Null',
amount: 'u128'
},
/**
- * Lookup424: orml_tokens::module::Error<T>
+ * Lookup426: orml_tokens::module::Error<T>
**/
OrmlTokensModuleError: {
_enum: ['BalanceTooLow', 'AmountIntoBalanceFailed', 'LiquidityRestrictions', 'MaxLocksExceeded', 'KeepAlive', 'ExistentialDeposit', 'DeadAccount', 'TooManyReserves']
},
/**
- * Lookup429: pallet_identity::types::RegistrarInfo<Balance, sp_core::crypto::AccountId32>
+ * Lookup431: pallet_identity::types::RegistrarInfo<Balance, sp_core::crypto::AccountId32>
**/
PalletIdentityRegistrarInfo: {
account: 'AccountId32',
@@ -3399,13 +3401,13 @@
fields: 'PalletIdentityBitFlags'
},
/**
- * Lookup431: pallet_identity::pallet::Error<T>
+ * Lookup433: pallet_identity::pallet::Error<T>
**/
PalletIdentityError: {
_enum: ['TooManySubAccounts', 'NotFound', 'NotNamed', 'EmptyIndex', 'FeeChanged', 'NoIdentity', 'StickyJudgement', 'JudgementGiven', 'InvalidJudgement', 'InvalidIndex', 'InvalidTarget', 'TooManyFields', 'TooManyRegistrars', 'AlreadyClaimed', 'NotSub', 'NotOwned', 'JudgementForDifferentIdentity', 'JudgementPaymentFailed']
},
/**
- * Lookup432: pallet_preimage::RequestStatus<sp_core::crypto::AccountId32, Balance>
+ * Lookup434: pallet_preimage::RequestStatus<sp_core::crypto::AccountId32, Balance>
**/
PalletPreimageRequestStatus: {
_enum: {
@@ -3421,13 +3423,13 @@
}
},
/**
- * Lookup437: pallet_preimage::pallet::Error<T>
+ * Lookup439: pallet_preimage::pallet::Error<T>
**/
PalletPreimageError: {
_enum: ['TooBig', 'AlreadyNoted', 'NotAuthorized', 'NotNoted', 'Requested', 'NotRequested']
},
/**
- * Lookup439: cumulus_pallet_xcmp_queue::InboundChannelDetails
+ * Lookup441: cumulus_pallet_xcmp_queue::InboundChannelDetails
**/
CumulusPalletXcmpQueueInboundChannelDetails: {
sender: 'u32',
@@ -3435,19 +3437,19 @@
messageMetadata: 'Vec<(u32,PolkadotParachainPrimitivesXcmpMessageFormat)>'
},
/**
- * Lookup440: cumulus_pallet_xcmp_queue::InboundState
+ * Lookup442: cumulus_pallet_xcmp_queue::InboundState
**/
CumulusPalletXcmpQueueInboundState: {
_enum: ['Ok', 'Suspended']
},
/**
- * Lookup443: polkadot_parachain::primitives::XcmpMessageFormat
+ * Lookup445: polkadot_parachain::primitives::XcmpMessageFormat
**/
PolkadotParachainPrimitivesXcmpMessageFormat: {
_enum: ['ConcatenatedVersionedXcm', 'ConcatenatedEncodedBlob', 'Signals']
},
/**
- * Lookup446: cumulus_pallet_xcmp_queue::OutboundChannelDetails
+ * Lookup448: cumulus_pallet_xcmp_queue::OutboundChannelDetails
**/
CumulusPalletXcmpQueueOutboundChannelDetails: {
recipient: 'u32',
@@ -3457,13 +3459,13 @@
lastIndex: 'u16'
},
/**
- * Lookup447: cumulus_pallet_xcmp_queue::OutboundState
+ * Lookup449: cumulus_pallet_xcmp_queue::OutboundState
**/
CumulusPalletXcmpQueueOutboundState: {
_enum: ['Ok', 'Suspended']
},
/**
- * Lookup449: cumulus_pallet_xcmp_queue::QueueConfigData
+ * Lookup451: cumulus_pallet_xcmp_queue::QueueConfigData
**/
CumulusPalletXcmpQueueQueueConfigData: {
suspendThreshold: 'u32',
@@ -3474,13 +3476,13 @@
xcmpMaxIndividualWeight: 'SpWeightsWeightV2Weight'
},
/**
- * Lookup451: cumulus_pallet_xcmp_queue::pallet::Error<T>
+ * Lookup453: cumulus_pallet_xcmp_queue::pallet::Error<T>
**/
CumulusPalletXcmpQueueError: {
_enum: ['FailedToSend', 'BadXcmOrigin', 'BadXcm', 'BadOverweightIndex', 'WeightOverLimit']
},
/**
- * Lookup452: pallet_xcm::pallet::QueryStatus<BlockNumber>
+ * Lookup454: pallet_xcm::pallet::QueryStatus<BlockNumber>
**/
PalletXcmQueryStatus: {
_enum: {
@@ -3501,7 +3503,7 @@
}
},
/**
- * Lookup456: xcm::VersionedResponse
+ * Lookup458: xcm::VersionedResponse
**/
XcmVersionedResponse: {
_enum: {
@@ -3512,7 +3514,7 @@
}
},
/**
- * Lookup462: pallet_xcm::pallet::VersionMigrationStage
+ * Lookup464: pallet_xcm::pallet::VersionMigrationStage
**/
PalletXcmVersionMigrationStage: {
_enum: {
@@ -3523,7 +3525,7 @@
}
},
/**
- * Lookup465: xcm::VersionedAssetId
+ * Lookup467: xcm::VersionedAssetId
**/
XcmVersionedAssetId: {
_enum: {
@@ -3534,7 +3536,7 @@
}
},
/**
- * Lookup466: pallet_xcm::pallet::RemoteLockedFungibleRecord<ConsumerIdentifier, MaxConsumers>
+ * Lookup468: pallet_xcm::pallet::RemoteLockedFungibleRecord<ConsumerIdentifier, MaxConsumers>
**/
PalletXcmRemoteLockedFungibleRecord: {
amount: 'u128',
@@ -3543,23 +3545,23 @@
consumers: 'Vec<(Null,u128)>'
},
/**
- * Lookup473: pallet_xcm::pallet::Error<T>
+ * Lookup475: pallet_xcm::pallet::Error<T>
**/
PalletXcmError: {
_enum: ['Unreachable', 'SendFailure', 'Filtered', 'UnweighableMessage', 'DestinationNotInvertible', 'Empty', 'CannotReanchor', 'TooManyAssets', 'InvalidOrigin', 'BadVersion', 'BadLocation', 'NoSubscription', 'AlreadySubscribed', 'InvalidAsset', 'LowBalance', 'TooManyLocks', 'AccountNotSovereign', 'FeesNotMet', 'LockNotFound', 'InUse']
},
/**
- * Lookup474: cumulus_pallet_xcm::pallet::Error<T>
+ * Lookup476: cumulus_pallet_xcm::pallet::Error<T>
**/
CumulusPalletXcmError: 'Null',
/**
- * Lookup475: cumulus_pallet_dmp_queue::ConfigData
+ * Lookup477: cumulus_pallet_dmp_queue::ConfigData
**/
CumulusPalletDmpQueueConfigData: {
maxIndividual: 'SpWeightsWeightV2Weight'
},
/**
- * Lookup476: cumulus_pallet_dmp_queue::PageIndexData
+ * Lookup478: cumulus_pallet_dmp_queue::PageIndexData
**/
CumulusPalletDmpQueuePageIndexData: {
beginUsed: 'u32',
@@ -3567,25 +3569,25 @@
overweightCount: 'u64'
},
/**
- * Lookup479: cumulus_pallet_dmp_queue::pallet::Error<T>
+ * Lookup481: cumulus_pallet_dmp_queue::pallet::Error<T>
**/
CumulusPalletDmpQueueError: {
_enum: ['Unknown', 'OverLimit']
},
/**
- * Lookup483: pallet_unique::pallet::Error<T>
+ * Lookup485: pallet_unique::pallet::Error<T>
**/
PalletUniqueError: {
_enum: ['CollectionDecimalPointLimitExceeded', 'EmptyArgument', 'RepartitionCalledOnNonRefungibleCollection']
},
/**
- * Lookup484: pallet_configuration::pallet::Error<T>
+ * Lookup486: pallet_configuration::pallet::Error<T>
**/
PalletConfigurationError: {
_enum: ['InconsistentConfiguration']
},
/**
- * Lookup485: up_data_structs::Collection<sp_core::crypto::AccountId32>
+ * Lookup487: up_data_structs::Collection<sp_core::crypto::AccountId32>
**/
UpDataStructsCollection: {
owner: 'AccountId32',
@@ -3599,7 +3601,7 @@
flags: '[u8;1]'
},
/**
- * Lookup486: up_data_structs::SponsorshipState<sp_core::crypto::AccountId32>
+ * Lookup488: up_data_structs::SponsorshipState<sp_core::crypto::AccountId32>
**/
UpDataStructsSponsorshipStateAccountId32: {
_enum: {
@@ -3609,7 +3611,7 @@
}
},
/**
- * Lookup487: up_data_structs::Properties
+ * Lookup489: up_data_structs::Properties
**/
UpDataStructsProperties: {
map: 'UpDataStructsPropertiesMapBoundedVec',
@@ -3617,15 +3619,15 @@
reserved: 'u32'
},
/**
- * Lookup488: up_data_structs::PropertiesMap<bounded_collections::bounded_vec::BoundedVec<T, S>>
+ * Lookup490: up_data_structs::PropertiesMap<bounded_collections::bounded_vec::BoundedVec<T, S>>
**/
UpDataStructsPropertiesMapBoundedVec: 'BTreeMap<Bytes, Bytes>',
/**
- * Lookup493: up_data_structs::PropertiesMap<up_data_structs::PropertyPermission>
+ * Lookup495: up_data_structs::PropertiesMap<up_data_structs::PropertyPermission>
**/
UpDataStructsPropertiesMapPropertyPermission: 'BTreeMap<Bytes, UpDataStructsPropertyPermission>',
/**
- * Lookup500: up_data_structs::CollectionStats
+ * Lookup502: up_data_structs::CollectionStats
**/
UpDataStructsCollectionStats: {
created: 'u32',
@@ -3633,18 +3635,18 @@
alive: 'u32'
},
/**
- * Lookup501: up_data_structs::TokenChild
+ * Lookup503: up_data_structs::TokenChild
**/
UpDataStructsTokenChild: {
token: 'u32',
collection: 'u32'
},
/**
- * Lookup502: PhantomType::up_data_structs<T>
+ * Lookup504: PhantomType::up_data_structs<T>
**/
PhantomTypeUpDataStructs: '[(UpDataStructsTokenData,UpDataStructsRpcCollection,UpPovEstimateRpcPovInfo);0]',
/**
- * Lookup504: up_data_structs::TokenData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+ * Lookup506: up_data_structs::TokenData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
**/
UpDataStructsTokenData: {
properties: 'Vec<UpDataStructsProperty>',
@@ -3652,7 +3654,7 @@
pieces: 'u128'
},
/**
- * Lookup506: up_data_structs::RpcCollection<sp_core::crypto::AccountId32>
+ * Lookup507: up_data_structs::RpcCollection<sp_core::crypto::AccountId32>
**/
UpDataStructsRpcCollection: {
owner: 'AccountId32',
@@ -3669,14 +3671,14 @@
flags: 'UpDataStructsRpcCollectionFlags'
},
/**
- * Lookup507: up_data_structs::RpcCollectionFlags
+ * Lookup508: up_data_structs::RpcCollectionFlags
**/
UpDataStructsRpcCollectionFlags: {
foreign: 'bool',
erc721metadata: 'bool'
},
/**
- * Lookup508: up_pov_estimate_rpc::PovInfo
+ * Lookup509: up_pov_estimate_rpc::PovInfo
**/
UpPovEstimateRpcPovInfo: {
proofSize: 'u64',
@@ -3686,7 +3688,7 @@
keyValues: 'Vec<UpPovEstimateRpcTrieKeyValue>'
},
/**
- * Lookup511: sp_runtime::transaction_validity::TransactionValidityError
+ * Lookup512: sp_runtime::transaction_validity::TransactionValidityError
**/
SpRuntimeTransactionValidityTransactionValidityError: {
_enum: {
@@ -3695,7 +3697,7 @@
}
},
/**
- * Lookup512: sp_runtime::transaction_validity::InvalidTransaction
+ * Lookup513: sp_runtime::transaction_validity::InvalidTransaction
**/
SpRuntimeTransactionValidityInvalidTransaction: {
_enum: {
@@ -3713,7 +3715,7 @@
}
},
/**
- * Lookup513: sp_runtime::transaction_validity::UnknownTransaction
+ * Lookup514: sp_runtime::transaction_validity::UnknownTransaction
**/
SpRuntimeTransactionValidityUnknownTransaction: {
_enum: {
@@ -3723,68 +3725,68 @@
}
},
/**
- * Lookup515: up_pov_estimate_rpc::TrieKeyValue
+ * Lookup516: up_pov_estimate_rpc::TrieKeyValue
**/
UpPovEstimateRpcTrieKeyValue: {
key: 'Bytes',
value: 'Bytes'
},
/**
- * Lookup517: pallet_common::pallet::Error<T>
+ * Lookup518: pallet_common::pallet::Error<T>
**/
PalletCommonError: {
_enum: ['CollectionNotFound', 'MustBeTokenOwner', 'NoPermission', 'CantDestroyNotEmptyCollection', 'PublicMintingNotAllowed', 'AddressNotInAllowlist', 'CollectionNameLimitExceeded', 'CollectionDescriptionLimitExceeded', 'CollectionTokenPrefixLimitExceeded', 'TotalCollectionsLimitExceeded', 'CollectionAdminCountExceeded', 'CollectionLimitBoundsExceeded', 'OwnerPermissionsCantBeReverted', 'TransferNotAllowed', 'AccountTokenLimitExceeded', 'CollectionTokenLimitExceeded', 'MetadataFlagFrozen', 'TokenNotFound', 'TokenValueTooLow', 'ApprovedValueTooLow', 'CantApproveMoreThanOwned', 'AddressIsNotEthMirror', 'AddressIsZero', 'UnsupportedOperation', 'NotSufficientFounds', 'UserIsNotAllowedToNest', 'SourceCollectionIsNotAllowedToNest', 'CollectionFieldSizeExceeded', 'NoSpaceForProperty', 'PropertyLimitReached', 'PropertyKeyIsTooLong', 'InvalidCharacterInPropertyKey', 'EmptyPropertyKey', 'CollectionIsExternal', 'CollectionIsInternal', 'ConfirmSponsorshipFail', 'UserIsNotCollectionAdmin']
},
/**
- * Lookup519: pallet_fungible::pallet::Error<T>
+ * Lookup520: pallet_fungible::pallet::Error<T>
**/
PalletFungibleError: {
_enum: ['NotFungibleDataUsedToMintFungibleCollectionToken', 'FungibleItemsHaveNoId', 'FungibleItemsDontHaveData', 'FungibleDisallowsNesting', 'SettingPropertiesNotAllowed', 'SettingAllowanceForAllNotAllowed', 'FungibleTokensAreAlwaysValid']
},
/**
- * Lookup524: pallet_refungible::pallet::Error<T>
+ * Lookup525: pallet_refungible::pallet::Error<T>
**/
PalletRefungibleError: {
_enum: ['NotRefungibleDataUsedToMintFungibleCollectionToken', 'WrongRefungiblePieces', 'RepartitionWhileNotOwningAllPieces', 'RefungibleDisallowsNesting', 'SettingPropertiesNotAllowed']
},
/**
- * Lookup525: pallet_nonfungible::ItemData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+ * Lookup526: pallet_nonfungible::ItemData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
**/
PalletNonfungibleItemData: {
owner: 'PalletEvmAccountBasicCrossAccountIdRepr'
},
/**
- * Lookup527: up_data_structs::PropertyScope
+ * Lookup528: up_data_structs::PropertyScope
**/
UpDataStructsPropertyScope: {
_enum: ['None', 'Rmrk']
},
/**
- * Lookup530: pallet_nonfungible::pallet::Error<T>
+ * Lookup531: pallet_nonfungible::pallet::Error<T>
**/
PalletNonfungibleError: {
_enum: ['NotNonfungibleDataUsedToMintFungibleCollectionToken', 'NonfungibleItemsHaveNoAmount', 'CantBurnNftWithChildren']
},
/**
- * Lookup531: pallet_structure::pallet::Error<T>
+ * Lookup532: pallet_structure::pallet::Error<T>
**/
PalletStructureError: {
_enum: ['OuroborosDetected', 'DepthLimit', 'BreadthLimit', 'TokenNotFound', 'CantNestTokenUnderCollection']
},
/**
- * Lookup536: pallet_app_promotion::pallet::Error<T>
+ * Lookup537: pallet_app_promotion::pallet::Error<T>
**/
PalletAppPromotionError: {
_enum: ['AdminNotSet', 'NoPermission', 'NotSufficientFunds', 'PendingForBlockOverflow', 'SponsorNotSet', 'InsufficientStakedBalance', 'InconsistencyState']
},
/**
- * Lookup537: pallet_foreign_assets::module::Error<T>
+ * Lookup538: pallet_foreign_assets::module::Error<T>
**/
PalletForeignAssetsModuleError: {
_enum: ['BadLocation', 'MultiLocationExisted', 'AssetIdNotExists', 'AssetIdExisted']
},
/**
- * Lookup538: pallet_evm::CodeMetadata
+ * Lookup539: pallet_evm::CodeMetadata
**/
PalletEvmCodeMetadata: {
_alias: {
@@ -3795,13 +3797,13 @@
hash_: 'H256'
},
/**
- * Lookup540: pallet_evm::pallet::Error<T>
+ * Lookup541: pallet_evm::pallet::Error<T>
**/
PalletEvmError: {
_enum: ['BalanceLow', 'FeeOverflow', 'PaymentOverflow', 'WithdrawFailed', 'GasPriceTooLow', 'InvalidNonce', 'GasLimitTooLow', 'GasLimitTooHigh', 'Undefined', 'Reentrancy', 'TransactionMustComeFromEOA']
},
/**
- * Lookup543: fp_rpc::TransactionStatus
+ * Lookup544: fp_rpc::TransactionStatus
**/
FpRpcTransactionStatus: {
transactionHash: 'H256',
@@ -3813,11 +3815,11 @@
logsBloom: 'EthbloomBloom'
},
/**
- * Lookup545: ethbloom::Bloom
+ * Lookup546: ethbloom::Bloom
**/
EthbloomBloom: '[u8;256]',
/**
- * Lookup547: ethereum::receipt::ReceiptV3
+ * Lookup548: ethereum::receipt::ReceiptV3
**/
EthereumReceiptReceiptV3: {
_enum: {
@@ -3827,7 +3829,7 @@
}
},
/**
- * Lookup548: ethereum::receipt::EIP658ReceiptData
+ * Lookup549: ethereum::receipt::EIP658ReceiptData
**/
EthereumReceiptEip658ReceiptData: {
statusCode: 'u8',
@@ -3836,7 +3838,7 @@
logs: 'Vec<EthereumLog>'
},
/**
- * Lookup549: ethereum::block::Block<ethereum::transaction::TransactionV2>
+ * Lookup550: ethereum::block::Block<ethereum::transaction::TransactionV2>
**/
EthereumBlock: {
header: 'EthereumHeader',
@@ -3844,7 +3846,7 @@
ommers: 'Vec<EthereumHeader>'
},
/**
- * Lookup550: ethereum::header::Header
+ * Lookup551: ethereum::header::Header
**/
EthereumHeader: {
parentHash: 'H256',
@@ -3864,23 +3866,23 @@
nonce: 'EthereumTypesHashH64'
},
/**
- * Lookup551: ethereum_types::hash::H64
+ * Lookup552: ethereum_types::hash::H64
**/
EthereumTypesHashH64: '[u8;8]',
/**
- * Lookup556: pallet_ethereum::pallet::Error<T>
+ * Lookup557: pallet_ethereum::pallet::Error<T>
**/
PalletEthereumError: {
_enum: ['InvalidSignature', 'PreLogExists']
},
/**
- * Lookup557: pallet_evm_coder_substrate::pallet::Error<T>
+ * Lookup558: pallet_evm_coder_substrate::pallet::Error<T>
**/
PalletEvmCoderSubstrateError: {
_enum: ['OutOfGas', 'OutOfFund']
},
/**
- * Lookup558: up_data_structs::SponsorshipState<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
+ * Lookup559: up_data_structs::SponsorshipState<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
**/
UpDataStructsSponsorshipStateBasicCrossAccountIdRepr: {
_enum: {
@@ -3890,35 +3892,35 @@
}
},
/**
- * Lookup559: pallet_evm_contract_helpers::SponsoringModeT
+ * Lookup560: pallet_evm_contract_helpers::SponsoringModeT
**/
PalletEvmContractHelpersSponsoringModeT: {
_enum: ['Disabled', 'Allowlisted', 'Generous']
},
/**
- * Lookup565: pallet_evm_contract_helpers::pallet::Error<T>
+ * Lookup566: pallet_evm_contract_helpers::pallet::Error<T>
**/
PalletEvmContractHelpersError: {
_enum: ['NoPermission', 'NoPendingSponsor', 'TooManyMethodsHaveSponsoredLimit']
},
/**
- * Lookup566: pallet_evm_migration::pallet::Error<T>
+ * Lookup567: pallet_evm_migration::pallet::Error<T>
**/
PalletEvmMigrationError: {
_enum: ['AccountNotEmpty', 'AccountIsNotMigrating', 'BadEvent']
},
/**
- * Lookup567: pallet_maintenance::pallet::Error<T>
+ * Lookup568: pallet_maintenance::pallet::Error<T>
**/
PalletMaintenanceError: 'Null',
/**
- * Lookup568: pallet_test_utils::pallet::Error<T>
+ * Lookup569: pallet_test_utils::pallet::Error<T>
**/
PalletTestUtilsError: {
_enum: ['TestPalletDisabled', 'TriggerRollback']
},
/**
- * Lookup570: sp_runtime::MultiSignature
+ * Lookup571: sp_runtime::MultiSignature
**/
SpRuntimeMultiSignature: {
_enum: {
@@ -3928,55 +3930,55 @@
}
},
/**
- * Lookup571: sp_core::ed25519::Signature
+ * Lookup572: sp_core::ed25519::Signature
**/
SpCoreEd25519Signature: '[u8;64]',
/**
- * Lookup573: sp_core::sr25519::Signature
+ * Lookup574: sp_core::sr25519::Signature
**/
SpCoreSr25519Signature: '[u8;64]',
/**
- * Lookup574: sp_core::ecdsa::Signature
+ * Lookup575: sp_core::ecdsa::Signature
**/
SpCoreEcdsaSignature: '[u8;65]',
/**
- * Lookup577: frame_system::extensions::check_spec_version::CheckSpecVersion<T>
+ * Lookup578: frame_system::extensions::check_spec_version::CheckSpecVersion<T>
**/
FrameSystemExtensionsCheckSpecVersion: 'Null',
/**
- * Lookup578: frame_system::extensions::check_tx_version::CheckTxVersion<T>
+ * Lookup579: frame_system::extensions::check_tx_version::CheckTxVersion<T>
**/
FrameSystemExtensionsCheckTxVersion: 'Null',
/**
- * Lookup579: frame_system::extensions::check_genesis::CheckGenesis<T>
+ * Lookup580: frame_system::extensions::check_genesis::CheckGenesis<T>
**/
FrameSystemExtensionsCheckGenesis: 'Null',
/**
- * Lookup582: frame_system::extensions::check_nonce::CheckNonce<T>
+ * Lookup583: frame_system::extensions::check_nonce::CheckNonce<T>
**/
FrameSystemExtensionsCheckNonce: 'Compact<u32>',
/**
- * Lookup583: frame_system::extensions::check_weight::CheckWeight<T>
+ * Lookup584: frame_system::extensions::check_weight::CheckWeight<T>
**/
FrameSystemExtensionsCheckWeight: 'Null',
/**
- * Lookup584: opal_runtime::runtime_common::maintenance::CheckMaintenance
+ * Lookup585: opal_runtime::runtime_common::maintenance::CheckMaintenance
**/
OpalRuntimeRuntimeCommonMaintenanceCheckMaintenance: 'Null',
/**
- * Lookup585: opal_runtime::runtime_common::identity::DisableIdentityCalls
+ * Lookup586: opal_runtime::runtime_common::identity::DisableIdentityCalls
**/
OpalRuntimeRuntimeCommonIdentityDisableIdentityCalls: 'Null',
/**
- * Lookup586: pallet_template_transaction_payment::ChargeTransactionPayment<opal_runtime::Runtime>
+ * Lookup587: pallet_template_transaction_payment::ChargeTransactionPayment<opal_runtime::Runtime>
**/
PalletTemplateTransactionPaymentChargeTransactionPayment: 'Compact<u128>',
/**
- * Lookup587: opal_runtime::Runtime
+ * Lookup588: opal_runtime::Runtime
**/
OpalRuntimeRuntime: 'Null',
/**
- * Lookup588: pallet_ethereum::FakeTransactionFinalizer<opal_runtime::Runtime>
+ * Lookup589: pallet_ethereum::FakeTransactionFinalizer<opal_runtime::Runtime>
**/
PalletEthereumFakeTransactionFinalizer: 'Null'
};
tests/src/interfaces/types-lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -3181,11 +3181,13 @@
readonly name: Vec<u16>;
readonly description: Vec<u16>;
readonly tokenPrefix: Bytes;
- readonly pendingSponsor: Option<AccountId32>;
readonly limits: Option<UpDataStructsCollectionLimits>;
readonly permissions: Option<UpDataStructsCollectionPermissions>;
readonly tokenPropertyPermissions: Vec<UpDataStructsPropertyKeyPermission>;
readonly properties: Vec<UpDataStructsProperty>;
+ readonly adminList: Vec<PalletEvmAccountBasicCrossAccountIdRepr>;
+ readonly pendingSponsor: Option<PalletEvmAccountBasicCrossAccountIdRepr>;
+ readonly flags: U8aFixed;
}
/** @name UpDataStructsAccessMode (337) */
@@ -3252,7 +3254,7 @@
readonly value: Bytes;
}
- /** @name UpDataStructsCreateItemData (360) */
+ /** @name UpDataStructsCreateItemData (362) */
interface UpDataStructsCreateItemData extends Enum {
readonly isNft: boolean;
readonly asNft: UpDataStructsCreateNftData;
@@ -3263,23 +3265,23 @@
readonly type: 'Nft' | 'Fungible' | 'ReFungible';
}
- /** @name UpDataStructsCreateNftData (361) */
+ /** @name UpDataStructsCreateNftData (363) */
interface UpDataStructsCreateNftData extends Struct {
readonly properties: Vec<UpDataStructsProperty>;
}
- /** @name UpDataStructsCreateFungibleData (362) */
+ /** @name UpDataStructsCreateFungibleData (364) */
interface UpDataStructsCreateFungibleData extends Struct {
readonly value: u128;
}
- /** @name UpDataStructsCreateReFungibleData (363) */
+ /** @name UpDataStructsCreateReFungibleData (365) */
interface UpDataStructsCreateReFungibleData extends Struct {
readonly pieces: u128;
readonly properties: Vec<UpDataStructsProperty>;
}
- /** @name UpDataStructsCreateItemExData (366) */
+ /** @name UpDataStructsCreateItemExData (368) */
interface UpDataStructsCreateItemExData extends Enum {
readonly isNft: boolean;
readonly asNft: Vec<UpDataStructsCreateNftExData>;
@@ -3292,26 +3294,26 @@
readonly type: 'Nft' | 'Fungible' | 'RefungibleMultipleItems' | 'RefungibleMultipleOwners';
}
- /** @name UpDataStructsCreateNftExData (368) */
+ /** @name UpDataStructsCreateNftExData (370) */
interface UpDataStructsCreateNftExData extends Struct {
readonly properties: Vec<UpDataStructsProperty>;
readonly owner: PalletEvmAccountBasicCrossAccountIdRepr;
}
- /** @name UpDataStructsCreateRefungibleExSingleOwner (375) */
+ /** @name UpDataStructsCreateRefungibleExSingleOwner (377) */
interface UpDataStructsCreateRefungibleExSingleOwner extends Struct {
readonly user: PalletEvmAccountBasicCrossAccountIdRepr;
readonly pieces: u128;
readonly properties: Vec<UpDataStructsProperty>;
}
- /** @name UpDataStructsCreateRefungibleExMultipleOwners (377) */
+ /** @name UpDataStructsCreateRefungibleExMultipleOwners (379) */
interface UpDataStructsCreateRefungibleExMultipleOwners extends Struct {
readonly users: BTreeMap<PalletEvmAccountBasicCrossAccountIdRepr, u128>;
readonly properties: Vec<UpDataStructsProperty>;
}
- /** @name PalletConfigurationCall (378) */
+ /** @name PalletConfigurationCall (380) */
interface PalletConfigurationCall extends Enum {
readonly isSetWeightToFeeCoefficientOverride: boolean;
readonly asSetWeightToFeeCoefficientOverride: {
@@ -3340,7 +3342,7 @@
readonly type: 'SetWeightToFeeCoefficientOverride' | 'SetMinGasPriceOverride' | 'SetAppPromotionConfigurationOverride' | 'SetCollatorSelectionDesiredCollators' | 'SetCollatorSelectionLicenseBond' | 'SetCollatorSelectionKickThreshold';
}
- /** @name PalletConfigurationAppPromotionConfiguration (380) */
+ /** @name PalletConfigurationAppPromotionConfiguration (382) */
interface PalletConfigurationAppPromotionConfiguration extends Struct {
readonly recalculationInterval: Option<u32>;
readonly pendingInterval: Option<u32>;
@@ -3348,10 +3350,10 @@
readonly maxStakersPerCalculation: Option<u8>;
}
- /** @name PalletStructureCall (384) */
+ /** @name PalletStructureCall (386) */
type PalletStructureCall = Null;
- /** @name PalletAppPromotionCall (385) */
+ /** @name PalletAppPromotionCall (387) */
interface PalletAppPromotionCall extends Enum {
readonly isSetAdminAddress: boolean;
readonly asSetAdminAddress: {
@@ -3393,7 +3395,7 @@
readonly type: 'SetAdminAddress' | 'Stake' | 'UnstakeAll' | 'SponsorCollection' | 'StopSponsoringCollection' | 'SponsorContract' | 'StopSponsoringContract' | 'PayoutStakers' | 'UnstakePartial' | 'ForceUnstake';
}
- /** @name PalletForeignAssetsModuleCall (386) */
+ /** @name PalletForeignAssetsModuleCall (388) */
interface PalletForeignAssetsModuleCall extends Enum {
readonly isRegisterForeignAsset: boolean;
readonly asRegisterForeignAsset: {
@@ -3410,7 +3412,7 @@
readonly type: 'RegisterForeignAsset' | 'UpdateForeignAsset';
}
- /** @name PalletEvmCall (387) */
+ /** @name PalletEvmCall (389) */
interface PalletEvmCall extends Enum {
readonly isWithdraw: boolean;
readonly asWithdraw: {
@@ -3455,7 +3457,7 @@
readonly type: 'Withdraw' | 'Call' | 'Create' | 'Create2';
}
- /** @name PalletEthereumCall (393) */
+ /** @name PalletEthereumCall (395) */
interface PalletEthereumCall extends Enum {
readonly isTransact: boolean;
readonly asTransact: {
@@ -3464,7 +3466,7 @@
readonly type: 'Transact';
}
- /** @name EthereumTransactionTransactionV2 (394) */
+ /** @name EthereumTransactionTransactionV2 (396) */
interface EthereumTransactionTransactionV2 extends Enum {
readonly isLegacy: boolean;
readonly asLegacy: EthereumTransactionLegacyTransaction;
@@ -3475,7 +3477,7 @@
readonly type: 'Legacy' | 'Eip2930' | 'Eip1559';
}
- /** @name EthereumTransactionLegacyTransaction (395) */
+ /** @name EthereumTransactionLegacyTransaction (397) */
interface EthereumTransactionLegacyTransaction extends Struct {
readonly nonce: U256;
readonly gasPrice: U256;
@@ -3486,7 +3488,7 @@
readonly signature: EthereumTransactionTransactionSignature;
}
- /** @name EthereumTransactionTransactionAction (396) */
+ /** @name EthereumTransactionTransactionAction (398) */
interface EthereumTransactionTransactionAction extends Enum {
readonly isCall: boolean;
readonly asCall: H160;
@@ -3494,14 +3496,14 @@
readonly type: 'Call' | 'Create';
}
- /** @name EthereumTransactionTransactionSignature (397) */
+ /** @name EthereumTransactionTransactionSignature (399) */
interface EthereumTransactionTransactionSignature extends Struct {
readonly v: u64;
readonly r: H256;
readonly s: H256;
}
- /** @name EthereumTransactionEip2930Transaction (399) */
+ /** @name EthereumTransactionEip2930Transaction (401) */
interface EthereumTransactionEip2930Transaction extends Struct {
readonly chainId: u64;
readonly nonce: U256;
@@ -3516,13 +3518,13 @@
readonly s: H256;
}
- /** @name EthereumTransactionAccessListItem (401) */
+ /** @name EthereumTransactionAccessListItem (403) */
interface EthereumTransactionAccessListItem extends Struct {
readonly address: H160;
readonly storageKeys: Vec<H256>;
}
- /** @name EthereumTransactionEip1559Transaction (402) */
+ /** @name EthereumTransactionEip1559Transaction (404) */
interface EthereumTransactionEip1559Transaction extends Struct {
readonly chainId: u64;
readonly nonce: U256;
@@ -3538,7 +3540,7 @@
readonly s: H256;
}
- /** @name PalletEvmContractHelpersCall (403) */
+ /** @name PalletEvmContractHelpersCall (405) */
interface PalletEvmContractHelpersCall extends Enum {
readonly isMigrateFromSelfSponsoring: boolean;
readonly asMigrateFromSelfSponsoring: {
@@ -3547,7 +3549,7 @@
readonly type: 'MigrateFromSelfSponsoring';
}
- /** @name PalletEvmMigrationCall (405) */
+ /** @name PalletEvmMigrationCall (407) */
interface PalletEvmMigrationCall extends Enum {
readonly isBegin: boolean;
readonly asBegin: {
@@ -3575,7 +3577,7 @@
readonly type: 'Begin' | 'SetData' | 'Finish' | 'InsertEthLogs' | 'InsertEvents' | 'RemoveRmrkData';
}
- /** @name PalletMaintenanceCall (409) */
+ /** @name PalletMaintenanceCall (411) */
interface PalletMaintenanceCall extends Enum {
readonly isEnable: boolean;
readonly isDisable: boolean;
@@ -3587,7 +3589,7 @@
readonly type: 'Enable' | 'Disable' | 'ExecutePreimage';
}
- /** @name PalletTestUtilsCall (410) */
+ /** @name PalletTestUtilsCall (412) */
interface PalletTestUtilsCall extends Enum {
readonly isEnable: boolean;
readonly isSetTestValue: boolean;
@@ -3607,13 +3609,13 @@
readonly type: 'Enable' | 'SetTestValue' | 'SetTestValueAndRollback' | 'IncTestValue' | 'JustTakeFee' | 'BatchAll';
}
- /** @name PalletSudoError (412) */
+ /** @name PalletSudoError (414) */
interface PalletSudoError extends Enum {
readonly isRequireSudo: boolean;
readonly type: 'RequireSudo';
}
- /** @name OrmlVestingModuleError (414) */
+ /** @name OrmlVestingModuleError (416) */
interface OrmlVestingModuleError extends Enum {
readonly isZeroVestingPeriod: boolean;
readonly isZeroVestingPeriodCount: boolean;
@@ -3624,7 +3626,7 @@
readonly type: 'ZeroVestingPeriod' | 'ZeroVestingPeriodCount' | 'InsufficientBalanceToLock' | 'TooManyVestingSchedules' | 'AmountLow' | 'MaxVestingSchedulesExceeded';
}
- /** @name OrmlXtokensModuleError (415) */
+ /** @name OrmlXtokensModuleError (417) */
interface OrmlXtokensModuleError extends Enum {
readonly isAssetHasNoReserve: boolean;
readonly isNotCrossChainTransfer: boolean;
@@ -3648,26 +3650,26 @@
readonly type: 'AssetHasNoReserve' | 'NotCrossChainTransfer' | 'InvalidDest' | 'NotCrossChainTransferableCurrency' | 'UnweighableMessage' | 'XcmExecutionFailed' | 'CannotReanchor' | 'InvalidAncestry' | 'InvalidAsset' | 'DestinationNotInvertible' | 'BadVersion' | 'DistinctReserveForAssetAndFee' | 'ZeroFee' | 'ZeroAmount' | 'TooManyAssetsBeingSent' | 'AssetIndexNonExistent' | 'FeeNotEnough' | 'NotSupportedMultiLocation' | 'MinXcmFeeNotDefined';
}
- /** @name OrmlTokensBalanceLock (418) */
+ /** @name OrmlTokensBalanceLock (420) */
interface OrmlTokensBalanceLock extends Struct {
readonly id: U8aFixed;
readonly amount: u128;
}
- /** @name OrmlTokensAccountData (420) */
+ /** @name OrmlTokensAccountData (422) */
interface OrmlTokensAccountData extends Struct {
readonly free: u128;
readonly reserved: u128;
readonly frozen: u128;
}
- /** @name OrmlTokensReserveData (422) */
+ /** @name OrmlTokensReserveData (424) */
interface OrmlTokensReserveData extends Struct {
readonly id: Null;
readonly amount: u128;
}
- /** @name OrmlTokensModuleError (424) */
+ /** @name OrmlTokensModuleError (426) */
interface OrmlTokensModuleError extends Enum {
readonly isBalanceTooLow: boolean;
readonly isAmountIntoBalanceFailed: boolean;
@@ -3680,14 +3682,14 @@
readonly type: 'BalanceTooLow' | 'AmountIntoBalanceFailed' | 'LiquidityRestrictions' | 'MaxLocksExceeded' | 'KeepAlive' | 'ExistentialDeposit' | 'DeadAccount' | 'TooManyReserves';
}
- /** @name PalletIdentityRegistrarInfo (429) */
+ /** @name PalletIdentityRegistrarInfo (431) */
interface PalletIdentityRegistrarInfo extends Struct {
readonly account: AccountId32;
readonly fee: u128;
readonly fields: PalletIdentityBitFlags;
}
- /** @name PalletIdentityError (431) */
+ /** @name PalletIdentityError (433) */
interface PalletIdentityError extends Enum {
readonly isTooManySubAccounts: boolean;
readonly isNotFound: boolean;
@@ -3710,7 +3712,7 @@
readonly type: 'TooManySubAccounts' | 'NotFound' | 'NotNamed' | 'EmptyIndex' | 'FeeChanged' | 'NoIdentity' | 'StickyJudgement' | 'JudgementGiven' | 'InvalidJudgement' | 'InvalidIndex' | 'InvalidTarget' | 'TooManyFields' | 'TooManyRegistrars' | 'AlreadyClaimed' | 'NotSub' | 'NotOwned' | 'JudgementForDifferentIdentity' | 'JudgementPaymentFailed';
}
- /** @name PalletPreimageRequestStatus (432) */
+ /** @name PalletPreimageRequestStatus (434) */
interface PalletPreimageRequestStatus extends Enum {
readonly isUnrequested: boolean;
readonly asUnrequested: {
@@ -3726,7 +3728,7 @@
readonly type: 'Unrequested' | 'Requested';
}
- /** @name PalletPreimageError (437) */
+ /** @name PalletPreimageError (439) */
interface PalletPreimageError extends Enum {
readonly isTooBig: boolean;
readonly isAlreadyNoted: boolean;
@@ -3737,21 +3739,21 @@
readonly type: 'TooBig' | 'AlreadyNoted' | 'NotAuthorized' | 'NotNoted' | 'Requested' | 'NotRequested';
}
- /** @name CumulusPalletXcmpQueueInboundChannelDetails (439) */
+ /** @name CumulusPalletXcmpQueueInboundChannelDetails (441) */
interface CumulusPalletXcmpQueueInboundChannelDetails extends Struct {
readonly sender: u32;
readonly state: CumulusPalletXcmpQueueInboundState;
readonly messageMetadata: Vec<ITuple<[u32, PolkadotParachainPrimitivesXcmpMessageFormat]>>;
}
- /** @name CumulusPalletXcmpQueueInboundState (440) */
+ /** @name CumulusPalletXcmpQueueInboundState (442) */
interface CumulusPalletXcmpQueueInboundState extends Enum {
readonly isOk: boolean;
readonly isSuspended: boolean;
readonly type: 'Ok' | 'Suspended';
}
- /** @name PolkadotParachainPrimitivesXcmpMessageFormat (443) */
+ /** @name PolkadotParachainPrimitivesXcmpMessageFormat (445) */
interface PolkadotParachainPrimitivesXcmpMessageFormat extends Enum {
readonly isConcatenatedVersionedXcm: boolean;
readonly isConcatenatedEncodedBlob: boolean;
@@ -3759,7 +3761,7 @@
readonly type: 'ConcatenatedVersionedXcm' | 'ConcatenatedEncodedBlob' | 'Signals';
}
- /** @name CumulusPalletXcmpQueueOutboundChannelDetails (446) */
+ /** @name CumulusPalletXcmpQueueOutboundChannelDetails (448) */
interface CumulusPalletXcmpQueueOutboundChannelDetails extends Struct {
readonly recipient: u32;
readonly state: CumulusPalletXcmpQueueOutboundState;
@@ -3768,14 +3770,14 @@
readonly lastIndex: u16;
}
- /** @name CumulusPalletXcmpQueueOutboundState (447) */
+ /** @name CumulusPalletXcmpQueueOutboundState (449) */
interface CumulusPalletXcmpQueueOutboundState extends Enum {
readonly isOk: boolean;
readonly isSuspended: boolean;
readonly type: 'Ok' | 'Suspended';
}
- /** @name CumulusPalletXcmpQueueQueueConfigData (449) */
+ /** @name CumulusPalletXcmpQueueQueueConfigData (451) */
interface CumulusPalletXcmpQueueQueueConfigData extends Struct {
readonly suspendThreshold: u32;
readonly dropThreshold: u32;
@@ -3785,7 +3787,7 @@
readonly xcmpMaxIndividualWeight: SpWeightsWeightV2Weight;
}
- /** @name CumulusPalletXcmpQueueError (451) */
+ /** @name CumulusPalletXcmpQueueError (453) */
interface CumulusPalletXcmpQueueError extends Enum {
readonly isFailedToSend: boolean;
readonly isBadXcmOrigin: boolean;
@@ -3795,7 +3797,7 @@
readonly type: 'FailedToSend' | 'BadXcmOrigin' | 'BadXcm' | 'BadOverweightIndex' | 'WeightOverLimit';
}
- /** @name PalletXcmQueryStatus (452) */
+ /** @name PalletXcmQueryStatus (454) */
interface PalletXcmQueryStatus extends Enum {
readonly isPending: boolean;
readonly asPending: {
@@ -3817,7 +3819,7 @@
readonly type: 'Pending' | 'VersionNotifier' | 'Ready';
}
- /** @name XcmVersionedResponse (456) */
+ /** @name XcmVersionedResponse (458) */
interface XcmVersionedResponse extends Enum {
readonly isV2: boolean;
readonly asV2: XcmV2Response;
@@ -3826,7 +3828,7 @@
readonly type: 'V2' | 'V3';
}
- /** @name PalletXcmVersionMigrationStage (462) */
+ /** @name PalletXcmVersionMigrationStage (464) */
interface PalletXcmVersionMigrationStage extends Enum {
readonly isMigrateSupportedVersion: boolean;
readonly isMigrateVersionNotifiers: boolean;
@@ -3836,14 +3838,14 @@
readonly type: 'MigrateSupportedVersion' | 'MigrateVersionNotifiers' | 'NotifyCurrentTargets' | 'MigrateAndNotifyOldTargets';
}
- /** @name XcmVersionedAssetId (465) */
+ /** @name XcmVersionedAssetId (467) */
interface XcmVersionedAssetId extends Enum {
readonly isV3: boolean;
readonly asV3: XcmV3MultiassetAssetId;
readonly type: 'V3';
}
- /** @name PalletXcmRemoteLockedFungibleRecord (466) */
+ /** @name PalletXcmRemoteLockedFungibleRecord (468) */
interface PalletXcmRemoteLockedFungibleRecord extends Struct {
readonly amount: u128;
readonly owner: XcmVersionedMultiLocation;
@@ -3851,7 +3853,7 @@
readonly consumers: Vec<ITuple<[Null, u128]>>;
}
- /** @name PalletXcmError (473) */
+ /** @name PalletXcmError (475) */
interface PalletXcmError extends Enum {
readonly isUnreachable: boolean;
readonly isSendFailure: boolean;
@@ -3876,29 +3878,29 @@
readonly type: 'Unreachable' | 'SendFailure' | 'Filtered' | 'UnweighableMessage' | 'DestinationNotInvertible' | 'Empty' | 'CannotReanchor' | 'TooManyAssets' | 'InvalidOrigin' | 'BadVersion' | 'BadLocation' | 'NoSubscription' | 'AlreadySubscribed' | 'InvalidAsset' | 'LowBalance' | 'TooManyLocks' | 'AccountNotSovereign' | 'FeesNotMet' | 'LockNotFound' | 'InUse';
}
- /** @name CumulusPalletXcmError (474) */
+ /** @name CumulusPalletXcmError (476) */
type CumulusPalletXcmError = Null;
- /** @name CumulusPalletDmpQueueConfigData (475) */
+ /** @name CumulusPalletDmpQueueConfigData (477) */
interface CumulusPalletDmpQueueConfigData extends Struct {
readonly maxIndividual: SpWeightsWeightV2Weight;
}
- /** @name CumulusPalletDmpQueuePageIndexData (476) */
+ /** @name CumulusPalletDmpQueuePageIndexData (478) */
interface CumulusPalletDmpQueuePageIndexData extends Struct {
readonly beginUsed: u32;
readonly endUsed: u32;
readonly overweightCount: u64;
}
- /** @name CumulusPalletDmpQueueError (479) */
+ /** @name CumulusPalletDmpQueueError (481) */
interface CumulusPalletDmpQueueError extends Enum {
readonly isUnknown: boolean;
readonly isOverLimit: boolean;
readonly type: 'Unknown' | 'OverLimit';
}
- /** @name PalletUniqueError (483) */
+ /** @name PalletUniqueError (485) */
interface PalletUniqueError extends Enum {
readonly isCollectionDecimalPointLimitExceeded: boolean;
readonly isEmptyArgument: boolean;
@@ -3906,13 +3908,13 @@
readonly type: 'CollectionDecimalPointLimitExceeded' | 'EmptyArgument' | 'RepartitionCalledOnNonRefungibleCollection';
}
- /** @name PalletConfigurationError (484) */
+ /** @name PalletConfigurationError (486) */
interface PalletConfigurationError extends Enum {
readonly isInconsistentConfiguration: boolean;
readonly type: 'InconsistentConfiguration';
}
- /** @name UpDataStructsCollection (485) */
+ /** @name UpDataStructsCollection (487) */
interface UpDataStructsCollection extends Struct {
readonly owner: AccountId32;
readonly mode: UpDataStructsCollectionMode;
@@ -3925,7 +3927,7 @@
readonly flags: U8aFixed;
}
- /** @name UpDataStructsSponsorshipStateAccountId32 (486) */
+ /** @name UpDataStructsSponsorshipStateAccountId32 (488) */
interface UpDataStructsSponsorshipStateAccountId32 extends Enum {
readonly isDisabled: boolean;
readonly isUnconfirmed: boolean;
@@ -3935,43 +3937,43 @@
readonly type: 'Disabled' | 'Unconfirmed' | 'Confirmed';
}
- /** @name UpDataStructsProperties (487) */
+ /** @name UpDataStructsProperties (489) */
interface UpDataStructsProperties extends Struct {
readonly map: UpDataStructsPropertiesMapBoundedVec;
readonly consumedSpace: u32;
readonly reserved: u32;
}
- /** @name UpDataStructsPropertiesMapBoundedVec (488) */
+ /** @name UpDataStructsPropertiesMapBoundedVec (490) */
interface UpDataStructsPropertiesMapBoundedVec extends BTreeMap<Bytes, Bytes> {}
- /** @name UpDataStructsPropertiesMapPropertyPermission (493) */
+ /** @name UpDataStructsPropertiesMapPropertyPermission (495) */
interface UpDataStructsPropertiesMapPropertyPermission extends BTreeMap<Bytes, UpDataStructsPropertyPermission> {}
- /** @name UpDataStructsCollectionStats (500) */
+ /** @name UpDataStructsCollectionStats (502) */
interface UpDataStructsCollectionStats extends Struct {
readonly created: u32;
readonly destroyed: u32;
readonly alive: u32;
}
- /** @name UpDataStructsTokenChild (501) */
+ /** @name UpDataStructsTokenChild (503) */
interface UpDataStructsTokenChild extends Struct {
readonly token: u32;
readonly collection: u32;
}
- /** @name PhantomTypeUpDataStructs (502) */
+ /** @name PhantomTypeUpDataStructs (504) */
interface PhantomTypeUpDataStructs extends Vec<ITuple<[UpDataStructsTokenData, UpDataStructsRpcCollection, UpPovEstimateRpcPovInfo]>> {}
- /** @name UpDataStructsTokenData (504) */
+ /** @name UpDataStructsTokenData (506) */
interface UpDataStructsTokenData extends Struct {
readonly properties: Vec<UpDataStructsProperty>;
readonly owner: Option<PalletEvmAccountBasicCrossAccountIdRepr>;
readonly pieces: u128;
}
- /** @name UpDataStructsRpcCollection (506) */
+ /** @name UpDataStructsRpcCollection (507) */
interface UpDataStructsRpcCollection extends Struct {
readonly owner: AccountId32;
readonly mode: UpDataStructsCollectionMode;
@@ -3987,13 +3989,13 @@
readonly flags: UpDataStructsRpcCollectionFlags;
}
- /** @name UpDataStructsRpcCollectionFlags (507) */
+ /** @name UpDataStructsRpcCollectionFlags (508) */
interface UpDataStructsRpcCollectionFlags extends Struct {
readonly foreign: bool;
readonly erc721metadata: bool;
}
- /** @name UpPovEstimateRpcPovInfo (508) */
+ /** @name UpPovEstimateRpcPovInfo (509) */
interface UpPovEstimateRpcPovInfo extends Struct {
readonly proofSize: u64;
readonly compactProofSize: u64;
@@ -4002,7 +4004,7 @@
readonly keyValues: Vec<UpPovEstimateRpcTrieKeyValue>;
}
- /** @name SpRuntimeTransactionValidityTransactionValidityError (511) */
+ /** @name SpRuntimeTransactionValidityTransactionValidityError (512) */
interface SpRuntimeTransactionValidityTransactionValidityError extends Enum {
readonly isInvalid: boolean;
readonly asInvalid: SpRuntimeTransactionValidityInvalidTransaction;
@@ -4011,7 +4013,7 @@
readonly type: 'Invalid' | 'Unknown';
}
- /** @name SpRuntimeTransactionValidityInvalidTransaction (512) */
+ /** @name SpRuntimeTransactionValidityInvalidTransaction (513) */
interface SpRuntimeTransactionValidityInvalidTransaction extends Enum {
readonly isCall: boolean;
readonly isPayment: boolean;
@@ -4028,7 +4030,7 @@
readonly type: 'Call' | 'Payment' | 'Future' | 'Stale' | 'BadProof' | 'AncientBirthBlock' | 'ExhaustsResources' | 'Custom' | 'BadMandatory' | 'MandatoryValidation' | 'BadSigner';
}
- /** @name SpRuntimeTransactionValidityUnknownTransaction (513) */
+ /** @name SpRuntimeTransactionValidityUnknownTransaction (514) */
interface SpRuntimeTransactionValidityUnknownTransaction extends Enum {
readonly isCannotLookup: boolean;
readonly isNoUnsignedValidator: boolean;
@@ -4037,13 +4039,13 @@
readonly type: 'CannotLookup' | 'NoUnsignedValidator' | 'Custom';
}
- /** @name UpPovEstimateRpcTrieKeyValue (515) */
+ /** @name UpPovEstimateRpcTrieKeyValue (516) */
interface UpPovEstimateRpcTrieKeyValue extends Struct {
readonly key: Bytes;
readonly value: Bytes;
}
- /** @name PalletCommonError (517) */
+ /** @name PalletCommonError (518) */
interface PalletCommonError extends Enum {
readonly isCollectionNotFound: boolean;
readonly isMustBeTokenOwner: boolean;
@@ -4085,7 +4087,7 @@
readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsNotEthMirror' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
}
- /** @name PalletFungibleError (519) */
+ /** @name PalletFungibleError (520) */
interface PalletFungibleError extends Enum {
readonly isNotFungibleDataUsedToMintFungibleCollectionToken: boolean;
readonly isFungibleItemsHaveNoId: boolean;
@@ -4097,7 +4099,7 @@
readonly type: 'NotFungibleDataUsedToMintFungibleCollectionToken' | 'FungibleItemsHaveNoId' | 'FungibleItemsDontHaveData' | 'FungibleDisallowsNesting' | 'SettingPropertiesNotAllowed' | 'SettingAllowanceForAllNotAllowed' | 'FungibleTokensAreAlwaysValid';
}
- /** @name PalletRefungibleError (524) */
+ /** @name PalletRefungibleError (525) */
interface PalletRefungibleError extends Enum {
readonly isNotRefungibleDataUsedToMintFungibleCollectionToken: boolean;
readonly isWrongRefungiblePieces: boolean;
@@ -4107,19 +4109,19 @@
readonly type: 'NotRefungibleDataUsedToMintFungibleCollectionToken' | 'WrongRefungiblePieces' | 'RepartitionWhileNotOwningAllPieces' | 'RefungibleDisallowsNesting' | 'SettingPropertiesNotAllowed';
}
- /** @name PalletNonfungibleItemData (525) */
+ /** @name PalletNonfungibleItemData (526) */
interface PalletNonfungibleItemData extends Struct {
readonly owner: PalletEvmAccountBasicCrossAccountIdRepr;
}
- /** @name UpDataStructsPropertyScope (527) */
+ /** @name UpDataStructsPropertyScope (528) */
interface UpDataStructsPropertyScope extends Enum {
readonly isNone: boolean;
readonly isRmrk: boolean;
readonly type: 'None' | 'Rmrk';
}
- /** @name PalletNonfungibleError (530) */
+ /** @name PalletNonfungibleError (531) */
interface PalletNonfungibleError extends Enum {
readonly isNotNonfungibleDataUsedToMintFungibleCollectionToken: boolean;
readonly isNonfungibleItemsHaveNoAmount: boolean;
@@ -4127,7 +4129,7 @@
readonly type: 'NotNonfungibleDataUsedToMintFungibleCollectionToken' | 'NonfungibleItemsHaveNoAmount' | 'CantBurnNftWithChildren';
}
- /** @name PalletStructureError (531) */
+ /** @name PalletStructureError (532) */
interface PalletStructureError extends Enum {
readonly isOuroborosDetected: boolean;
readonly isDepthLimit: boolean;
@@ -4137,7 +4139,7 @@
readonly type: 'OuroborosDetected' | 'DepthLimit' | 'BreadthLimit' | 'TokenNotFound' | 'CantNestTokenUnderCollection';
}
- /** @name PalletAppPromotionError (536) */
+ /** @name PalletAppPromotionError (537) */
interface PalletAppPromotionError extends Enum {
readonly isAdminNotSet: boolean;
readonly isNoPermission: boolean;
@@ -4149,7 +4151,7 @@
readonly type: 'AdminNotSet' | 'NoPermission' | 'NotSufficientFunds' | 'PendingForBlockOverflow' | 'SponsorNotSet' | 'InsufficientStakedBalance' | 'InconsistencyState';
}
- /** @name PalletForeignAssetsModuleError (537) */
+ /** @name PalletForeignAssetsModuleError (538) */
interface PalletForeignAssetsModuleError extends Enum {
readonly isBadLocation: boolean;
readonly isMultiLocationExisted: boolean;
@@ -4158,13 +4160,13 @@
readonly type: 'BadLocation' | 'MultiLocationExisted' | 'AssetIdNotExists' | 'AssetIdExisted';
}
- /** @name PalletEvmCodeMetadata (538) */
+ /** @name PalletEvmCodeMetadata (539) */
interface PalletEvmCodeMetadata extends Struct {
readonly size_: u64;
readonly hash_: H256;
}
- /** @name PalletEvmError (540) */
+ /** @name PalletEvmError (541) */
interface PalletEvmError extends Enum {
readonly isBalanceLow: boolean;
readonly isFeeOverflow: boolean;
@@ -4180,7 +4182,7 @@
readonly type: 'BalanceLow' | 'FeeOverflow' | 'PaymentOverflow' | 'WithdrawFailed' | 'GasPriceTooLow' | 'InvalidNonce' | 'GasLimitTooLow' | 'GasLimitTooHigh' | 'Undefined' | 'Reentrancy' | 'TransactionMustComeFromEOA';
}
- /** @name FpRpcTransactionStatus (543) */
+ /** @name FpRpcTransactionStatus (544) */
interface FpRpcTransactionStatus extends Struct {
readonly transactionHash: H256;
readonly transactionIndex: u32;
@@ -4191,10 +4193,10 @@
readonly logsBloom: EthbloomBloom;
}
- /** @name EthbloomBloom (545) */
+ /** @name EthbloomBloom (546) */
interface EthbloomBloom extends U8aFixed {}
- /** @name EthereumReceiptReceiptV3 (547) */
+ /** @name EthereumReceiptReceiptV3 (548) */
interface EthereumReceiptReceiptV3 extends Enum {
readonly isLegacy: boolean;
readonly asLegacy: EthereumReceiptEip658ReceiptData;
@@ -4205,7 +4207,7 @@
readonly type: 'Legacy' | 'Eip2930' | 'Eip1559';
}
- /** @name EthereumReceiptEip658ReceiptData (548) */
+ /** @name EthereumReceiptEip658ReceiptData (549) */
interface EthereumReceiptEip658ReceiptData extends Struct {
readonly statusCode: u8;
readonly usedGas: U256;
@@ -4213,14 +4215,14 @@
readonly logs: Vec<EthereumLog>;
}
- /** @name EthereumBlock (549) */
+ /** @name EthereumBlock (550) */
interface EthereumBlock extends Struct {
readonly header: EthereumHeader;
readonly transactions: Vec<EthereumTransactionTransactionV2>;
readonly ommers: Vec<EthereumHeader>;
}
- /** @name EthereumHeader (550) */
+ /** @name EthereumHeader (551) */
interface EthereumHeader extends Struct {
readonly parentHash: H256;
readonly ommersHash: H256;
@@ -4239,24 +4241,24 @@
readonly nonce: EthereumTypesHashH64;
}
- /** @name EthereumTypesHashH64 (551) */
+ /** @name EthereumTypesHashH64 (552) */
interface EthereumTypesHashH64 extends U8aFixed {}
- /** @name PalletEthereumError (556) */
+ /** @name PalletEthereumError (557) */
interface PalletEthereumError extends Enum {
readonly isInvalidSignature: boolean;
readonly isPreLogExists: boolean;
readonly type: 'InvalidSignature' | 'PreLogExists';
}
- /** @name PalletEvmCoderSubstrateError (557) */
+ /** @name PalletEvmCoderSubstrateError (558) */
interface PalletEvmCoderSubstrateError extends Enum {
readonly isOutOfGas: boolean;
readonly isOutOfFund: boolean;
readonly type: 'OutOfGas' | 'OutOfFund';
}
- /** @name UpDataStructsSponsorshipStateBasicCrossAccountIdRepr (558) */
+ /** @name UpDataStructsSponsorshipStateBasicCrossAccountIdRepr (559) */
interface UpDataStructsSponsorshipStateBasicCrossAccountIdRepr extends Enum {
readonly isDisabled: boolean;
readonly isUnconfirmed: boolean;
@@ -4266,7 +4268,7 @@
readonly type: 'Disabled' | 'Unconfirmed' | 'Confirmed';
}
- /** @name PalletEvmContractHelpersSponsoringModeT (559) */
+ /** @name PalletEvmContractHelpersSponsoringModeT (560) */
interface PalletEvmContractHelpersSponsoringModeT extends Enum {
readonly isDisabled: boolean;
readonly isAllowlisted: boolean;
@@ -4274,7 +4276,7 @@
readonly type: 'Disabled' | 'Allowlisted' | 'Generous';
}
- /** @name PalletEvmContractHelpersError (565) */
+ /** @name PalletEvmContractHelpersError (566) */
interface PalletEvmContractHelpersError extends Enum {
readonly isNoPermission: boolean;
readonly isNoPendingSponsor: boolean;
@@ -4282,7 +4284,7 @@
readonly type: 'NoPermission' | 'NoPendingSponsor' | 'TooManyMethodsHaveSponsoredLimit';
}
- /** @name PalletEvmMigrationError (566) */
+ /** @name PalletEvmMigrationError (567) */
interface PalletEvmMigrationError extends Enum {
readonly isAccountNotEmpty: boolean;
readonly isAccountIsNotMigrating: boolean;
@@ -4290,17 +4292,17 @@
readonly type: 'AccountNotEmpty' | 'AccountIsNotMigrating' | 'BadEvent';
}
- /** @name PalletMaintenanceError (567) */
+ /** @name PalletMaintenanceError (568) */
type PalletMaintenanceError = Null;
- /** @name PalletTestUtilsError (568) */
+ /** @name PalletTestUtilsError (569) */
interface PalletTestUtilsError extends Enum {
readonly isTestPalletDisabled: boolean;
readonly isTriggerRollback: boolean;
readonly type: 'TestPalletDisabled' | 'TriggerRollback';
}
- /** @name SpRuntimeMultiSignature (570) */
+ /** @name SpRuntimeMultiSignature (571) */
interface SpRuntimeMultiSignature extends Enum {
readonly isEd25519: boolean;
readonly asEd25519: SpCoreEd25519Signature;
@@ -4311,43 +4313,43 @@
readonly type: 'Ed25519' | 'Sr25519' | 'Ecdsa';
}
- /** @name SpCoreEd25519Signature (571) */
+ /** @name SpCoreEd25519Signature (572) */
interface SpCoreEd25519Signature extends U8aFixed {}
- /** @name SpCoreSr25519Signature (573) */
+ /** @name SpCoreSr25519Signature (574) */
interface SpCoreSr25519Signature extends U8aFixed {}
- /** @name SpCoreEcdsaSignature (574) */
+ /** @name SpCoreEcdsaSignature (575) */
interface SpCoreEcdsaSignature extends U8aFixed {}
- /** @name FrameSystemExtensionsCheckSpecVersion (577) */
+ /** @name FrameSystemExtensionsCheckSpecVersion (578) */
type FrameSystemExtensionsCheckSpecVersion = Null;
- /** @name FrameSystemExtensionsCheckTxVersion (578) */
+ /** @name FrameSystemExtensionsCheckTxVersion (579) */
type FrameSystemExtensionsCheckTxVersion = Null;
- /** @name FrameSystemExtensionsCheckGenesis (579) */
+ /** @name FrameSystemExtensionsCheckGenesis (580) */
type FrameSystemExtensionsCheckGenesis = Null;
- /** @name FrameSystemExtensionsCheckNonce (582) */
+ /** @name FrameSystemExtensionsCheckNonce (583) */
interface FrameSystemExtensionsCheckNonce extends Compact<u32> {}
- /** @name FrameSystemExtensionsCheckWeight (583) */
+ /** @name FrameSystemExtensionsCheckWeight (584) */
type FrameSystemExtensionsCheckWeight = Null;
- /** @name OpalRuntimeRuntimeCommonMaintenanceCheckMaintenance (584) */
+ /** @name OpalRuntimeRuntimeCommonMaintenanceCheckMaintenance (585) */
type OpalRuntimeRuntimeCommonMaintenanceCheckMaintenance = Null;
- /** @name OpalRuntimeRuntimeCommonIdentityDisableIdentityCalls (585) */
+ /** @name OpalRuntimeRuntimeCommonIdentityDisableIdentityCalls (586) */
type OpalRuntimeRuntimeCommonIdentityDisableIdentityCalls = Null;
- /** @name PalletTemplateTransactionPaymentChargeTransactionPayment (586) */
+ /** @name PalletTemplateTransactionPaymentChargeTransactionPayment (587) */
interface PalletTemplateTransactionPaymentChargeTransactionPayment extends Compact<u128> {}
- /** @name OpalRuntimeRuntime (587) */
+ /** @name OpalRuntimeRuntime (588) */
type OpalRuntimeRuntime = Null;
- /** @name PalletEthereumFakeTransactionFinalizer (588) */
+ /** @name PalletEthereumFakeTransactionFinalizer (589) */
type PalletEthereumFakeTransactionFinalizer = Null;
} // declare module
tests/src/sub/appPromotion/appPromotion.test.tsdiffbeforeafterboth--- a/tests/src/sub/appPromotion/appPromotion.test.ts
+++ b/tests/src/sub/appPromotion/appPromotion.test.ts
@@ -51,6 +51,7 @@
donor = await privateKey({url: import.meta.url});
palletAddress = helper.arrange.calculatePalletAddress('appstake');
palletAdmin = await privateKey('//PromotionAdmin');
+
nominal = helper.balance.getOneTokenNominal();
const accountBalances = new Array(200).fill(1000n);
@@ -96,7 +97,6 @@
expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
// it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?
expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased
-
await helper.staking.stake(staker, 200n * nominal);
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);
@@ -497,13 +497,13 @@
expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
// Can set sponsoring for collection with unconfirmed sponsor
- const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
+ const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: {Substrate: oldSponsor.address}});
expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});
await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;
expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
// Can set sponsoring for collection with confirmed sponsor
- const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
+ const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: {Substrate: oldSponsor.address}});
await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);
await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;
expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
@@ -584,7 +584,7 @@
itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {
const api = helper.getApi();
const [collectionOwner] = await getAccounts(1);
- const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});
+ const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: {Substrate: collectionOwner.address}});
await collection.confirmSponsorship(collectionOwner);
await expect(helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -142,6 +142,21 @@
}
}
+export interface ICollectionFlags {
+ foreign: boolean,
+ erc721metadata: boolean,
+}
+
+export enum CollectionFlag {
+ None = 0,
+ /// External collections can't be managed using `unique` api
+ External = 1,
+ /// Supports ERC721Metadata
+ Erc721metadata = 64,
+ /// Tokens in foreign collections can be transferred, but not burnt
+ Foreign = 128,
+}
+
export interface ICollectionCreationOptions {
name?: string | number[];
description?: string | number[];
@@ -155,7 +170,9 @@
properties?: IProperty[];
tokenPropertyPermissions?: ITokenPropertyPermission[];
limits?: ICollectionLimits;
- pendingSponsor?: TSubstrateAccount;
+ pendingSponsor?: ICrossAccountId;
+ adminList?: ICrossAccountId[];
+ flags?: number[] | CollectionFlag[] ,
}
export interface IChainProperties {
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {SignerOptions} from '@polkadot/api/types/submittable';10import '../../interfaces/augment-api';11import {AugmentedSubmittables} from '@polkadot/api-base/types/submittable';12import {ApiInterfaceEvents} from '@polkadot/api/types';13import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';14import {IKeyringPair} from '@polkadot/types/types';15import {hexToU8a} from '@polkadot/util/hex';16import {u8aConcat} from '@polkadot/util/u8a';17import {18 IApiListeners,19 IBlock,20 IEvent,21 IChainProperties,22 ICollectionCreationOptions,23 ICollectionLimits,24 ICollectionPermissions,25 ICrossAccountId,26 ICrossAccountIdLower,27 ILogger,28 INestingPermissions,29 IProperty,30 IStakingInfo,31 ISchedulerOptions,32 ISubstrateBalance,33 IToken,34 ITokenPropertyPermission,35 ITransactionResult,36 IUniqueHelperLog,37 TApiAllowedListeners,38 TEthereumAccount,39 TSigner,40 TSubstrateAccount,41 TNetworks,42 IForeignAssetMetadata,43 AcalaAssetMetadata,44 MoonbeamAssetInfo,45 DemocracyStandardAccountVote,46 IEthCrossAccountId,47} from './types';48import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';49import type {Vec} from '@polkadot/types-codec';50import {FrameSystemEventRecord, PalletBalancesIdAmount} from '@polkadot/types/lookup';5152export class CrossAccountId {53 Substrate!: TSubstrateAccount;54 Ethereum!: TEthereumAccount;5556 constructor(account: ICrossAccountId) {57 if('Substrate' in account) this.Substrate = account.Substrate;58 else this.Ethereum = account.Ethereum;59 }6061 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {62 switch (domain) {63 case 'Substrate': return new CrossAccountId({Substrate: account.address});64 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();65 }66 }6768 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {69 if('substrate' in address) return new CrossAccountId({Substrate: address.substrate});70 else return new CrossAccountId({Ethereum: address.ethereum});71 }7273 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {74 return encodeAddress(decodeAddress(address), ss58Format);75 }7677 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {78 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});79 }8081 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {82 if(this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);83 return this;84 }8586 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {87 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));88 }8990 toEthereum(): CrossAccountId {91 if(this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});92 return this;93 }9495 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {96 return evmToAddress(address, ss58Format);97 }9899 toSubstrate(ss58Format?: number): CrossAccountId {100 if(this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});101 return this;102 }103104 toLowerCase(): CrossAccountId {105 if(this.Substrate) this.Substrate = this.Substrate.toLowerCase();106 if(this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();107 return this;108 }109}110111const nesting = {112 toChecksumAddress(address: string): string {113 if(typeof address === 'undefined') return '';114115 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);116117 address = address.toLowerCase().replace(/^0x/i, '');118 const addressHash = keccakAsHex(address).replace(/^0x/i, '');119 const checksumAddress = ['0x'];120121 for(let i = 0; i < address.length; i++) {122 // If ith character is 8 to f then make it uppercase123 if(parseInt(addressHash[i], 16) > 7) {124 checksumAddress.push(address[i].toUpperCase());125 } else {126 checksumAddress.push(address[i]);127 }128 }129 return checksumAddress.join('');130 },131 tokenIdToAddress(collectionId: number, tokenId: number) {132 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);133 },134};135136class UniqueUtil {137 static transactionStatus = {138 NOT_READY: 'NotReady',139 FAIL: 'Fail',140 SUCCESS: 'Success',141 };142143 static chainLogType = {144 EXTRINSIC: 'extrinsic',145 RPC: 'rpc',146 };147148 static getTokenAccount(token: IToken): CrossAccountId {149 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});150 }151152 static getTokenAddress(token: IToken): string {153 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);154 }155156 static getDefaultLogger(): ILogger {157 return {158 log(msg: any, level = 'INFO') {159 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));160 },161 level: {162 ERROR: 'ERROR',163 WARNING: 'WARNING',164 INFO: 'INFO',165 },166 };167 }168169 static vec2str(arr: string[] | number[]) {170 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');171 }172173 static str2vec(string: string) {174 if(typeof string !== 'string') return string;175 return Array.from(string).map(x => x.charCodeAt(0));176 }177178 static fromSeed(seed: string, ss58Format = 42) {179 const keyring = new Keyring({type: 'sr25519', ss58Format});180 return keyring.addFromUri(seed);181 }182183 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {184 if(creationResult.status !== this.transactionStatus.SUCCESS) {185 throw Error('Unable to create collection!');186 }187188 let collectionId = null;189 creationResult.result.events.forEach(({event: {data, method, section}}) => {190 if((section === 'common') && (method === 'CollectionCreated')) {191 collectionId = parseInt(data[0].toString(), 10);192 }193 });194195 if(collectionId === null) {196 throw Error('No CollectionCreated event was found!');197 }198199 return collectionId;200 }201202 static extractTokensFromCreationResult(creationResult: ITransactionResult): {203 success: boolean,204 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],205 } {206 if(creationResult.status !== this.transactionStatus.SUCCESS) {207 throw Error('Unable to create tokens!');208 }209 let success = false;210 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];211 creationResult.result.events.forEach(({event: {data, method, section}}) => {212 if(method === 'ExtrinsicSuccess') {213 success = true;214 } else if((section === 'common') && (method === 'ItemCreated')) {215 tokens.push({216 collectionId: parseInt(data[0].toString(), 10),217 tokenId: parseInt(data[1].toString(), 10),218 owner: data[2].toHuman(),219 amount: data[3].toBigInt(),220 });221 }222 });223 return {success, tokens};224 }225226 static extractTokensFromBurnResult(burnResult: ITransactionResult): {227 success: boolean,228 tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],229 } {230 if(burnResult.status !== this.transactionStatus.SUCCESS) {231 throw Error('Unable to burn tokens!');232 }233 let success = false;234 const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];235 burnResult.result.events.forEach(({event: {data, method, section}}) => {236 if(method === 'ExtrinsicSuccess') {237 success = true;238 } else if((section === 'common') && (method === 'ItemDestroyed')) {239 tokens.push({240 collectionId: parseInt(data[0].toString(), 10),241 tokenId: parseInt(data[1].toString(), 10),242 owner: data[2].toHuman(),243 amount: data[3].toBigInt(),244 });245 }246 });247 return {success, tokens};248 }249250 static findCollectionInEvents(events: { event: IEvent }[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {251 let eventId = null;252 events.forEach(({event: {data, method, section}}) => {253 if((section === expectedSection) && (method === expectedMethod)) {254 eventId = parseInt(data[0].toString(), 10);255 }256 });257258 if(eventId === null) {259 throw Error(`No ${expectedMethod} event was found!`);260 }261 return eventId === collectionId;262 }263264 static isTokenTransferSuccess(events: { event: IEvent }[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {265 const normalizeAddress = (address: string | ICrossAccountId) => {266 if(typeof address === 'string') return address;267 const obj = {} as any;268 Object.keys(address).forEach(k => {269 obj[k.toLocaleLowerCase()] = (address as any)[k];270 });271 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);272 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();273 return address;274 };275 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;276 events.forEach(({event: {data, method, section}}) => {277 if((section === 'common') && (method === 'Transfer')) {278 const hData = (data as any).toJSON();279 transfer = {280 collectionId: hData[0],281 tokenId: hData[1],282 from: normalizeAddress(hData[2]),283 to: normalizeAddress(hData[3]),284 amount: BigInt(hData[4]),285 };286 }287 });288 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;289 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);290 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);291 isSuccess = isSuccess && amount === transfer.amount;292 return isSuccess;293 }294295 static bigIntToDecimals(number: bigint, decimals = 18) {296 const numberStr = number.toString();297 const dotPos = numberStr.length - decimals;298299 if(dotPos <= 0) {300 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;301 } else {302 const intPart = numberStr.substring(0, dotPos);303 const fractPart = numberStr.substring(dotPos);304 return intPart + '.' + fractPart;305 }306 }307}308309class UniqueEventHelper {310 private static extractIndex(index: any): [number, number] | string {311 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];312 return index.toJSON();313 }314315 private static extractSub(data: any, subTypes: any): { [key: string]: any } {316 let obj: any = {};317 let index = 0;318319 if(data.entries) {320 for(const [key, value] of data.entries()) {321 obj[key] = this.extractData(value, subTypes[index]);322 index++;323 }324 } else obj = data.toJSON();325326 return obj;327 }328329 private static toHuman(data: any) {330 return data && data.toHuman ? data.toHuman() : `${data}`;331 }332333 private static extractData(data: any, type: any): any {334 if(!type) return this.toHuman(data);335 if(['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();336 if(['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();337 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);338 return this.toHuman(data);339 }340341 public static extractEvents(events: { event: any, phase: any }[]): IEvent[] {342 const parsedEvents: IEvent[] = [];343344 events.forEach((record) => {345 const {event, phase} = record;346 const types = event.typeDef;347348 const eventData: IEvent = {349 section: event.section.toString(),350 method: event.method.toString(),351 index: this.extractIndex(event.index),352 data: [],353 phase: phase.toJSON(),354 };355356 event.data.forEach((val: any, index: number) => {357 eventData.data.push(this.extractData(val, types[index]));358 });359360 parsedEvents.push(eventData);361 });362363 return parsedEvents;364 }365}366const InvalidTypeSymbol = Symbol('Invalid type');367// eslint-disable-next-line @typescript-eslint/no-unused-vars368export type Invalid<ErrorMessage> =369 | ((370 invalidType: typeof InvalidTypeSymbol,371 ..._: typeof InvalidTypeSymbol[]372 ) => typeof InvalidTypeSymbol)373 | null374 | undefined;375// Has slightly better error messages than Get376type Get2<T, P extends string, E> =377 P extends `${infer Key}.${infer Key2}` ? Key extends keyof T ? Key2 extends keyof T[Key] ? T[Key][Key2] : E : E : E;378type ForceFunction<T> = T extends (...args: any) => any ? T : (...args: any) => Invalid<'not a function'>;379380export class ChainHelperBase {381 helperBase: any;382383 transactionStatus = UniqueUtil.transactionStatus;384 chainLogType = UniqueUtil.chainLogType;385 util: typeof UniqueUtil;386 eventHelper: typeof UniqueEventHelper;387 logger: ILogger;388 api: ApiPromise | null;389 forcedNetwork: TNetworks | null;390 network: TNetworks | null;391 wsEndpoint: string | null;392 chainLog: IUniqueHelperLog[];393 children: ChainHelperBase[];394 address: AddressGroup;395 chain: ChainGroup;396397 constructor(logger?: ILogger, helperBase?: any) {398 this.helperBase = helperBase;399400 this.util = UniqueUtil;401 this.eventHelper = UniqueEventHelper;402 if(typeof logger == 'undefined') logger = this.util.getDefaultLogger();403 this.logger = logger;404 this.api = null;405 this.forcedNetwork = null;406 this.network = null;407 this.wsEndpoint = null;408 this.chainLog = [];409 this.children = [];410 this.address = new AddressGroup(this);411 this.chain = new ChainGroup(this);412 }413414 clone(helperCls: ChainHelperBaseConstructor, options: { [key: string]: any } = {}) {415 Object.setPrototypeOf(helperCls.prototype, this);416 const newHelper = new helperCls(this.logger, options);417418 newHelper.api = this.api;419 newHelper.network = this.network;420 newHelper.forceNetwork = this.forceNetwork;421422 this.children.push(newHelper);423424 return newHelper;425 }426427 getEndpoint(): string {428 if(this.wsEndpoint === null) throw Error('No connection was established');429 return this.wsEndpoint;430 }431432 getApi(): ApiPromise {433 if(this.api === null) throw Error('API not initialized');434 return this.api;435 }436437 async subscribeEvents(expectedEvents: { section: string, names: string[] }[]) {438 const collectedEvents: IEvent[] = [];439 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {440 const ievents = this.eventHelper.extractEvents(events);441 ievents.forEach((event) => {442 expectedEvents.forEach((e => {443 if(event.section === e.section && e.names.includes(event.method)) {444 collectedEvents.push(event);445 }446 }));447 });448 });449 return {unsubscribe: unsubscribe as any, collectedEvents};450 }451452 clearChainLog(): void {453 this.chainLog = [];454 }455456 forceNetwork(value: TNetworks): void {457 this.forcedNetwork = value;458 }459460 async connect(wsEndpoint: string, listeners?: IApiListeners) {461 if(this.api !== null) throw Error('Already connected');462 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);463 this.wsEndpoint = wsEndpoint;464 this.api = api;465 this.network = network;466 }467468 async disconnect() {469 for(const child of this.children) {470 child.clearApi();471 }472473 if(this.api === null) return;474 await this.api.disconnect();475 this.clearApi();476 }477478 clearApi() {479 this.api = null;480 this.network = null;481 }482483 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {484 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;485 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];486487 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;488489 if(['quartz', 'unique', 'sapphire'].indexOf(spec.specName) > -1) return spec.specName;490 return 'opal';491 }492493 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {494 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});495 await api.isReady;496497 const network = await this.detectNetwork(api);498499 await api.disconnect();500501 return network;502 }503504 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{505 api: ApiPromise;506 network: TNetworks;507 }> {508 if(typeof network === 'undefined' || network === null) network = 'opal';509 const supportedRPC = {510 opal: {511 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,512 },513 quartz: {514 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,515 },516 unique: {517 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,518 },519 rococo: {},520 westend: {},521 moonbeam: {},522 moonriver: {},523 acala: {},524 karura: {},525 westmint: {},526 };527 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);528 const rpc = supportedRPC[network];529530 // TODO: investigate how to replace rpc in runtime531 // api._rpcCore.addUserInterfaces(rpc);532533 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});534535 await api.isReadyOrError;536537 if(typeof listeners === 'undefined') listeners = {};538 for(const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {539 if(!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;540 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);541 }542543 return {api, network};544 }545546 getTransactionStatus(data: { events: { event: IEvent }[], status: any }) {547 const {events, status} = data;548 if(status.isReady) {549 return this.transactionStatus.NOT_READY;550 }551 if(status.isBroadcast) {552 return this.transactionStatus.NOT_READY;553 }554 if(status.isInBlock || status.isFinalized) {555 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');556 if(errors.length > 0) {557 return this.transactionStatus.FAIL;558 }559 if(events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {560 return this.transactionStatus.SUCCESS;561 }562 }563564 return this.transactionStatus.FAIL;565 }566567 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {568 const sign = (callback: any) => {569 if(options !== null) return transaction.signAndSend(sender, options, callback);570 return transaction.signAndSend(sender, callback);571 };572 // eslint-disable-next-line no-async-promise-executor573 return new Promise(async (resolve, reject) => {574 try {575 const unsub = await sign((result: any) => {576 const status = this.getTransactionStatus(result);577578 if(status === this.transactionStatus.SUCCESS) {579 this.logger.log(`${label} successful`);580 unsub();581 resolve({result, status, blockHash: result.status.asInBlock.toHuman()});582 } else if(status === this.transactionStatus.FAIL) {583 let moduleError = null;584585 if(result.hasOwnProperty('dispatchError')) {586 const dispatchError = result['dispatchError'];587588 if(dispatchError) {589 if(dispatchError.isModule) {590 const modErr = dispatchError.asModule;591 const errorMeta = dispatchError.registry.findMetaError(modErr);592593 moduleError = `${errorMeta.section}.${errorMeta.name}`;594 } else if(dispatchError.isToken) {595 moduleError = `Token: ${dispatchError.asToken}`;596 } else {597 // May be [object Object] in case of unhandled non-unit enum598 moduleError = `Misc: ${dispatchError.toHuman()}`;599 }600 } else {601 this.logger.log(result, this.logger.level.ERROR);602 }603 }604605 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);606 unsub();607 reject({status, moduleError, result});608 }609 });610 } catch (e) {611 this.logger.log(e, this.logger.level.ERROR);612 reject(e);613 }614 });615 }616617 async signTransactionWithoutSending(signer: TSigner, tx: any) {618 const api = this.getApi();619 const signingInfo = await api.derive.tx.signingInfo(signer.address);620621 tx.sign(signer, {622 blockHash: api.genesisHash,623 genesisHash: api.genesisHash,624 runtimeVersion: api.runtimeVersion,625 nonce: signingInfo.nonce,626 });627628 return tx.toHex();629 }630631 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {632 const api = this.getApi();633 const signingInfo = await api.derive.tx.signingInfo(signer.address);634635 // We need to sign the tx because636 // unsigned transactions does not have an inclusion fee637 tx.sign(signer, {638 blockHash: api.genesisHash,639 genesisHash: api.genesisHash,640 runtimeVersion: api.runtimeVersion,641 nonce: signingInfo.nonce,642 });643644 if(len === null) {645 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;646 } else {647 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;648 }649 }650651 constructApiCall(apiCall: string, params: any[]) {652 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);653 let call = this.getApi() as any;654 for(const part of apiCall.slice(4).split('.')) {655 call = call[part];656 if(!call) {657 const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';658 throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);659 }660 }661 return call(...params);662 }663664 encodeApiCall(apiCall: string, params: any[]) {665 return this.constructApiCall(apiCall, params).method.toHex();666 }667668 async executeExtrinsic<669 E extends string,670 V extends (671 ...args: any) => any = ForceFunction<672 Get2<673 AugmentedSubmittables<'promise'>,674 E, (...args: any) => Invalid<'not found'>675 >676 >677 >(678 sender: TSigner,679 extrinsic: `api.tx.${E}`,680 params: Parameters<V>,681 expectSuccess = true,682 options: Partial<SignerOptions> | null = null,/*, failureMessage='expected success'*/683 ): Promise<ITransactionResult> {684 if(this.api === null) throw Error('API not initialized');685686 const startTime = (new Date()).getTime();687 let result: ITransactionResult;688 let events: IEvent[] = [];689 try {690 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;691 events = this.eventHelper.extractEvents(result.result.events);692 const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');693 if(errorEvent)694 throw Error(errorEvent.method + ': ' + extrinsic);695 }696 catch (e) {697 if(!(e as object).hasOwnProperty('status')) throw e;698 result = e as ITransactionResult;699 }700701 const endTime = (new Date()).getTime();702703 const log = {704 executedAt: endTime,705 executionTime: endTime - startTime,706 type: this.chainLogType.EXTRINSIC,707 status: result.status,708 call: extrinsic,709 signer: this.getSignerAddress(sender),710 params,711 } as IUniqueHelperLog;712713 let errorMessage = '';714715 if(result.status !== this.transactionStatus.SUCCESS) {716 if(result.moduleError) {717 errorMessage = typeof result.moduleError === 'string'718 ? result.moduleError719 : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;720 log.moduleError = errorMessage;721 }722 else if(result.result.dispatchError) log.dispatchError = result.result.dispatchError;723 }724 if(events.length > 0) log.events = events;725726 this.chainLog.push(log);727728 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {729 if(result.moduleError) throw Error(`${errorMessage}`);730 else if(result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));731 }732 return result as any;733 }734735 async callRpc736 // TODO: make it strongly typed, or use api.query/api.rpc directly737 // <738 // K extends 'rpc' | 'query',739 // E extends string,740 // V extends (...args: any) => any = ForceFunction<741 // Get2<742 // K extends 'rpc' ? DecoratedRpc<'promise', RpcInterface> : QueryableStorage<'promise'>,743 // E, (...args: any) => Invalid<'not found'>744 // >745 // >,746 // P = Parameters<V>,747 // >748 (rpc: string, params?: any[]): Promise<any> {749750 if(typeof params === 'undefined') params = [] as any;751 if(this.api === null) throw Error('API not initialized');752 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);753754 const startTime = (new Date()).getTime();755 let result;756 let error = null;757 const log = {758 type: this.chainLogType.RPC,759 call: rpc,760 params,761 } as any as IUniqueHelperLog;762763 try {764 result = await this.constructApiCall(rpc, params as any);765 }766 catch (e) {767 error = e;768 }769770 const endTime = (new Date()).getTime();771772 log.executedAt = endTime;773 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';774 log.executionTime = endTime - startTime;775776 this.chainLog.push(log);777778 if(error !== null) throw error;779780 return result;781 }782783 getSignerAddress(signer: IKeyringPair | string): string {784 if(typeof signer === 'string') return signer;785 return signer.address;786 }787788 fetchAllPalletNames(): string[] {789 if(this.api === null) throw Error('API not initialized');790 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase()).sort();791 }792793 fetchMissingPalletNames(requiredPallets: readonly string[]): string[] {794 const palletNames = this.fetchAllPalletNames();795 return requiredPallets.filter(p => !palletNames.includes(p));796 }797}798799800class HelperGroup<T extends ChainHelperBase> {801 helper: T;802803 constructor(uniqueHelper: T) {804 this.helper = uniqueHelper;805 }806}807808809class CollectionGroup extends HelperGroup<UniqueHelper> {810 /**811 * Get number of blocks when sponsored transaction is available.812 *813 * @param collectionId ID of collection814 * @param tokenId ID of token815 * @param addressObj address for which the sponsorship is checked816 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});817 * @returns number of blocks or null if sponsorship hasn't been set818 */819 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {820 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();821 }822823 /**824 * Get the number of created collections.825 *826 * @returns number of created collections827 */828 async getTotalCount(): Promise<number> {829 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();830 }831832 /**833 * Get information about the collection with additional data,834 * including the number of tokens it contains, its administrators,835 * the normalized address of the collection's owner, and decoded name and description.836 *837 * @param collectionId ID of collection838 * @example await getData(2)839 * @returns collection information object840 */841 async getData(collectionId: number): Promise<{842 id: number;843 name: string;844 description: string;845 tokensCount: number;846 admins: CrossAccountId[];847 normalizedOwner: TSubstrateAccount;848 raw: any849 } | null> {850 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);851 const humanCollection = collection.toHuman(), collectionData = {852 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],853 raw: humanCollection,854 } as any, jsonCollection = collection.toJSON();855 if(humanCollection === null) return null;856 collectionData.raw.limits = jsonCollection.limits;857 collectionData.raw.permissions = jsonCollection.permissions;858 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);859 for(const key of ['name', 'description']) {860 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);861 }862863 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))864 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)865 : 0;866 collectionData.admins = await this.getAdmins(collectionId);867868 return collectionData;869 }870871 /**872 * Get the addresses of the collection's administrators, optionally normalized.873 *874 * @param collectionId ID of collection875 * @param normalize whether to normalize the addresses to the default ss58 format876 * @example await getAdmins(1)877 * @returns array of administrators878 */879 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {880 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();881882 return normalize883 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())884 : admins;885 }886887 /**888 * Get the addresses added to the collection allow-list, optionally normalized.889 * @param collectionId ID of collection890 * @param normalize whether to normalize the addresses to the default ss58 format891 * @example await getAllowList(1)892 * @returns array of allow-listed addresses893 */894 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {895 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();896 return normalize897 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())898 : allowListed;899 }900901 /**902 * Get the effective limits of the collection instead of null for default values903 *904 * @param collectionId ID of collection905 * @example await getEffectiveLimits(2)906 * @returns object of collection limits907 */908 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {909 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();910 }911912 /**913 * Burns the collection if the signer has sufficient permissions and collection is empty.914 *915 * @param signer keyring of signer916 * @param collectionId ID of collection917 * @example await helper.collection.burn(aliceKeyring, 3);918 * @returns ```true``` if extrinsic success, otherwise ```false```919 */920 async burn(signer: TSigner, collectionId: number): Promise<boolean> {921 const result = await this.helper.executeExtrinsic(922 signer,923 'api.tx.unique.destroyCollection', [collectionId],924 true,925 );926927 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');928 }929930 /**931 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.932 *933 * @param signer keyring of signer934 * @param collectionId ID of collection935 * @param sponsorAddress Sponsor substrate address936 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")937 * @returns ```true``` if extrinsic success, otherwise ```false```938 */939 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {940 const result = await this.helper.executeExtrinsic(941 signer,942 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],943 true,944 );945946 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');947 }948949 /**950 * Confirms consent to sponsor the collection on behalf of the signer.951 *952 * @param signer keyring of signer953 * @param collectionId ID of collection954 * @example confirmSponsorship(aliceKeyring, 10)955 * @returns ```true``` if extrinsic success, otherwise ```false```956 */957 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {958 const result = await this.helper.executeExtrinsic(959 signer,960 'api.tx.unique.confirmSponsorship', [collectionId],961 true,962 );963964 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');965 }966967 /**968 * Removes the sponsor of a collection, regardless if it consented or not.969 *970 * @param signer keyring of signer971 * @param collectionId ID of collection972 * @example removeSponsor(aliceKeyring, 10)973 * @returns ```true``` if extrinsic success, otherwise ```false```974 */975 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {976 const result = await this.helper.executeExtrinsic(977 signer,978 'api.tx.unique.removeCollectionSponsor', [collectionId],979 true,980 );981982 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');983 }984985 /**986 * Sets the limits of the collection. At least one limit must be specified for a correct call.987 *988 * @param signer keyring of signer989 * @param collectionId ID of collection990 * @param limits collection limits object991 * @example992 * await setLimits(993 * aliceKeyring,994 * 10,995 * {996 * sponsorTransferTimeout: 0,997 * ownerCanDestroy: false998 * }999 * )1000 * @returns ```true``` if extrinsic success, otherwise ```false```1001 */1002 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {1003 const result = await this.helper.executeExtrinsic(1004 signer,1005 'api.tx.unique.setCollectionLimits', [collectionId, limits],1006 true,1007 );10081009 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');1010 }10111012 /**1013 * Changes the owner of the collection to the new Substrate address.1014 *1015 * @param signer keyring of signer1016 * @param collectionId ID of collection1017 * @param ownerAddress substrate address of new owner1018 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")1019 * @returns ```true``` if extrinsic success, otherwise ```false```1020 */1021 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {1022 const result = await this.helper.executeExtrinsic(1023 signer,1024 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],1025 true,1026 );10271028 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');1029 }10301031 /**1032 * Adds a collection administrator.1033 *1034 * @param signer keyring of signer1035 * @param collectionId ID of collection1036 * @param adminAddressObj Administrator address (substrate or ethereum)1037 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1038 * @returns ```true``` if extrinsic success, otherwise ```false```1039 */1040 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1041 const result = await this.helper.executeExtrinsic(1042 signer,1043 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],1044 true,1045 );10461047 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');1048 }10491050 /**1051 * Removes a collection administrator.1052 *1053 * @param signer keyring of signer1054 * @param collectionId ID of collection1055 * @param adminAddressObj Administrator address (substrate or ethereum)1056 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1057 * @returns ```true``` if extrinsic success, otherwise ```false```1058 */1059 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1060 const result = await this.helper.executeExtrinsic(1061 signer,1062 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1063 true,1064 );10651066 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1067 }10681069 /**1070 * Check if user is in allow list.1071 *1072 * @param collectionId ID of collection1073 * @param user Account to check1074 * @example await getAdmins(1)1075 * @returns is user in allow list1076 */1077 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1078 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1079 }10801081 /**1082 * Adds an address to allow list1083 * @param signer keyring of signer1084 * @param collectionId ID of collection1085 * @param addressObj address to add to the allow list1086 * @returns ```true``` if extrinsic success, otherwise ```false```1087 */1088 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1089 const result = await this.helper.executeExtrinsic(1090 signer,1091 'api.tx.unique.addToAllowList', [collectionId, addressObj],1092 true,1093 );10941095 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1096 }10971098 /**1099 * Removes an address from allow list1100 *1101 * @param signer keyring of signer1102 * @param collectionId ID of collection1103 * @param addressObj address to remove from the allow list1104 * @returns ```true``` if extrinsic success, otherwise ```false```1105 */1106 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1107 const result = await this.helper.executeExtrinsic(1108 signer,1109 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1110 true,1111 );11121113 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1114 }11151116 /**1117 * Sets onchain permissions for selected collection.1118 *1119 * @param signer keyring of signer1120 * @param collectionId ID of collection1121 * @param permissions collection permissions object1122 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1123 * @returns ```true``` if extrinsic success, otherwise ```false```1124 */1125 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1126 const result = await this.helper.executeExtrinsic(1127 signer,1128 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1129 true,1130 );11311132 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1133 }11341135 /**1136 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1137 *1138 * @param signer keyring of signer1139 * @param collectionId ID of collection1140 * @param permissions nesting permissions object1141 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1142 * @returns ```true``` if extrinsic success, otherwise ```false```1143 */1144 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1145 return await this.setPermissions(signer, collectionId, {nesting: permissions});1146 }11471148 /**1149 * Disables nesting for selected collection.1150 *1151 * @param signer keyring of signer1152 * @param collectionId ID of collection1153 * @example disableNesting(aliceKeyring, 10);1154 * @returns ```true``` if extrinsic success, otherwise ```false```1155 */1156 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1157 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1158 }11591160 /**1161 * Sets onchain properties to the collection.1162 *1163 * @param signer keyring of signer1164 * @param collectionId ID of collection1165 * @param properties array of property objects1166 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1167 * @returns ```true``` if extrinsic success, otherwise ```false```1168 */1169 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1170 const result = await this.helper.executeExtrinsic(1171 signer,1172 'api.tx.unique.setCollectionProperties', [collectionId, properties],1173 true,1174 );11751176 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1177 }11781179 /**1180 * Get collection properties.1181 *1182 * @param collectionId ID of collection1183 * @param propertyKeys optionally filter the returned properties to only these keys1184 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1185 * @returns array of key-value pairs1186 */1187 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1188 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1189 }11901191 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1192 const api = this.helper.getApi();1193 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11941195 return (props! as any).consumedSpace;1196 }11971198 async getCollectionOptions(collectionId: number) {1199 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1200 }12011202 /**1203 * Deletes onchain properties from the collection.1204 *1205 * @param signer keyring of signer1206 * @param collectionId ID of collection1207 * @param propertyKeys array of property keys to delete1208 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1209 * @returns ```true``` if extrinsic success, otherwise ```false```1210 */1211 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1212 const result = await this.helper.executeExtrinsic(1213 signer,1214 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1215 true,1216 );12171218 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1219 }12201221 /**1222 * Changes the owner of the token.1223 *1224 * @param signer keyring of signer1225 * @param collectionId ID of collection1226 * @param tokenId ID of token1227 * @param addressObj address of a new owner1228 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1229 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1230 * @returns true if the token success, otherwise false1231 */1232 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1233 const result = await this.helper.executeExtrinsic(1234 signer,1235 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1236 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1237 );12381239 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1240 }12411242 /**1243 *1244 * Change ownership of a token(s) on behalf of the owner.1245 *1246 * @param signer keyring of signer1247 * @param collectionId ID of collection1248 * @param tokenId ID of token1249 * @param fromAddressObj address on behalf of which the token will be sent1250 * @param toAddressObj new token owner1251 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1252 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1253 * @returns true if the token success, otherwise false1254 */1255 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1256 const result = await this.helper.executeExtrinsic(1257 signer,1258 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1259 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1260 );1261 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1262 }12631264 /**1265 *1266 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1267 *1268 * @param signer keyring of signer1269 * @param collectionId ID of collection1270 * @param tokenId ID of token1271 * @param amount amount of tokens to be burned. For NFT must be set to 1n1272 * @example burnToken(aliceKeyring, 10, 5);1273 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1274 */1275 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {1276 const burnResult = await this.helper.executeExtrinsic(1277 signer,1278 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1279 true, // `Unable to burn token for ${label}`,1280 );1281 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1282 if(burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1283 return burnedTokens.success;1284 }12851286 /**1287 * Destroys a concrete instance of NFT on behalf of the owner1288 *1289 * @param signer keyring of signer1290 * @param collectionId ID of collection1291 * @param tokenId ID of token1292 * @param fromAddressObj address on behalf of which the token will be burnt1293 * @param amount amount of tokens to be burned. For NFT must be set to 1n1294 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1295 * @returns ```true``` if extrinsic success, otherwise ```false```1296 */1297 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1298 const burnResult = await this.helper.executeExtrinsic(1299 signer,1300 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1301 true, // `Unable to burn token from for ${label}`,1302 );1303 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1304 return burnedTokens.success && burnedTokens.tokens.length > 0;1305 }13061307 /**1308 * Set, change, or remove approved address to transfer the ownership of the NFT.1309 *1310 * @param signer keyring of signer1311 * @param collectionId ID of collection1312 * @param tokenId ID of token1313 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1314 * @param amount amount of token to be approved. For NFT must be set to 1n1315 * @returns ```true``` if extrinsic success, otherwise ```false```1316 */1317 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1318 const approveResult = await this.helper.executeExtrinsic(1319 signer,1320 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1321 true, // `Unable to approve token for ${label}`,1322 );13231324 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1325 }13261327 /**1328 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1329 *1330 * @param signer keyring of signer1331 * @param collectionId ID of collection1332 * @param tokenId ID of token1333 * @param fromAddressObj Signer's Ethereum address containing her tokens1334 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1335 * @param amount amount of token to be approved. For NFT must be set to 1n1336 * @returns ```true``` if extrinsic success, otherwise ```false```1337 */1338 async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {1339 const approveResult = await this.helper.executeExtrinsic(1340 signer,1341 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1342 true, // `Unable to approve token for ${label}`,1343 );13441345 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1346 }13471348 /**1349 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1350 *1351 * @param signer keyring of signer1352 * @param collectionId ID of collection1353 * @param tokenId ID of token1354 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1355 * @param amount amount of token to be approved. For NFT must be set to 1n1356 * @returns ```true``` if extrinsic success, otherwise ```false```1357 */1358 async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1359 const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1360 return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1361 }13621363 /**1364 * Get the amount of token pieces approved to transfer or burn. Normally 0.1365 *1366 * @param collectionId ID of collection1367 * @param tokenId ID of token1368 * @param toAccountObj address which is approved to use token pieces1369 * @param fromAccountObj address which may have allowed the use of its owned tokens1370 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1371 * @returns number of approved to transfer pieces1372 */1373 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1374 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1375 }13761377 /**1378 * Get the last created token ID in a collection1379 *1380 * @param collectionId ID of collection1381 * @example getLastTokenId(10);1382 * @returns id of the last created token1383 */1384 async getLastTokenId(collectionId: number): Promise<number> {1385 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1386 }13871388 /**1389 * Check if token exists1390 *1391 * @param collectionId ID of collection1392 * @param tokenId ID of token1393 * @example doesTokenExist(10, 20);1394 * @returns true if the token exists, otherwise false1395 */1396 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1397 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1398 }1399}14001401class NFTnRFT extends CollectionGroup {1402 /**1403 * Get tokens owned by account1404 *1405 * @param collectionId ID of collection1406 * @param addressObj tokens owner1407 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1408 * @returns array of token ids owned by account1409 */1410 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1411 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1412 }14131414 /**1415 * Get token data1416 *1417 * @param collectionId ID of collection1418 * @param tokenId ID of token1419 * @param propertyKeys optionally filter the token properties to only these keys1420 * @param blockHashAt optionally query the data at some block with this hash1421 * @example getToken(10, 5);1422 * @returns human readable token data1423 */1424 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1425 properties: IProperty[];1426 owner: CrossAccountId;1427 normalizedOwner: CrossAccountId;1428 } | null> {1429 let tokenData;1430 if(typeof blockHashAt === 'undefined') {1431 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1432 }1433 else {1434 if(propertyKeys.length == 0) {1435 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1436 if(!collection) return null;1437 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1438 }1439 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1440 }1441 tokenData = tokenData.toHuman();1442 if(tokenData === null || tokenData.owner === null) return null;1443 const owner = {} as any;1444 for(const key of Object.keys(tokenData.owner)) {1445 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1446 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1447 : tokenData.owner[key];1448 }1449 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1450 return tokenData;1451 }14521453 /**1454 * Get token's owner1455 * @param collectionId ID of collection1456 * @param tokenId ID of token1457 * @param blockHashAt optionally query the data at the block with this hash1458 * @example getTokenOwner(10, 5);1459 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1460 */1461 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1462 let owner;1463 if(typeof blockHashAt === 'undefined') {1464 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1465 } else {1466 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1467 }1468 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1469 }14701471 /**1472 * Recursively find the address that owns the token1473 * @param collectionId ID of collection1474 * @param tokenId ID of token1475 * @param blockHashAt1476 * @example getTokenTopmostOwner(10, 5);1477 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1478 */1479 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1480 let owner;1481 if(typeof blockHashAt === 'undefined') {1482 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1483 } else {1484 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1485 }14861487 if(owner === null) return null;14881489 return owner.toHuman();1490 }14911492 /**1493 * Nest one token into another1494 * @param signer keyring of signer1495 * @param tokenObj token to be nested1496 * @param rootTokenObj token to be parent1497 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1498 * @returns ```true``` if extrinsic success, otherwise ```false```1499 */1500 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1501 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1502 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1503 if(!result) {1504 throw Error('Unable to nest token!');1505 }1506 return result;1507 }15081509 /**1510 * Remove token from nested state1511 * @param signer keyring of signer1512 * @param tokenObj token to unnest1513 * @param rootTokenObj parent of a token1514 * @param toAddressObj address of a new token owner1515 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1516 * @returns ```true``` if extrinsic success, otherwise ```false```1517 */1518 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1519 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1520 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1521 if(!result) {1522 throw Error('Unable to unnest token!');1523 }1524 return result;1525 }15261527 /**1528 * Set permissions to change token properties1529 *1530 * @param signer keyring of signer1531 * @param collectionId ID of collection1532 * @param permissions permissions to change a property by the collection admin or token owner1533 * @example setTokenPropertyPermissions(1534 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1535 * )1536 * @returns true if extrinsic success otherwise false1537 */1538 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1539 const result = await this.helper.executeExtrinsic(1540 signer,1541 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1542 true,1543 );15441545 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1546 }15471548 /**1549 * Get token property permissions.1550 *1551 * @param collectionId ID of collection1552 * @param propertyKeys optionally filter the returned property permissions to only these keys1553 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1554 * @returns array of key-permission pairs1555 */1556 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1557 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1558 }15591560 /**1561 * Set token properties1562 *1563 * @param signer keyring of signer1564 * @param collectionId ID of collection1565 * @param tokenId ID of token1566 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1567 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1568 * @returns ```true``` if extrinsic success, otherwise ```false```1569 */1570 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1571 const result = await this.helper.executeExtrinsic(1572 signer,1573 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1574 true,1575 );15761577 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1578 }15791580 /**1581 * Get properties, metadata assigned to a token.1582 *1583 * @param collectionId ID of collection1584 * @param tokenId ID of token1585 * @param propertyKeys optionally filter the returned properties to only these keys1586 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1587 * @returns array of key-value pairs1588 */1589 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1590 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1591 }15921593 /**1594 * Delete the provided properties of a token1595 * @param signer keyring of signer1596 * @param collectionId ID of collection1597 * @param tokenId ID of token1598 * @param propertyKeys property keys to be deleted1599 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1600 * @returns ```true``` if extrinsic success, otherwise ```false```1601 */1602 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1603 const result = await this.helper.executeExtrinsic(1604 signer,1605 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1606 true,1607 );16081609 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1610 }16111612 /**1613 * Mint new collection1614 *1615 * @param signer keyring of signer1616 * @param collectionOptions basic collection options and properties1617 * @param mode NFT or RFT type of a collection1618 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1619 * @returns object of the created collection1620 */1621 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1622 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1623 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1624 for(const key of ['name', 'description', 'tokenPrefix']) {1625 if(typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1626 }1627 const creationResult = await this.helper.executeExtrinsic(1628 signer,1629 'api.tx.unique.createCollectionEx', [collectionOptions],1630 true, // errorLabel,1631 );1632 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1633 }16341635 getCollectionObject(_collectionId: number): any {1636 return null;1637 }16381639 getTokenObject(_collectionId: number, _tokenId: number): any {1640 return null;1641 }16421643 /**1644 * Tells whether the given `owner` approves the `operator`.1645 * @param collectionId ID of collection1646 * @param owner owner address1647 * @param operator operator addrees1648 * @returns true if operator is enabled1649 */1650 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1651 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1652 }16531654 /** Sets or unsets the approval of a given operator.1655 * The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1656 * @param operator Operator1657 * @param approved Should operator status be granted or revoked?1658 * @returns ```true``` if extrinsic success, otherwise ```false```1659 */1660 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1661 const result = await this.helper.executeExtrinsic(1662 signer,1663 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1664 true,1665 );1666 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1667 }1668}166916701671class NFTGroup extends NFTnRFT {1672 /**1673 * Get collection object1674 * @param collectionId ID of collection1675 * @example getCollectionObject(2);1676 * @returns instance of UniqueNFTCollection1677 */1678 getCollectionObject(collectionId: number): UniqueNFTCollection {1679 return new UniqueNFTCollection(collectionId, this.helper);1680 }16811682 /**1683 * Get token object1684 * @param collectionId ID of collection1685 * @param tokenId ID of token1686 * @example getTokenObject(10, 5);1687 * @returns instance of UniqueNFTToken1688 */1689 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1690 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1691 }16921693 /**1694 * Is token approved to transfer1695 * @param collectionId ID of collection1696 * @param tokenId ID of token1697 * @param toAccountObj address to be approved1698 * @returns ```true``` if extrinsic success, otherwise ```false```1699 */1700 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1701 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1702 }17031704 /**1705 * Changes the owner of the token.1706 *1707 * @param signer keyring of signer1708 * @param collectionId ID of collection1709 * @param tokenId ID of token1710 * @param addressObj address of a new owner1711 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1712 * @returns ```true``` if extrinsic success, otherwise ```false```1713 */1714 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1715 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1716 }17171718 /**1719 *1720 * Change ownership of a NFT on behalf of the owner.1721 *1722 * @param signer keyring of signer1723 * @param collectionId ID of collection1724 * @param tokenId ID of token1725 * @param fromAddressObj address on behalf of which the token will be sent1726 * @param toAddressObj new token owner1727 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1728 * @returns ```true``` if extrinsic success, otherwise ```false```1729 */1730 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1731 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1732 }17331734 /**1735 * Get tokens nested in the provided token1736 * @param collectionId ID of collection1737 * @param tokenId ID of token1738 * @param blockHashAt optionally query the data at the block with this hash1739 * @example getTokenChildren(10, 5);1740 * @returns tokens whose depth of nesting is <= 51741 */1742 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1743 let children;1744 if(typeof blockHashAt === 'undefined') {1745 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1746 } else {1747 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1748 }17491750 return children.toJSON().map((x: any) => ({collectionId: x.collection, tokenId: x.token}));1751 }17521753 /**1754 * Mint new collection1755 * @param signer keyring of signer1756 * @param collectionOptions Collection options1757 * @example1758 * mintCollection(aliceKeyring, {1759 * name: 'New',1760 * description: 'New collection',1761 * tokenPrefix: 'NEW',1762 * })1763 * @returns object of the created collection1764 */1765 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1766 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1767 }17681769 /**1770 * Mint new token1771 * @param signer keyring of signer1772 * @param data token data1773 * @returns created token object1774 */1775 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1776 const creationResult = await this.helper.executeExtrinsic(1777 signer,1778 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1779 NFT: {1780 properties: data.properties,1781 },1782 }],1783 true,1784 );1785 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1786 if(createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1787 if(createdTokens.tokens.length < 1) throw Error('No tokens minted');1788 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1789 }17901791 /**1792 * Mint multiple NFT tokens1793 * @param signer keyring of signer1794 * @param collectionId ID of collection1795 * @param tokens array of tokens with owner and properties1796 * @example1797 * mintMultipleTokens(aliceKeyring, 10, [{1798 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1799 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1800 * },{1801 * owner: {Ethereum: "0x9F0583DbB855d..."},1802 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1803 * }]);1804 * @returns ```true``` if extrinsic success, otherwise ```false```1805 */1806 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1807 const creationResult = await this.helper.executeExtrinsic(1808 signer,1809 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1810 true,1811 );1812 const collection = this.getCollectionObject(collectionId);1813 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1814 }18151816 /**1817 * Mint multiple NFT tokens with one owner1818 * @param signer keyring of signer1819 * @param collectionId ID of collection1820 * @param owner tokens owner1821 * @param tokens array of tokens with owner and properties1822 * @example1823 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1824 * properties: [{1825 * key: "gender",1826 * value: "female",1827 * },{1828 * key: "age",1829 * value: "33",1830 * }],1831 * }]);1832 * @returns array of newly created tokens1833 */1834 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1835 const rawTokens = [];1836 for(const token of tokens) {1837 const raw = {NFT: {properties: token.properties}};1838 rawTokens.push(raw);1839 }1840 const creationResult = await this.helper.executeExtrinsic(1841 signer,1842 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1843 true,1844 );1845 const collection = this.getCollectionObject(collectionId);1846 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1847 }18481849 /**1850 * Set, change, or remove approved address to transfer the ownership of the NFT.1851 *1852 * @param signer keyring of signer1853 * @param collectionId ID of collection1854 * @param tokenId ID of token1855 * @param toAddressObj address to approve1856 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1857 * @returns ```true``` if extrinsic success, otherwise ```false```1858 */1859 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1860 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1861 }1862}186318641865class RFTGroup extends NFTnRFT {1866 /**1867 * Get collection object1868 * @param collectionId ID of collection1869 * @example getCollectionObject(2);1870 * @returns instance of UniqueRFTCollection1871 */1872 getCollectionObject(collectionId: number): UniqueRFTCollection {1873 return new UniqueRFTCollection(collectionId, this.helper);1874 }18751876 /**1877 * Get token object1878 * @param collectionId ID of collection1879 * @param tokenId ID of token1880 * @example getTokenObject(10, 5);1881 * @returns instance of UniqueNFTToken1882 */1883 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1884 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1885 }18861887 /**1888 * Get top 10 token owners with the largest number of pieces1889 * @param collectionId ID of collection1890 * @param tokenId ID of token1891 * @example getTokenTop10Owners(10, 5);1892 * @returns array of top 10 owners1893 */1894 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1895 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1896 }18971898 /**1899 * Get number of pieces owned by address1900 * @param collectionId ID of collection1901 * @param tokenId ID of token1902 * @param addressObj address token owner1903 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1904 * @returns number of pieces ownerd by address1905 */1906 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1907 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1908 }19091910 /**1911 * Transfer pieces of token to another address1912 * @param signer keyring of signer1913 * @param collectionId ID of collection1914 * @param tokenId ID of token1915 * @param addressObj address of a new owner1916 * @param amount number of pieces to be transfered1917 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1918 * @returns ```true``` if extrinsic success, otherwise ```false```1919 */1920 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1921 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1922 }19231924 /**1925 * Change ownership of some pieces of RFT on behalf of the owner.1926 * @param signer keyring of signer1927 * @param collectionId ID of collection1928 * @param tokenId ID of token1929 * @param fromAddressObj address on behalf of which the token will be sent1930 * @param toAddressObj new token owner1931 * @param amount number of pieces to be transfered1932 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1933 * @returns ```true``` if extrinsic success, otherwise ```false```1934 */1935 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1936 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1937 }19381939 /**1940 * Mint new collection1941 * @param signer keyring of signer1942 * @param collectionOptions Collection options1943 * @example1944 * mintCollection(aliceKeyring, {1945 * name: 'New',1946 * description: 'New collection',1947 * tokenPrefix: 'NEW',1948 * })1949 * @returns object of the created collection1950 */1951 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1952 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1953 }19541955 /**1956 * Mint new token1957 * @param signer keyring of signer1958 * @param data token data1959 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1960 * @returns created token object1961 */1962 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1963 const creationResult = await this.helper.executeExtrinsic(1964 signer,1965 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1966 ReFungible: {1967 pieces: data.pieces,1968 properties: data.properties,1969 },1970 }],1971 true,1972 );1973 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1974 if(createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1975 if(createdTokens.tokens.length < 1) throw Error('No tokens minted');1976 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1977 }19781979 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {1980 throw Error('Not implemented');1981 const creationResult = await this.helper.executeExtrinsic(1982 signer,1983 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1984 true, // `Unable to mint RFT tokens for ${label}`,1985 );1986 const collection = this.getCollectionObject(collectionId);1987 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1988 }19891990 /**1991 * Mint multiple RFT tokens with one owner1992 * @param signer keyring of signer1993 * @param collectionId ID of collection1994 * @param owner tokens owner1995 * @param tokens array of tokens with properties and pieces1996 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1997 * @returns array of newly created RFT tokens1998 */1999 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {2000 const rawTokens = [];2001 for(const token of tokens) {2002 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};2003 rawTokens.push(raw);2004 }2005 const creationResult = await this.helper.executeExtrinsic(2006 signer,2007 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2008 true,2009 );2010 const collection = this.getCollectionObject(collectionId);2011 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));2012 }20132014 /**2015 * Destroys a concrete instance of RFT.2016 * @param signer keyring of signer2017 * @param collectionId ID of collection2018 * @param tokenId ID of token2019 * @param amount number of pieces to be burnt2020 * @example burnToken(aliceKeyring, 10, 5);2021 * @returns ```true``` if the extrinsic is successful, otherwise ```false```2022 */2023 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {2024 return await super.burnToken(signer, collectionId, tokenId, amount);2025 }20262027 /**2028 * Destroys a concrete instance of RFT on behalf of the owner.2029 * @param signer keyring of signer2030 * @param collectionId ID of collection2031 * @param tokenId ID of token2032 * @param fromAddressObj address on behalf of which the token will be burnt2033 * @param amount number of pieces to be burnt2034 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)2035 * @returns ```true``` if extrinsic success, otherwise ```false```2036 */2037 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2038 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);2039 }20402041 /**2042 * Set, change, or remove approved address to transfer the ownership of the RFT.2043 *2044 * @param signer keyring of signer2045 * @param collectionId ID of collection2046 * @param tokenId ID of token2047 * @param toAddressObj address to approve2048 * @param amount number of pieces to be approved2049 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);2050 * @returns true if the token success, otherwise false2051 */2052 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {2053 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2054 }20552056 /**2057 * Get total number of pieces2058 * @param collectionId ID of collection2059 * @param tokenId ID of token2060 * @example getTokenTotalPieces(10, 5);2061 * @returns number of pieces2062 */2063 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2064 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2065 }20662067 /**2068 * Change number of token pieces. Signer must be the owner of all token pieces.2069 * @param signer keyring of signer2070 * @param collectionId ID of collection2071 * @param tokenId ID of token2072 * @param amount new number of pieces2073 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2074 * @returns true if the repartion was success, otherwise false2075 */2076 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2077 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2078 const repartitionResult = await this.helper.executeExtrinsic(2079 signer,2080 'api.tx.unique.repartition', [collectionId, tokenId, amount],2081 true,2082 );2083 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2084 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2085 }2086}208720882089class FTGroup extends CollectionGroup {2090 /**2091 * Get collection object2092 * @param collectionId ID of collection2093 * @example getCollectionObject(2);2094 * @returns instance of UniqueFTCollection2095 */2096 getCollectionObject(collectionId: number): UniqueFTCollection {2097 return new UniqueFTCollection(collectionId, this.helper);2098 }20992100 /**2101 * Mint new fungible collection2102 * @param signer keyring of signer2103 * @param collectionOptions Collection options2104 * @param decimalPoints number of token decimals2105 * @example2106 * mintCollection(aliceKeyring, {2107 * name: 'New',2108 * description: 'New collection',2109 * tokenPrefix: 'NEW',2110 * }, 18)2111 * @returns newly created fungible collection2112 */2113 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2114 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2115 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2116 collectionOptions.mode = {fungible: decimalPoints};2117 for(const key of ['name', 'description', 'tokenPrefix']) {2118 if(typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);2119 }2120 const creationResult = await this.helper.executeExtrinsic(2121 signer,2122 'api.tx.unique.createCollectionEx', [collectionOptions],2123 true,2124 );2125 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2126 }21272128 /**2129 * Mint tokens2130 * @param signer keyring of signer2131 * @param collectionId ID of collection2132 * @param owner address owner of new tokens2133 * @param amount amount of tokens to be meanted2134 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2135 * @returns ```true``` if extrinsic success, otherwise ```false```2136 */2137 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2138 const creationResult = await this.helper.executeExtrinsic(2139 signer,2140 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2141 Fungible: {2142 value: amount,2143 },2144 }],2145 true, // `Unable to mint fungible tokens for ${label}`,2146 );2147 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2148 }21492150 /**2151 * Mint multiple Fungible tokens with one owner2152 * @param signer keyring of signer2153 * @param collectionId ID of collection2154 * @param owner tokens owner2155 * @param tokens array of tokens with properties and pieces2156 * @returns ```true``` if extrinsic success, otherwise ```false```2157 */2158 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: { value: bigint }[], owner: ICrossAccountId): Promise<boolean> {2159 const rawTokens = [];2160 for(const token of tokens) {2161 const raw = {Fungible: {Value: token.value}};2162 rawTokens.push(raw);2163 }2164 const creationResult = await this.helper.executeExtrinsic(2165 signer,2166 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2167 true,2168 );2169 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2170 }21712172 /**2173 * Get the top 10 owners with the largest balance for the Fungible collection2174 * @param collectionId ID of collection2175 * @example getTop10Owners(10);2176 * @returns array of ```ICrossAccountId```2177 */2178 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2179 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2180 }21812182 /**2183 * Get account balance2184 * @param collectionId ID of collection2185 * @param addressObj address of owner2186 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2187 * @returns amount of fungible tokens owned by address2188 */2189 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2190 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2191 }21922193 /**2194 * Transfer tokens to address2195 * @param signer keyring of signer2196 * @param collectionId ID of collection2197 * @param toAddressObj address recipient2198 * @param amount amount of tokens to be sent2199 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2200 * @returns ```true``` if extrinsic success, otherwise ```false```2201 */2202 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2203 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2204 }22052206 /**2207 * Transfer some tokens on behalf of the owner.2208 * @param signer keyring of signer2209 * @param collectionId ID of collection2210 * @param fromAddressObj address on behalf of which tokens will be sent2211 * @param toAddressObj address where token to be sent2212 * @param amount number of tokens to be sent2213 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2214 * @returns ```true``` if extrinsic success, otherwise ```false```2215 */2216 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {2217 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2218 }22192220 /**2221 * Destroy some amount of tokens2222 * @param signer keyring of signer2223 * @param collectionId ID of collection2224 * @param amount amount of tokens to be destroyed2225 * @example burnTokens(aliceKeyring, 10, 1000n);2226 * @returns ```true``` if extrinsic success, otherwise ```false```2227 */2228 async burnTokens(signer: IKeyringPair, collectionId: number, amount = 1n): Promise<boolean> {2229 return await super.burnToken(signer, collectionId, 0, amount);2230 }22312232 /**2233 * Burn some tokens on behalf of the owner.2234 * @param signer keyring of signer2235 * @param collectionId ID of collection2236 * @param fromAddressObj address on behalf of which tokens will be burnt2237 * @param amount amount of tokens to be burnt2238 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2239 * @returns ```true``` if extrinsic success, otherwise ```false```2240 */2241 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2242 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2243 }22442245 /**2246 * Get total collection supply2247 * @param collectionId2248 * @returns2249 */2250 async getTotalPieces(collectionId: number): Promise<bigint> {2251 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2252 }22532254 /**2255 * Set, change, or remove approved address to transfer tokens.2256 *2257 * @param signer keyring of signer2258 * @param collectionId ID of collection2259 * @param toAddressObj address to be approved2260 * @param amount amount of tokens to be approved2261 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2262 * @returns ```true``` if extrinsic success, otherwise ```false```2263 */2264 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2265 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2266 }22672268 /**2269 * Get amount of fungible tokens approved to transfer2270 * @param collectionId ID of collection2271 * @param fromAddressObj owner of tokens2272 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2273 * @returns number of tokens approved for the transfer2274 */2275 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2276 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2277 }2278}227922802281class ChainGroup extends HelperGroup<ChainHelperBase> {2282 /**2283 * Get system properties of a chain2284 * @example getChainProperties();2285 * @returns ss58Format, token decimals, and token symbol2286 */2287 getChainProperties(): IChainProperties {2288 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2289 return {2290 ss58Format: properties.ss58Format.toJSON(),2291 tokenDecimals: properties.tokenDecimals.toJSON(),2292 tokenSymbol: properties.tokenSymbol.toJSON(),2293 };2294 }22952296 /**2297 * Get chain header2298 * @example getLatestBlockNumber();2299 * @returns the number of the last block2300 */2301 async getLatestBlockNumber(): Promise<number> {2302 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2303 }23042305 /**2306 * Get block hash by block number2307 * @param blockNumber number of block2308 * @example getBlockHashByNumber(12345);2309 * @returns hash of a block2310 */2311 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2312 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2313 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2314 return blockHash;2315 }23162317 // TODO add docs2318 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2319 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2320 if(!blockHash) return null;2321 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2322 }23232324 /**2325 * Get latest relay block2326 * @returns {number} relay block2327 */2328 async getRelayBlockNumber(): Promise<bigint> {2329 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2330 return BigInt(blockNumber);2331 }23322333 /**2334 * Get account nonce2335 * @param address substrate address2336 * @example getNonce("5GrwvaEF5zXb26Fz...");2337 * @returns number, account's nonce2338 */2339 async getNonce(address: TSubstrateAccount): Promise<number> {2340 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2341 }2342}23432344class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2345 /**2346 * Get substrate address balance2347 * @param address substrate address2348 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2349 * @returns amount of tokens on address2350 */2351 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2352 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2353 }23542355 /**2356 * Transfer tokens to substrate address2357 * @param signer keyring of signer2358 * @param address substrate address of a recipient2359 * @param amount amount of tokens to be transfered2360 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2361 * @returns ```true``` if extrinsic success, otherwise ```false```2362 */2363 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2364 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);23652366 let transfer = {from: null, to: null, amount: 0n} as any;2367 result.result.events.forEach(({event: {data, method, section}}) => {2368 if((section === 'balances') && (method === 'Transfer')) {2369 transfer = {2370 from: this.helper.address.normalizeSubstrate(data[0]),2371 to: this.helper.address.normalizeSubstrate(data[1]),2372 amount: BigInt(data[2]),2373 };2374 }2375 });2376 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2377 && this.helper.address.normalizeSubstrate(address) === transfer.to2378 && BigInt(amount) === transfer.amount;2379 return isSuccess;2380 }23812382 /**2383 * Get full substrate balance including free, frozen, and reserved2384 * @param address substrate address2385 * @returns2386 */2387 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2388 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2389 return {free: accountInfo.free.toBigInt(), frozen: accountInfo.frozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2390 }23912392 /**2393 * Get total issuance2394 * @returns2395 */2396 async getTotalIssuance(): Promise<bigint> {2397 const total = (await this.helper.callRpc('api.query.balances.totalIssuance', []));2398 return total.toBigInt();2399 }24002401 async getLocked(address: TSubstrateAccount): Promise<{ id: string, amount: bigint, reason: string }[]> {2402 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2403 return locks.map((lock: any) => ({id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}));2404 }2405 async getFrozen(address: TSubstrateAccount): Promise<{ id: string, amount: bigint }[]> {2406 const locks = (await this.helper.api!.query.balances.freezes(address)) as unknown as Array<any>;2407 return locks.map(lock => ({id: lock.id.toUtf8(), amount: lock.amount.toBigInt()}));2408 }2409}24102411class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2412 /**2413 * Get ethereum address balance2414 * @param address ethereum address2415 * @example getEthereum("0x9F0583DbB855d...")2416 * @returns amount of tokens on address2417 */2418 async getEthereum(address: TEthereumAccount): Promise<bigint> {2419 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2420 }24212422 /**2423 * Transfer tokens to address2424 * @param signer keyring of signer2425 * @param address Ethereum address of a recipient2426 * @param amount amount of tokens to be transfered2427 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2428 * @returns ```true``` if extrinsic success, otherwise ```false```2429 */2430 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2431 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);24322433 let transfer = {from: null, to: null, amount: 0n} as any;2434 result.result.events.forEach(({event: {data, method, section}}) => {2435 if((section === 'balances') && (method === 'Transfer')) {2436 transfer = {2437 from: data[0].toString(),2438 to: data[1].toString(),2439 amount: BigInt(data[2]),2440 };2441 }2442 });2443 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2444 && address === transfer.to2445 && BigInt(amount) === transfer.amount;2446 return isSuccess;2447 }2448}24492450class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2451 subBalanceGroup: SubstrateBalanceGroup<T>;2452 ethBalanceGroup: EthereumBalanceGroup<T>;24532454 constructor(helper: T) {2455 super(helper);2456 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2457 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2458 }24592460 getCollectionCreationPrice(): bigint {2461 return 2n * this.getOneTokenNominal();2462 }2463 /**2464 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2465 * @example getOneTokenNominal()2466 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2467 */2468 getOneTokenNominal(): bigint {2469 const chainProperties = this.helper.chain.getChainProperties();2470 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2471 }24722473 /**2474 * Get substrate address balance2475 * @param address substrate address2476 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2477 * @returns amount of tokens on address2478 */2479 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2480 return this.subBalanceGroup.getSubstrate(address);2481 }24822483 /**2484 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2485 * @param address substrate address2486 * @returns2487 */2488 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2489 return this.subBalanceGroup.getSubstrateFull(address);2490 }24912492 /**2493 * Get total issuance2494 * @returns2495 */2496 getTotalIssuance(): Promise<bigint> {2497 return this.subBalanceGroup.getTotalIssuance();2498 }24992500 /**2501 * Get locked balances2502 * @param address substrate address2503 * @returns locked balances with reason via api.query.balances.locks2504 * @deprecated all the methods should switch to getFrozen2505 */2506 getLocked(address: TSubstrateAccount) {2507 return this.subBalanceGroup.getLocked(address);2508 }25092510 /**2511 * Get frozen balances2512 * @param address substrate address2513 * @returns frozen balances with id via api.query.balances.freezes2514 */2515 getFrozen(address: TSubstrateAccount) {2516 return this.subBalanceGroup.getFrozen(address);2517 }25182519 /**2520 * Get ethereum address balance2521 * @param address ethereum address2522 * @example getEthereum("0x9F0583DbB855d...")2523 * @returns amount of tokens on address2524 */2525 getEthereum(address: TEthereumAccount): Promise<bigint> {2526 return this.ethBalanceGroup.getEthereum(address);2527 }25282529 async setBalanceSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint) {2530 await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceSetBalance', [address, amount], true);2531 }25322533 /**2534 * Transfer tokens to substrate address2535 * @param signer keyring of signer2536 * @param address substrate address of a recipient2537 * @param amount amount of tokens to be transfered2538 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2539 * @returns ```true``` if extrinsic success, otherwise ```false```2540 */2541 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2542 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2543 }25442545 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2546 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);25472548 let transfer = {from: null, to: null, amount: 0n} as any;2549 result.result.events.forEach(({event: {data, method, section}}) => {2550 if((section === 'balances') && (method === 'Transfer')) {2551 transfer = {2552 from: this.helper.address.normalizeSubstrate(data[0]),2553 to: this.helper.address.normalizeSubstrate(data[1]),2554 amount: BigInt(data[2]),2555 };2556 }2557 });2558 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2559 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2560 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2561 return isSuccess;2562 }25632564 /**2565 * Transfer tokens with the unlock period2566 * @param signer signers Keyring2567 * @param address Substrate address of recipient2568 * @param schedule Schedule params2569 * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002570 */2571 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: { start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }): Promise<void> {2572 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2573 const event = result.result.events2574 .find(e => e.event.section === 'vesting' &&2575 e.event.method === 'VestingScheduleAdded' &&2576 e.event.data[0].toHuman() === signer.address);2577 if(!event) throw Error('Cannot find transfer in events');2578 }25792580 /**2581 * Get schedule for recepient of vested transfer2582 * @param address Substrate address of recipient2583 * @returns2584 */2585 async getVestingSchedules(address: TSubstrateAccount): Promise<{ start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }[]> {2586 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2587 return schedule.map((schedule: any) => ({2588 start: BigInt(schedule.start),2589 period: BigInt(schedule.period),2590 periodCount: BigInt(schedule.periodCount),2591 perPeriod: BigInt(schedule.perPeriod),2592 }));2593 }25942595 /**2596 * Claim vested tokens2597 * @param signer signers Keyring2598 */2599 async claim(signer: TSigner) {2600 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2601 const event = result.result.events2602 .find(e => e.event.section === 'vesting' &&2603 e.event.method === 'Claimed' &&2604 e.event.data[0].toHuman() === signer.address);2605 if(!event) throw Error('Cannot find claim in events');2606 }2607}26082609class AddressGroup extends HelperGroup<ChainHelperBase> {2610 /**2611 * Normalizes the address to the specified ss58 format, by default ```42```.2612 * @param address substrate address2613 * @param ss58Format format for address conversion, by default ```42```2614 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2615 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2616 */2617 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2618 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2619 }26202621 /**2622 * Get address in the connected chain format2623 * @param address substrate address2624 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2625 * @returns address in chain format2626 */2627 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2628 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2629 }26302631 /**2632 * Get substrate mirror of an ethereum address2633 * @param ethAddress ethereum address2634 * @param toChainFormat false for normalized account2635 * @example ethToSubstrate('0x9F0583DbB855d...')2636 * @returns substrate mirror of a provided ethereum address2637 */2638 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat = false): TSubstrateAccount {2639 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2640 }26412642 /**2643 * Get ethereum mirror of a substrate address2644 * @param subAddress substrate account2645 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2646 * @returns ethereum mirror of a provided substrate address2647 */2648 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2649 return CrossAccountId.translateSubToEth(subAddress);2650 }26512652 /**2653 * Encode key to substrate address2654 * @param key key for encoding address2655 * @param ss58Format prefix for encoding to the address of the corresponding network2656 * @returns encoded substrate address2657 */2658 encodeSubstrateAddress(key: Uint8Array | string | bigint, ss58Format = 42): string {2659 const u8a: Uint8Array = typeof key === 'string'2660 ? hexToU8a(key)2661 : typeof key === 'bigint'2662 ? hexToU8a(key.toString(16))2663 : key;26642665 if(ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2666 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2667 }26682669 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2670 if(!allowedDecodedLengths.includes(u8a.length)) {2671 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2672 }26732674 const u8aPrefix = ss58Format < 642675 ? new Uint8Array([ss58Format])2676 : new Uint8Array([2677 ((ss58Format & 0xfc) >> 2) | 0x40,2678 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2679 ]);26802681 const input = u8aConcat(u8aPrefix, u8a);26822683 return base58Encode(u8aConcat(2684 input,2685 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2686 ));2687 }26882689 /**2690 * Restore substrate address from bigint representation2691 * @param number decimal representation of substrate address2692 * @returns substrate address2693 */2694 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2695 if(this.helper.api === null) {2696 throw 'Not connected';2697 }2698 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2699 if(res === undefined || res === null) {2700 throw 'Restore address error';2701 }2702 return res.toString();2703 }27042705 /**2706 * Convert etherium cross account id to substrate cross account id2707 * @param ethCrossAccount etherium cross account2708 * @returns substrate cross account id2709 */2710 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2711 if(ethCrossAccount.sub === '0') {2712 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2713 }27142715 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2716 return {Substrate: ss58};2717 }27182719 paraSiblingSovereignAccount(paraid: number) {2720 // We are getting a *sibling* parachain sovereign account,2721 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2722 const siblingPrefix = '0x7369626c';27232724 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2725 const suffix = '000000000000000000000000000000000000000000000000';27262727 return siblingPrefix + encodedParaId + suffix;2728 }2729}27302731class StakingGroup extends HelperGroup<UniqueHelper> {2732 /**2733 * Stake tokens for App Promotion2734 * @param signer keyring of signer2735 * @param amountToStake amount of tokens to stake2736 * @param label extra label for log2737 * @returns2738 */2739 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2740 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2741 const _stakeResult = await this.helper.executeExtrinsic(2742 signer, 'api.tx.appPromotion.stake',2743 [amountToStake], true,2744 );2745 // TODO extract info from stakeResult2746 return true;2747 }27482749 /**2750 * Unstake all staked tokens2751 * @param signer keyring of signer2752 * @param amountToUnstake amount of tokens to unstake2753 * @param label extra label for log2754 * @returns block hash where unstake happened2755 */2756 async unstakeAll(signer: TSigner, label?: string): Promise<string> {2757 if(typeof label === 'undefined') label = `${signer.address}`;2758 const unstakeResult = await this.helper.executeExtrinsic(2759 signer, 'api.tx.appPromotion.unstakeAll',2760 [], true,2761 );2762 return unstakeResult.blockHash;2763 }27642765 /**2766 * Unstake the part of a staked tokens2767 * @param signer keyring of signer2768 * @param amount amount of tokens to unstake2769 * @param label extra label for log2770 * @returns block hash where unstake happened2771 */2772 async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2773 if(typeof label === 'undefined') label = `${signer.address}`;2774 const unstakeResult = await this.helper.executeExtrinsic(2775 signer, 'api.tx.appPromotion.unstakePartial',2776 [amount], true,2777 );2778 return unstakeResult.blockHash;2779 }27802781 /**2782 * Get total number of active stakes2783 * @param address substrate address2784 * @returns {number}2785 */2786 async getStakesNumber(address: ICrossAccountId): Promise<number> {2787 if('Ethereum' in address) throw Error('only substrate address');2788 return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2789 }27902791 /**2792 * Get total staked amount for address2793 * @param address substrate or ethereum address2794 * @returns total staked amount2795 */2796 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2797 if(address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2798 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2799 }28002801 /**2802 * Get total staked per block2803 * @param address substrate or ethereum address2804 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2805 */2806 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2807 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2808 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => ({2809 block: block.toBigInt(),2810 amount: amount.toBigInt(),2811 }));2812 }28132814 /**2815 * Get total pending unstake amount for address2816 * @param address substrate or ethereum address2817 * @returns total pending unstake amount2818 */2819 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2820 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2821 }28222823 /**2824 * Get pending unstake amount per block for address2825 * @param address substrate or ethereum address2826 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2827 */2828 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2829 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2830 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => ({2831 block: block.toBigInt(),2832 amount: amount.toBigInt(),2833 }));2834 return result;2835 }2836}28372838class SchedulerGroup extends HelperGroup<UniqueHelper> {2839 constructor(helper: UniqueHelper) {2840 super(helper);2841 }28422843 cancelScheduled(signer: TSigner, scheduledId: string) {2844 return this.helper.executeExtrinsic(2845 signer,2846 'api.tx.scheduler.cancelNamed',2847 [scheduledId],2848 true,2849 );2850 }28512852 changePriority(signer: TSigner, scheduledId: string, priority: number) {2853 return this.helper.executeExtrinsic(2854 signer,2855 'api.tx.scheduler.changeNamedPriority',2856 [scheduledId, priority],2857 true,2858 );2859 }28602861 scheduleAt<T extends UniqueHelper>(2862 executionBlockNumber: number,2863 options: ISchedulerOptions = {},2864 ) {2865 return this.schedule<T>('schedule', executionBlockNumber, options);2866 }28672868 scheduleAfter<T extends UniqueHelper>(2869 blocksBeforeExecution: number,2870 options: ISchedulerOptions = {},2871 ) {2872 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2873 }28742875 schedule<T extends UniqueHelper>(2876 scheduleFn: 'schedule' | 'scheduleAfter',2877 blocksNum: number,2878 options: ISchedulerOptions = {},2879 ) {2880 // eslint-disable-next-line @typescript-eslint/naming-convention2881 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2882 return this.helper.clone(ScheduledHelperType, {2883 scheduleFn,2884 blocksNum,2885 options,2886 }) as T;2887 }2888}28892890class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2891 //todo:collator documentation2892 addInvulnerable(signer: TSigner, address: string) {2893 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2894 }28952896 removeInvulnerable(signer: TSigner, address: string) {2897 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2898 }28992900 async getInvulnerables(): Promise<string[]> {2901 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2902 }29032904 /** and also total max invulnerables */2905 maxCollators(): number {2906 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2907 }29082909 async getDesiredCollators(): Promise<number> {2910 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2911 }29122913 setLicenseBond(signer: TSigner, amount: bigint) {2914 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2915 }29162917 async getLicenseBond(): Promise<bigint> {2918 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2919 }29202921 obtainLicense(signer: TSigner) {2922 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2923 }29242925 releaseLicense(signer: TSigner) {2926 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2927 }29282929 forceReleaseLicense(signer: TSigner, released: string) {2930 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2931 }29322933 async hasLicense(address: string): Promise<bigint> {2934 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2935 }29362937 onboard(signer: TSigner) {2938 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2939 }29402941 offboard(signer: TSigner) {2942 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2943 }29442945 async getCandidates(): Promise<string[]> {2946 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2947 }2948}29492950class PreimageGroup extends HelperGroup<UniqueHelper> {2951 async getPreimageInfo(h256: string) {2952 return (await this.helper.callRpc('api.query.preimage.statusFor', [h256])).toJSON();2953 }29542955 /**2956 * Create a preimage with a hex or a byte array.2957 * @param signer keyring of the signer.2958 * @param bytes preimage encoded in hex or a byte array, e.g. an extrinsic call.2959 * @example await notePreimage(preimageMaker,2960 * helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd]).method.toHex()2961 * );2962 * @returns promise of extrinsic execution.2963 */2964 notePreimage(signer: TSigner, bytes: string | Uint8Array) {2965 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.notePreimage', [bytes]);2966 }29672968 /**2969 * Delete an existing preimage and return the deposit.2970 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2971 * @param h256 hash of the preimage.2972 * @returns promise of extrinsic execution.2973 */2974 unnotePreimage(signer: TSigner, h256: string) {2975 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unnotePreimage', [h256]);2976 }29772978 /**2979 * Request a preimage be uploaded to the chain without paying any fees or deposits.2980 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2981 * @param h256 hash of the preimage.2982 * @returns promise of extrinsic execution.2983 */2984 requestPreimage(signer: TSigner, h256: string) {2985 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.requestPreimage', [h256]);2986 }29872988 /**2989 * Clear a previously made request for a preimage.2990 * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2991 * @param h256 hash of the preimage.2992 * @returns promise of extrinsic execution.2993 */2994 unrequestPreimage(signer: TSigner, h256: string) {2995 return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unrequestPreimage', [h256]);2996 }2997}29982999class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {3000 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {3001 await this.helper.executeExtrinsic(3002 signer,3003 'api.tx.foreignAssets.registerForeignAsset',3004 [ownerAddress, location, metadata],3005 true,3006 );3007 }30083009 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {3010 await this.helper.executeExtrinsic(3011 signer,3012 'api.tx.foreignAssets.updateForeignAsset',3013 [foreignAssetId, location, metadata],3014 true,3015 );3016 }3017}30183019class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {3020 palletName: string;30213022 constructor(helper: T, palletName: string) {3023 super(helper);30243025 this.palletName = palletName;3026 }30273028 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {3029 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);3030 }30313032 async setSafeXcmVersion(signer: TSigner, version: number) {3033 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.forceDefaultXcmVersion`, [version], true);3034 }30353036 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {3037 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);3038 }30393040 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint, xcmVersion = 3) {3041 const destinationContent = {3042 parents: 0,3043 interior: {3044 X1: {3045 Parachain: destinationParaId,3046 },3047 },3048 };30493050 const beneficiaryContent = {3051 parents: 0,3052 interior: {3053 X1: {3054 AccountId32: {3055 network: 'Any',3056 id: targetAccount,3057 },3058 },3059 },3060 };30613062 const assetsContent = [3063 {3064 id: {3065 Concrete: {3066 parents: 0,3067 interior: 'Here',3068 },3069 },3070 fun: {3071 Fungible: amount,3072 },3073 },3074 ];30753076 let destination;3077 let beneficiary;3078 let assets;30793080 if(xcmVersion == 2) {3081 destination = {V1: destinationContent};3082 beneficiary = {V1: beneficiaryContent};3083 assets = {V1: assetsContent};30843085 } else if(xcmVersion == 3) {3086 destination = {V2: destinationContent};3087 beneficiary = {V2: beneficiaryContent};3088 assets = {V2: assetsContent};30893090 } else {3091 throw Error('Unknown XCM version: ' + xcmVersion);3092 }30933094 const feeAssetItem = 0;30953096 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);3097 }30983099 async send(signer: IKeyringPair, destination: any, message: any) {3100 await this.helper.executeExtrinsic(3101 signer,3102 `api.tx.${this.palletName}.send`,3103 [3104 destination,3105 message,3106 ],3107 true,3108 );3109 }3110}31113112class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3113 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {3114 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);3115 }31163117 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {3118 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);3119 }31203121 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {3122 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);3123 }3124}31253126class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3127 async accounts(address: string, currencyId: any) {3128 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;3129 return BigInt(free);3130 }3131}31323133class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {3134 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {3135 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);3136 }31373138 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {3139 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);3140 }31413142 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {3143 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);3144 }31453146 async account(assetId: string | number, address: string) {3147 const accountAsset = (3148 await this.helper.callRpc('api.query.assets.account', [assetId, address])3149 ).toJSON()! as any;31503151 if(accountAsset !== null) {3152 return BigInt(accountAsset['balance']);3153 } else {3154 return null;3155 }3156 }3157}31583159class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {3160 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {3161 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);3162 }3163}31643165class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3166 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3167 const apiPrefix = 'api.tx.assetManager.';31683169 const registerTx = this.helper.constructApiCall(3170 apiPrefix + 'registerForeignAsset',3171 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3172 );31733174 const setUnitsTx = this.helper.constructApiCall(3175 apiPrefix + 'setAssetUnitsPerSecond',3176 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3177 );31783179 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3180 const encodedProposal = batchCall?.method.toHex() || '';3181 return encodedProposal;3182 }31833184 async assetTypeId(location: any) {3185 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3186 }3187}31883189class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3190 notePreimagePallet: string;31913192 constructor(helper: MoonbeamHelper, options: { [key: string]: any } = {}) {3193 super(helper);3194 this.notePreimagePallet = options.notePreimagePallet;3195 }31963197 async notePreimage(signer: TSigner, encodedProposal: string) {3198 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3199 }32003201 externalProposeMajority(proposal: any) {3202 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3203 }32043205 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3206 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3207 }32083209 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3210 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3211 }3212}32133214class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3215 collective: string;32163217 constructor(helper: MoonbeamHelper, collective: string) {3218 super(helper);32193220 this.collective = collective;3221 }32223223 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3224 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3225 }32263227 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3228 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3229 }32303231 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3232 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3233 }32343235 async proposalCount() {3236 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3237 }3238}32393240export type ChainHelperBaseConstructor = new (...args: any[]) => ChainHelperBase;3241export type UniqueHelperConstructor = new (...args: any[]) => UniqueHelper;32423243export class UniqueHelper extends ChainHelperBase {3244 balance: BalanceGroup<UniqueHelper>;3245 collection: CollectionGroup;3246 nft: NFTGroup;3247 rft: RFTGroup;3248 ft: FTGroup;3249 staking: StakingGroup;3250 scheduler: SchedulerGroup;3251 collatorSelection: CollatorSelectionGroup;3252 preimage: PreimageGroup;3253 foreignAssets: ForeignAssetsGroup;3254 xcm: XcmGroup<UniqueHelper>;3255 xTokens: XTokensGroup<UniqueHelper>;3256 tokens: TokensGroup<UniqueHelper>;32573258 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3259 super(logger, options.helperBase ?? UniqueHelper);32603261 this.balance = new BalanceGroup(this);3262 this.collection = new CollectionGroup(this);3263 this.nft = new NFTGroup(this);3264 this.rft = new RFTGroup(this);3265 this.ft = new FTGroup(this);3266 this.staking = new StakingGroup(this);3267 this.scheduler = new SchedulerGroup(this);3268 this.collatorSelection = new CollatorSelectionGroup(this);3269 this.preimage = new PreimageGroup(this);3270 this.foreignAssets = new ForeignAssetsGroup(this);3271 this.xcm = new XcmGroup(this, 'polkadotXcm');3272 this.xTokens = new XTokensGroup(this);3273 this.tokens = new TokensGroup(this);3274 }32753276 getSudo<T extends UniqueHelper>() {3277 // eslint-disable-next-line @typescript-eslint/naming-convention3278 const SudoHelperType = SudoHelper(this.helperBase);3279 return this.clone(SudoHelperType) as T;3280 }3281}32823283export class XcmChainHelper extends ChainHelperBase {3284 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3285 const wsProvider = new WsProvider(wsEndpoint);3286 this.api = new ApiPromise({3287 provider: wsProvider,3288 });3289 await this.api.isReadyOrError;3290 this.network = await UniqueHelper.detectNetwork(this.api);3291 }3292}32933294export class RelayHelper extends XcmChainHelper {3295 balance: SubstrateBalanceGroup<RelayHelper>;3296 xcm: XcmGroup<RelayHelper>;32973298 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3299 super(logger, options.helperBase ?? RelayHelper);33003301 this.balance = new SubstrateBalanceGroup(this);3302 this.xcm = new XcmGroup(this, 'xcmPallet');3303 }3304}33053306export class WestmintHelper extends XcmChainHelper {3307 balance: SubstrateBalanceGroup<WestmintHelper>;3308 xcm: XcmGroup<WestmintHelper>;3309 assets: AssetsGroup<WestmintHelper>;3310 xTokens: XTokensGroup<WestmintHelper>;33113312 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3313 super(logger, options.helperBase ?? WestmintHelper);33143315 this.balance = new SubstrateBalanceGroup(this);3316 this.xcm = new XcmGroup(this, 'polkadotXcm');3317 this.assets = new AssetsGroup(this);3318 this.xTokens = new XTokensGroup(this);3319 }3320}33213322export class MoonbeamHelper extends XcmChainHelper {3323 balance: EthereumBalanceGroup<MoonbeamHelper>;3324 assetManager: MoonbeamAssetManagerGroup;3325 assets: AssetsGroup<MoonbeamHelper>;3326 xTokens: XTokensGroup<MoonbeamHelper>;3327 democracy: MoonbeamDemocracyGroup;3328 collective: {3329 council: MoonbeamCollectiveGroup,3330 techCommittee: MoonbeamCollectiveGroup,3331 };33323333 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3334 super(logger, options.helperBase ?? MoonbeamHelper);33353336 this.balance = new EthereumBalanceGroup(this);3337 this.assetManager = new MoonbeamAssetManagerGroup(this);3338 this.assets = new AssetsGroup(this);3339 this.xTokens = new XTokensGroup(this);3340 this.democracy = new MoonbeamDemocracyGroup(this, options);3341 this.collective = {3342 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3343 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3344 };3345 }3346}33473348export class AstarHelper extends XcmChainHelper {3349 balance: SubstrateBalanceGroup<AstarHelper>;3350 assets: AssetsGroup<AstarHelper>;3351 xcm: XcmGroup<AstarHelper>;33523353 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3354 super(logger, options.helperBase ?? AstarHelper);33553356 this.balance = new SubstrateBalanceGroup(this);3357 this.assets = new AssetsGroup(this);3358 this.xcm = new XcmGroup(this, 'polkadotXcm');3359 }33603361 getSudo<T extends UniqueHelper>() {3362 // eslint-disable-next-line @typescript-eslint/naming-convention3363 const SudoHelperType = SudoHelper(this.helperBase);3364 return this.clone(SudoHelperType) as T;3365 }3366}33673368export class AcalaHelper extends XcmChainHelper {3369 balance: SubstrateBalanceGroup<AcalaHelper>;3370 assetRegistry: AcalaAssetRegistryGroup;3371 xTokens: XTokensGroup<AcalaHelper>;3372 tokens: TokensGroup<AcalaHelper>;3373 xcm: XcmGroup<AcalaHelper>;33743375 constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3376 super(logger, options.helperBase ?? AcalaHelper);33773378 this.balance = new SubstrateBalanceGroup(this);3379 this.assetRegistry = new AcalaAssetRegistryGroup(this);3380 this.xTokens = new XTokensGroup(this);3381 this.tokens = new TokensGroup(this);3382 this.xcm = new XcmGroup(this, 'polkadotXcm');3383 }33843385 getSudo<T extends AcalaHelper>() {3386 // eslint-disable-next-line @typescript-eslint/naming-convention3387 const SudoHelperType = SudoHelper(this.helperBase);3388 return this.clone(SudoHelperType) as T;3389 }3390}33913392// eslint-disable-next-line @typescript-eslint/naming-convention3393function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3394 return class extends Base {3395 scheduleFn: 'schedule' | 'scheduleAfter';3396 blocksNum: number;3397 options: ISchedulerOptions;33983399 constructor(...args: any[]) {3400 const logger = args[0] as ILogger;3401 const options = args[1] as {3402 scheduleFn: 'schedule' | 'scheduleAfter',3403 blocksNum: number,3404 options: ISchedulerOptions3405 };34063407 super(logger);34083409 this.scheduleFn = options.scheduleFn;3410 this.blocksNum = options.blocksNum;3411 this.options = options.options;3412 }34133414 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3415 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);34163417 const mandatorySchedArgs = [3418 this.blocksNum,3419 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3420 this.options.priority ?? null,3421 scheduledTx,3422 ];34233424 let schedArgs;3425 let scheduleFn;34263427 if(this.options.scheduledId) {3428 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];34293430 if(this.scheduleFn == 'schedule') {3431 scheduleFn = 'scheduleNamed';3432 } else if(this.scheduleFn == 'scheduleAfter') {3433 scheduleFn = 'scheduleNamedAfter';3434 }3435 } else {3436 schedArgs = mandatorySchedArgs;3437 scheduleFn = this.scheduleFn;3438 }34393440 const extrinsic = 'api.tx.scheduler.' + scheduleFn;34413442 return super.executeExtrinsic(3443 sender,3444 extrinsic as any,3445 schedArgs,3446 expectSuccess,3447 );3448 }3449 };3450}34513452// eslint-disable-next-line @typescript-eslint/naming-convention3453function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3454 return class extends Base {3455 constructor(...args: any[]) {3456 super(...args);3457 }34583459 async executeExtrinsic(3460 sender: IKeyringPair,3461 extrinsic: string,3462 params: any[],3463 expectSuccess?: boolean,3464 options: Partial<SignerOptions> | null = null,3465 ): Promise<ITransactionResult> {3466 const call = this.constructApiCall(extrinsic, params);3467 const result = await super.executeExtrinsic(3468 sender,3469 'api.tx.sudo.sudo',3470 [call],3471 expectSuccess,3472 options,3473 );34743475 if(result.status === 'Fail') return result;34763477 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3478 if(data.isErr) {3479 if(data.asErr.isModule) {3480 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3481 const metaError = super.getApi()?.registry.findMetaError(error);3482 throw new Error(`${metaError.section}.${metaError.name}`);3483 } else if(data.asErr.isToken) {3484 throw new Error(`Token: ${data.asErr.asToken}`);3485 }3486 // May be [object Object] in case of unhandled non-unit enum3487 throw new Error(`Misc: ${data.asErr.toHuman()}`);3488 }3489 return result;3490 }3491 };3492}34933494export class UniqueBaseCollection {3495 helper: UniqueHelper;3496 collectionId: number;34973498 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3499 this.collectionId = collectionId;3500 this.helper = uniqueHelper;3501 }35023503 async getData() {3504 return await this.helper.collection.getData(this.collectionId);3505 }35063507 async getLastTokenId() {3508 return await this.helper.collection.getLastTokenId(this.collectionId);3509 }35103511 async doesTokenExist(tokenId: number) {3512 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3513 }35143515 async getAdmins() {3516 return await this.helper.collection.getAdmins(this.collectionId);3517 }35183519 async getAllowList() {3520 return await this.helper.collection.getAllowList(this.collectionId);3521 }35223523 async getEffectiveLimits() {3524 return await this.helper.collection.getEffectiveLimits(this.collectionId);3525 }35263527 async getProperties(propertyKeys?: string[] | null) {3528 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3529 }35303531 async getPropertiesConsumedSpace() {3532 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3533 }35343535 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3536 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3537 }35383539 async getOptions() {3540 return await this.helper.collection.getCollectionOptions(this.collectionId);3541 }35423543 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3544 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3545 }35463547 async confirmSponsorship(signer: TSigner) {3548 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3549 }35503551 async removeSponsor(signer: TSigner) {3552 return await this.helper.collection.removeSponsor(signer, this.collectionId);3553 }35543555 async setLimits(signer: TSigner, limits: ICollectionLimits) {3556 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3557 }35583559 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3560 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3561 }35623563 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3564 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3565 }35663567 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3568 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3569 }35703571 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3572 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3573 }35743575 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3576 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3577 }35783579 async setProperties(signer: TSigner, properties: IProperty[]) {3580 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3581 }35823583 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3584 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3585 }35863587 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3588 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3589 }35903591 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3592 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3593 }35943595 async disableNesting(signer: TSigner) {3596 return await this.helper.collection.disableNesting(signer, this.collectionId);3597 }35983599 async burn(signer: TSigner) {3600 return await this.helper.collection.burn(signer, this.collectionId);3601 }36023603 scheduleAt<T extends UniqueHelper>(3604 executionBlockNumber: number,3605 options: ISchedulerOptions = {},3606 ) {3607 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3608 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3609 }36103611 scheduleAfter<T extends UniqueHelper>(3612 blocksBeforeExecution: number,3613 options: ISchedulerOptions = {},3614 ) {3615 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3616 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3617 }36183619 getSudo<T extends UniqueHelper>() {3620 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3621 }3622}362336243625export class UniqueNFTCollection extends UniqueBaseCollection {3626 getTokenObject(tokenId: number) {3627 return new UniqueNFToken(tokenId, this);3628 }36293630 async getTokensByAddress(addressObj: ICrossAccountId) {3631 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3632 }36333634 async getToken(tokenId: number, blockHashAt?: string) {3635 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3636 }36373638 async getTokenOwner(tokenId: number, blockHashAt?: string) {3639 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3640 }36413642 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3643 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3644 }36453646 async getTokenChildren(tokenId: number, blockHashAt?: string) {3647 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3648 }36493650 async getPropertyPermissions(propertyKeys: string[] | null = null) {3651 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3652 }36533654 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3655 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3656 }36573658 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3659 const api = this.helper.getApi();3660 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();36613662 return (props! as any).consumedSpace;3663 }36643665 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3666 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3667 }36683669 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3670 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3671 }36723673 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3674 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3675 }36763677 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3678 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3679 }36803681 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3682 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3683 }36843685 async mintMultipleTokens(signer: TSigner, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]) {3686 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3687 }36883689 async burnToken(signer: TSigner, tokenId: number) {3690 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3691 }36923693 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3694 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3695 }36963697 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3698 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3699 }37003701 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3702 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3703 }37043705 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3706 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3707 }37083709 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3710 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3711 }37123713 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3714 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3715 }37163717 scheduleAt<T extends UniqueHelper>(3718 executionBlockNumber: number,3719 options: ISchedulerOptions = {},3720 ) {3721 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3722 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3723 }37243725 scheduleAfter<T extends UniqueHelper>(3726 blocksBeforeExecution: number,3727 options: ISchedulerOptions = {},3728 ) {3729 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3730 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3731 }37323733 getSudo<T extends UniqueHelper>() {3734 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3735 }3736}373737383739export class UniqueRFTCollection extends UniqueBaseCollection {3740 getTokenObject(tokenId: number) {3741 return new UniqueRFToken(tokenId, this);3742 }37433744 async getToken(tokenId: number, blockHashAt?: string) {3745 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3746 }37473748 async getTokenOwner(tokenId: number, blockHashAt?: string) {3749 return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3750 }37513752 async getTokensByAddress(addressObj: ICrossAccountId) {3753 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3754 }37553756 async getTop10TokenOwners(tokenId: number) {3757 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3758 }37593760 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3761 return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3762 }37633764 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3765 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3766 }37673768 async getTokenTotalPieces(tokenId: number) {3769 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3770 }37713772 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3773 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3774 }37753776 async getPropertyPermissions(propertyKeys: string[] | null = null) {3777 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3778 }37793780 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3781 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3782 }37833784 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3785 const api = this.helper.getApi();3786 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();37873788 return (props! as any).consumedSpace;3789 }37903791 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount = 1n) {3792 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3793 }37943795 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3796 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3797 }37983799 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {3800 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3801 }38023803 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3804 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3805 }38063807 async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3808 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3809 }38103811 async mintMultipleTokens(signer: TSigner, tokens: { pieces: bigint, owner: ICrossAccountId, properties?: IProperty[] }[]) {3812 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3813 }38143815 async burnToken(signer: TSigner, tokenId: number, amount = 1n) {3816 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3817 }38183819 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n) {3820 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3821 }38223823 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3824 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3825 }38263827 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3828 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3829 }38303831 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3832 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3833 }38343835 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3836 return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3837 }38383839 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3840 return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3841 }38423843 scheduleAt<T extends UniqueHelper>(3844 executionBlockNumber: number,3845 options: ISchedulerOptions = {},3846 ) {3847 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3848 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3849 }38503851 scheduleAfter<T extends UniqueHelper>(3852 blocksBeforeExecution: number,3853 options: ISchedulerOptions = {},3854 ) {3855 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3856 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3857 }38583859 getSudo<T extends UniqueHelper>() {3860 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3861 }3862}386338643865export class UniqueFTCollection extends UniqueBaseCollection {3866 async getBalance(addressObj: ICrossAccountId) {3867 return await this.helper.ft.getBalance(this.collectionId, addressObj);3868 }38693870 async getTotalPieces() {3871 return await this.helper.ft.getTotalPieces(this.collectionId);3872 }38733874 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3875 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3876 }38773878 async getTop10Owners() {3879 return await this.helper.ft.getTop10Owners(this.collectionId);3880 }38813882 async mint(signer: TSigner, amount = 1n, owner: ICrossAccountId = {Substrate: signer.address}) {3883 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3884 }38853886 async mintWithOneOwner(signer: TSigner, tokens: { value: bigint }[], owner: ICrossAccountId = {Substrate: signer.address}) {3887 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3888 }38893890 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3891 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3892 }38933894 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3895 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3896 }38973898 async burnTokens(signer: TSigner, amount = 1n) {3899 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3900 }39013902 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {3903 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3904 }39053906 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3907 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3908 }39093910 scheduleAt<T extends UniqueHelper>(3911 executionBlockNumber: number,3912 options: ISchedulerOptions = {},3913 ) {3914 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3915 return new UniqueFTCollection(this.collectionId, scheduledHelper);3916 }39173918 scheduleAfter<T extends UniqueHelper>(3919 blocksBeforeExecution: number,3920 options: ISchedulerOptions = {},3921 ) {3922 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3923 return new UniqueFTCollection(this.collectionId, scheduledHelper);3924 }39253926 getSudo<T extends UniqueHelper>() {3927 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3928 }3929}393039313932export class UniqueBaseToken {3933 collection: UniqueNFTCollection | UniqueRFTCollection;3934 collectionId: number;3935 tokenId: number;39363937 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3938 this.collection = collection;3939 this.collectionId = collection.collectionId;3940 this.tokenId = tokenId;3941 }39423943 async getNextSponsored(addressObj: ICrossAccountId) {3944 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3945 }39463947 async getProperties(propertyKeys?: string[] | null) {3948 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3949 }39503951 async getTokenPropertiesConsumedSpace() {3952 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3953 }39543955 async setProperties(signer: TSigner, properties: IProperty[]) {3956 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3957 }39583959 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3960 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3961 }39623963 async doesExist() {3964 return await this.collection.doesTokenExist(this.tokenId);3965 }39663967 nestingAccount() {3968 return this.collection.helper.util.getTokenAccount(this);3969 }39703971 scheduleAt<T extends UniqueHelper>(3972 executionBlockNumber: number,3973 options: ISchedulerOptions = {},3974 ) {3975 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3976 return new UniqueBaseToken(this.tokenId, scheduledCollection);3977 }39783979 scheduleAfter<T extends UniqueHelper>(3980 blocksBeforeExecution: number,3981 options: ISchedulerOptions = {},3982 ) {3983 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3984 return new UniqueBaseToken(this.tokenId, scheduledCollection);3985 }39863987 getSudo<T extends UniqueHelper>() {3988 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3989 }3990}399139923993export class UniqueNFToken extends UniqueBaseToken {3994 collection: UniqueNFTCollection;39953996 constructor(tokenId: number, collection: UniqueNFTCollection) {3997 super(tokenId, collection);3998 this.collection = collection;3999 }40004001 async getData(blockHashAt?: string) {4002 return await this.collection.getToken(this.tokenId, blockHashAt);4003 }40044005 async getOwner(blockHashAt?: string) {4006 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4007 }40084009 async getTopmostOwner(blockHashAt?: string) {4010 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4011 }40124013 async getChildren(blockHashAt?: string) {4014 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);4015 }40164017 async nest(signer: TSigner, toTokenObj: IToken) {4018 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4019 }40204021 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4022 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4023 }40244025 async transfer(signer: TSigner, addressObj: ICrossAccountId) {4026 return await this.collection.transferToken(signer, this.tokenId, addressObj);4027 }40284029 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4030 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);4031 }40324033 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {4034 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);4035 }40364037 async isApproved(toAddressObj: ICrossAccountId) {4038 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);4039 }40404041 async burn(signer: TSigner) {4042 return await this.collection.burnToken(signer, this.tokenId);4043 }40444045 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {4046 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);4047 }40484049 scheduleAt<T extends UniqueHelper>(4050 executionBlockNumber: number,4051 options: ISchedulerOptions = {},4052 ) {4053 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4054 return new UniqueNFToken(this.tokenId, scheduledCollection);4055 }40564057 scheduleAfter<T extends UniqueHelper>(4058 blocksBeforeExecution: number,4059 options: ISchedulerOptions = {},4060 ) {4061 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4062 return new UniqueNFToken(this.tokenId, scheduledCollection);4063 }40644065 getSudo<T extends UniqueHelper>() {4066 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());4067 }4068}40694070export class UniqueRFToken extends UniqueBaseToken {4071 collection: UniqueRFTCollection;40724073 constructor(tokenId: number, collection: UniqueRFTCollection) {4074 super(tokenId, collection);4075 this.collection = collection;4076 }40774078 async getData(blockHashAt?: string) {4079 return await this.collection.getToken(this.tokenId, blockHashAt);4080 }40814082 async getOwner(blockHashAt?: string) {4083 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4084 }40854086 async getTop10Owners() {4087 return await this.collection.getTop10TokenOwners(this.tokenId);4088 }40894090 async getTopmostOwner(blockHashAt?: string) {4091 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4092 }40934094 async nest(signer: TSigner, toTokenObj: IToken) {4095 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4096 }40974098 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4099 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4100 }41014102 async getBalance(addressObj: ICrossAccountId) {4103 return await this.collection.getTokenBalance(this.tokenId, addressObj);4104 }41054106 async getTotalPieces() {4107 return await this.collection.getTokenTotalPieces(this.tokenId);4108 }41094110 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {4111 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);4112 }41134114 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount = 1n) {4115 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);4116 }41174118 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {4119 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);4120 }41214122 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {4123 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);4124 }41254126 async repartition(signer: TSigner, amount: bigint) {4127 return await this.collection.repartitionToken(signer, this.tokenId, amount);4128 }41294130 async burn(signer: TSigner, amount = 1n) {4131 return await this.collection.burnToken(signer, this.tokenId, amount);4132 }41334134 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {4135 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);4136 }41374138 scheduleAt<T extends UniqueHelper>(4139 executionBlockNumber: number,4140 options: ISchedulerOptions = {},4141 ) {4142 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4143 return new UniqueRFToken(this.tokenId, scheduledCollection);4144 }41454146 scheduleAfter<T extends UniqueHelper>(4147 blocksBeforeExecution: number,4148 options: ISchedulerOptions = {},4149 ) {4150 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4151 return new UniqueRFToken(this.tokenId, scheduledCollection);4152 }41534154 getSudo<T extends UniqueHelper>() {4155 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());4156 }4157}