difftreelog
feat(collator-selection) interaction with configuration pallet
in: master
17 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -24,7 +24,6 @@
use serde_json::map::Map;
use up_common::types::opaque::*;
-use up_common::constants::{GENESIS_LICENSE_BOND, SESSION_LENGTH};
#[cfg(feature = "unique-runtime")]
pub use unique_runtime as default_runtime;
@@ -196,9 +195,6 @@
.cloned()
.map(|(acc, _)| acc)
.collect(),
- desired_collators: 10,
- license_bond: GENESIS_LICENSE_BOND,
- kick_threshold: SESSION_LENGTH,
},
session: SessionConfig {
keys: $initial_invulnerables
node/cli/src/service.rsdiffbeforeafterboth--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -921,7 +921,7 @@
.import_notification_stream()
.map(|_| EngineCommand::SealNewBlock {
create_empty: true,
- finalize: false,
+ finalize: false, // todo:collator finalize true
parent_hash: None,
sender: None,
}),
@@ -932,7 +932,7 @@
dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,
> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {
create_empty: true,
- finalize: false,
+ finalize: false, // todo:collator finalize true
parent_hash: None,
sender: None,
}));
pallets/collator-selection/Cargo.tomldiffbeforeafterboth--- a/pallets/collator-selection/Cargo.toml
+++ b/pallets/collator-selection/Cargo.toml
@@ -25,6 +25,7 @@
frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.33" }
pallet-authorship = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.33" }
pallet-session = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.33" }
+pallet-configuration = { default-features = false, path = "../configuration" }
frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.33" }
pallets/collator-selection/src/lib.rsdiffbeforeafterboth--- a/pallets/collator-selection/src/lib.rs
+++ b/pallets/collator-selection/src/lib.rs
@@ -105,16 +105,15 @@
},
BoundedVec, PalletId,
};
- use frame_system::{pallet_prelude::*, Config as SystemConfig};
+ use frame_system::pallet_prelude::*;
use pallet_session::SessionManager;
- use sp_runtime::{
- Perbill,
- traits::{One, Convert},
+ use sp_runtime::{Perbill, traits::Convert};
+ use pallet_configuration::{
+ CollatorSelectionDesiredCollatorsOverride as DesiredCollators,
+ CollatorSelectionLicenseBondOverride as LicenseBond,
+ CollatorSelectionKickThresholdOverride as KickThreshold, BalanceOf,
};
use sp_staking::SessionIndex;
-
- type BalanceOf<T> =
- <<T as Config>::Currency as Currency<<T as SystemConfig>::AccountId>>::Balance;
/// A convertor from collators id. Since this pallet does not have stash/controller, this is
/// just identity.
@@ -127,13 +126,10 @@
/// Configure the pallet by specifying the parameters and types on which it depends.
#[pallet::config]
- pub trait Config: frame_system::Config {
+ pub trait Config: frame_system::Config + pallet_configuration::Config {
/// Overarching event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
- /// The currency mechanism.
- type Currency: ReservableCurrency<Self::AccountId>;
-
/// Origin that can dictate updating parameters of this pallet.
type UpdateOrigin: EnsureOrigin<Self::RuntimeOrigin>;
@@ -176,8 +172,8 @@
/// The (community) collation license holders.
#[pallet::storage]
- #[pallet::getter(fn licenses)]
- pub type Licenses<T: Config> =
+ #[pallet::getter(fn license_deposit_of)]
+ pub type LicenseDepositOf<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, BalanceOf<T>, ValueQuery>;
/// The (community, limited) collation candidates.
@@ -185,40 +181,16 @@
#[pallet::getter(fn candidates)]
pub type Candidates<T: Config> =
StorageValue<_, BoundedVec<T::AccountId, T::MaxCollators>, ValueQuery>;
-
- /// Collator will be kicked if it does not produce a block within the threshold (does not apply to invulnerables).
- ///
- /// Should be a multiple of session or things will get inconsistent. todo:collator reword?
- #[pallet::storage]
- #[pallet::getter(fn kick_threshold)]
- pub type KickThreshold<T: Config> = StorageValue<_, T::BlockNumber, ValueQuery>;
/// Last block authored by collator.
#[pallet::storage]
#[pallet::getter(fn last_authored_block)]
pub type LastAuthoredBlock<T: Config> =
StorageMap<_, Twox64Concat, T::AccountId, T::BlockNumber, ValueQuery>;
-
- /// Desired number of candidates.
- ///
- /// This should ideally always be less than [`Config::MaxCollators`] for weights to be correct.
- #[pallet::storage]
- #[pallet::getter(fn desired_collators)]
- pub type DesiredCollators<T> = StorageValue<_, u32, ValueQuery>;
- /// Fixed amount to deposit to become a collator.
- ///
- /// When a collator calls `leave_intent` they immediately receive the deposit back.
- #[pallet::storage]
- #[pallet::getter(fn license_bond)]
- pub type LicenseBond<T> = StorageValue<_, BalanceOf<T>, ValueQuery>;
-
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub invulnerables: Vec<T::AccountId>,
- pub license_bond: BalanceOf<T>,
- pub kick_threshold: T::BlockNumber,
- pub desired_collators: u32,
}
#[cfg(feature = "std")]
@@ -226,9 +198,6 @@
fn default() -> Self {
Self {
invulnerables: Default::default(),
- license_bond: Default::default(),
- kick_threshold: T::BlockNumber::one(),
- desired_collators: Default::default(),
}
}
}
@@ -248,14 +217,7 @@
let bounded_invulnerables =
BoundedVec::<_, T::MaxCollators>::try_from(self.invulnerables.clone())
.expect("genesis invulnerables are more than T::MaxCollators");
- assert!(
- T::MaxCollators::get() >= self.desired_collators,
- "genesis desired_collators are more than T::MaxCollators",
- );
-
- <DesiredCollators<T>>::put(self.desired_collators);
- <LicenseBond<T>>::put(self.license_bond);
- <KickThreshold<T>>::put(self.kick_threshold);
+
<Invulnerables<T>>::put(bounded_invulnerables);
}
}
@@ -263,15 +225,6 @@
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
- NewDesiredCollators {
- desired_collators: u32,
- },
- NewLicenseBond {
- bond_amount: BalanceOf<T>,
- },
- NewKickThreshold {
- length_in_blocks: T::BlockNumber,
- },
InvulnerableAdded {
invulnerable: T::AccountId,
},
@@ -383,51 +336,6 @@
Ok(().into())
}
- /// Set the ideal number of collators. If lowering this number,
- /// then the number of running collators could be higher than this figure.
- /// Aside from that edge case, there should be no other way to have more collators than the desired number.
- #[pallet::weight(T::WeightInfo::set_desired_collators())]
- pub fn set_desired_collators(origin: OriginFor<T>, max: u32) -> DispatchResultWithPostInfo {
- T::UpdateOrigin::ensure_origin(origin)?;
- // we trust origin calls, this is just a for more accurate benchmarking
- if max > T::MaxCollators::get() {
- log::warn!("max > T::MaxCollators; you might need to run benchmarks again");
- }
- <DesiredCollators<T>>::put(max);
- Self::deposit_event(Event::NewDesiredCollators {
- desired_collators: max,
- });
- Ok(().into())
- }
-
- /// Set the candidacy bond amount.
- #[pallet::weight(T::WeightInfo::set_license_bond())]
- pub fn set_license_bond(
- origin: OriginFor<T>,
- bond: BalanceOf<T>,
- ) -> DispatchResultWithPostInfo {
- T::UpdateOrigin::ensure_origin(origin)?;
- <LicenseBond<T>>::put(bond);
- Self::deposit_event(Event::NewLicenseBond { bond_amount: bond });
- Ok(().into())
- }
-
- /// Set the length of the kick threshold.
- /// Note that if the length is not a multiple of the session period, it might get inconsistent.
- #[pallet::weight(T::WeightInfo::set_license_bond())] // todo:collator weight
- pub fn set_kick_threshold(
- origin: OriginFor<T>,
- kick_threshold: T::BlockNumber,
- ) -> DispatchResultWithPostInfo {
- T::UpdateOrigin::ensure_origin(origin)?;
- // todo:collator insert something to guarantee consistency?
- <KickThreshold<T>>::put(kick_threshold);
- Self::deposit_event(Event::NewKickThreshold {
- length_in_blocks: kick_threshold,
- });
- Ok(().into())
- }
-
/// Purchase a license on block collation for this account.
/// It does not make it a collator candidate, use `onboard` afterward. The account must
/// (a) already have registered session keys and (b) be able to reserve the `LicenseBond`.
@@ -438,7 +346,7 @@
// register_as_candidate
let who = ensure_signed(origin)?;
- if Licenses::<T>::contains_key(&who) {
+ if LicenseDepositOf::<T>::contains_key(&who) {
return Err(Error::<T>::AlreadyHoldingLicense.into());
}
@@ -449,10 +357,10 @@
Error::<T>::ValidatorNotRegistered
);
- let deposit = Self::license_bond();
+ let deposit = <LicenseBond<T>>::get();
T::Currency::reserve(&who, deposit)?;
- Licenses::<T>::insert(who.clone(), deposit);
+ LicenseDepositOf::<T>::insert(who.clone(), deposit);
Self::deposit_event(Event::LicenseObtained {
account_id: who,
@@ -471,12 +379,15 @@
let who = ensure_signed(origin)?;
// ensure the user obtained the license.
- ensure!(Licenses::<T>::contains_key(&who), Error::<T>::NoLicense);
+ ensure!(
+ LicenseDepositOf::<T>::contains_key(&who),
+ Error::<T>::NoLicense
+ );
// ensure we are below limit.
let length = <Candidates<T>>::decode_len().unwrap_or_default()
+ <Invulnerables<T>>::decode_len().unwrap_or_default();
ensure!(
- (length as u32) < Self::desired_collators(),
+ (length as u32) < <DesiredCollators<T>>::get(),
Error::<T>::TooManyCandidates
);
ensure!(
@@ -495,7 +406,7 @@
// First authored block is current block plus kick threshold to handle session delay
<LastAuthoredBlock<T>>::insert(
who.clone(),
- frame_system::Pallet::<T>::block_number() + Self::kick_threshold(),
+ frame_system::Pallet::<T>::block_number() + <KickThreshold<T>>::get(),
);
Ok(candidates.len())
}
@@ -594,7 +505,7 @@
/// Removes a candidate if they exist and sends them back their deposit, optionally slashed.
fn try_release_license(who: &T::AccountId, should_slash: bool) -> DispatchResult {
let mut deposit_returned = BalanceOf::<T>::default();
- Licenses::<T>::try_mutate_exists(who, |deposit| -> DispatchResult {
+ LicenseDepositOf::<T>::try_mutate_exists(who, |deposit| -> DispatchResult {
if let Some(deposit) = deposit.take() {
if should_slash {
let slashed = T::SlashRatio::get() * deposit;
@@ -640,7 +551,7 @@
candidates: BoundedVec<T::AccountId, T::MaxCollators>,
) -> BoundedVec<T::AccountId, T::MaxCollators> {
let now = frame_system::Pallet::<T>::block_number();
- let kick_threshold = Self::kick_threshold();
+ let kick_threshold = <KickThreshold<T>>::get();
candidates
.into_iter()
.filter_map(|c| {
pallets/collator-selection/src/mock.rsdiffbeforeafterboth--- a/pallets/collator-selection/src/mock.rs
+++ b/pallets/collator-selection/src/mock.rs
@@ -63,6 +63,7 @@
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
CollatorSelection: collator_selection::{Pallet, Call, Storage, Event<T>},
Authorship: pallet_authorship::{Pallet, Call, Storage, Inherent},
+ Configuration: pallet_configuration::{Pallet, Call, Storage, Event<T>},
}
);
@@ -200,13 +201,38 @@
type WeightInfo = ();
}
+parameter_types! {
+ pub const MaxCollators: u32 = 5;
+ pub const LicenseBond: u64 = 10;
+ pub const KickThreshold: u64 = 10;
+ // the following values do not matter and are meaningless, etc.
+ pub const DefaultWeightToFeeCoefficient: u32 = 100_000;
+ pub const DefaultMinGasPrice: u64 = 100_000;
+ pub const MaxXcmAllowedLocations: u32 = 16;
+ pub AppPromotionDailyRate: Perbill = Perbill::from_rational(5u32, 10_000);
+ pub const DayRelayBlocks: u32 = 1;
+}
+
+impl pallet_configuration::Config for Test {
+ type RuntimeEvent = RuntimeEvent;
+ type Currency = Balances;
+ type DefaultCollatorSelectionMaxCollators = MaxCollators;
+ type DefaultCollatorSelectionKickThreshold = KickThreshold;
+ type DefaultCollatorSelectionLicenseBond = LicenseBond;
+ // the following we don't care about
+ type DefaultWeightToFeeCoefficient = DefaultWeightToFeeCoefficient;
+ type DefaultMinGasPrice = DefaultMinGasPrice;
+ type MaxXcmAllowedLocations = MaxXcmAllowedLocations;
+ type AppPromotionDailyRate = AppPromotionDailyRate;
+ type DayRelayBlocks = DayRelayBlocks;
+}
+
ord_parameter_types! {
pub const RootAccount: u64 = 777;
}
parameter_types! {
pub const PotId: PalletId = PalletId(*b"PotStake");
- pub const MaxCollators: u32 = 20;
pub const MaxAuthorities: u32 = 100_000;
pub const SlashRatio: Perbill = Perbill::one();
}
@@ -224,7 +250,6 @@
impl Config for Test {
type RuntimeEvent = RuntimeEvent;
- type Currency = Balances;
type UpdateOrigin = EnsureSignedBy<RootAccount, u64>;
type PotId = PotId;
type MaxCollators = MaxCollators;
@@ -257,9 +282,6 @@
})
.collect::<Vec<_>>();
let collator_selection = collator_selection::GenesisConfig::<Test> {
- desired_collators: 5,
- license_bond: 10,
- kick_threshold: 10,
invulnerables,
};
let session = pallet_session::GenesisConfig::<Test> { keys };
pallets/collator-selection/src/tests.rsdiffbeforeafterboth--- a/pallets/collator-selection/src/tests.rs
+++ b/pallets/collator-selection/src/tests.rs
@@ -36,8 +36,14 @@
assert_noop, assert_ok,
traits::{Currency, GenesisBuild, OnInitialize},
};
+use frame_system::RawOrigin;
use pallet_balances::Error as BalancesError;
use sp_runtime::traits::BadOrigin;
+use pallet_configuration::{
+ CollatorSelectionDesiredCollatorsOverride as DesiredCollators,
+ CollatorSelectionKickThresholdOverride as KickThreshold,
+ CollatorSelectionLicenseBondOverride as LicenseBond,
+};
fn get_license_and_onboard(account_id: <Test as frame_system::Config>::AccountId) {
assert_ok!(CollatorSelection::get_license(RuntimeOrigin::signed(
@@ -51,8 +57,8 @@
#[test]
fn basic_setup_works() {
new_test_ext().execute_with(|| {
- assert_eq!(CollatorSelection::desired_collators(), 5);
- assert_eq!(CollatorSelection::license_bond(), 10);
+ assert_eq!(<DesiredCollators<Test>>::get(), 5);
+ assert_eq!(<LicenseBond<Test>>::get(), 10);
assert!(CollatorSelection::candidates().is_empty());
assert_eq!(CollatorSelection::invulnerables(), vec![1, 2]);
@@ -122,18 +128,21 @@
fn set_desired_collators_works() {
new_test_ext().execute_with(|| {
// given
- assert_eq!(CollatorSelection::desired_collators(), 5);
+ assert_eq!(<DesiredCollators<Test>>::get(), 5);
// can set
- assert_ok!(CollatorSelection::set_desired_collators(
- RuntimeOrigin::signed(RootAccount::get()),
- 7
+ assert_ok!(Configuration::set_collator_selection_desired_collators(
+ RawOrigin::Root.into(),
+ Some(7)
));
- assert_eq!(CollatorSelection::desired_collators(), 7);
+ assert_eq!(<DesiredCollators<Test>>::get(), 7);
// rejects bad origin
assert_noop!(
- CollatorSelection::set_desired_collators(RuntimeOrigin::signed(1), 8),
+ Configuration::set_collator_selection_desired_collators(
+ RuntimeOrigin::signed(1),
+ Some(8)
+ ),
BadOrigin
);
});
@@ -143,18 +152,18 @@
fn set_license_bond() {
new_test_ext().execute_with(|| {
// given
- assert_eq!(CollatorSelection::license_bond(), 10);
+ assert_eq!(<LicenseBond<Test>>::get(), 10);
// can set
- assert_ok!(CollatorSelection::set_license_bond(
- RuntimeOrigin::signed(RootAccount::get()),
- 7
+ assert_ok!(Configuration::set_collator_selection_license_bond(
+ RawOrigin::Root.into(),
+ Some(7)
));
- assert_eq!(CollatorSelection::license_bond(), 7);
+ assert_eq!(<LicenseBond<Test>>::get(), 7);
// rejects bad origin.
assert_noop!(
- CollatorSelection::set_license_bond(RuntimeOrigin::signed(1), 8),
+ Configuration::set_collator_selection_license_bond(RuntimeOrigin::signed(1), Some(8)),
BadOrigin
);
});
@@ -179,7 +188,7 @@
fn cannot_onboard_candidate_if_too_many() {
new_test_ext().execute_with(|| {
// reset desired candidates
- <crate::DesiredCollators<Test>>::put(0);
+ <pallet_configuration::CollatorSelectionDesiredCollatorsOverride<Test>>::put(0);
// can still get a license.
assert_ok!(CollatorSelection::get_license(RuntimeOrigin::signed(4)));
@@ -191,7 +200,7 @@
);
// reset desired candidates to invulnerables + 1
- <crate::DesiredCollators<Test>>::put(3);
+ <pallet_configuration::CollatorSelectionDesiredCollatorsOverride<Test>>::put(3);
assert_ok!(CollatorSelection::onboard(RuntimeOrigin::signed(4)));
// but no more.
@@ -236,7 +245,7 @@
new_test_ext().execute_with(|| {
// can add 3 as candidate
get_license_and_onboard(3);
- assert_eq!(CollatorSelection::licenses(3), 10);
+ assert_eq!(CollatorSelection::license_deposit_of(3), 10);
assert_eq!(CollatorSelection::candidates(), vec![3]);
assert_eq!(CollatorSelection::last_authored_block(3), 10);
assert_eq!(Balances::free_balance(3), 90);
@@ -257,8 +266,8 @@
fn becoming_candidate_works() {
new_test_ext().execute_with(|| {
// given
- assert_eq!(CollatorSelection::desired_collators(), 5);
- assert_eq!(CollatorSelection::license_bond(), 10);
+ assert_eq!(<DesiredCollators<Test>>::get(), 5);
+ assert_eq!(<LicenseBond<Test>>::get(), 10);
assert_eq!(CollatorSelection::candidates(), Vec::new());
assert_eq!(CollatorSelection::invulnerables(), vec![1, 2]);
@@ -315,7 +324,7 @@
));
// should exclude from candidates, but not revoke the license
assert_eq!(CollatorSelection::candidates(), vec![]);
- assert_eq!(CollatorSelection::licenses(3), 10);
+ assert_eq!(CollatorSelection::license_deposit_of(3), 10);
assert_eq!(Balances::free_balance(3), 90);
});
}
@@ -503,7 +512,7 @@
assert_eq!(SessionHandlerCollators::get(), vec![1, 2, 3, 4]);
assert_eq!(CollatorSelection::candidates(), vec![4]);
- assert_eq!(CollatorSelection::kick_threshold(), 10);
+ assert_eq!(<KickThreshold<Test>>::get(), 10);
assert_eq!(CollatorSelection::last_authored_block(4), 20);
initialize_to_block(30);
@@ -524,9 +533,6 @@
let invulnerables = vec![1, 1];
let collator_selection = collator_selection::GenesisConfig::<Test> {
- desired_collators: 5,
- license_bond: 10,
- kick_threshold: 10,
invulnerables,
};
// collator selection must be initialized before session.
pallets/configuration/src/lib.rsdiffbeforeafterboth--- a/pallets/configuration/src/lib.rs
+++ b/pallets/configuration/src/lib.rs
@@ -36,15 +36,24 @@
mod pallet {
use super::*;
use frame_support::{
- traits::Get,
- pallet_prelude::{StorageValue, ValueQuery, DispatchResult, OptionQuery},
- BoundedVec,
+ traits::{Get, ReservableCurrency, Currency},
+ pallet_prelude::{StorageValue, ValueQuery, DispatchResult, IsType, OptionQuery},
+ BoundedVec, log,
};
- use frame_system::{pallet_prelude::OriginFor, ensure_root};
+ use frame_system::{pallet_prelude::OriginFor, ensure_root, Config as SystemConfig};
use xcm::v1::MultiLocation;
+ pub type BalanceOf<T> =
+ <<T as Config>::Currency as Currency<<T as SystemConfig>::AccountId>>::Balance;
+
#[pallet::config]
pub trait Config: frame_system::Config {
+ /// Overarching event type.
+ type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
+
+ /// The currency mechanism.
+ type Currency: ReservableCurrency<Self::AccountId>;
+
#[pallet::constant]
type DefaultWeightToFeeCoefficient: Get<u32>;
@@ -57,6 +66,27 @@
type AppPromotionDailyRate: Get<Perbill>;
#[pallet::constant]
type DayRelayBlocks: Get<Self::BlockNumber>;
+
+ #[pallet::constant]
+ type DefaultCollatorSelectionMaxCollators: Get<u32>;
+ #[pallet::constant]
+ type DefaultCollatorSelectionLicenseBond: Get<BalanceOf<Self>>;
+ #[pallet::constant]
+ type DefaultCollatorSelectionKickThreshold: Get<Self::BlockNumber>;
+ }
+
+ #[pallet::event]
+ #[pallet::generate_deposit(pub(super) fn deposit_event)]
+ pub enum Event<T: Config> {
+ NewDesiredCollators {
+ desired_collators: Option<u32>,
+ },
+ NewCollatorLicenseBond {
+ bond_cost: Option<BalanceOf<T>>,
+ },
+ NewCollatorKickThreshold {
+ length_in_blocks: Option<T::BlockNumber>,
+ },
}
#[pallet::error]
@@ -85,6 +115,27 @@
pub type AppPromomotionConfigurationOverride<T: Config> =
StorageValue<Value = AppPromotionConfiguration<T::BlockNumber>, QueryKind = ValueQuery>;
+ #[pallet::storage]
+ pub type CollatorSelectionDesiredCollatorsOverride<T: Config> = StorageValue<
+ Value = u32,
+ QueryKind = ValueQuery,
+ OnEmpty = T::DefaultCollatorSelectionMaxCollators,
+ >;
+
+ #[pallet::storage]
+ pub type CollatorSelectionLicenseBondOverride<T: Config> = StorageValue<
+ Value = BalanceOf<T>,
+ QueryKind = ValueQuery,
+ OnEmpty = T::DefaultCollatorSelectionLicenseBond,
+ >;
+
+ #[pallet::storage]
+ pub type CollatorSelectionKickThresholdOverride<T: Config> = StorageValue<
+ Value = T::BlockNumber,
+ QueryKind = ValueQuery,
+ OnEmpty = T::DefaultCollatorSelectionKickThreshold,
+ >;
+
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::weight(T::DbWeight::get().writes(1))]
@@ -144,6 +195,55 @@
Ok(())
}
+
+ #[pallet::weight(T::DbWeight::get().writes(1))]
+ pub fn set_collator_selection_desired_collators(
+ origin: OriginFor<T>,
+ max: Option<u32>,
+ ) -> DispatchResult {
+ ensure_root(origin)?;
+ if let Some(max) = max {
+ // we trust origin calls, this is just a for more accurate benchmarking
+ if max > T::DefaultCollatorSelectionMaxCollators::get() {
+ log::warn!("max > T::DefaultCollatorSelectionMaxCollators; you might need to run benchmarks again");
+ }
+ <CollatorSelectionDesiredCollatorsOverride<T>>::set(max);
+ } else {
+ <CollatorSelectionDesiredCollatorsOverride<T>>::kill();
+ }
+ Self::deposit_event(Event::NewDesiredCollators { desired_collators: max });
+ Ok(())
+ }
+
+ #[pallet::weight(T::DbWeight::get().writes(1))]
+ pub fn set_collator_selection_license_bond(
+ origin: OriginFor<T>,
+ amount: Option<BalanceOf<T>>,
+ ) -> DispatchResult {
+ ensure_root(origin)?;
+ if let Some(amount) = amount {
+ <CollatorSelectionLicenseBondOverride<T>>::set(amount);
+ } else {
+ <CollatorSelectionLicenseBondOverride<T>>::kill();
+ }
+ Self::deposit_event(Event::NewCollatorLicenseBond { bond_cost: amount });
+ Ok(())
+ }
+
+ #[pallet::weight(T::DbWeight::get().writes(1))]
+ pub fn set_collator_selection_kick_threshold(
+ origin: OriginFor<T>,
+ threshold: Option<T::BlockNumber>,
+ ) -> DispatchResult {
+ ensure_root(origin)?;
+ if let Some(threshold) = threshold {
+ <CollatorSelectionKickThresholdOverride<T>>::set(threshold);
+ } else {
+ <CollatorSelectionKickThresholdOverride<T>>::kill();
+ }
+ Self::deposit_event(Event::NewCollatorKickThreshold { length_in_blocks: threshold });
+ Ok(())
+ }
}
#[pallet::pallet]
primitives/common/src/constants.rsdiffbeforeafterboth--- a/primitives/common/src/constants.rs
+++ b/primitives/common/src/constants.rs
@@ -46,6 +46,8 @@
pub const EXISTENTIAL_DEPOSIT: u128 = 0;
/// Amount of Balance reserved for candidate registration.
pub const GENESIS_LICENSE_BOND: u128 = 1_000_000_000_000 * UNIQUE;
+/// Amount of maximum collators for Collator Selection.
+pub const MAX_COLLATORS: u32 = 10;
/// How long a periodic session lasts in blocks.
pub const SESSION_LENGTH: BlockNumber = HOURS;
runtime/common/config/pallets/collator_selection.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/collator_selection.rs
+++ b/runtime/common/config/pallets/collator_selection.rs
@@ -17,14 +17,14 @@
use frame_support::{parameter_types, PalletId};
use frame_system::EnsureRoot;
use crate::{
- AccountId, BlockNumber, Runtime, RuntimeEvent, Balances, Aura, Session, SessionKeys,
- CollatorSelection, config::pallets::TreasuryAccountId,
+ AccountId, Balance, Balances, BlockNumber, Runtime, RuntimeEvent, Aura, Session, SessionKeys,
+ CollatorSelection, Treasury,
+ config::pallets::{MaxCollators, SessionPeriod, TreasuryAccountId},
};
use sp_runtime::Perbill;
-use up_common::constants::*;
+use up_common::constants::{UNIQUE, MILLIUNIQUE};
parameter_types! {
- pub const SessionPeriod: BlockNumber = SESSION_LENGTH;
pub const SessionOffset: BlockNumber = 0;
}
@@ -55,13 +55,11 @@
parameter_types! {
pub const PotId: PalletId = PalletId(*b"PotStake");
- pub const MaxCollators: u32 = 10;
pub const SlashRatio: Perbill = Perbill::from_percent(100);
}
impl pallet_collator_selection::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
- type Currency = Balances;
// We allow root only to execute privileged collator selection operations.
type UpdateOrigin = EnsureRoot<AccountId>;
type TreasuryAccountId = TreasuryAccountId;
runtime/common/config/pallets/mod.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -25,7 +25,7 @@
},
Runtime, RuntimeEvent, RuntimeCall, Balances,
};
-use frame_support::traits::{ConstU32, ConstU64};
+use frame_support::traits::{ConstU32, ConstU64, ConstU128};
use up_common::{
types::{AccountId, Balance, BlockNumber},
constants::*,
@@ -104,11 +104,20 @@
parameter_types! {
pub AppPromotionDailyRate: Perbill = Perbill::from_rational(5u32, 10_000);
+ pub const MaxCollators: u32 = MAX_COLLATORS;
+ pub const SessionPeriod: BlockNumber = SESSION_LENGTH;
pub const DayRelayBlocks: BlockNumber = RELAY_DAYS;
}
+
impl pallet_configuration::Config for Runtime {
+ type RuntimeEvent = RuntimeEvent;
+ type Currency = Balances;
type DefaultWeightToFeeCoefficient = ConstU32<{ up_common::constants::WEIGHT_TO_FEE_COEFF }>;
type DefaultMinGasPrice = ConstU64<{ up_common::constants::MIN_GAS_PRICE }>;
+ type DefaultCollatorSelectionMaxCollators = MaxCollators;
+ type DefaultCollatorSelectionKickThreshold = SessionPeriod;
+ type DefaultCollatorSelectionLicenseBond =
+ ConstU128<{ up_common::constants::GENESIS_LICENSE_BOND }>;
type MaxXcmAllowedLocations = ConstU32<16>;
type AppPromotionDailyRate = AppPromotionDailyRate;
type DayRelayBlocks = DayRelayBlocks;
runtime/common/construct_runtime/mod.rsdiffbeforeafterboth--- a/runtime/common/construct_runtime/mod.rs
+++ b/runtime/common/construct_runtime/mod.rs
@@ -69,7 +69,7 @@
// #[runtimes(opal)]
// Scheduler: pallet_unique_scheduler_v2::{Pallet, Call, Storage, Event<T>} = 62,
- Configuration: pallet_configuration::{Pallet, Call, Storage} = 63,
+ Configuration: pallet_configuration::{Pallet, Call, Storage, Event<T>} = 63,
Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
runtime/common/maintenance.rsdiffbeforeafterboth--- a/runtime/common/maintenance.rs
+++ b/runtime/common/maintenance.rs
@@ -85,6 +85,12 @@
Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
}
+ #[cfg(feature = "collator-selection")]
+ RuntimeCall::CollatorSelection(_)
+ | RuntimeCall::Authorship(_)
+ | RuntimeCall::Session(_)
+ | RuntimeCall::Identity(_) => Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
+
#[cfg(feature = "pallet-test-utils")]
RuntimeCall::TestUtils(_) => Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
@@ -110,7 +116,7 @@
) -> TransactionValidity {
if Maintenance::is_enabled() {
match call {
- RuntimeCall::EVM(_) | RuntimeCall::Ethereum(_) | RuntimeCall::EvmMigration(_) => {
+ RuntimeCall::EVM(_) | RuntimeCall::Ethereum(_) | RuntimeCall::DataManagement(_) => {
Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
}
_ => Ok(ValidTransaction::default()),
runtime/common/mod.rsdiffbeforeafterboth--- a/runtime/common/mod.rs
+++ b/runtime/common/mod.rs
@@ -186,13 +186,9 @@
#[cfg(feature = "collator-selection")]
{
use frame_support::{BoundedVec, storage::migration};
- use sp_runtime::{
- traits::{OpaqueKeys, Saturating},
- RuntimeAppPublic,
- };
+ use sp_runtime::{traits::OpaqueKeys, RuntimeAppPublic};
use pallet_session::SessionManager;
- use up_common::constants::{GENESIS_LICENSE_BOND, SESSION_LENGTH};
- use crate::config::pallets::collator_selection::MaxCollators;
+ use crate::config::pallets::MaxCollators;
let mut weight = <Runtime as frame_system::Config>::DbWeight::get().reads(1);
@@ -241,9 +237,6 @@
.expect("Existing collators/invulnerables are more than MaxCollators");
<pallet_collator_selection::Invulnerables<Runtime>>::put(bounded_invulnerables);
- <pallet_collator_selection::KickThreshold<Runtime>>::put(SESSION_LENGTH);
- <pallet_collator_selection::DesiredCollators<Runtime>>::put(MaxCollators::get());
- <pallet_collator_selection::LicenseBond<Runtime>>::put(GENESIS_LICENSE_BOND);
let keys = invulnerables
.into_iter()
runtime/common/tests/mod.rsdiffbeforeafterboth--- a/runtime/common/tests/mod.rs
+++ b/runtime/common/tests/mod.rs
@@ -64,9 +64,6 @@
let cfg = GenesisConfig {
collator_selection: CollatorSelectionConfig {
- desired_collators: 2,
- license_bond: 10,
- kick_threshold: 10,
invulnerables,
},
session: SessionConfig { keys },
tests/src/collatorSelection.seqtest.tsdiffbeforeafterboth--- a/tests/src/collatorSelection.seqtest.ts
+++ b/tests/src/collatorSelection.seqtest.ts
@@ -17,8 +17,6 @@
import {IKeyringPair} from '@polkadot/types/types';
import {usingPlaygrounds, expect, itSub, Pallets, requirePalletsOrSkip} from './util';
-const MAX_INVULNERABLES = 10;
-
async function resetInvulnerables() {
await usingPlaygrounds(async (helper, privateKey) => {
const superuser = await privateKey('//Alice');
@@ -31,7 +29,7 @@
let nonce = await helper.chain.getNonce(alice.address);
// In case there are too many invulnerables already, remove some of them, leaving space for Alice and Bob.
- if (invulnerables.length + 2 >= MAX_INVULNERABLES) {
+ if (invulnerables.length + 2 >= helper.collatorSelection.maxCollators()) {
await Promise.all([
helper.getSudo().executeExtrinsic(superuser, 'api.tx.collatorSelection.removeInvulnerable', [invulnerables.pop()], true, {nonce: nonce++}),
helper.getSudo().executeExtrinsic(superuser, 'api.tx.collatorSelection.removeInvulnerable', [invulnerables.pop()], true, {nonce: nonce++}),
@@ -409,7 +407,7 @@
// 28 non-functioning collators, teehee.
const invulnerablesLength = (await helper.collatorSelection.getInvulnerables()).length;
- const invulnerablesUntilLimit = MAX_INVULNERABLES - invulnerablesLength;
+ const invulnerablesUntilLimit = helper.collatorSelection.maxCollators() - invulnerablesLength;
const newInvulnerables = await helper.arrange.createAccounts(Array(invulnerablesUntilLimit).fill(10n), superuser);
const [lastInvulnerable] = await helper.arrange.createAccounts([10n], superuser);
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -65,6 +65,7 @@
arrange: ArrangeGroup;
wait: WaitGroup;
admin: AdminGroup;
+ session: SessionGroup;
testUtils: TestUtilGroup;
constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
@@ -75,6 +76,7 @@
this.wait = new WaitGroup(this);
this.admin = new AdminGroup(this);
this.testUtils = new TestUtilGroup(this);
+ this.session = new SessionGroup(this);
}
async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
@@ -456,14 +458,14 @@
console.log(`Waiting for ${sessionCount} new session${sessionCount > 1 ? 's' : ''}.`
+ ' This might take a while -- check SessionPeriod in pallet_session::Config for session time.');
- const expectedSessionIndex = await this.helper.session.getIndex() + sessionCount;
+ const expectedSessionIndex = await (this.helper as DevUniqueHelper).session.getIndex() + sessionCount;
let currentSessionIndex = -1;
while (currentSessionIndex < expectedSessionIndex) {
// eslint-disable-next-line no-async-promise-executor
currentSessionIndex = await this.withTimeout(new Promise(async (resolve) => {
await this.newBlocks(1);
- const res = this.helper.session.getIndex();
+ const res = await (this.helper as DevUniqueHelper).session.getIndex();
resolve(res);
}), blockTimeout, 'The chain has stopped producing blocks!');
}
@@ -552,6 +554,36 @@
}
}
+class SessionGroup {
+ helper: ChainHelperBase;
+
+ constructor(helper: ChainHelperBase) {
+ this.helper = helper;
+ }
+
+ //todo:collator documentation
+ async getIndex(): Promise<number> {
+ return (await this.helper.callRpc('api.query.session.currentIndex')).toNumber();
+ }
+
+ newSessions(sessionCount = 1, blockTimeout = 24000): Promise<void> {
+ return (this.helper as DevUniqueHelper).wait.newSessions(sessionCount, blockTimeout);
+ }
+
+ setOwnKeys(signer: TSigner, key: string) {
+ return this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.session.setKeys',
+ [key, '0x0'],
+ true,
+ );
+ }
+
+ setOwnKeysFromAddress(signer: TSigner) {
+ return this.setOwnKeys(signer, '0x' + Buffer.from(signer.addressRaw).toString('hex'));
+ }
+}
+
class TestUtilGroup {
helper: DevUniqueHelper;
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 {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15 IApiListeners,16 IBlock,17 IEvent,18 IChainProperties,19 ICollectionCreationOptions,20 ICollectionLimits,21 ICollectionPermissions,22 ICrossAccountId,23 ICrossAccountIdLower,24 ILogger,25 INestingPermissions,26 IProperty,27 IStakingInfo,28 ISchedulerOptions,29 ISubstrateBalance,30 IToken,31 ITokenPropertyPermission,32 ITransactionResult,33 IUniqueHelperLog,34 TApiAllowedListeners,35 TEthereumAccount,36 TSigner,37 TSubstrateAccount,38 TNetworks,39 IForeignAssetMetadata,40 AcalaAssetMetadata,41 MoonbeamAssetInfo,42 DemocracyStandardAccountVote,43 IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';48import {DevUniqueHelper} from './unique.dev';4950export class CrossAccountId implements ICrossAccountId {51 Substrate?: TSubstrateAccount;52 Ethereum?: TEthereumAccount;5354 constructor(account: ICrossAccountId) {55 if (account.Substrate) this.Substrate = account.Substrate;56 if (account.Ethereum) this.Ethereum = account.Ethereum;57 }5859 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {60 switch (domain) {61 case 'Substrate': return new CrossAccountId({Substrate: account.address});62 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();63 }64 }6566 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {67 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});68 }6970 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {71 return encodeAddress(decodeAddress(address), ss58Format);72 }7374 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {75 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});76 }7778 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {79 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);80 return this;81 }8283 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {84 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));85 }8687 toEthereum(): CrossAccountId {88 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});89 return this;90 }9192 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {93 return evmToAddress(address, ss58Format);94 }9596 toSubstrate(ss58Format?: number): CrossAccountId {97 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});98 return this;99 }100101 toLowerCase(): CrossAccountId {102 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();103 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();104 return this;105 }106}107108const nesting = {109 toChecksumAddress(address: string): string {110 if (typeof address === 'undefined') return '';111112 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);113114 address = address.toLowerCase().replace(/^0x/i,'');115 const addressHash = keccakAsHex(address).replace(/^0x/i,'');116 const checksumAddress = ['0x'];117118 for (let i = 0; i < address.length; i++) {119 // If ith character is 8 to f then make it uppercase120 if (parseInt(addressHash[i], 16) > 7) {121 checksumAddress.push(address[i].toUpperCase());122 } else {123 checksumAddress.push(address[i]);124 }125 }126 return checksumAddress.join('');127 },128 tokenIdToAddress(collectionId: number, tokenId: number) {129 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);130 },131};132133class UniqueUtil {134 static transactionStatus = {135 NOT_READY: 'NotReady',136 FAIL: 'Fail',137 SUCCESS: 'Success',138 };139140 static chainLogType = {141 EXTRINSIC: 'extrinsic',142 RPC: 'rpc',143 };144145 static getTokenAccount(token: IToken): CrossAccountId {146 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});147 }148149 static getTokenAddress(token: IToken): string {150 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);151 }152153 static getDefaultLogger(): ILogger {154 return {155 log(msg: any, level = 'INFO') {156 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));157 },158 level: {159 ERROR: 'ERROR',160 WARNING: 'WARNING',161 INFO: 'INFO',162 },163 };164 }165166 static vec2str(arr: string[] | number[]) {167 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');168 }169170 static str2vec(string: string) {171 if (typeof string !== 'string') return string;172 return Array.from(string).map(x => x.charCodeAt(0));173 }174175 static fromSeed(seed: string, ss58Format = 42) {176 const keyring = new Keyring({type: 'sr25519', ss58Format});177 return keyring.addFromUri(seed);178 }179180 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {181 if (creationResult.status !== this.transactionStatus.SUCCESS) {182 throw Error('Unable to create collection!');183 }184185 let collectionId = null;186 creationResult.result.events.forEach(({event: {data, method, section}}) => {187 if ((section === 'common') && (method === 'CollectionCreated')) {188 collectionId = parseInt(data[0].toString(), 10);189 }190 });191192 if (collectionId === null) {193 throw Error('No CollectionCreated event was found!');194 }195196 return collectionId;197 }198199 static extractTokensFromCreationResult(creationResult: ITransactionResult): {200 success: boolean,201 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],202 } {203 if (creationResult.status !== this.transactionStatus.SUCCESS) {204 throw Error('Unable to create tokens!');205 }206 let success = false;207 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];208 creationResult.result.events.forEach(({event: {data, method, section}}) => {209 if (method === 'ExtrinsicSuccess') {210 success = true;211 } else if ((section === 'common') && (method === 'ItemCreated')) {212 tokens.push({213 collectionId: parseInt(data[0].toString(), 10),214 tokenId: parseInt(data[1].toString(), 10),215 owner: data[2].toHuman(),216 amount: data[3].toBigInt(),217 });218 }219 });220 return {success, tokens};221 }222223 static extractTokensFromBurnResult(burnResult: ITransactionResult): {224 success: boolean,225 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],226 } {227 if (burnResult.status !== this.transactionStatus.SUCCESS) {228 throw Error('Unable to burn tokens!');229 }230 let success = false;231 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];232 burnResult.result.events.forEach(({event: {data, method, section}}) => {233 if (method === 'ExtrinsicSuccess') {234 success = true;235 } else if ((section === 'common') && (method === 'ItemDestroyed')) {236 tokens.push({237 collectionId: parseInt(data[0].toString(), 10),238 tokenId: parseInt(data[1].toString(), 10),239 owner: data[2].toHuman(),240 amount: data[3].toBigInt(),241 });242 }243 });244 return {success, tokens};245 }246247 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {248 let eventId = null;249 events.forEach(({event: {data, method, section}}) => {250 if ((section === expectedSection) && (method === expectedMethod)) {251 eventId = parseInt(data[0].toString(), 10);252 }253 });254255 if (eventId === null) {256 throw Error(`No ${expectedMethod} event was found!`);257 }258 return eventId === collectionId;259 }260261 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {262 const normalizeAddress = (address: string | ICrossAccountId) => {263 if(typeof address === 'string') return address;264 const obj = {} as any;265 Object.keys(address).forEach(k => {266 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];267 });268 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);269 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();270 return address;271 };272 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;273 events.forEach(({event: {data, method, section}}) => {274 if ((section === 'common') && (method === 'Transfer')) {275 const hData = (data as any).toJSON();276 transfer = {277 collectionId: hData[0],278 tokenId: hData[1],279 from: normalizeAddress(hData[2]),280 to: normalizeAddress(hData[3]),281 amount: BigInt(hData[4]),282 };283 }284 });285 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;286 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);287 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);288 isSuccess = isSuccess && amount === transfer.amount;289 return isSuccess;290 }291292 static bigIntToDecimals(number: bigint, decimals = 18) {293 const numberStr = number.toString();294 const dotPos = numberStr.length - decimals;295296 if (dotPos <= 0) {297 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;298 } else {299 const intPart = numberStr.substring(0, dotPos);300 const fractPart = numberStr.substring(dotPos);301 return intPart + '.' + fractPart;302 }303 }304}305306class UniqueEventHelper {307 private static extractIndex(index: any): [number, number] | string {308 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];309 return index.toJSON();310 }311312 private static extractSub(data: any, subTypes: any): {[key: string]: any} {313 let obj: any = {};314 let index = 0;315316 if (data.entries) {317 for(const [key, value] of data.entries()) {318 obj[key] = this.extractData(value, subTypes[index]);319 index++;320 }321 } else obj = data.toJSON();322323 return obj;324 }325326 private static toHuman(data: any) {327 return data && data.toHuman ? data.toHuman() : `${data}`;328 }329330 private static extractData(data: any, type: any): any {331 if(!type) return this.toHuman(data);332 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();333 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();334 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);335 return this.toHuman(data);336 }337338 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {339 const parsedEvents: IEvent[] = [];340341 events.forEach((record) => {342 const {event, phase} = record;343 const types = event.typeDef;344345 const eventData: IEvent = {346 section: event.section.toString(),347 method: event.method.toString(),348 index: this.extractIndex(event.index),349 data: [],350 phase: phase.toJSON(),351 };352353 event.data.forEach((val: any, index: number) => {354 eventData.data.push(this.extractData(val, types[index]));355 });356357 parsedEvents.push(eventData);358 });359360 return parsedEvents;361 }362}363364export class ChainHelperBase {365 helperBase: any;366367 transactionStatus = UniqueUtil.transactionStatus;368 chainLogType = UniqueUtil.chainLogType;369 util: typeof UniqueUtil;370 eventHelper: typeof UniqueEventHelper;371 logger: ILogger;372 api: ApiPromise | null;373 forcedNetwork: TNetworks | null;374 network: TNetworks | null;375 chainLog: IUniqueHelperLog[];376 children: ChainHelperBase[];377 address: AddressGroup;378 chain: ChainGroup;379 session: SessionGroup;380381 constructor(logger?: ILogger, helperBase?: any) {382 this.helperBase = helperBase;383384 this.util = UniqueUtil;385 this.eventHelper = UniqueEventHelper;386 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();387 this.logger = logger;388 this.api = null;389 this.forcedNetwork = null;390 this.network = null;391 this.chainLog = [];392 this.children = [];393 this.address = new AddressGroup(this);394 this.chain = new ChainGroup(this);395 this.session = new SessionGroup(this);396 }397398 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {399 Object.setPrototypeOf(helperCls.prototype, this);400 const newHelper = new helperCls(this.logger, options);401402 newHelper.api = this.api;403 newHelper.network = this.network;404 newHelper.forceNetwork = this.forceNetwork;405406 this.children.push(newHelper);407408 return newHelper;409 }410411 getApi(): ApiPromise {412 if(this.api === null) throw Error('API not initialized');413 return this.api;414 }415416 async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {417 const collectedEvents: IEvent[] = [];418 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {419 const ievents = this.eventHelper.extractEvents(events);420 ievents.forEach((event) => {421 expectedEvents.forEach((e => {422 if (event.section === e.section && e.names.includes(event.method)) {423 collectedEvents.push(event);424 }425 }));426 });427 });428 return {unsubscribe: unsubscribe as any, collectedEvents};429 }430431 clearChainLog(): void {432 this.chainLog = [];433 }434435 forceNetwork(value: TNetworks): void {436 this.forcedNetwork = value;437 }438439 async connect(wsEndpoint: string, listeners?: IApiListeners) {440 if (this.api !== null) throw Error('Already connected');441 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);442 this.api = api;443 this.network = network;444 }445446 async disconnect() {447 for (const child of this.children) {448 child.clearApi();449 }450451 if (this.api === null) return;452 await this.api.disconnect();453 this.clearApi();454 }455456 clearApi() {457 this.api = null;458 this.network = null;459 }460461 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {462 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;463 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];464465 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;466467 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;468 return 'opal';469 }470471 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {472 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});473 await api.isReady;474475 const network = await this.detectNetwork(api);476477 await api.disconnect();478479 return network;480 }481482 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{483 api: ApiPromise;484 network: TNetworks;485 }> {486 if(typeof network === 'undefined' || network === null) network = 'opal';487 const supportedRPC = {488 opal: {489 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,490 },491 quartz: {492 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,493 },494 unique: {495 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,496 },497 rococo: {},498 westend: {},499 moonbeam: {},500 moonriver: {},501 acala: {},502 karura: {},503 westmint: {},504 };505 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);506 const rpc = supportedRPC[network];507508 // TODO: investigate how to replace rpc in runtime509 // api._rpcCore.addUserInterfaces(rpc);510511 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});512513 await api.isReadyOrError;514515 if (typeof listeners === 'undefined') listeners = {};516 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {517 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;518 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);519 }520521 return {api, network};522 }523524 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {525 const {events, status} = data;526 if (status.isReady) {527 return this.transactionStatus.NOT_READY;528 }529 if (status.isBroadcast) {530 return this.transactionStatus.NOT_READY;531 }532 if (status.isInBlock || status.isFinalized) {533 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');534 if (errors.length > 0) {535 return this.transactionStatus.FAIL;536 }537 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {538 return this.transactionStatus.SUCCESS;539 }540 }541542 return this.transactionStatus.FAIL;543 }544545 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {546 const sign = (callback: any) => {547 if(options !== null) return transaction.signAndSend(sender, options, callback);548 return transaction.signAndSend(sender, callback);549 };550 // eslint-disable-next-line no-async-promise-executor551 return new Promise(async (resolve, reject) => {552 try {553 const unsub = await sign((result: any) => {554 const status = this.getTransactionStatus(result);555556 if (status === this.transactionStatus.SUCCESS) {557 this.logger.log(`${label} successful`);558 unsub();559 resolve({result, status});560 } else if (status === this.transactionStatus.FAIL) {561 let moduleError = null;562563 if (result.hasOwnProperty('dispatchError')) {564 const dispatchError = result['dispatchError'];565566 if (dispatchError) {567 if (dispatchError.isModule) {568 const modErr = dispatchError.asModule;569 const errorMeta = dispatchError.registry.findMetaError(modErr);570571 moduleError = `${errorMeta.section}.${errorMeta.name}`;572 } else {573 moduleError = dispatchError.toHuman();574 }575 } else {576 this.logger.log(result, this.logger.level.ERROR);577 }578 }579580 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);581 unsub();582 reject({status, moduleError, result});583 }584 });585 } catch (e) {586 this.logger.log(e, this.logger.level.ERROR);587 reject(e);588 }589 });590 }591592 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {593 const api = this.getApi();594 const signingInfo = await api.derive.tx.signingInfo(signer.address);595596 // We need to sign the tx because597 // unsigned transactions does not have an inclusion fee598 tx.sign(signer, {599 blockHash: api.genesisHash,600 genesisHash: api.genesisHash,601 runtimeVersion: api.runtimeVersion,602 nonce: signingInfo.nonce,603 });604605 if (len === null) {606 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;607 } else {608 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;609 }610 }611612 constructApiCall(apiCall: string, params: any[]) {613 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);614 let call = this.getApi() as any;615 for(const part of apiCall.slice(4).split('.')) {616 call = call[part];617 }618 return call(...params);619 }620621 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {622 if(this.api === null) throw Error('API not initialized');623 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);624625 const startTime = (new Date()).getTime();626 let result: ITransactionResult;627 let events: IEvent[] = [];628 try {629 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;630 events = this.eventHelper.extractEvents(result.result.events);631 }632 catch(e) {633 if(!(e as object).hasOwnProperty('status')) throw e;634 result = e as ITransactionResult;635 }636637 const endTime = (new Date()).getTime();638639 const log = {640 executedAt: endTime,641 executionTime: endTime - startTime,642 type: this.chainLogType.EXTRINSIC,643 status: result.status,644 call: extrinsic,645 signer: this.getSignerAddress(sender),646 params,647 } as IUniqueHelperLog;648649 if(result.status !== this.transactionStatus.SUCCESS) {650 if (result.moduleError) log.moduleError = result.moduleError;651 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;652 }653 if(events.length > 0) log.events = events;654655 this.chainLog.push(log);656657 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {658 if (result.moduleError) throw Error(`${result.moduleError}`);659 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));660 }661 return result;662 }663664 async callRpc(rpc: string, params?: any[]) {665 if(typeof params === 'undefined') params = [];666 if(this.api === null) throw Error('API not initialized');667 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);668669 const startTime = (new Date()).getTime();670 let result;671 let error = null;672 const log = {673 type: this.chainLogType.RPC,674 call: rpc,675 params,676 } as IUniqueHelperLog;677678 try {679 result = await this.constructApiCall(rpc, params);680 }681 catch(e) {682 error = e;683 }684685 const endTime = (new Date()).getTime();686687 log.executedAt = endTime;688 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';689 log.executionTime = endTime - startTime;690691 this.chainLog.push(log);692693 if(error !== null) throw error;694695 return result;696 }697698 getSignerAddress(signer: IKeyringPair | string): string {699 if(typeof signer === 'string') return signer;700 return signer.address;701 }702703 fetchAllPalletNames(): string[] {704 if(this.api === null) throw Error('API not initialized');705 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());706 }707708 fetchMissingPalletNames(requiredPallets: string[]): string[] {709 const palletNames = this.fetchAllPalletNames();710 return requiredPallets.filter(p => !palletNames.includes(p));711 }712}713714715class HelperGroup<T extends ChainHelperBase> {716 helper: T;717718 constructor(uniqueHelper: T) {719 this.helper = uniqueHelper;720 }721}722723724class CollectionGroup extends HelperGroup<UniqueHelper> {725 /**726 * Get number of blocks when sponsored transaction is available.727 *728 * @param collectionId ID of collection729 * @param tokenId ID of token730 * @param addressObj address for which the sponsorship is checked731 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});732 * @returns number of blocks or null if sponsorship hasn't been set733 */734 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {735 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();736 }737738 /**739 * Get the number of created collections.740 *741 * @returns number of created collections742 */743 async getTotalCount(): Promise<number> {744 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();745 }746747 /**748 * Get information about the collection with additional data,749 * including the number of tokens it contains, its administrators,750 * the normalized address of the collection's owner, and decoded name and description.751 *752 * @param collectionId ID of collection753 * @example await getData(2)754 * @returns collection information object755 */756 async getData(collectionId: number): Promise<{757 id: number;758 name: string;759 description: string;760 tokensCount: number;761 admins: CrossAccountId[];762 normalizedOwner: TSubstrateAccount;763 raw: any764 } | null> {765 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);766 const humanCollection = collection.toHuman(), collectionData = {767 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],768 raw: humanCollection,769 } as any, jsonCollection = collection.toJSON();770 if (humanCollection === null) return null;771 collectionData.raw.limits = jsonCollection.limits;772 collectionData.raw.permissions = jsonCollection.permissions;773 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);774 for (const key of ['name', 'description']) {775 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);776 }777778 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))779 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)780 : 0;781 collectionData.admins = await this.getAdmins(collectionId);782783 return collectionData;784 }785786 /**787 * Get the addresses of the collection's administrators, optionally normalized.788 *789 * @param collectionId ID of collection790 * @param normalize whether to normalize the addresses to the default ss58 format791 * @example await getAdmins(1)792 * @returns array of administrators793 */794 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {795 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();796797 return normalize798 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())799 : admins;800 }801802 /**803 * Get the addresses added to the collection allow-list, optionally normalized.804 * @param collectionId ID of collection805 * @param normalize whether to normalize the addresses to the default ss58 format806 * @example await getAllowList(1)807 * @returns array of allow-listed addresses808 */809 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {810 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();811 return normalize812 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())813 : allowListed;814 }815816 /**817 * Get the effective limits of the collection instead of null for default values818 *819 * @param collectionId ID of collection820 * @example await getEffectiveLimits(2)821 * @returns object of collection limits822 */823 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {824 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();825 }826827 /**828 * Burns the collection if the signer has sufficient permissions and collection is empty.829 *830 * @param signer keyring of signer831 * @param collectionId ID of collection832 * @example await helper.collection.burn(aliceKeyring, 3);833 * @returns ```true``` if extrinsic success, otherwise ```false```834 */835 async burn(signer: TSigner, collectionId: number): Promise<boolean> {836 const result = await this.helper.executeExtrinsic(837 signer,838 'api.tx.unique.destroyCollection', [collectionId],839 true,840 );841842 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');843 }844845 /**846 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.847 *848 * @param signer keyring of signer849 * @param collectionId ID of collection850 * @param sponsorAddress Sponsor substrate address851 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")852 * @returns ```true``` if extrinsic success, otherwise ```false```853 */854 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {855 const result = await this.helper.executeExtrinsic(856 signer,857 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],858 true,859 );860861 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');862 }863864 /**865 * Confirms consent to sponsor the collection on behalf of the signer.866 *867 * @param signer keyring of signer868 * @param collectionId ID of collection869 * @example confirmSponsorship(aliceKeyring, 10)870 * @returns ```true``` if extrinsic success, otherwise ```false```871 */872 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {873 const result = await this.helper.executeExtrinsic(874 signer,875 'api.tx.unique.confirmSponsorship', [collectionId],876 true,877 );878879 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');880 }881882 /**883 * Removes the sponsor of a collection, regardless if it consented or not.884 *885 * @param signer keyring of signer886 * @param collectionId ID of collection887 * @example removeSponsor(aliceKeyring, 10)888 * @returns ```true``` if extrinsic success, otherwise ```false```889 */890 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {891 const result = await this.helper.executeExtrinsic(892 signer,893 'api.tx.unique.removeCollectionSponsor', [collectionId],894 true,895 );896897 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');898 }899900 /**901 * Sets the limits of the collection. At least one limit must be specified for a correct call.902 *903 * @param signer keyring of signer904 * @param collectionId ID of collection905 * @param limits collection limits object906 * @example907 * await setLimits(908 * aliceKeyring,909 * 10,910 * {911 * sponsorTransferTimeout: 0,912 * ownerCanDestroy: false913 * }914 * )915 * @returns ```true``` if extrinsic success, otherwise ```false```916 */917 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {918 const result = await this.helper.executeExtrinsic(919 signer,920 'api.tx.unique.setCollectionLimits', [collectionId, limits],921 true,922 );923924 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');925 }926927 /**928 * Changes the owner of the collection to the new Substrate address.929 *930 * @param signer keyring of signer931 * @param collectionId ID of collection932 * @param ownerAddress substrate address of new owner933 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")934 * @returns ```true``` if extrinsic success, otherwise ```false```935 */936 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {937 const result = await this.helper.executeExtrinsic(938 signer,939 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],940 true,941 );942943 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');944 }945946 /**947 * Adds a collection administrator.948 *949 * @param signer keyring of signer950 * @param collectionId ID of collection951 * @param adminAddressObj Administrator address (substrate or ethereum)952 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})953 * @returns ```true``` if extrinsic success, otherwise ```false```954 */955 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {956 const result = await this.helper.executeExtrinsic(957 signer,958 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],959 true,960 );961962 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');963 }964965 /**966 * Removes a collection administrator.967 *968 * @param signer keyring of signer969 * @param collectionId ID of collection970 * @param adminAddressObj Administrator address (substrate or ethereum)971 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})972 * @returns ```true``` if extrinsic success, otherwise ```false```973 */974 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {975 const result = await this.helper.executeExtrinsic(976 signer,977 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],978 true,979 );980981 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');982 }983984 /**985 * Check if user is in allow list.986 *987 * @param collectionId ID of collection988 * @param user Account to check989 * @example await getAdmins(1)990 * @returns is user in allow list991 */992 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {993 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();994 }995996 /**997 * Adds an address to allow list998 * @param signer keyring of signer999 * @param collectionId ID of collection1000 * @param addressObj address to add to the allow list1001 * @returns ```true``` if extrinsic success, otherwise ```false```1002 */1003 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1004 const result = await this.helper.executeExtrinsic(1005 signer,1006 'api.tx.unique.addToAllowList', [collectionId, addressObj],1007 true,1008 );10091010 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1011 }10121013 /**1014 * Removes an address from allow list1015 *1016 * @param signer keyring of signer1017 * @param collectionId ID of collection1018 * @param addressObj address to remove from the allow list1019 * @returns ```true``` if extrinsic success, otherwise ```false```1020 */1021 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1022 const result = await this.helper.executeExtrinsic(1023 signer,1024 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1025 true,1026 );10271028 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1029 }10301031 /**1032 * Sets onchain permissions for selected collection.1033 *1034 * @param signer keyring of signer1035 * @param collectionId ID of collection1036 * @param permissions collection permissions object1037 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1038 * @returns ```true``` if extrinsic success, otherwise ```false```1039 */1040 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1041 const result = await this.helper.executeExtrinsic(1042 signer,1043 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1044 true,1045 );10461047 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1048 }10491050 /**1051 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1052 *1053 * @param signer keyring of signer1054 * @param collectionId ID of collection1055 * @param permissions nesting permissions object1056 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1057 * @returns ```true``` if extrinsic success, otherwise ```false```1058 */1059 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1060 return await this.setPermissions(signer, collectionId, {nesting: permissions});1061 }10621063 /**1064 * Disables nesting for selected collection.1065 *1066 * @param signer keyring of signer1067 * @param collectionId ID of collection1068 * @example disableNesting(aliceKeyring, 10);1069 * @returns ```true``` if extrinsic success, otherwise ```false```1070 */1071 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1072 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1073 }10741075 /**1076 * Sets onchain properties to the collection.1077 *1078 * @param signer keyring of signer1079 * @param collectionId ID of collection1080 * @param properties array of property objects1081 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1082 * @returns ```true``` if extrinsic success, otherwise ```false```1083 */1084 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1085 const result = await this.helper.executeExtrinsic(1086 signer,1087 'api.tx.unique.setCollectionProperties', [collectionId, properties],1088 true,1089 );10901091 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1092 }10931094 /**1095 * Get collection properties.1096 *1097 * @param collectionId ID of collection1098 * @param propertyKeys optionally filter the returned properties to only these keys1099 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1100 * @returns array of key-value pairs1101 */1102 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1103 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1104 }11051106 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1107 const api = this.helper.getApi();1108 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();1109 1110 return (props! as any).consumedSpace;1111 }11121113 async getCollectionOptions(collectionId: number) {1114 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1115 }11161117 /**1118 * Deletes onchain properties from the collection.1119 *1120 * @param signer keyring of signer1121 * @param collectionId ID of collection1122 * @param propertyKeys array of property keys to delete1123 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1124 * @returns ```true``` if extrinsic success, otherwise ```false```1125 */1126 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1127 const result = await this.helper.executeExtrinsic(1128 signer,1129 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1130 true,1131 );11321133 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1134 }11351136 /**1137 * Changes the owner of the token.1138 *1139 * @param signer keyring of signer1140 * @param collectionId ID of collection1141 * @param tokenId ID of token1142 * @param addressObj address of a new owner1143 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1144 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1145 * @returns true if the token success, otherwise false1146 */1147 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1148 const result = await this.helper.executeExtrinsic(1149 signer,1150 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1151 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1152 );11531154 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1155 }11561157 /**1158 *1159 * Change ownership of a token(s) on behalf of the owner.1160 *1161 * @param signer keyring of signer1162 * @param collectionId ID of collection1163 * @param tokenId ID of token1164 * @param fromAddressObj address on behalf of which the token will be sent1165 * @param toAddressObj new token owner1166 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1167 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1168 * @returns true if the token success, otherwise false1169 */1170 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1171 const result = await this.helper.executeExtrinsic(1172 signer,1173 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1174 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1175 );1176 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1177 }11781179 /**1180 *1181 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1182 *1183 * @param signer keyring of signer1184 * @param collectionId ID of collection1185 * @param tokenId ID of token1186 * @param amount amount of tokens to be burned. For NFT must be set to 1n1187 * @example burnToken(aliceKeyring, 10, 5);1188 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1189 */1190 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1191 const burnResult = await this.helper.executeExtrinsic(1192 signer,1193 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1194 true, // `Unable to burn token for ${label}`,1195 );1196 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1197 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1198 return burnedTokens.success;1199 }12001201 /**1202 * Destroys a concrete instance of NFT on behalf of the owner1203 *1204 * @param signer keyring of signer1205 * @param collectionId ID of collection1206 * @param tokenId ID of token1207 * @param fromAddressObj address on behalf of which the token will be burnt1208 * @param amount amount of tokens to be burned. For NFT must be set to 1n1209 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1210 * @returns ```true``` if extrinsic success, otherwise ```false```1211 */1212 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1213 const burnResult = await this.helper.executeExtrinsic(1214 signer,1215 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1216 true, // `Unable to burn token from for ${label}`,1217 );1218 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1219 return burnedTokens.success && burnedTokens.tokens.length > 0;1220 }12211222 /**1223 * Set, change, or remove approved address to transfer the ownership of the NFT.1224 *1225 * @param signer keyring of signer1226 * @param collectionId ID of collection1227 * @param tokenId ID of token1228 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1229 * @param amount amount of token to be approved. For NFT must be set to 1n1230 * @returns ```true``` if extrinsic success, otherwise ```false```1231 */1232 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1233 const approveResult = await this.helper.executeExtrinsic(1234 signer,1235 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1236 true, // `Unable to approve token for ${label}`,1237 );12381239 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1240 }12411242 /**1243 * Get the amount of token pieces approved to transfer or burn. Normally 0.1244 *1245 * @param collectionId ID of collection1246 * @param tokenId ID of token1247 * @param toAccountObj address which is approved to use token pieces1248 * @param fromAccountObj address which may have allowed the use of its owned tokens1249 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1250 * @returns number of approved to transfer pieces1251 */1252 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1253 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1254 }12551256 /**1257 * Get the last created token ID in a collection1258 *1259 * @param collectionId ID of collection1260 * @example getLastTokenId(10);1261 * @returns id of the last created token1262 */1263 async getLastTokenId(collectionId: number): Promise<number> {1264 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1265 }12661267 /**1268 * Check if token exists1269 *1270 * @param collectionId ID of collection1271 * @param tokenId ID of token1272 * @example doesTokenExist(10, 20);1273 * @returns true if the token exists, otherwise false1274 */1275 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1276 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1277 }1278}12791280class NFTnRFT extends CollectionGroup {1281 /**1282 * Get tokens owned by account1283 *1284 * @param collectionId ID of collection1285 * @param addressObj tokens owner1286 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1287 * @returns array of token ids owned by account1288 */1289 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1290 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1291 }12921293 /**1294 * Get token data1295 *1296 * @param collectionId ID of collection1297 * @param tokenId ID of token1298 * @param propertyKeys optionally filter the token properties to only these keys1299 * @param blockHashAt optionally query the data at some block with this hash1300 * @example getToken(10, 5);1301 * @returns human readable token data1302 */1303 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1304 properties: IProperty[];1305 owner: CrossAccountId;1306 normalizedOwner: CrossAccountId;1307 }| null> {1308 let tokenData;1309 if(typeof blockHashAt === 'undefined') {1310 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1311 }1312 else {1313 if(propertyKeys.length == 0) {1314 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1315 if(!collection) return null;1316 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1317 }1318 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1319 }1320 tokenData = tokenData.toHuman();1321 if (tokenData === null || tokenData.owner === null) return null;1322 const owner = {} as any;1323 for (const key of Object.keys(tokenData.owner)) {1324 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1325 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1326 : tokenData.owner[key];1327 }1328 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1329 return tokenData;1330 }13311332 /**1333 * Set permissions to change token properties1334 *1335 * @param signer keyring of signer1336 * @param collectionId ID of collection1337 * @param permissions permissions to change a property by the collection admin or token owner1338 * @example setTokenPropertyPermissions(1339 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1340 * )1341 * @returns true if extrinsic success otherwise false1342 */1343 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1344 const result = await this.helper.executeExtrinsic(1345 signer,1346 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1347 true,1348 );13491350 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1351 }13521353 /**1354 * Get token property permissions.1355 *1356 * @param collectionId ID of collection1357 * @param propertyKeys optionally filter the returned property permissions to only these keys1358 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1359 * @returns array of key-permission pairs1360 */1361 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1362 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1363 }13641365 /**1366 * Set token properties1367 *1368 * @param signer keyring of signer1369 * @param collectionId ID of collection1370 * @param tokenId ID of token1371 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1372 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1373 * @returns ```true``` if extrinsic success, otherwise ```false```1374 */1375 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1376 const result = await this.helper.executeExtrinsic(1377 signer,1378 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1379 true,1380 );13811382 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1383 }13841385 /**1386 * Get properties, metadata assigned to a token.1387 *1388 * @param collectionId ID of collection1389 * @param tokenId ID of token1390 * @param propertyKeys optionally filter the returned properties to only these keys1391 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1392 * @returns array of key-value pairs1393 */1394 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1395 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1396 }13971398 /**1399 * Delete the provided properties of a token1400 * @param signer keyring of signer1401 * @param collectionId ID of collection1402 * @param tokenId ID of token1403 * @param propertyKeys property keys to be deleted1404 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1405 * @returns ```true``` if extrinsic success, otherwise ```false```1406 */1407 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1408 const result = await this.helper.executeExtrinsic(1409 signer,1410 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1411 true,1412 );14131414 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1415 }14161417 /**1418 * Mint new collection1419 *1420 * @param signer keyring of signer1421 * @param collectionOptions basic collection options and properties1422 * @param mode NFT or RFT type of a collection1423 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1424 * @returns object of the created collection1425 */1426 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1427 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1428 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1429 for (const key of ['name', 'description', 'tokenPrefix']) {1430 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);1431 }1432 const creationResult = await this.helper.executeExtrinsic(1433 signer,1434 'api.tx.unique.createCollectionEx', [collectionOptions],1435 true, // errorLabel,1436 );1437 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1438 }14391440 getCollectionObject(_collectionId: number): any {1441 return null;1442 }14431444 getTokenObject(_collectionId: number, _tokenId: number): any {1445 return null;1446 }14471448 /**1449 * Tells whether the given `owner` approves the `operator`.1450 * @param collectionId ID of collection1451 * @param owner owner address1452 * @param operator operator addrees1453 * @returns true if operator is enabled1454 */1455 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1456 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1457 }14581459 /** Sets or unsets the approval of a given operator.1460 * The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1461 * @param operator Operator1462 * @param approved Should operator status be granted or revoked?1463 * @returns ```true``` if extrinsic success, otherwise ```false```1464 */1465 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1466 const result = await this.helper.executeExtrinsic(1467 signer,1468 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1469 true,1470 );1471 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1472 }1473}147414751476class NFTGroup extends NFTnRFT {1477 /**1478 * Get collection object1479 * @param collectionId ID of collection1480 * @example getCollectionObject(2);1481 * @returns instance of UniqueNFTCollection1482 */1483 getCollectionObject(collectionId: number): UniqueNFTCollection {1484 return new UniqueNFTCollection(collectionId, this.helper);1485 }14861487 /**1488 * Get token object1489 * @param collectionId ID of collection1490 * @param tokenId ID of token1491 * @example getTokenObject(10, 5);1492 * @returns instance of UniqueNFTToken1493 */1494 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1495 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1496 }14971498 /**1499 * Get token's owner1500 * @param collectionId ID of collection1501 * @param tokenId ID of token1502 * @param blockHashAt optionally query the data at the block with this hash1503 * @example getTokenOwner(10, 5);1504 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1505 */1506 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1507 let owner;1508 if (typeof blockHashAt === 'undefined') {1509 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1510 } else {1511 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1512 }1513 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1514 }15151516 /**1517 * Is token approved to transfer1518 * @param collectionId ID of collection1519 * @param tokenId ID of token1520 * @param toAccountObj address to be approved1521 * @returns ```true``` if extrinsic success, otherwise ```false```1522 */1523 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1524 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1525 }15261527 /**1528 * Changes the owner of the token.1529 *1530 * @param signer keyring of signer1531 * @param collectionId ID of collection1532 * @param tokenId ID of token1533 * @param addressObj address of a new owner1534 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1535 * @returns ```true``` if extrinsic success, otherwise ```false```1536 */1537 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1538 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1539 }15401541 /**1542 *1543 * Change ownership of a NFT on behalf of the owner.1544 *1545 * @param signer keyring of signer1546 * @param collectionId ID of collection1547 * @param tokenId ID of token1548 * @param fromAddressObj address on behalf of which the token will be sent1549 * @param toAddressObj new token owner1550 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1551 * @returns ```true``` if extrinsic success, otherwise ```false```1552 */1553 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1554 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1555 }15561557 /**1558 * Recursively find the address that owns the token1559 * @param collectionId ID of collection1560 * @param tokenId ID of token1561 * @param blockHashAt1562 * @example getTokenTopmostOwner(10, 5);1563 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1564 */1565 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1566 let owner;1567 if (typeof blockHashAt === 'undefined') {1568 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1569 } else {1570 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1571 }15721573 if (owner === null) return null;15741575 return owner.toHuman();1576 }15771578 /**1579 * Get tokens nested in the provided token1580 * @param collectionId ID of collection1581 * @param tokenId ID of token1582 * @param blockHashAt optionally query the data at the block with this hash1583 * @example getTokenChildren(10, 5);1584 * @returns tokens whose depth of nesting is <= 51585 */1586 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1587 let children;1588 if(typeof blockHashAt === 'undefined') {1589 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1590 } else {1591 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1592 }15931594 return children.toJSON().map((x: any) => {1595 return {collectionId: x.collection, tokenId: x.token};1596 });1597 }15981599 /**1600 * Nest one token into another1601 * @param signer keyring of signer1602 * @param tokenObj token to be nested1603 * @param rootTokenObj token to be parent1604 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1605 * @returns ```true``` if extrinsic success, otherwise ```false```1606 */1607 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1608 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1609 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1610 if(!result) {1611 throw Error('Unable to nest token!');1612 }1613 return result;1614 }16151616 /**1617 * Remove token from nested state1618 * @param signer keyring of signer1619 * @param tokenObj token to unnest1620 * @param rootTokenObj parent of a token1621 * @param toAddressObj address of a new token owner1622 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1623 * @returns ```true``` if extrinsic success, otherwise ```false```1624 */1625 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1626 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1627 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1628 if(!result) {1629 throw Error('Unable to unnest token!');1630 }1631 return result;1632 }16331634 /**1635 * Mint new collection1636 * @param signer keyring of signer1637 * @param collectionOptions Collection options1638 * @example1639 * mintCollection(aliceKeyring, {1640 * name: 'New',1641 * description: 'New collection',1642 * tokenPrefix: 'NEW',1643 * })1644 * @returns object of the created collection1645 */1646 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1647 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1648 }16491650 /**1651 * Mint new token1652 * @param signer keyring of signer1653 * @param data token data1654 * @returns created token object1655 */1656 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1657 const creationResult = await this.helper.executeExtrinsic(1658 signer,1659 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1660 nft: {1661 properties: data.properties,1662 },1663 }],1664 true,1665 );1666 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1667 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1668 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1669 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1670 }16711672 /**1673 * Mint multiple NFT tokens1674 * @param signer keyring of signer1675 * @param collectionId ID of collection1676 * @param tokens array of tokens with owner and properties1677 * @example1678 * mintMultipleTokens(aliceKeyring, 10, [{1679 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1680 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1681 * },{1682 * owner: {Ethereum: "0x9F0583DbB855d..."},1683 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1684 * }]);1685 * @returns ```true``` if extrinsic success, otherwise ```false```1686 */1687 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1688 const creationResult = await this.helper.executeExtrinsic(1689 signer,1690 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1691 true,1692 );1693 const collection = this.getCollectionObject(collectionId);1694 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1695 }16961697 /**1698 * Mint multiple NFT tokens with one owner1699 * @param signer keyring of signer1700 * @param collectionId ID of collection1701 * @param owner tokens owner1702 * @param tokens array of tokens with owner and properties1703 * @example1704 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1705 * properties: [{1706 * key: "gender",1707 * value: "female",1708 * },{1709 * key: "age",1710 * value: "33",1711 * }],1712 * }]);1713 * @returns array of newly created tokens1714 */1715 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1716 const rawTokens = [];1717 for (const token of tokens) {1718 const raw = {NFT: {properties: token.properties}};1719 rawTokens.push(raw);1720 }1721 const creationResult = await this.helper.executeExtrinsic(1722 signer,1723 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1724 true,1725 );1726 const collection = this.getCollectionObject(collectionId);1727 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1728 }17291730 /**1731 * Set, change, or remove approved address to transfer the ownership of the NFT.1732 *1733 * @param signer keyring of signer1734 * @param collectionId ID of collection1735 * @param tokenId ID of token1736 * @param toAddressObj address to approve1737 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1738 * @returns ```true``` if extrinsic success, otherwise ```false```1739 */1740 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1741 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1742 }1743}174417451746class RFTGroup extends NFTnRFT {1747 /**1748 * Get collection object1749 * @param collectionId ID of collection1750 * @example getCollectionObject(2);1751 * @returns instance of UniqueRFTCollection1752 */1753 getCollectionObject(collectionId: number): UniqueRFTCollection {1754 return new UniqueRFTCollection(collectionId, this.helper);1755 }17561757 /**1758 * Get token object1759 * @param collectionId ID of collection1760 * @param tokenId ID of token1761 * @example getTokenObject(10, 5);1762 * @returns instance of UniqueNFTToken1763 */1764 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1765 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1766 }17671768 /**1769 * Get top 10 token owners with the largest number of pieces1770 * @param collectionId ID of collection1771 * @param tokenId ID of token1772 * @example getTokenTop10Owners(10, 5);1773 * @returns array of top 10 owners1774 */1775 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1776 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1777 }17781779 /**1780 * Get number of pieces owned by address1781 * @param collectionId ID of collection1782 * @param tokenId ID of token1783 * @param addressObj address token owner1784 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1785 * @returns number of pieces ownerd by address1786 */1787 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1788 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1789 }17901791 /**1792 * Transfer pieces of token to another address1793 * @param signer keyring of signer1794 * @param collectionId ID of collection1795 * @param tokenId ID of token1796 * @param addressObj address of a new owner1797 * @param amount number of pieces to be transfered1798 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1799 * @returns ```true``` if extrinsic success, otherwise ```false```1800 */1801 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1802 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1803 }18041805 /**1806 * Change ownership of some pieces of RFT on behalf of the owner.1807 * @param signer keyring of signer1808 * @param collectionId ID of collection1809 * @param tokenId ID of token1810 * @param fromAddressObj address on behalf of which the token will be sent1811 * @param toAddressObj new token owner1812 * @param amount number of pieces to be transfered1813 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1814 * @returns ```true``` if extrinsic success, otherwise ```false```1815 */1816 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1817 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1818 }18191820 /**1821 * Mint new collection1822 * @param signer keyring of signer1823 * @param collectionOptions Collection options1824 * @example1825 * mintCollection(aliceKeyring, {1826 * name: 'New',1827 * description: 'New collection',1828 * tokenPrefix: 'NEW',1829 * })1830 * @returns object of the created collection1831 */1832 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1833 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1834 }18351836 /**1837 * Mint new token1838 * @param signer keyring of signer1839 * @param data token data1840 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1841 * @returns created token object1842 */1843 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1844 const creationResult = await this.helper.executeExtrinsic(1845 signer,1846 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1847 refungible: {1848 pieces: data.pieces,1849 properties: data.properties,1850 },1851 }],1852 true,1853 );1854 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1855 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1856 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1857 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1858 }18591860 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1861 throw Error('Not implemented');1862 const creationResult = await this.helper.executeExtrinsic(1863 signer,1864 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1865 true, // `Unable to mint RFT tokens for ${label}`,1866 );1867 const collection = this.getCollectionObject(collectionId);1868 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1869 }18701871 /**1872 * Mint multiple RFT tokens with one owner1873 * @param signer keyring of signer1874 * @param collectionId ID of collection1875 * @param owner tokens owner1876 * @param tokens array of tokens with properties and pieces1877 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1878 * @returns array of newly created RFT tokens1879 */1880 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1881 const rawTokens = [];1882 for (const token of tokens) {1883 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1884 rawTokens.push(raw);1885 }1886 const creationResult = await this.helper.executeExtrinsic(1887 signer,1888 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1889 true,1890 );1891 const collection = this.getCollectionObject(collectionId);1892 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1893 }18941895 /**1896 * Destroys a concrete instance of RFT.1897 * @param signer keyring of signer1898 * @param collectionId ID of collection1899 * @param tokenId ID of token1900 * @param amount number of pieces to be burnt1901 * @example burnToken(aliceKeyring, 10, 5);1902 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1903 */1904 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1905 return await super.burnToken(signer, collectionId, tokenId, amount);1906 }19071908 /**1909 * Destroys a concrete instance of RFT on behalf of the owner.1910 * @param signer keyring of signer1911 * @param collectionId ID of collection1912 * @param tokenId ID of token1913 * @param fromAddressObj address on behalf of which the token will be burnt1914 * @param amount number of pieces to be burnt1915 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1916 * @returns ```true``` if extrinsic success, otherwise ```false```1917 */1918 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1919 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1920 }19211922 /**1923 * Set, change, or remove approved address to transfer the ownership of the RFT.1924 *1925 * @param signer keyring of signer1926 * @param collectionId ID of collection1927 * @param tokenId ID of token1928 * @param toAddressObj address to approve1929 * @param amount number of pieces to be approved1930 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1931 * @returns true if the token success, otherwise false1932 */1933 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1934 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1935 }19361937 /**1938 * Get total number of pieces1939 * @param collectionId ID of collection1940 * @param tokenId ID of token1941 * @example getTokenTotalPieces(10, 5);1942 * @returns number of pieces1943 */1944 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1945 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1946 }19471948 /**1949 * Change number of token pieces. Signer must be the owner of all token pieces.1950 * @param signer keyring of signer1951 * @param collectionId ID of collection1952 * @param tokenId ID of token1953 * @param amount new number of pieces1954 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1955 * @returns true if the repartion was success, otherwise false1956 */1957 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1958 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1959 const repartitionResult = await this.helper.executeExtrinsic(1960 signer,1961 'api.tx.unique.repartition', [collectionId, tokenId, amount],1962 true,1963 );1964 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1965 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1966 }1967}196819691970class FTGroup extends CollectionGroup {1971 /**1972 * Get collection object1973 * @param collectionId ID of collection1974 * @example getCollectionObject(2);1975 * @returns instance of UniqueFTCollection1976 */1977 getCollectionObject(collectionId: number): UniqueFTCollection {1978 return new UniqueFTCollection(collectionId, this.helper);1979 }19801981 /**1982 * Mint new fungible collection1983 * @param signer keyring of signer1984 * @param collectionOptions Collection options1985 * @param decimalPoints number of token decimals1986 * @example1987 * mintCollection(aliceKeyring, {1988 * name: 'New',1989 * description: 'New collection',1990 * tokenPrefix: 'NEW',1991 * }, 18)1992 * @returns newly created fungible collection1993 */1994 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1995 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1996 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1997 collectionOptions.mode = {fungible: decimalPoints};1998 for (const key of ['name', 'description', 'tokenPrefix']) {1999 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);2000 }2001 const creationResult = await this.helper.executeExtrinsic(2002 signer,2003 'api.tx.unique.createCollectionEx', [collectionOptions],2004 true,2005 );2006 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2007 }20082009 /**2010 * Mint tokens2011 * @param signer keyring of signer2012 * @param collectionId ID of collection2013 * @param owner address owner of new tokens2014 * @param amount amount of tokens to be meanted2015 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2016 * @returns ```true``` if extrinsic success, otherwise ```false```2017 */2018 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2019 const creationResult = await this.helper.executeExtrinsic(2020 signer,2021 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2022 fungible: {2023 value: amount,2024 },2025 }],2026 true, // `Unable to mint fungible tokens for ${label}`,2027 );2028 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2029 }20302031 /**2032 * Mint multiple Fungible tokens with one owner2033 * @param signer keyring of signer2034 * @param collectionId ID of collection2035 * @param owner tokens owner2036 * @param tokens array of tokens with properties and pieces2037 * @returns ```true``` if extrinsic success, otherwise ```false```2038 */2039 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2040 const rawTokens = [];2041 for (const token of tokens) {2042 const raw = {Fungible: {Value: token.value}};2043 rawTokens.push(raw);2044 }2045 const creationResult = await this.helper.executeExtrinsic(2046 signer,2047 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2048 true,2049 );2050 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2051 }20522053 /**2054 * Get the top 10 owners with the largest balance for the Fungible collection2055 * @param collectionId ID of collection2056 * @example getTop10Owners(10);2057 * @returns array of ```ICrossAccountId```2058 */2059 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2060 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2061 }20622063 /**2064 * Get account balance2065 * @param collectionId ID of collection2066 * @param addressObj address of owner2067 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2068 * @returns amount of fungible tokens owned by address2069 */2070 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2071 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2072 }20732074 /**2075 * Transfer tokens to address2076 * @param signer keyring of signer2077 * @param collectionId ID of collection2078 * @param toAddressObj address recipient2079 * @param amount amount of tokens to be sent2080 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2081 * @returns ```true``` if extrinsic success, otherwise ```false```2082 */2083 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2084 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2085 }20862087 /**2088 * Transfer some tokens on behalf of the owner.2089 * @param signer keyring of signer2090 * @param collectionId ID of collection2091 * @param fromAddressObj address on behalf of which tokens will be sent2092 * @param toAddressObj address where token to be sent2093 * @param amount number of tokens to be sent2094 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2095 * @returns ```true``` if extrinsic success, otherwise ```false```2096 */2097 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2098 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2099 }21002101 /**2102 * Destroy some amount of tokens2103 * @param signer keyring of signer2104 * @param collectionId ID of collection2105 * @param amount amount of tokens to be destroyed2106 * @example burnTokens(aliceKeyring, 10, 1000n);2107 * @returns ```true``` if extrinsic success, otherwise ```false```2108 */2109 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2110 return await super.burnToken(signer, collectionId, 0, amount);2111 }21122113 /**2114 * Burn some tokens on behalf of the owner.2115 * @param signer keyring of signer2116 * @param collectionId ID of collection2117 * @param fromAddressObj address on behalf of which tokens will be burnt2118 * @param amount amount of tokens to be burnt2119 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2120 * @returns ```true``` if extrinsic success, otherwise ```false```2121 */2122 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2123 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2124 }21252126 /**2127 * Get total collection supply2128 * @param collectionId2129 * @returns2130 */2131 async getTotalPieces(collectionId: number): Promise<bigint> {2132 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2133 }21342135 /**2136 * Set, change, or remove approved address to transfer tokens.2137 *2138 * @param signer keyring of signer2139 * @param collectionId ID of collection2140 * @param toAddressObj address to be approved2141 * @param amount amount of tokens to be approved2142 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2143 * @returns ```true``` if extrinsic success, otherwise ```false```2144 */2145 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2146 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2147 }21482149 /**2150 * Get amount of fungible tokens approved to transfer2151 * @param collectionId ID of collection2152 * @param fromAddressObj owner of tokens2153 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2154 * @returns number of tokens approved for the transfer2155 */2156 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2157 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2158 }2159}216021612162class ChainGroup extends HelperGroup<ChainHelperBase> {2163 /**2164 * Get system properties of a chain2165 * @example getChainProperties();2166 * @returns ss58Format, token decimals, and token symbol2167 */2168 getChainProperties(): IChainProperties {2169 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2170 return {2171 ss58Format: properties.ss58Format.toJSON(),2172 tokenDecimals: properties.tokenDecimals.toJSON(),2173 tokenSymbol: properties.tokenSymbol.toJSON(),2174 };2175 }21762177 /**2178 * Get chain header2179 * @example getLatestBlockNumber();2180 * @returns the number of the last block2181 */2182 async getLatestBlockNumber(): Promise<number> {2183 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2184 }21852186 /**2187 * Get block hash by block number2188 * @param blockNumber number of block2189 * @example getBlockHashByNumber(12345);2190 * @returns hash of a block2191 */2192 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2193 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2194 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2195 return blockHash;2196 }21972198 // TODO add docs2199 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2200 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2201 if (!blockHash) return null;2202 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2203 }22042205 /**2206 * Get account nonce2207 * @param address substrate address2208 * @example getNonce("5GrwvaEF5zXb26Fz...");2209 * @returns number, account's nonce2210 */2211 async getNonce(address: TSubstrateAccount): Promise<number> {2212 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2213 }2214}22152216class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2217 /**2218 * Get substrate address balance2219 * @param address substrate address2220 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2221 * @returns amount of tokens on address2222 */2223 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2224 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2225 }22262227 /**2228 * Transfer tokens to substrate address2229 * @param signer keyring of signer2230 * @param address substrate address of a recipient2231 * @param amount amount of tokens to be transfered2232 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2233 * @returns ```true``` if extrinsic success, otherwise ```false```2234 */2235 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2236 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}`*/);22372238 let transfer = {from: null, to: null, amount: 0n} as any;2239 result.result.events.forEach(({event: {data, method, section}}) => {2240 if ((section === 'balances') && (method === 'Transfer')) {2241 transfer = {2242 from: this.helper.address.normalizeSubstrate(data[0]),2243 to: this.helper.address.normalizeSubstrate(data[1]),2244 amount: BigInt(data[2]),2245 };2246 }2247 });2248 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2249 && this.helper.address.normalizeSubstrate(address) === transfer.to2250 && BigInt(amount) === transfer.amount;2251 return isSuccess;2252 }22532254 /**2255 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2256 * @param address substrate address2257 * @returns2258 */2259 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2260 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2261 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2262 }2263}22642265class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2266 /**2267 * Get ethereum address balance2268 * @param address ethereum address2269 * @example getEthereum("0x9F0583DbB855d...")2270 * @returns amount of tokens on address2271 */2272 async getEthereum(address: TEthereumAccount): Promise<bigint> {2273 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2274 }22752276 /**2277 * Transfer tokens to address2278 * @param signer keyring of signer2279 * @param address Ethereum address of a recipient2280 * @param amount amount of tokens to be transfered2281 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2282 * @returns ```true``` if extrinsic success, otherwise ```false```2283 */2284 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2285 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22862287 let transfer = {from: null, to: null, amount: 0n} as any;2288 result.result.events.forEach(({event: {data, method, section}}) => {2289 if ((section === 'balances') && (method === 'Transfer')) {2290 transfer = {2291 from: data[0].toString(),2292 to: data[1].toString(),2293 amount: BigInt(data[2]),2294 };2295 }2296 });2297 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2298 && address === transfer.to2299 && BigInt(amount) === transfer.amount;2300 return isSuccess;2301 }2302}23032304class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2305 subBalanceGroup: SubstrateBalanceGroup<T>;2306 ethBalanceGroup: EthereumBalanceGroup<T>;23072308 constructor(helper: T) {2309 super(helper);2310 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2311 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2312 }23132314 getCollectionCreationPrice(): bigint {2315 return 2n * this.getOneTokenNominal();2316 }2317 /**2318 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2319 * @example getOneTokenNominal()2320 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2321 */2322 getOneTokenNominal(): bigint {2323 const chainProperties = this.helper.chain.getChainProperties();2324 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2325 }23262327 /**2328 * Get substrate address balance2329 * @param address substrate address2330 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2331 * @returns amount of tokens on address2332 */2333 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2334 return this.subBalanceGroup.getSubstrate(address);2335 }23362337 /**2338 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2339 * @param address substrate address2340 * @returns2341 */2342 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2343 return this.subBalanceGroup.getSubstrateFull(address);2344 }23452346 /**2347 * Get ethereum address balance2348 * @param address ethereum address2349 * @example getEthereum("0x9F0583DbB855d...")2350 * @returns amount of tokens on address2351 */2352 getEthereum(address: TEthereumAccount): Promise<bigint> {2353 return this.ethBalanceGroup.getEthereum(address);2354 }23552356 /**2357 * Transfer tokens to substrate address2358 * @param signer keyring of signer2359 * @param address substrate address of a recipient2360 * @param amount amount of tokens to be transfered2361 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2362 * @returns ```true``` if extrinsic success, otherwise ```false```2363 */2364 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2365 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2366 }23672368 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2369 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);23702371 let transfer = {from: null, to: null, amount: 0n} as any;2372 result.result.events.forEach(({event: {data, method, section}}) => {2373 if ((section === 'balances') && (method === 'Transfer')) {2374 transfer = {2375 from: this.helper.address.normalizeSubstrate(data[0]),2376 to: this.helper.address.normalizeSubstrate(data[1]),2377 amount: BigInt(data[2]),2378 };2379 }2380 });2381 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2382 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2383 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2384 return isSuccess;2385 }2386}23872388class AddressGroup extends HelperGroup<ChainHelperBase> {2389 /**2390 * Normalizes the address to the specified ss58 format, by default ```42```.2391 * @param address substrate address2392 * @param ss58Format format for address conversion, by default ```42```2393 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2394 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2395 */2396 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2397 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2398 }23992400 /**2401 * Get address in the connected chain format2402 * @param address substrate address2403 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2404 * @returns address in chain format2405 */2406 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2407 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2408 }24092410 /**2411 * Get substrate mirror of an ethereum address2412 * @param ethAddress ethereum address2413 * @param toChainFormat false for normalized account2414 * @example ethToSubstrate('0x9F0583DbB855d...')2415 * @returns substrate mirror of a provided ethereum address2416 */2417 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2418 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2419 }24202421 /**2422 * Get ethereum mirror of a substrate address2423 * @param subAddress substrate account2424 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2425 * @returns ethereum mirror of a provided substrate address2426 */2427 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2428 return CrossAccountId.translateSubToEth(subAddress);2429 }24302431 /**2432 * Encode key to substrate address2433 * @param key key for encoding address2434 * @param ss58Format prefix for encoding to the address of the corresponding network2435 * @returns encoded substrate address2436 */2437 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2438 const u8a :Uint8Array = typeof key === 'string'2439 ? hexToU8a(key)2440 : typeof key === 'bigint'2441 ? hexToU8a(key.toString(16))2442 : key;2443 2444 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2445 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2446 }2447 2448 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2449 if (!allowedDecodedLengths.includes(u8a.length)) {2450 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2451 }2452 2453 const u8aPrefix = ss58Format < 642454 ? new Uint8Array([ss58Format])2455 : new Uint8Array([2456 ((ss58Format & 0xfc) >> 2) | 0x40,2457 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2458 ]);24592460 const input = u8aConcat(u8aPrefix, u8a);2461 2462 return base58Encode(u8aConcat(2463 input,2464 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2465 ));2466 }24672468 /**2469 * Restore substrate address from bigint representation2470 * @param number decimal representation of substrate address2471 * @returns substrate address2472 */2473 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2474 if (this.helper.api === null) {2475 throw 'Not connected';2476 }2477 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2478 if (res === undefined || res === null) {2479 throw 'Restore address error';2480 }2481 return res.toString();2482 }24832484 /**2485 * Convert etherium cross account id to substrate cross account id2486 * @param ethCrossAccount etherium cross account2487 * @returns substrate cross account id2488 */2489 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2490 if (ethCrossAccount.sub === '0') {2491 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2492 }2493 2494 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2495 return {Substrate: ss58};2496 }24972498 paraSiblingSovereignAccount(paraid: number) {2499 // We are getting a *sibling* parachain sovereign account,2500 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2501 const siblingPrefix = '0x7369626c';25022503 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2504 const suffix = '000000000000000000000000000000000000000000000000';25052506 return siblingPrefix + encodedParaId + suffix;2507 }2508}25092510class StakingGroup extends HelperGroup<UniqueHelper> {2511 /**2512 * Stake tokens for App Promotion2513 * @param signer keyring of signer2514 * @param amountToStake amount of tokens to stake2515 * @param label extra label for log2516 * @returns2517 */2518 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2519 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2520 const _stakeResult = await this.helper.executeExtrinsic(2521 signer, 'api.tx.appPromotion.stake',2522 [amountToStake], true,2523 );2524 // TODO extract info from stakeResult2525 return true;2526 }25272528 /**2529 * Unstake tokens for App Promotion2530 * @param signer keyring of signer2531 * @param amountToUnstake amount of tokens to unstake2532 * @param label extra label for log2533 * @returns block number where balances will be unlocked2534 */2535 async unstake(signer: TSigner, label?: string): Promise<number> {2536 if(typeof label === 'undefined') label = `${signer.address}`;2537 const _unstakeResult = await this.helper.executeExtrinsic(2538 signer, 'api.tx.appPromotion.unstake',2539 [], true,2540 );2541 // TODO extract block number fron events2542 return 1;2543 }25442545 /**2546 * Get total staked amount for address2547 * @param address substrate or ethereum address2548 * @returns total staked amount2549 */2550 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2551 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2552 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2553 }25542555 /**2556 * Get total staked per block2557 * @param address substrate or ethereum address2558 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2559 */2560 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2561 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2562 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2563 return {2564 block: block.toBigInt(),2565 amount: amount.toBigInt(),2566 };2567 });2568 }25692570 /**2571 * Get total pending unstake amount for address2572 * @param address substrate or ethereum address2573 * @returns total pending unstake amount2574 */2575 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2576 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2577 }25782579 /**2580 * Get pending unstake amount per block for address2581 * @param address substrate or ethereum address2582 * @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 block2583 */2584 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2585 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2586 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2587 return {2588 block: block.toBigInt(),2589 amount: amount.toBigInt(),2590 };2591 });2592 return result;2593 }2594}25952596class SchedulerGroup extends HelperGroup<UniqueHelper> {2597 constructor(helper: UniqueHelper) {2598 super(helper);2599 }26002601 cancelScheduled(signer: TSigner, scheduledId: string) {2602 return this.helper.executeExtrinsic(2603 signer,2604 'api.tx.scheduler.cancelNamed',2605 [scheduledId],2606 true,2607 );2608 }26092610 changePriority(signer: TSigner, scheduledId: string, priority: number) {2611 return this.helper.executeExtrinsic(2612 signer,2613 'api.tx.scheduler.changeNamedPriority',2614 [scheduledId, priority],2615 true,2616 );2617 }26182619 scheduleAt<T extends UniqueHelper>(2620 executionBlockNumber: number,2621 options: ISchedulerOptions = {},2622 ) {2623 return this.schedule<T>('schedule', executionBlockNumber, options);2624 }26252626 scheduleAfter<T extends UniqueHelper>(2627 blocksBeforeExecution: number,2628 options: ISchedulerOptions = {},2629 ) {2630 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2631 }26322633 schedule<T extends UniqueHelper>(2634 scheduleFn: 'schedule' | 'scheduleAfter',2635 blocksNum: number,2636 options: ISchedulerOptions = {},2637 ) {2638 // eslint-disable-next-line @typescript-eslint/naming-convention2639 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2640 return this.helper.clone(ScheduledHelperType, {2641 scheduleFn,2642 blocksNum,2643 options,2644 }) as T;2645 }2646}26472648class SessionGroup extends HelperGroup<ChainHelperBase> {2649 //todo:collator documentation2650 async getIndex(): Promise<number> {2651 return (await this.helper.callRpc('api.query.session.currentIndex')).toNumber();2652 }26532654 newSessions(sessionCount = 1, blockTimeout = 24000): Promise<void> {2655 return (this.helper as DevUniqueHelper).wait.newSessions(sessionCount, blockTimeout);2656 }26572658 setOwnKeys(signer: TSigner, key: string) {2659 return this.helper.executeExtrinsic(2660 signer,2661 'api.tx.session.setKeys', 2662 [key, '0x0'],2663 true,2664 );2665 }26662667 setOwnKeysFromAddress(signer: TSigner) {2668 return this.setOwnKeys(signer, '0x' + Buffer.from(signer.addressRaw).toString('hex'));2669 }2670}26712672class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2673 //todo:collator documentation2674 addInvulnerable(signer: TSigner, address: string) {2675 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2676 }26772678 removeInvulnerable(signer: TSigner, address: string) {2679 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2680 }26812682 async getInvulnerables(): Promise<string[]> {2683 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2684 }26852686 setLicenseBond(signer: TSigner, amount: bigint) {2687 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.setLicenseBond', [amount]);2688 }26892690 async getLicenseBond(): Promise<bigint> {2691 return (await this.helper.callRpc('api.query.collatorSelection.licenseBond')).toBigInt();2692 }26932694 obtainLicense(signer: TSigner) {2695 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2696 }26972698 releaseLicense(signer: TSigner) {2699 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2700 }27012702 forceRevokeLicense(signer: TSigner, released: string) {2703 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceRevokeLicense', [released]);2704 }27052706 async hasLicense(address: string): Promise<bigint> {2707 return (await this.helper.callRpc('api.query.collatorSelection.licenses', [address])).toBigInt();2708 }27092710 onboard(signer: TSigner) {2711 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2712 }27132714 offboard(signer: TSigner) {2715 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2716 }27172718 async getCandidates(): Promise<string[]> {2719 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2720 }2721}27222723class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2724 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2725 await this.helper.executeExtrinsic(2726 signer,2727 'api.tx.foreignAssets.registerForeignAsset',2728 [ownerAddress, location, metadata],2729 true,2730 );2731 }27322733 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2734 await this.helper.executeExtrinsic(2735 signer,2736 'api.tx.foreignAssets.updateForeignAsset',2737 [foreignAssetId, location, metadata],2738 true,2739 );2740 }2741}27422743class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2744 palletName: string;27452746 constructor(helper: T, palletName: string) {2747 super(helper);27482749 this.palletName = palletName;2750 }27512752 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2753 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2754 }2755}27562757class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2758 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2759 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2760 }27612762 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2763 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2764 }27652766 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2767 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2768 }2769}27702771class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2772 async accounts(address: string, currencyId: any) {2773 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2774 return BigInt(free);2775 }2776}27772778class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2779 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2780 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2781 }27822783 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2784 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2785 }27862787 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2788 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2789 }27902791 async account(assetId: string | number, address: string) {2792 const accountAsset = (2793 await this.helper.callRpc('api.query.assets.account', [assetId, address])2794 ).toJSON()! as any;27952796 if (accountAsset !== null) {2797 return BigInt(accountAsset['balance']);2798 } else {2799 return null;2800 }2801 }2802}28032804class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2805 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2806 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2807 }2808}28092810class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2811 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2812 const apiPrefix = 'api.tx.assetManager.';28132814 const registerTx = this.helper.constructApiCall(2815 apiPrefix + 'registerForeignAsset',2816 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2817 );28182819 const setUnitsTx = this.helper.constructApiCall(2820 apiPrefix + 'setAssetUnitsPerSecond',2821 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2822 );28232824 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2825 const encodedProposal = batchCall?.method.toHex() || '';2826 return encodedProposal;2827 }28282829 async assetTypeId(location: any) {2830 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2831 }2832}28332834class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2835 async notePreimage(signer: TSigner, encodedProposal: string) {2836 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2837 }28382839 externalProposeMajority(proposalHash: string) {2840 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2841 }28422843 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2844 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2845 }28462847 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2848 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2849 }2850}28512852class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2853 collective: string;28542855 constructor(helper: MoonbeamHelper, collective: string) {2856 super(helper);28572858 this.collective = collective;2859 }28602861 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2862 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2863 }28642865 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2866 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2867 }28682869 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2870 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2871 }28722873 async proposalCount() {2874 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2875 }2876}28772878export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2879export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;28802881export class UniqueHelper extends ChainHelperBase {2882 balance: BalanceGroup<UniqueHelper>;2883 collection: CollectionGroup;2884 nft: NFTGroup;2885 rft: RFTGroup;2886 ft: FTGroup;2887 staking: StakingGroup;2888 scheduler: SchedulerGroup;2889 collatorSelection: CollatorSelectionGroup;2890 foreignAssets: ForeignAssetsGroup;2891 xcm: XcmGroup<UniqueHelper>;2892 xTokens: XTokensGroup<UniqueHelper>;2893 tokens: TokensGroup<UniqueHelper>;28942895 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2896 super(logger, options.helperBase ?? UniqueHelper);28972898 this.balance = new BalanceGroup(this);2899 this.collection = new CollectionGroup(this);2900 this.nft = new NFTGroup(this);2901 this.rft = new RFTGroup(this);2902 this.ft = new FTGroup(this);2903 this.staking = new StakingGroup(this);2904 this.scheduler = new SchedulerGroup(this);2905 this.collatorSelection = new CollatorSelectionGroup(this);2906 this.foreignAssets = new ForeignAssetsGroup(this);2907 this.xcm = new XcmGroup(this, 'polkadotXcm');2908 this.xTokens = new XTokensGroup(this);2909 this.tokens = new TokensGroup(this);2910 }29112912 getSudo<T extends UniqueHelper>() {2913 // eslint-disable-next-line @typescript-eslint/naming-convention2914 const SudoHelperType = SudoHelper(this.helperBase);2915 return this.clone(SudoHelperType) as T;2916 }2917}29182919export class XcmChainHelper extends ChainHelperBase {2920 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2921 const wsProvider = new WsProvider(wsEndpoint);2922 this.api = new ApiPromise({2923 provider: wsProvider,2924 });2925 await this.api.isReadyOrError;2926 this.network = await UniqueHelper.detectNetwork(this.api);2927 }2928}29292930export class RelayHelper extends XcmChainHelper {2931 xcm: XcmGroup<RelayHelper>;29322933 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2934 super(logger, options.helperBase ?? RelayHelper);29352936 this.xcm = new XcmGroup(this, 'xcmPallet');2937 }2938}29392940export class WestmintHelper extends XcmChainHelper {2941 balance: SubstrateBalanceGroup<WestmintHelper>;2942 xcm: XcmGroup<WestmintHelper>;2943 assets: AssetsGroup<WestmintHelper>;2944 xTokens: XTokensGroup<WestmintHelper>;29452946 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2947 super(logger, options.helperBase ?? WestmintHelper);29482949 this.balance = new SubstrateBalanceGroup(this);2950 this.xcm = new XcmGroup(this, 'polkadotXcm');2951 this.assets = new AssetsGroup(this);2952 this.xTokens = new XTokensGroup(this);2953 }2954}29552956export class MoonbeamHelper extends XcmChainHelper {2957 balance: EthereumBalanceGroup<MoonbeamHelper>;2958 assetManager: MoonbeamAssetManagerGroup;2959 assets: AssetsGroup<MoonbeamHelper>;2960 xTokens: XTokensGroup<MoonbeamHelper>;2961 democracy: MoonbeamDemocracyGroup;2962 collective: {2963 council: MoonbeamCollectiveGroup,2964 techCommittee: MoonbeamCollectiveGroup,2965 };29662967 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2968 super(logger, options.helperBase ?? MoonbeamHelper);29692970 this.balance = new EthereumBalanceGroup(this);2971 this.assetManager = new MoonbeamAssetManagerGroup(this);2972 this.assets = new AssetsGroup(this);2973 this.xTokens = new XTokensGroup(this);2974 this.democracy = new MoonbeamDemocracyGroup(this);2975 this.collective = {2976 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2977 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2978 };2979 }2980}29812982export class AcalaHelper extends XcmChainHelper {2983 balance: SubstrateBalanceGroup<AcalaHelper>;2984 assetRegistry: AcalaAssetRegistryGroup;2985 xTokens: XTokensGroup<AcalaHelper>;2986 tokens: TokensGroup<AcalaHelper>;29872988 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2989 super(logger, options.helperBase ?? AcalaHelper);29902991 this.balance = new SubstrateBalanceGroup(this);2992 this.assetRegistry = new AcalaAssetRegistryGroup(this);2993 this.xTokens = new XTokensGroup(this);2994 this.tokens = new TokensGroup(this);2995 }29962997 getSudo<T extends AcalaHelper>() {2998 // eslint-disable-next-line @typescript-eslint/naming-convention2999 const SudoHelperType = SudoHelper(this.helperBase);3000 return this.clone(SudoHelperType) as T;3001 }3002}30033004// eslint-disable-next-line @typescript-eslint/naming-convention3005function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3006 return class extends Base {3007 scheduleFn: 'schedule' | 'scheduleAfter';3008 blocksNum: number;3009 options: ISchedulerOptions;30103011 constructor(...args: any[]) {3012 const logger = args[0] as ILogger;3013 const options = args[1] as {3014 scheduleFn: 'schedule' | 'scheduleAfter',3015 blocksNum: number,3016 options: ISchedulerOptions3017 };30183019 super(logger);30203021 this.scheduleFn = options.scheduleFn;3022 this.blocksNum = options.blocksNum;3023 this.options = options.options;3024 }30253026 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3027 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);3028 3029 const mandatorySchedArgs = [3030 this.blocksNum,3031 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3032 this.options.priority ?? null,3033 scheduledTx,3034 ];3035 3036 let schedArgs;3037 let scheduleFn;30383039 if (this.options.scheduledId) {3040 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];30413042 if (this.scheduleFn == 'schedule') {3043 scheduleFn = 'scheduleNamed';3044 } else if (this.scheduleFn == 'scheduleAfter') {3045 scheduleFn = 'scheduleNamedAfter';3046 }3047 } else {3048 schedArgs = mandatorySchedArgs;3049 scheduleFn = this.scheduleFn;3050 }30513052 const extrinsic = 'api.tx.scheduler.' + scheduleFn;30533054 return super.executeExtrinsic(3055 sender,3056 extrinsic,3057 schedArgs,3058 expectSuccess,3059 );3060 }3061 };3062}30633064// eslint-disable-next-line @typescript-eslint/naming-convention3065function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3066 return class extends Base {3067 constructor(...args: any[]) {3068 super(...args);3069 }30703071 async executeExtrinsic(3072 sender: IKeyringPair,3073 extrinsic: string,3074 params: any[],3075 expectSuccess?: boolean,3076 options: Partial<SignerOptions>|null = null,3077 ): Promise<ITransactionResult> {3078 const call = this.constructApiCall(extrinsic, params);3079 const result = await super.executeExtrinsic(3080 sender,3081 'api.tx.sudo.sudo',3082 [call],3083 expectSuccess,3084 options,3085 );30863087 if (result.status === 'Fail') return result;30883089 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3090 if (data.isErr) {3091 if (data.asErr.isModule) {3092 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3093 const metaError = super.getApi()?.registry.findMetaError(error);3094 throw new Error(`${metaError.section}.${metaError.name}`);3095 } else {3096 throw new Error(data.asErr.toHuman());3097 }3098 }3099 return result;3100 }3101 };3102}31033104export class UniqueBaseCollection {3105 helper: UniqueHelper;3106 collectionId: number;31073108 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3109 this.collectionId = collectionId;3110 this.helper = uniqueHelper;3111 }31123113 async getData() {3114 return await this.helper.collection.getData(this.collectionId);3115 }31163117 async getLastTokenId() {3118 return await this.helper.collection.getLastTokenId(this.collectionId);3119 }31203121 async doesTokenExist(tokenId: number) {3122 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3123 }31243125 async getAdmins() {3126 return await this.helper.collection.getAdmins(this.collectionId);3127 }31283129 async getAllowList() {3130 return await this.helper.collection.getAllowList(this.collectionId);3131 }31323133 async getEffectiveLimits() {3134 return await this.helper.collection.getEffectiveLimits(this.collectionId);3135 }31363137 async getProperties(propertyKeys?: string[] | null) {3138 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3139 }31403141 async getPropertiesConsumedSpace() {3142 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3143 }31443145 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3146 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3147 }31483149 async getOptions() {3150 return await this.helper.collection.getCollectionOptions(this.collectionId);3151 }31523153 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3154 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3155 }31563157 async confirmSponsorship(signer: TSigner) {3158 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3159 }31603161 async removeSponsor(signer: TSigner) {3162 return await this.helper.collection.removeSponsor(signer, this.collectionId);3163 }31643165 async setLimits(signer: TSigner, limits: ICollectionLimits) {3166 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3167 }31683169 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3170 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3171 }31723173 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3174 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3175 }31763177 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3178 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3179 }31803181 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3182 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3183 }31843185 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3186 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3187 }31883189 async setProperties(signer: TSigner, properties: IProperty[]) {3190 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3191 }31923193 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3194 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3195 }31963197 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3198 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3199 }32003201 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3202 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3203 }32043205 async disableNesting(signer: TSigner) {3206 return await this.helper.collection.disableNesting(signer, this.collectionId);3207 }32083209 async burn(signer: TSigner) {3210 return await this.helper.collection.burn(signer, this.collectionId);3211 }32123213 scheduleAt<T extends UniqueHelper>(3214 executionBlockNumber: number,3215 options: ISchedulerOptions = {},3216 ) {3217 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3218 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3219 }32203221 scheduleAfter<T extends UniqueHelper>(3222 blocksBeforeExecution: number,3223 options: ISchedulerOptions = {},3224 ) {3225 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3226 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3227 }32283229 getSudo<T extends UniqueHelper>() {3230 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3231 }3232}323332343235export class UniqueNFTCollection extends UniqueBaseCollection {3236 getTokenObject(tokenId: number) {3237 return new UniqueNFToken(tokenId, this);3238 }32393240 async getTokensByAddress(addressObj: ICrossAccountId) {3241 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3242 }32433244 async getToken(tokenId: number, blockHashAt?: string) {3245 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3246 }32473248 async getTokenOwner(tokenId: number, blockHashAt?: string) {3249 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3250 }32513252 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3253 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3254 }32553256 async getTokenChildren(tokenId: number, blockHashAt?: string) {3257 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3258 }32593260 async getPropertyPermissions(propertyKeys: string[] | null = null) {3261 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3262 }32633264 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3265 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3266 }32673268 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3269 const api = this.helper.getApi();3270 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();3271 3272 return (props! as any).consumedSpace;3273 }32743275 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3276 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3277 }32783279 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3280 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3281 }32823283 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3284 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3285 }32863287 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3288 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3289 }32903291 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3292 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3293 }32943295 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3296 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3297 }32983299 async burnToken(signer: TSigner, tokenId: number) {3300 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3301 }33023303 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3304 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3305 }33063307 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3308 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3309 }33103311 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3312 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3313 }33143315 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3316 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3317 }33183319 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3320 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3321 }33223323 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3324 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3325 }33263327 scheduleAt<T extends UniqueHelper>(3328 executionBlockNumber: number,3329 options: ISchedulerOptions = {},3330 ) {3331 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3332 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3333 }33343335 scheduleAfter<T extends UniqueHelper>(3336 blocksBeforeExecution: number,3337 options: ISchedulerOptions = {},3338 ) {3339 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3340 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3341 }33423343 getSudo<T extends UniqueHelper>() {3344 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3345 }3346}334733483349export class UniqueRFTCollection extends UniqueBaseCollection {3350 getTokenObject(tokenId: number) {3351 return new UniqueRFToken(tokenId, this);3352 }33533354 async getToken(tokenId: number, blockHashAt?: string) {3355 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3356 }33573358 async getTokensByAddress(addressObj: ICrossAccountId) {3359 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3360 }33613362 async getTop10TokenOwners(tokenId: number) {3363 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3364 }33653366 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3367 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3368 }33693370 async getTokenTotalPieces(tokenId: number) {3371 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3372 }33733374 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3375 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3376 }33773378 async getPropertyPermissions(propertyKeys: string[] | null = null) {3379 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3380 }33813382 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3383 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3384 }33853386 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3387 const api = this.helper.getApi();3388 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();3389 3390 return (props! as any).consumedSpace;3391 }33923393 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3394 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3395 }33963397 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3398 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3399 }34003401 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3402 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3403 }34043405 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3406 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3407 }34083409 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3410 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3411 }34123413 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3414 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3415 }34163417 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3418 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3419 }34203421 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3422 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3423 }34243425 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3426 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3427 }34283429 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3430 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3431 }34323433 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3434 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3435 }34363437 scheduleAt<T extends UniqueHelper>(3438 executionBlockNumber: number,3439 options: ISchedulerOptions = {},3440 ) {3441 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3442 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3443 }34443445 scheduleAfter<T extends UniqueHelper>(3446 blocksBeforeExecution: number,3447 options: ISchedulerOptions = {},3448 ) {3449 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3450 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3451 }34523453 getSudo<T extends UniqueHelper>() {3454 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3455 }3456}345734583459export class UniqueFTCollection extends UniqueBaseCollection {3460 async getBalance(addressObj: ICrossAccountId) {3461 return await this.helper.ft.getBalance(this.collectionId, addressObj);3462 }34633464 async getTotalPieces() {3465 return await this.helper.ft.getTotalPieces(this.collectionId);3466 }34673468 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3469 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3470 }34713472 async getTop10Owners() {3473 return await this.helper.ft.getTop10Owners(this.collectionId);3474 }34753476 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3477 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3478 }34793480 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3481 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3482 }34833484 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3485 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3486 }34873488 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3489 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3490 }34913492 async burnTokens(signer: TSigner, amount=1n) {3493 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3494 }34953496 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3497 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3498 }34993500 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3501 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3502 }35033504 scheduleAt<T extends UniqueHelper>(3505 executionBlockNumber: number,3506 options: ISchedulerOptions = {},3507 ) {3508 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3509 return new UniqueFTCollection(this.collectionId, scheduledHelper);3510 }35113512 scheduleAfter<T extends UniqueHelper>(3513 blocksBeforeExecution: number,3514 options: ISchedulerOptions = {},3515 ) {3516 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3517 return new UniqueFTCollection(this.collectionId, scheduledHelper);3518 }35193520 getSudo<T extends UniqueHelper>() {3521 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3522 }3523}352435253526export class UniqueBaseToken {3527 collection: UniqueNFTCollection | UniqueRFTCollection;3528 collectionId: number;3529 tokenId: number;35303531 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3532 this.collection = collection;3533 this.collectionId = collection.collectionId;3534 this.tokenId = tokenId;3535 }35363537 async getNextSponsored(addressObj: ICrossAccountId) {3538 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3539 }35403541 async getProperties(propertyKeys?: string[] | null) {3542 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3543 }35443545 async getTokenPropertiesConsumedSpace() {3546 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3547 }35483549 async setProperties(signer: TSigner, properties: IProperty[]) {3550 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3551 }35523553 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3554 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3555 }35563557 async doesExist() {3558 return await this.collection.doesTokenExist(this.tokenId);3559 }35603561 nestingAccount() {3562 return this.collection.helper.util.getTokenAccount(this);3563 }35643565 scheduleAt<T extends UniqueHelper>(3566 executionBlockNumber: number,3567 options: ISchedulerOptions = {},3568 ) {3569 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3570 return new UniqueBaseToken(this.tokenId, scheduledCollection);3571 }35723573 scheduleAfter<T extends UniqueHelper>(3574 blocksBeforeExecution: number,3575 options: ISchedulerOptions = {},3576 ) {3577 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3578 return new UniqueBaseToken(this.tokenId, scheduledCollection);3579 }35803581 getSudo<T extends UniqueHelper>() {3582 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3583 }3584}358535863587export class UniqueNFToken extends UniqueBaseToken {3588 collection: UniqueNFTCollection;35893590 constructor(tokenId: number, collection: UniqueNFTCollection) {3591 super(tokenId, collection);3592 this.collection = collection;3593 }35943595 async getData(blockHashAt?: string) {3596 return await this.collection.getToken(this.tokenId, blockHashAt);3597 }35983599 async getOwner(blockHashAt?: string) {3600 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3601 }36023603 async getTopmostOwner(blockHashAt?: string) {3604 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3605 }36063607 async getChildren(blockHashAt?: string) {3608 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3609 }36103611 async nest(signer: TSigner, toTokenObj: IToken) {3612 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3613 }36143615 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3616 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3617 }36183619 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3620 return await this.collection.transferToken(signer, this.tokenId, addressObj);3621 }36223623 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3624 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3625 }36263627 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3628 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3629 }36303631 async isApproved(toAddressObj: ICrossAccountId) {3632 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3633 }36343635 async burn(signer: TSigner) {3636 return await this.collection.burnToken(signer, this.tokenId);3637 }36383639 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3640 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3641 }36423643 scheduleAt<T extends UniqueHelper>(3644 executionBlockNumber: number,3645 options: ISchedulerOptions = {},3646 ) {3647 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3648 return new UniqueNFToken(this.tokenId, scheduledCollection);3649 }36503651 scheduleAfter<T extends UniqueHelper>(3652 blocksBeforeExecution: number,3653 options: ISchedulerOptions = {},3654 ) {3655 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3656 return new UniqueNFToken(this.tokenId, scheduledCollection);3657 }36583659 getSudo<T extends UniqueHelper>() {3660 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3661 }3662}36633664export class UniqueRFToken extends UniqueBaseToken {3665 collection: UniqueRFTCollection;36663667 constructor(tokenId: number, collection: UniqueRFTCollection) {3668 super(tokenId, collection);3669 this.collection = collection;3670 }36713672 async getData(blockHashAt?: string) {3673 return await this.collection.getToken(this.tokenId, blockHashAt);3674 }36753676 async getTop10Owners() {3677 return await this.collection.getTop10TokenOwners(this.tokenId);3678 }36793680 async getBalance(addressObj: ICrossAccountId) {3681 return await this.collection.getTokenBalance(this.tokenId, addressObj);3682 }36833684 async getTotalPieces() {3685 return await this.collection.getTokenTotalPieces(this.tokenId);3686 }36873688 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3689 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3690 }36913692 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3693 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3694 }36953696 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3697 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3698 }36993700 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3701 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3702 }37033704 async repartition(signer: TSigner, amount: bigint) {3705 return await this.collection.repartitionToken(signer, this.tokenId, amount);3706 }37073708 async burn(signer: TSigner, amount=1n) {3709 return await this.collection.burnToken(signer, this.tokenId, amount);3710 }37113712 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3713 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3714 }37153716 scheduleAt<T extends UniqueHelper>(3717 executionBlockNumber: number,3718 options: ISchedulerOptions = {},3719 ) {3720 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3721 return new UniqueRFToken(this.tokenId, scheduledCollection);3722 }37233724 scheduleAfter<T extends UniqueHelper>(3725 blocksBeforeExecution: number,3726 options: ISchedulerOptions = {},3727 ) {3728 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3729 return new UniqueRFToken(this.tokenId, scheduledCollection);3730 }37313732 getSudo<T extends UniqueHelper>() {3733 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3734 }3735}1// 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 {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15 IApiListeners,16 IBlock,17 IEvent,18 IChainProperties,19 ICollectionCreationOptions,20 ICollectionLimits,21 ICollectionPermissions,22 ICrossAccountId,23 ICrossAccountIdLower,24 ILogger,25 INestingPermissions,26 IProperty,27 IStakingInfo,28 ISchedulerOptions,29 ISubstrateBalance,30 IToken,31 ITokenPropertyPermission,32 ITransactionResult,33 IUniqueHelperLog,34 TApiAllowedListeners,35 TEthereumAccount,36 TSigner,37 TSubstrateAccount,38 TNetworks,39 IForeignAssetMetadata,40 AcalaAssetMetadata,41 MoonbeamAssetInfo,42 DemocracyStandardAccountVote,43 IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50 Substrate?: TSubstrateAccount;51 Ethereum?: TEthereumAccount;5253 constructor(account: ICrossAccountId) {54 if (account.Substrate) this.Substrate = account.Substrate;55 if (account.Ethereum) this.Ethereum = account.Ethereum;56 }5758 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59 switch (domain) {60 case 'Substrate': return new CrossAccountId({Substrate: account.address});61 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62 }63 }6465 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67 }6869 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70 return encodeAddress(decodeAddress(address), ss58Format);71 }7273 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75 }7677 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79 return this;80 }8182 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84 }8586 toEthereum(): CrossAccountId {87 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88 return this;89 }9091 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92 return evmToAddress(address, ss58Format);93 }9495 toSubstrate(ss58Format?: number): CrossAccountId {96 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97 return this;98 }99100 toLowerCase(): CrossAccountId {101 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103 return this;104 }105}106107const nesting = {108 toChecksumAddress(address: string): string {109 if (typeof address === 'undefined') return '';110111 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113 address = address.toLowerCase().replace(/^0x/i,'');114 const addressHash = keccakAsHex(address).replace(/^0x/i,'');115 const checksumAddress = ['0x'];116117 for (let i = 0; i < address.length; i++) {118 // If ith character is 8 to f then make it uppercase119 if (parseInt(addressHash[i], 16) > 7) {120 checksumAddress.push(address[i].toUpperCase());121 } else {122 checksumAddress.push(address[i]);123 }124 }125 return checksumAddress.join('');126 },127 tokenIdToAddress(collectionId: number, tokenId: number) {128 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);129 },130};131132class UniqueUtil {133 static transactionStatus = {134 NOT_READY: 'NotReady',135 FAIL: 'Fail',136 SUCCESS: 'Success',137 };138139 static chainLogType = {140 EXTRINSIC: 'extrinsic',141 RPC: 'rpc',142 };143144 static getTokenAccount(token: IToken): CrossAccountId {145 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146 }147148 static getTokenAddress(token: IToken): string {149 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150 }151152 static getDefaultLogger(): ILogger {153 return {154 log(msg: any, level = 'INFO') {155 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156 },157 level: {158 ERROR: 'ERROR',159 WARNING: 'WARNING',160 INFO: 'INFO',161 },162 };163 }164165 static vec2str(arr: string[] | number[]) {166 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167 }168169 static str2vec(string: string) {170 if (typeof string !== 'string') return string;171 return Array.from(string).map(x => x.charCodeAt(0));172 }173174 static fromSeed(seed: string, ss58Format = 42) {175 const keyring = new Keyring({type: 'sr25519', ss58Format});176 return keyring.addFromUri(seed);177 }178179 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180 if (creationResult.status !== this.transactionStatus.SUCCESS) {181 throw Error('Unable to create collection!');182 }183184 let collectionId = null;185 creationResult.result.events.forEach(({event: {data, method, section}}) => {186 if ((section === 'common') && (method === 'CollectionCreated')) {187 collectionId = parseInt(data[0].toString(), 10);188 }189 });190191 if (collectionId === null) {192 throw Error('No CollectionCreated event was found!');193 }194195 return collectionId;196 }197198 static extractTokensFromCreationResult(creationResult: ITransactionResult): {199 success: boolean,200 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201 } {202 if (creationResult.status !== this.transactionStatus.SUCCESS) {203 throw Error('Unable to create tokens!');204 }205 let success = false;206 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207 creationResult.result.events.forEach(({event: {data, method, section}}) => {208 if (method === 'ExtrinsicSuccess') {209 success = true;210 } else if ((section === 'common') && (method === 'ItemCreated')) {211 tokens.push({212 collectionId: parseInt(data[0].toString(), 10),213 tokenId: parseInt(data[1].toString(), 10),214 owner: data[2].toHuman(),215 amount: data[3].toBigInt(),216 });217 }218 });219 return {success, tokens};220 }221222 static extractTokensFromBurnResult(burnResult: ITransactionResult): {223 success: boolean,224 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225 } {226 if (burnResult.status !== this.transactionStatus.SUCCESS) {227 throw Error('Unable to burn tokens!');228 }229 let success = false;230 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231 burnResult.result.events.forEach(({event: {data, method, section}}) => {232 if (method === 'ExtrinsicSuccess') {233 success = true;234 } else if ((section === 'common') && (method === 'ItemDestroyed')) {235 tokens.push({236 collectionId: parseInt(data[0].toString(), 10),237 tokenId: parseInt(data[1].toString(), 10),238 owner: data[2].toHuman(),239 amount: data[3].toBigInt(),240 });241 }242 });243 return {success, tokens};244 }245246 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247 let eventId = null;248 events.forEach(({event: {data, method, section}}) => {249 if ((section === expectedSection) && (method === expectedMethod)) {250 eventId = parseInt(data[0].toString(), 10);251 }252 });253254 if (eventId === null) {255 throw Error(`No ${expectedMethod} event was found!`);256 }257 return eventId === collectionId;258 }259260 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261 const normalizeAddress = (address: string | ICrossAccountId) => {262 if(typeof address === 'string') return address;263 const obj = {} as any;264 Object.keys(address).forEach(k => {265 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266 });267 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269 return address;270 };271 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272 events.forEach(({event: {data, method, section}}) => {273 if ((section === 'common') && (method === 'Transfer')) {274 const hData = (data as any).toJSON();275 transfer = {276 collectionId: hData[0],277 tokenId: hData[1],278 from: normalizeAddress(hData[2]),279 to: normalizeAddress(hData[3]),280 amount: BigInt(hData[4]),281 };282 }283 });284 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287 isSuccess = isSuccess && amount === transfer.amount;288 return isSuccess;289 }290291 static bigIntToDecimals(number: bigint, decimals = 18) {292 const numberStr = number.toString();293 const dotPos = numberStr.length - decimals;294295 if (dotPos <= 0) {296 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297 } else {298 const intPart = numberStr.substring(0, dotPos);299 const fractPart = numberStr.substring(dotPos);300 return intPart + '.' + fractPart;301 }302 }303}304305class UniqueEventHelper {306 private static extractIndex(index: any): [number, number] | string {307 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308 return index.toJSON();309 }310311 private static extractSub(data: any, subTypes: any): {[key: string]: any} {312 let obj: any = {};313 let index = 0;314315 if (data.entries) {316 for(const [key, value] of data.entries()) {317 obj[key] = this.extractData(value, subTypes[index]);318 index++;319 }320 } else obj = data.toJSON();321322 return obj;323 }324325 private static toHuman(data: any) {326 return data && data.toHuman ? data.toHuman() : `${data}`;327 }328329 private static extractData(data: any, type: any): any {330 if(!type) return this.toHuman(data);331 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334 return this.toHuman(data);335 }336337 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338 const parsedEvents: IEvent[] = [];339340 events.forEach((record) => {341 const {event, phase} = record;342 const types = event.typeDef;343344 const eventData: IEvent = {345 section: event.section.toString(),346 method: event.method.toString(),347 index: this.extractIndex(event.index),348 data: [],349 phase: phase.toJSON(),350 };351352 event.data.forEach((val: any, index: number) => {353 eventData.data.push(this.extractData(val, types[index]));354 });355356 parsedEvents.push(eventData);357 });358359 return parsedEvents;360 }361}362363export class ChainHelperBase {364 helperBase: any;365366 transactionStatus = UniqueUtil.transactionStatus;367 chainLogType = UniqueUtil.chainLogType;368 util: typeof UniqueUtil;369 eventHelper: typeof UniqueEventHelper;370 logger: ILogger;371 api: ApiPromise | null;372 forcedNetwork: TNetworks | null;373 network: TNetworks | null;374 chainLog: IUniqueHelperLog[];375 children: ChainHelperBase[];376 address: AddressGroup;377 chain: ChainGroup;378379 constructor(logger?: ILogger, helperBase?: any) {380 this.helperBase = helperBase;381382 this.util = UniqueUtil;383 this.eventHelper = UniqueEventHelper;384 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();385 this.logger = logger;386 this.api = null;387 this.forcedNetwork = null;388 this.network = null;389 this.chainLog = [];390 this.children = [];391 this.address = new AddressGroup(this);392 this.chain = new ChainGroup(this);393 }394395 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {396 Object.setPrototypeOf(helperCls.prototype, this);397 const newHelper = new helperCls(this.logger, options);398399 newHelper.api = this.api;400 newHelper.network = this.network;401 newHelper.forceNetwork = this.forceNetwork;402403 this.children.push(newHelper);404405 return newHelper;406 }407408 getApi(): ApiPromise {409 if(this.api === null) throw Error('API not initialized');410 return this.api;411 }412413 async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {414 const collectedEvents: IEvent[] = [];415 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {416 const ievents = this.eventHelper.extractEvents(events);417 ievents.forEach((event) => {418 expectedEvents.forEach((e => {419 if (event.section === e.section && e.names.includes(event.method)) {420 collectedEvents.push(event);421 }422 }));423 });424 });425 return {unsubscribe: unsubscribe as any, collectedEvents};426 }427428 clearChainLog(): void {429 this.chainLog = [];430 }431432 forceNetwork(value: TNetworks): void {433 this.forcedNetwork = value;434 }435436 async connect(wsEndpoint: string, listeners?: IApiListeners) {437 if (this.api !== null) throw Error('Already connected');438 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);439 this.api = api;440 this.network = network;441 }442443 async disconnect() {444 for (const child of this.children) {445 child.clearApi();446 }447448 if (this.api === null) return;449 await this.api.disconnect();450 this.clearApi();451 }452453 clearApi() {454 this.api = null;455 this.network = null;456 }457458 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {459 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;460 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];461462 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;463464 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;465 return 'opal';466 }467468 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {469 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});470 await api.isReady;471472 const network = await this.detectNetwork(api);473474 await api.disconnect();475476 return network;477 }478479 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{480 api: ApiPromise;481 network: TNetworks;482 }> {483 if(typeof network === 'undefined' || network === null) network = 'opal';484 const supportedRPC = {485 opal: {486 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,487 },488 quartz: {489 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,490 },491 unique: {492 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,493 },494 rococo: {},495 westend: {},496 moonbeam: {},497 moonriver: {},498 acala: {},499 karura: {},500 westmint: {},501 };502 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);503 const rpc = supportedRPC[network];504505 // TODO: investigate how to replace rpc in runtime506 // api._rpcCore.addUserInterfaces(rpc);507508 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});509510 await api.isReadyOrError;511512 if (typeof listeners === 'undefined') listeners = {};513 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {514 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;515 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);516 }517518 return {api, network};519 }520521 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {522 const {events, status} = data;523 if (status.isReady) {524 return this.transactionStatus.NOT_READY;525 }526 if (status.isBroadcast) {527 return this.transactionStatus.NOT_READY;528 }529 if (status.isInBlock || status.isFinalized) {530 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');531 if (errors.length > 0) {532 return this.transactionStatus.FAIL;533 }534 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {535 return this.transactionStatus.SUCCESS;536 }537 }538539 return this.transactionStatus.FAIL;540 }541542 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {543 const sign = (callback: any) => {544 if(options !== null) return transaction.signAndSend(sender, options, callback);545 return transaction.signAndSend(sender, callback);546 };547 // eslint-disable-next-line no-async-promise-executor548 return new Promise(async (resolve, reject) => {549 try {550 const unsub = await sign((result: any) => {551 const status = this.getTransactionStatus(result);552553 if (status === this.transactionStatus.SUCCESS) {554 this.logger.log(`${label} successful`);555 unsub();556 resolve({result, status});557 } else if (status === this.transactionStatus.FAIL) {558 let moduleError = null;559560 if (result.hasOwnProperty('dispatchError')) {561 const dispatchError = result['dispatchError'];562563 if (dispatchError) {564 if (dispatchError.isModule) {565 const modErr = dispatchError.asModule;566 const errorMeta = dispatchError.registry.findMetaError(modErr);567568 moduleError = `${errorMeta.section}.${errorMeta.name}`;569 } else {570 moduleError = dispatchError.toHuman();571 }572 } else {573 this.logger.log(result, this.logger.level.ERROR);574 }575 }576577 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);578 unsub();579 reject({status, moduleError, result});580 }581 });582 } catch (e) {583 this.logger.log(e, this.logger.level.ERROR);584 reject(e);585 }586 });587 }588589 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {590 const api = this.getApi();591 const signingInfo = await api.derive.tx.signingInfo(signer.address);592593 // We need to sign the tx because594 // unsigned transactions does not have an inclusion fee595 tx.sign(signer, {596 blockHash: api.genesisHash,597 genesisHash: api.genesisHash,598 runtimeVersion: api.runtimeVersion,599 nonce: signingInfo.nonce,600 });601602 if (len === null) {603 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;604 } else {605 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;606 }607 }608609 constructApiCall(apiCall: string, params: any[]) {610 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);611 let call = this.getApi() as any;612 for(const part of apiCall.slice(4).split('.')) {613 call = call[part];614 }615 return call(...params);616 }617618 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {619 if(this.api === null) throw Error('API not initialized');620 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);621622 const startTime = (new Date()).getTime();623 let result: ITransactionResult;624 let events: IEvent[] = [];625 try {626 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;627 events = this.eventHelper.extractEvents(result.result.events);628 }629 catch(e) {630 if(!(e as object).hasOwnProperty('status')) throw e;631 result = e as ITransactionResult;632 }633634 const endTime = (new Date()).getTime();635636 const log = {637 executedAt: endTime,638 executionTime: endTime - startTime,639 type: this.chainLogType.EXTRINSIC,640 status: result.status,641 call: extrinsic,642 signer: this.getSignerAddress(sender),643 params,644 } as IUniqueHelperLog;645646 if(result.status !== this.transactionStatus.SUCCESS) {647 if (result.moduleError) log.moduleError = result.moduleError;648 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;649 }650 if(events.length > 0) log.events = events;651652 this.chainLog.push(log);653654 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {655 if (result.moduleError) throw Error(`${result.moduleError}`);656 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));657 }658 return result;659 }660661 async callRpc(rpc: string, params?: any[]) {662 if(typeof params === 'undefined') params = [];663 if(this.api === null) throw Error('API not initialized');664 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);665666 const startTime = (new Date()).getTime();667 let result;668 let error = null;669 const log = {670 type: this.chainLogType.RPC,671 call: rpc,672 params,673 } as IUniqueHelperLog;674675 try {676 result = await this.constructApiCall(rpc, params);677 }678 catch(e) {679 error = e;680 }681682 const endTime = (new Date()).getTime();683684 log.executedAt = endTime;685 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';686 log.executionTime = endTime - startTime;687688 this.chainLog.push(log);689690 if(error !== null) throw error;691692 return result;693 }694695 getSignerAddress(signer: IKeyringPair | string): string {696 if(typeof signer === 'string') return signer;697 return signer.address;698 }699700 fetchAllPalletNames(): string[] {701 if(this.api === null) throw Error('API not initialized');702 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());703 }704705 fetchMissingPalletNames(requiredPallets: string[]): string[] {706 const palletNames = this.fetchAllPalletNames();707 return requiredPallets.filter(p => !palletNames.includes(p));708 }709}710711712class HelperGroup<T extends ChainHelperBase> {713 helper: T;714715 constructor(uniqueHelper: T) {716 this.helper = uniqueHelper;717 }718}719720721class CollectionGroup extends HelperGroup<UniqueHelper> {722 /**723 * Get number of blocks when sponsored transaction is available.724 *725 * @param collectionId ID of collection726 * @param tokenId ID of token727 * @param addressObj address for which the sponsorship is checked728 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});729 * @returns number of blocks or null if sponsorship hasn't been set730 */731 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {732 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();733 }734735 /**736 * Get the number of created collections.737 *738 * @returns number of created collections739 */740 async getTotalCount(): Promise<number> {741 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();742 }743744 /**745 * Get information about the collection with additional data,746 * including the number of tokens it contains, its administrators,747 * the normalized address of the collection's owner, and decoded name and description.748 *749 * @param collectionId ID of collection750 * @example await getData(2)751 * @returns collection information object752 */753 async getData(collectionId: number): Promise<{754 id: number;755 name: string;756 description: string;757 tokensCount: number;758 admins: CrossAccountId[];759 normalizedOwner: TSubstrateAccount;760 raw: any761 } | null> {762 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);763 const humanCollection = collection.toHuman(), collectionData = {764 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],765 raw: humanCollection,766 } as any, jsonCollection = collection.toJSON();767 if (humanCollection === null) return null;768 collectionData.raw.limits = jsonCollection.limits;769 collectionData.raw.permissions = jsonCollection.permissions;770 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);771 for (const key of ['name', 'description']) {772 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);773 }774775 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))776 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)777 : 0;778 collectionData.admins = await this.getAdmins(collectionId);779780 return collectionData;781 }782783 /**784 * Get the addresses of the collection's administrators, optionally normalized.785 *786 * @param collectionId ID of collection787 * @param normalize whether to normalize the addresses to the default ss58 format788 * @example await getAdmins(1)789 * @returns array of administrators790 */791 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {792 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();793794 return normalize795 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())796 : admins;797 }798799 /**800 * Get the addresses added to the collection allow-list, optionally normalized.801 * @param collectionId ID of collection802 * @param normalize whether to normalize the addresses to the default ss58 format803 * @example await getAllowList(1)804 * @returns array of allow-listed addresses805 */806 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {807 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();808 return normalize809 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())810 : allowListed;811 }812813 /**814 * Get the effective limits of the collection instead of null for default values815 *816 * @param collectionId ID of collection817 * @example await getEffectiveLimits(2)818 * @returns object of collection limits819 */820 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {821 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();822 }823824 /**825 * Burns the collection if the signer has sufficient permissions and collection is empty.826 *827 * @param signer keyring of signer828 * @param collectionId ID of collection829 * @example await helper.collection.burn(aliceKeyring, 3);830 * @returns ```true``` if extrinsic success, otherwise ```false```831 */832 async burn(signer: TSigner, collectionId: number): Promise<boolean> {833 const result = await this.helper.executeExtrinsic(834 signer,835 'api.tx.unique.destroyCollection', [collectionId],836 true,837 );838839 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');840 }841842 /**843 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.844 *845 * @param signer keyring of signer846 * @param collectionId ID of collection847 * @param sponsorAddress Sponsor substrate address848 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")849 * @returns ```true``` if extrinsic success, otherwise ```false```850 */851 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {852 const result = await this.helper.executeExtrinsic(853 signer,854 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],855 true,856 );857858 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');859 }860861 /**862 * Confirms consent to sponsor the collection on behalf of the signer.863 *864 * @param signer keyring of signer865 * @param collectionId ID of collection866 * @example confirmSponsorship(aliceKeyring, 10)867 * @returns ```true``` if extrinsic success, otherwise ```false```868 */869 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {870 const result = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.confirmSponsorship', [collectionId],873 true,874 );875876 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');877 }878879 /**880 * Removes the sponsor of a collection, regardless if it consented or not.881 *882 * @param signer keyring of signer883 * @param collectionId ID of collection884 * @example removeSponsor(aliceKeyring, 10)885 * @returns ```true``` if extrinsic success, otherwise ```false```886 */887 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {888 const result = await this.helper.executeExtrinsic(889 signer,890 'api.tx.unique.removeCollectionSponsor', [collectionId],891 true,892 );893894 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');895 }896897 /**898 * Sets the limits of the collection. At least one limit must be specified for a correct call.899 *900 * @param signer keyring of signer901 * @param collectionId ID of collection902 * @param limits collection limits object903 * @example904 * await setLimits(905 * aliceKeyring,906 * 10,907 * {908 * sponsorTransferTimeout: 0,909 * ownerCanDestroy: false910 * }911 * )912 * @returns ```true``` if extrinsic success, otherwise ```false```913 */914 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {915 const result = await this.helper.executeExtrinsic(916 signer,917 'api.tx.unique.setCollectionLimits', [collectionId, limits],918 true,919 );920921 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');922 }923924 /**925 * Changes the owner of the collection to the new Substrate address.926 *927 * @param signer keyring of signer928 * @param collectionId ID of collection929 * @param ownerAddress substrate address of new owner930 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")931 * @returns ```true``` if extrinsic success, otherwise ```false```932 */933 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {934 const result = await this.helper.executeExtrinsic(935 signer,936 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],937 true,938 );939940 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');941 }942943 /**944 * Adds a collection administrator.945 *946 * @param signer keyring of signer947 * @param collectionId ID of collection948 * @param adminAddressObj Administrator address (substrate or ethereum)949 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})950 * @returns ```true``` if extrinsic success, otherwise ```false```951 */952 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {953 const result = await this.helper.executeExtrinsic(954 signer,955 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],956 true,957 );958959 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');960 }961962 /**963 * Removes a collection administrator.964 *965 * @param signer keyring of signer966 * @param collectionId ID of collection967 * @param adminAddressObj Administrator address (substrate or ethereum)968 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})969 * @returns ```true``` if extrinsic success, otherwise ```false```970 */971 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {972 const result = await this.helper.executeExtrinsic(973 signer,974 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],975 true,976 );977978 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');979 }980981 /**982 * Check if user is in allow list.983 *984 * @param collectionId ID of collection985 * @param user Account to check986 * @example await getAdmins(1)987 * @returns is user in allow list988 */989 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {990 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();991 }992993 /**994 * Adds an address to allow list995 * @param signer keyring of signer996 * @param collectionId ID of collection997 * @param addressObj address to add to the allow list998 * @returns ```true``` if extrinsic success, otherwise ```false```999 */1000 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1001 const result = await this.helper.executeExtrinsic(1002 signer,1003 'api.tx.unique.addToAllowList', [collectionId, addressObj],1004 true,1005 );10061007 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1008 }10091010 /**1011 * Removes an address from allow list1012 *1013 * @param signer keyring of signer1014 * @param collectionId ID of collection1015 * @param addressObj address to remove from the allow list1016 * @returns ```true``` if extrinsic success, otherwise ```false```1017 */1018 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1019 const result = await this.helper.executeExtrinsic(1020 signer,1021 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1022 true,1023 );10241025 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1026 }10271028 /**1029 * Sets onchain permissions for selected collection.1030 *1031 * @param signer keyring of signer1032 * @param collectionId ID of collection1033 * @param permissions collection permissions object1034 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1035 * @returns ```true``` if extrinsic success, otherwise ```false```1036 */1037 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1038 const result = await this.helper.executeExtrinsic(1039 signer,1040 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1041 true,1042 );10431044 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1045 }10461047 /**1048 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1049 *1050 * @param signer keyring of signer1051 * @param collectionId ID of collection1052 * @param permissions nesting permissions object1053 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1054 * @returns ```true``` if extrinsic success, otherwise ```false```1055 */1056 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1057 return await this.setPermissions(signer, collectionId, {nesting: permissions});1058 }10591060 /**1061 * Disables nesting for selected collection.1062 *1063 * @param signer keyring of signer1064 * @param collectionId ID of collection1065 * @example disableNesting(aliceKeyring, 10);1066 * @returns ```true``` if extrinsic success, otherwise ```false```1067 */1068 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1069 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1070 }10711072 /**1073 * Sets onchain properties to the collection.1074 *1075 * @param signer keyring of signer1076 * @param collectionId ID of collection1077 * @param properties array of property objects1078 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1079 * @returns ```true``` if extrinsic success, otherwise ```false```1080 */1081 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1082 const result = await this.helper.executeExtrinsic(1083 signer,1084 'api.tx.unique.setCollectionProperties', [collectionId, properties],1085 true,1086 );10871088 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1089 }10901091 /**1092 * Get collection properties.1093 *1094 * @param collectionId ID of collection1095 * @param propertyKeys optionally filter the returned properties to only these keys1096 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1097 * @returns array of key-value pairs1098 */1099 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1100 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1101 }11021103 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1104 const api = this.helper.getApi();1105 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();1106 1107 return (props! as any).consumedSpace;1108 }11091110 async getCollectionOptions(collectionId: number) {1111 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1112 }11131114 /**1115 * Deletes onchain properties from the collection.1116 *1117 * @param signer keyring of signer1118 * @param collectionId ID of collection1119 * @param propertyKeys array of property keys to delete1120 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1121 * @returns ```true``` if extrinsic success, otherwise ```false```1122 */1123 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1124 const result = await this.helper.executeExtrinsic(1125 signer,1126 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1127 true,1128 );11291130 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1131 }11321133 /**1134 * Changes the owner of the token.1135 *1136 * @param signer keyring of signer1137 * @param collectionId ID of collection1138 * @param tokenId ID of token1139 * @param addressObj address of a new owner1140 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1141 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1142 * @returns true if the token success, otherwise false1143 */1144 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1145 const result = await this.helper.executeExtrinsic(1146 signer,1147 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1148 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1149 );11501151 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1152 }11531154 /**1155 *1156 * Change ownership of a token(s) on behalf of the owner.1157 *1158 * @param signer keyring of signer1159 * @param collectionId ID of collection1160 * @param tokenId ID of token1161 * @param fromAddressObj address on behalf of which the token will be sent1162 * @param toAddressObj new token owner1163 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1164 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1165 * @returns true if the token success, otherwise false1166 */1167 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1168 const result = await this.helper.executeExtrinsic(1169 signer,1170 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1171 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1172 );1173 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1174 }11751176 /**1177 *1178 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1179 *1180 * @param signer keyring of signer1181 * @param collectionId ID of collection1182 * @param tokenId ID of token1183 * @param amount amount of tokens to be burned. For NFT must be set to 1n1184 * @example burnToken(aliceKeyring, 10, 5);1185 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1186 */1187 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1188 const burnResult = await this.helper.executeExtrinsic(1189 signer,1190 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1191 true, // `Unable to burn token for ${label}`,1192 );1193 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1194 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1195 return burnedTokens.success;1196 }11971198 /**1199 * Destroys a concrete instance of NFT on behalf of the owner1200 *1201 * @param signer keyring of signer1202 * @param collectionId ID of collection1203 * @param tokenId ID of token1204 * @param fromAddressObj address on behalf of which the token will be burnt1205 * @param amount amount of tokens to be burned. For NFT must be set to 1n1206 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1207 * @returns ```true``` if extrinsic success, otherwise ```false```1208 */1209 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1210 const burnResult = await this.helper.executeExtrinsic(1211 signer,1212 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1213 true, // `Unable to burn token from for ${label}`,1214 );1215 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1216 return burnedTokens.success && burnedTokens.tokens.length > 0;1217 }12181219 /**1220 * Set, change, or remove approved address to transfer the ownership of the NFT.1221 *1222 * @param signer keyring of signer1223 * @param collectionId ID of collection1224 * @param tokenId ID of token1225 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1226 * @param amount amount of token to be approved. For NFT must be set to 1n1227 * @returns ```true``` if extrinsic success, otherwise ```false```1228 */1229 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1230 const approveResult = await this.helper.executeExtrinsic(1231 signer,1232 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1233 true, // `Unable to approve token for ${label}`,1234 );12351236 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1237 }12381239 /**1240 * Get the amount of token pieces approved to transfer or burn. Normally 0.1241 *1242 * @param collectionId ID of collection1243 * @param tokenId ID of token1244 * @param toAccountObj address which is approved to use token pieces1245 * @param fromAccountObj address which may have allowed the use of its owned tokens1246 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1247 * @returns number of approved to transfer pieces1248 */1249 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1250 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1251 }12521253 /**1254 * Get the last created token ID in a collection1255 *1256 * @param collectionId ID of collection1257 * @example getLastTokenId(10);1258 * @returns id of the last created token1259 */1260 async getLastTokenId(collectionId: number): Promise<number> {1261 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1262 }12631264 /**1265 * Check if token exists1266 *1267 * @param collectionId ID of collection1268 * @param tokenId ID of token1269 * @example doesTokenExist(10, 20);1270 * @returns true if the token exists, otherwise false1271 */1272 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1273 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1274 }1275}12761277class NFTnRFT extends CollectionGroup {1278 /**1279 * Get tokens owned by account1280 *1281 * @param collectionId ID of collection1282 * @param addressObj tokens owner1283 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1284 * @returns array of token ids owned by account1285 */1286 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1287 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1288 }12891290 /**1291 * Get token data1292 *1293 * @param collectionId ID of collection1294 * @param tokenId ID of token1295 * @param propertyKeys optionally filter the token properties to only these keys1296 * @param blockHashAt optionally query the data at some block with this hash1297 * @example getToken(10, 5);1298 * @returns human readable token data1299 */1300 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1301 properties: IProperty[];1302 owner: CrossAccountId;1303 normalizedOwner: CrossAccountId;1304 }| null> {1305 let tokenData;1306 if(typeof blockHashAt === 'undefined') {1307 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1308 }1309 else {1310 if(propertyKeys.length == 0) {1311 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1312 if(!collection) return null;1313 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1314 }1315 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1316 }1317 tokenData = tokenData.toHuman();1318 if (tokenData === null || tokenData.owner === null) return null;1319 const owner = {} as any;1320 for (const key of Object.keys(tokenData.owner)) {1321 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1322 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1323 : tokenData.owner[key];1324 }1325 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1326 return tokenData;1327 }13281329 /**1330 * Set permissions to change token properties1331 *1332 * @param signer keyring of signer1333 * @param collectionId ID of collection1334 * @param permissions permissions to change a property by the collection admin or token owner1335 * @example setTokenPropertyPermissions(1336 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1337 * )1338 * @returns true if extrinsic success otherwise false1339 */1340 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1341 const result = await this.helper.executeExtrinsic(1342 signer,1343 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1344 true,1345 );13461347 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1348 }13491350 /**1351 * Get token property permissions.1352 *1353 * @param collectionId ID of collection1354 * @param propertyKeys optionally filter the returned property permissions to only these keys1355 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1356 * @returns array of key-permission pairs1357 */1358 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1359 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1360 }13611362 /**1363 * Set token properties1364 *1365 * @param signer keyring of signer1366 * @param collectionId ID of collection1367 * @param tokenId ID of token1368 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1369 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1370 * @returns ```true``` if extrinsic success, otherwise ```false```1371 */1372 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1373 const result = await this.helper.executeExtrinsic(1374 signer,1375 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1376 true,1377 );13781379 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1380 }13811382 /**1383 * Get properties, metadata assigned to a token.1384 *1385 * @param collectionId ID of collection1386 * @param tokenId ID of token1387 * @param propertyKeys optionally filter the returned properties to only these keys1388 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1389 * @returns array of key-value pairs1390 */1391 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1392 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1393 }13941395 /**1396 * Delete the provided properties of a token1397 * @param signer keyring of signer1398 * @param collectionId ID of collection1399 * @param tokenId ID of token1400 * @param propertyKeys property keys to be deleted1401 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1402 * @returns ```true``` if extrinsic success, otherwise ```false```1403 */1404 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1405 const result = await this.helper.executeExtrinsic(1406 signer,1407 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1408 true,1409 );14101411 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1412 }14131414 /**1415 * Mint new collection1416 *1417 * @param signer keyring of signer1418 * @param collectionOptions basic collection options and properties1419 * @param mode NFT or RFT type of a collection1420 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1421 * @returns object of the created collection1422 */1423 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1424 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1425 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1426 for (const key of ['name', 'description', 'tokenPrefix']) {1427 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);1428 }1429 const creationResult = await this.helper.executeExtrinsic(1430 signer,1431 'api.tx.unique.createCollectionEx', [collectionOptions],1432 true, // errorLabel,1433 );1434 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1435 }14361437 getCollectionObject(_collectionId: number): any {1438 return null;1439 }14401441 getTokenObject(_collectionId: number, _tokenId: number): any {1442 return null;1443 }14441445 /**1446 * Tells whether the given `owner` approves the `operator`.1447 * @param collectionId ID of collection1448 * @param owner owner address1449 * @param operator operator addrees1450 * @returns true if operator is enabled1451 */1452 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1453 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1454 }14551456 /** Sets or unsets the approval of a given operator.1457 * The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1458 * @param operator Operator1459 * @param approved Should operator status be granted or revoked?1460 * @returns ```true``` if extrinsic success, otherwise ```false```1461 */1462 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1463 const result = await this.helper.executeExtrinsic(1464 signer,1465 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1466 true,1467 );1468 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1469 }1470}147114721473class NFTGroup extends NFTnRFT {1474 /**1475 * Get collection object1476 * @param collectionId ID of collection1477 * @example getCollectionObject(2);1478 * @returns instance of UniqueNFTCollection1479 */1480 getCollectionObject(collectionId: number): UniqueNFTCollection {1481 return new UniqueNFTCollection(collectionId, this.helper);1482 }14831484 /**1485 * Get token object1486 * @param collectionId ID of collection1487 * @param tokenId ID of token1488 * @example getTokenObject(10, 5);1489 * @returns instance of UniqueNFTToken1490 */1491 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1492 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1493 }14941495 /**1496 * Get token's owner1497 * @param collectionId ID of collection1498 * @param tokenId ID of token1499 * @param blockHashAt optionally query the data at the block with this hash1500 * @example getTokenOwner(10, 5);1501 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1502 */1503 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1504 let owner;1505 if (typeof blockHashAt === 'undefined') {1506 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1507 } else {1508 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1509 }1510 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1511 }15121513 /**1514 * Is token approved to transfer1515 * @param collectionId ID of collection1516 * @param tokenId ID of token1517 * @param toAccountObj address to be approved1518 * @returns ```true``` if extrinsic success, otherwise ```false```1519 */1520 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1521 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1522 }15231524 /**1525 * Changes the owner of the token.1526 *1527 * @param signer keyring of signer1528 * @param collectionId ID of collection1529 * @param tokenId ID of token1530 * @param addressObj address of a new owner1531 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1532 * @returns ```true``` if extrinsic success, otherwise ```false```1533 */1534 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1535 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1536 }15371538 /**1539 *1540 * Change ownership of a NFT on behalf of the owner.1541 *1542 * @param signer keyring of signer1543 * @param collectionId ID of collection1544 * @param tokenId ID of token1545 * @param fromAddressObj address on behalf of which the token will be sent1546 * @param toAddressObj new token owner1547 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1548 * @returns ```true``` if extrinsic success, otherwise ```false```1549 */1550 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1551 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1552 }15531554 /**1555 * Recursively find the address that owns the token1556 * @param collectionId ID of collection1557 * @param tokenId ID of token1558 * @param blockHashAt1559 * @example getTokenTopmostOwner(10, 5);1560 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1561 */1562 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1563 let owner;1564 if (typeof blockHashAt === 'undefined') {1565 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1566 } else {1567 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1568 }15691570 if (owner === null) return null;15711572 return owner.toHuman();1573 }15741575 /**1576 * Get tokens nested in the provided token1577 * @param collectionId ID of collection1578 * @param tokenId ID of token1579 * @param blockHashAt optionally query the data at the block with this hash1580 * @example getTokenChildren(10, 5);1581 * @returns tokens whose depth of nesting is <= 51582 */1583 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1584 let children;1585 if(typeof blockHashAt === 'undefined') {1586 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1587 } else {1588 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1589 }15901591 return children.toJSON().map((x: any) => {1592 return {collectionId: x.collection, tokenId: x.token};1593 });1594 }15951596 /**1597 * Nest one token into another1598 * @param signer keyring of signer1599 * @param tokenObj token to be nested1600 * @param rootTokenObj token to be parent1601 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1602 * @returns ```true``` if extrinsic success, otherwise ```false```1603 */1604 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1605 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1606 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1607 if(!result) {1608 throw Error('Unable to nest token!');1609 }1610 return result;1611 }16121613 /**1614 * Remove token from nested state1615 * @param signer keyring of signer1616 * @param tokenObj token to unnest1617 * @param rootTokenObj parent of a token1618 * @param toAddressObj address of a new token owner1619 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1620 * @returns ```true``` if extrinsic success, otherwise ```false```1621 */1622 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1623 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1624 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1625 if(!result) {1626 throw Error('Unable to unnest token!');1627 }1628 return result;1629 }16301631 /**1632 * Mint new collection1633 * @param signer keyring of signer1634 * @param collectionOptions Collection options1635 * @example1636 * mintCollection(aliceKeyring, {1637 * name: 'New',1638 * description: 'New collection',1639 * tokenPrefix: 'NEW',1640 * })1641 * @returns object of the created collection1642 */1643 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1644 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1645 }16461647 /**1648 * Mint new token1649 * @param signer keyring of signer1650 * @param data token data1651 * @returns created token object1652 */1653 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1654 const creationResult = await this.helper.executeExtrinsic(1655 signer,1656 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1657 nft: {1658 properties: data.properties,1659 },1660 }],1661 true,1662 );1663 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1664 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1665 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1666 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1667 }16681669 /**1670 * Mint multiple NFT tokens1671 * @param signer keyring of signer1672 * @param collectionId ID of collection1673 * @param tokens array of tokens with owner and properties1674 * @example1675 * mintMultipleTokens(aliceKeyring, 10, [{1676 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1677 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1678 * },{1679 * owner: {Ethereum: "0x9F0583DbB855d..."},1680 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1681 * }]);1682 * @returns ```true``` if extrinsic success, otherwise ```false```1683 */1684 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1685 const creationResult = await this.helper.executeExtrinsic(1686 signer,1687 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1688 true,1689 );1690 const collection = this.getCollectionObject(collectionId);1691 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1692 }16931694 /**1695 * Mint multiple NFT tokens with one owner1696 * @param signer keyring of signer1697 * @param collectionId ID of collection1698 * @param owner tokens owner1699 * @param tokens array of tokens with owner and properties1700 * @example1701 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1702 * properties: [{1703 * key: "gender",1704 * value: "female",1705 * },{1706 * key: "age",1707 * value: "33",1708 * }],1709 * }]);1710 * @returns array of newly created tokens1711 */1712 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1713 const rawTokens = [];1714 for (const token of tokens) {1715 const raw = {NFT: {properties: token.properties}};1716 rawTokens.push(raw);1717 }1718 const creationResult = await this.helper.executeExtrinsic(1719 signer,1720 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1721 true,1722 );1723 const collection = this.getCollectionObject(collectionId);1724 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1725 }17261727 /**1728 * Set, change, or remove approved address to transfer the ownership of the NFT.1729 *1730 * @param signer keyring of signer1731 * @param collectionId ID of collection1732 * @param tokenId ID of token1733 * @param toAddressObj address to approve1734 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1735 * @returns ```true``` if extrinsic success, otherwise ```false```1736 */1737 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1738 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1739 }1740}174117421743class RFTGroup extends NFTnRFT {1744 /**1745 * Get collection object1746 * @param collectionId ID of collection1747 * @example getCollectionObject(2);1748 * @returns instance of UniqueRFTCollection1749 */1750 getCollectionObject(collectionId: number): UniqueRFTCollection {1751 return new UniqueRFTCollection(collectionId, this.helper);1752 }17531754 /**1755 * Get token object1756 * @param collectionId ID of collection1757 * @param tokenId ID of token1758 * @example getTokenObject(10, 5);1759 * @returns instance of UniqueNFTToken1760 */1761 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1762 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1763 }17641765 /**1766 * Get top 10 token owners with the largest number of pieces1767 * @param collectionId ID of collection1768 * @param tokenId ID of token1769 * @example getTokenTop10Owners(10, 5);1770 * @returns array of top 10 owners1771 */1772 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1773 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1774 }17751776 /**1777 * Get number of pieces owned by address1778 * @param collectionId ID of collection1779 * @param tokenId ID of token1780 * @param addressObj address token owner1781 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1782 * @returns number of pieces ownerd by address1783 */1784 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1785 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1786 }17871788 /**1789 * Transfer pieces of token to another address1790 * @param signer keyring of signer1791 * @param collectionId ID of collection1792 * @param tokenId ID of token1793 * @param addressObj address of a new owner1794 * @param amount number of pieces to be transfered1795 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1796 * @returns ```true``` if extrinsic success, otherwise ```false```1797 */1798 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1799 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1800 }18011802 /**1803 * Change ownership of some pieces of RFT on behalf of the owner.1804 * @param signer keyring of signer1805 * @param collectionId ID of collection1806 * @param tokenId ID of token1807 * @param fromAddressObj address on behalf of which the token will be sent1808 * @param toAddressObj new token owner1809 * @param amount number of pieces to be transfered1810 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1811 * @returns ```true``` if extrinsic success, otherwise ```false```1812 */1813 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1814 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1815 }18161817 /**1818 * Mint new collection1819 * @param signer keyring of signer1820 * @param collectionOptions Collection options1821 * @example1822 * mintCollection(aliceKeyring, {1823 * name: 'New',1824 * description: 'New collection',1825 * tokenPrefix: 'NEW',1826 * })1827 * @returns object of the created collection1828 */1829 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1830 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1831 }18321833 /**1834 * Mint new token1835 * @param signer keyring of signer1836 * @param data token data1837 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1838 * @returns created token object1839 */1840 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1841 const creationResult = await this.helper.executeExtrinsic(1842 signer,1843 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1844 refungible: {1845 pieces: data.pieces,1846 properties: data.properties,1847 },1848 }],1849 true,1850 );1851 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1852 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1853 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1854 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1855 }18561857 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1858 throw Error('Not implemented');1859 const creationResult = await this.helper.executeExtrinsic(1860 signer,1861 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1862 true, // `Unable to mint RFT tokens for ${label}`,1863 );1864 const collection = this.getCollectionObject(collectionId);1865 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1866 }18671868 /**1869 * Mint multiple RFT tokens with one owner1870 * @param signer keyring of signer1871 * @param collectionId ID of collection1872 * @param owner tokens owner1873 * @param tokens array of tokens with properties and pieces1874 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1875 * @returns array of newly created RFT tokens1876 */1877 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1878 const rawTokens = [];1879 for (const token of tokens) {1880 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1881 rawTokens.push(raw);1882 }1883 const creationResult = await this.helper.executeExtrinsic(1884 signer,1885 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1886 true,1887 );1888 const collection = this.getCollectionObject(collectionId);1889 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1890 }18911892 /**1893 * Destroys a concrete instance of RFT.1894 * @param signer keyring of signer1895 * @param collectionId ID of collection1896 * @param tokenId ID of token1897 * @param amount number of pieces to be burnt1898 * @example burnToken(aliceKeyring, 10, 5);1899 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1900 */1901 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1902 return await super.burnToken(signer, collectionId, tokenId, amount);1903 }19041905 /**1906 * Destroys a concrete instance of RFT on behalf of the owner.1907 * @param signer keyring of signer1908 * @param collectionId ID of collection1909 * @param tokenId ID of token1910 * @param fromAddressObj address on behalf of which the token will be burnt1911 * @param amount number of pieces to be burnt1912 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1913 * @returns ```true``` if extrinsic success, otherwise ```false```1914 */1915 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1916 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1917 }19181919 /**1920 * Set, change, or remove approved address to transfer the ownership of the RFT.1921 *1922 * @param signer keyring of signer1923 * @param collectionId ID of collection1924 * @param tokenId ID of token1925 * @param toAddressObj address to approve1926 * @param amount number of pieces to be approved1927 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1928 * @returns true if the token success, otherwise false1929 */1930 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1931 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1932 }19331934 /**1935 * Get total number of pieces1936 * @param collectionId ID of collection1937 * @param tokenId ID of token1938 * @example getTokenTotalPieces(10, 5);1939 * @returns number of pieces1940 */1941 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1942 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1943 }19441945 /**1946 * Change number of token pieces. Signer must be the owner of all token pieces.1947 * @param signer keyring of signer1948 * @param collectionId ID of collection1949 * @param tokenId ID of token1950 * @param amount new number of pieces1951 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1952 * @returns true if the repartion was success, otherwise false1953 */1954 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1955 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1956 const repartitionResult = await this.helper.executeExtrinsic(1957 signer,1958 'api.tx.unique.repartition', [collectionId, tokenId, amount],1959 true,1960 );1961 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1962 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1963 }1964}196519661967class FTGroup extends CollectionGroup {1968 /**1969 * Get collection object1970 * @param collectionId ID of collection1971 * @example getCollectionObject(2);1972 * @returns instance of UniqueFTCollection1973 */1974 getCollectionObject(collectionId: number): UniqueFTCollection {1975 return new UniqueFTCollection(collectionId, this.helper);1976 }19771978 /**1979 * Mint new fungible collection1980 * @param signer keyring of signer1981 * @param collectionOptions Collection options1982 * @param decimalPoints number of token decimals1983 * @example1984 * mintCollection(aliceKeyring, {1985 * name: 'New',1986 * description: 'New collection',1987 * tokenPrefix: 'NEW',1988 * }, 18)1989 * @returns newly created fungible collection1990 */1991 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1992 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1993 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1994 collectionOptions.mode = {fungible: decimalPoints};1995 for (const key of ['name', 'description', 'tokenPrefix']) {1996 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);1997 }1998 const creationResult = await this.helper.executeExtrinsic(1999 signer,2000 'api.tx.unique.createCollectionEx', [collectionOptions],2001 true,2002 );2003 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2004 }20052006 /**2007 * Mint tokens2008 * @param signer keyring of signer2009 * @param collectionId ID of collection2010 * @param owner address owner of new tokens2011 * @param amount amount of tokens to be meanted2012 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2013 * @returns ```true``` if extrinsic success, otherwise ```false```2014 */2015 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2016 const creationResult = await this.helper.executeExtrinsic(2017 signer,2018 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2019 fungible: {2020 value: amount,2021 },2022 }],2023 true, // `Unable to mint fungible tokens for ${label}`,2024 );2025 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2026 }20272028 /**2029 * Mint multiple Fungible tokens with one owner2030 * @param signer keyring of signer2031 * @param collectionId ID of collection2032 * @param owner tokens owner2033 * @param tokens array of tokens with properties and pieces2034 * @returns ```true``` if extrinsic success, otherwise ```false```2035 */2036 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2037 const rawTokens = [];2038 for (const token of tokens) {2039 const raw = {Fungible: {Value: token.value}};2040 rawTokens.push(raw);2041 }2042 const creationResult = await this.helper.executeExtrinsic(2043 signer,2044 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2045 true,2046 );2047 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2048 }20492050 /**2051 * Get the top 10 owners with the largest balance for the Fungible collection2052 * @param collectionId ID of collection2053 * @example getTop10Owners(10);2054 * @returns array of ```ICrossAccountId```2055 */2056 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2057 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2058 }20592060 /**2061 * Get account balance2062 * @param collectionId ID of collection2063 * @param addressObj address of owner2064 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2065 * @returns amount of fungible tokens owned by address2066 */2067 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2068 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2069 }20702071 /**2072 * Transfer tokens to address2073 * @param signer keyring of signer2074 * @param collectionId ID of collection2075 * @param toAddressObj address recipient2076 * @param amount amount of tokens to be sent2077 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2078 * @returns ```true``` if extrinsic success, otherwise ```false```2079 */2080 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2081 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2082 }20832084 /**2085 * Transfer some tokens on behalf of the owner.2086 * @param signer keyring of signer2087 * @param collectionId ID of collection2088 * @param fromAddressObj address on behalf of which tokens will be sent2089 * @param toAddressObj address where token to be sent2090 * @param amount number of tokens to be sent2091 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2092 * @returns ```true``` if extrinsic success, otherwise ```false```2093 */2094 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2095 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2096 }20972098 /**2099 * Destroy some amount of tokens2100 * @param signer keyring of signer2101 * @param collectionId ID of collection2102 * @param amount amount of tokens to be destroyed2103 * @example burnTokens(aliceKeyring, 10, 1000n);2104 * @returns ```true``` if extrinsic success, otherwise ```false```2105 */2106 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2107 return await super.burnToken(signer, collectionId, 0, amount);2108 }21092110 /**2111 * Burn some tokens on behalf of the owner.2112 * @param signer keyring of signer2113 * @param collectionId ID of collection2114 * @param fromAddressObj address on behalf of which tokens will be burnt2115 * @param amount amount of tokens to be burnt2116 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2117 * @returns ```true``` if extrinsic success, otherwise ```false```2118 */2119 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2120 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2121 }21222123 /**2124 * Get total collection supply2125 * @param collectionId2126 * @returns2127 */2128 async getTotalPieces(collectionId: number): Promise<bigint> {2129 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2130 }21312132 /**2133 * Set, change, or remove approved address to transfer tokens.2134 *2135 * @param signer keyring of signer2136 * @param collectionId ID of collection2137 * @param toAddressObj address to be approved2138 * @param amount amount of tokens to be approved2139 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2140 * @returns ```true``` if extrinsic success, otherwise ```false```2141 */2142 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2143 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2144 }21452146 /**2147 * Get amount of fungible tokens approved to transfer2148 * @param collectionId ID of collection2149 * @param fromAddressObj owner of tokens2150 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2151 * @returns number of tokens approved for the transfer2152 */2153 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2154 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2155 }2156}215721582159class ChainGroup extends HelperGroup<ChainHelperBase> {2160 /**2161 * Get system properties of a chain2162 * @example getChainProperties();2163 * @returns ss58Format, token decimals, and token symbol2164 */2165 getChainProperties(): IChainProperties {2166 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2167 return {2168 ss58Format: properties.ss58Format.toJSON(),2169 tokenDecimals: properties.tokenDecimals.toJSON(),2170 tokenSymbol: properties.tokenSymbol.toJSON(),2171 };2172 }21732174 /**2175 * Get chain header2176 * @example getLatestBlockNumber();2177 * @returns the number of the last block2178 */2179 async getLatestBlockNumber(): Promise<number> {2180 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2181 }21822183 /**2184 * Get block hash by block number2185 * @param blockNumber number of block2186 * @example getBlockHashByNumber(12345);2187 * @returns hash of a block2188 */2189 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2190 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2191 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2192 return blockHash;2193 }21942195 // TODO add docs2196 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2197 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2198 if (!blockHash) return null;2199 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2200 }22012202 /**2203 * Get account nonce2204 * @param address substrate address2205 * @example getNonce("5GrwvaEF5zXb26Fz...");2206 * @returns number, account's nonce2207 */2208 async getNonce(address: TSubstrateAccount): Promise<number> {2209 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2210 }2211}22122213class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2214 /**2215 * Get substrate address balance2216 * @param address substrate address2217 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2218 * @returns amount of tokens on address2219 */2220 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2221 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2222 }22232224 /**2225 * Transfer tokens to substrate address2226 * @param signer keyring of signer2227 * @param address substrate address of a recipient2228 * @param amount amount of tokens to be transfered2229 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2230 * @returns ```true``` if extrinsic success, otherwise ```false```2231 */2232 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2233 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}`*/);22342235 let transfer = {from: null, to: null, amount: 0n} as any;2236 result.result.events.forEach(({event: {data, method, section}}) => {2237 if ((section === 'balances') && (method === 'Transfer')) {2238 transfer = {2239 from: this.helper.address.normalizeSubstrate(data[0]),2240 to: this.helper.address.normalizeSubstrate(data[1]),2241 amount: BigInt(data[2]),2242 };2243 }2244 });2245 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2246 && this.helper.address.normalizeSubstrate(address) === transfer.to2247 && BigInt(amount) === transfer.amount;2248 return isSuccess;2249 }22502251 /**2252 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2253 * @param address substrate address2254 * @returns2255 */2256 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2257 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2258 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2259 }2260}22612262class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2263 /**2264 * Get ethereum address balance2265 * @param address ethereum address2266 * @example getEthereum("0x9F0583DbB855d...")2267 * @returns amount of tokens on address2268 */2269 async getEthereum(address: TEthereumAccount): Promise<bigint> {2270 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2271 }22722273 /**2274 * Transfer tokens to address2275 * @param signer keyring of signer2276 * @param address Ethereum address of a recipient2277 * @param amount amount of tokens to be transfered2278 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2279 * @returns ```true``` if extrinsic success, otherwise ```false```2280 */2281 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2282 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22832284 let transfer = {from: null, to: null, amount: 0n} as any;2285 result.result.events.forEach(({event: {data, method, section}}) => {2286 if ((section === 'balances') && (method === 'Transfer')) {2287 transfer = {2288 from: data[0].toString(),2289 to: data[1].toString(),2290 amount: BigInt(data[2]),2291 };2292 }2293 });2294 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2295 && address === transfer.to2296 && BigInt(amount) === transfer.amount;2297 return isSuccess;2298 }2299}23002301class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2302 subBalanceGroup: SubstrateBalanceGroup<T>;2303 ethBalanceGroup: EthereumBalanceGroup<T>;23042305 constructor(helper: T) {2306 super(helper);2307 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2308 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2309 }23102311 getCollectionCreationPrice(): bigint {2312 return 2n * this.getOneTokenNominal();2313 }2314 /**2315 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2316 * @example getOneTokenNominal()2317 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2318 */2319 getOneTokenNominal(): bigint {2320 const chainProperties = this.helper.chain.getChainProperties();2321 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2322 }23232324 /**2325 * Get substrate address balance2326 * @param address substrate address2327 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2328 * @returns amount of tokens on address2329 */2330 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2331 return this.subBalanceGroup.getSubstrate(address);2332 }23332334 /**2335 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2336 * @param address substrate address2337 * @returns2338 */2339 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2340 return this.subBalanceGroup.getSubstrateFull(address);2341 }23422343 /**2344 * Get ethereum address balance2345 * @param address ethereum address2346 * @example getEthereum("0x9F0583DbB855d...")2347 * @returns amount of tokens on address2348 */2349 getEthereum(address: TEthereumAccount): Promise<bigint> {2350 return this.ethBalanceGroup.getEthereum(address);2351 }23522353 /**2354 * Transfer tokens to substrate address2355 * @param signer keyring of signer2356 * @param address substrate address of a recipient2357 * @param amount amount of tokens to be transfered2358 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2359 * @returns ```true``` if extrinsic success, otherwise ```false```2360 */2361 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2362 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2363 }23642365 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2366 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);23672368 let transfer = {from: null, to: null, amount: 0n} as any;2369 result.result.events.forEach(({event: {data, method, section}}) => {2370 if ((section === 'balances') && (method === 'Transfer')) {2371 transfer = {2372 from: this.helper.address.normalizeSubstrate(data[0]),2373 to: this.helper.address.normalizeSubstrate(data[1]),2374 amount: BigInt(data[2]),2375 };2376 }2377 });2378 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2379 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2380 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2381 return isSuccess;2382 }2383}23842385class AddressGroup extends HelperGroup<ChainHelperBase> {2386 /**2387 * Normalizes the address to the specified ss58 format, by default ```42```.2388 * @param address substrate address2389 * @param ss58Format format for address conversion, by default ```42```2390 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2391 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2392 */2393 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2394 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2395 }23962397 /**2398 * Get address in the connected chain format2399 * @param address substrate address2400 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2401 * @returns address in chain format2402 */2403 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2404 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2405 }24062407 /**2408 * Get substrate mirror of an ethereum address2409 * @param ethAddress ethereum address2410 * @param toChainFormat false for normalized account2411 * @example ethToSubstrate('0x9F0583DbB855d...')2412 * @returns substrate mirror of a provided ethereum address2413 */2414 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2415 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2416 }24172418 /**2419 * Get ethereum mirror of a substrate address2420 * @param subAddress substrate account2421 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2422 * @returns ethereum mirror of a provided substrate address2423 */2424 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2425 return CrossAccountId.translateSubToEth(subAddress);2426 }24272428 /**2429 * Encode key to substrate address2430 * @param key key for encoding address2431 * @param ss58Format prefix for encoding to the address of the corresponding network2432 * @returns encoded substrate address2433 */2434 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2435 const u8a :Uint8Array = typeof key === 'string'2436 ? hexToU8a(key)2437 : typeof key === 'bigint'2438 ? hexToU8a(key.toString(16))2439 : key;2440 2441 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2442 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2443 }2444 2445 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2446 if (!allowedDecodedLengths.includes(u8a.length)) {2447 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2448 }2449 2450 const u8aPrefix = ss58Format < 642451 ? new Uint8Array([ss58Format])2452 : new Uint8Array([2453 ((ss58Format & 0xfc) >> 2) | 0x40,2454 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2455 ]);24562457 const input = u8aConcat(u8aPrefix, u8a);2458 2459 return base58Encode(u8aConcat(2460 input,2461 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2462 ));2463 }24642465 /**2466 * Restore substrate address from bigint representation2467 * @param number decimal representation of substrate address2468 * @returns substrate address2469 */2470 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2471 if (this.helper.api === null) {2472 throw 'Not connected';2473 }2474 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2475 if (res === undefined || res === null) {2476 throw 'Restore address error';2477 }2478 return res.toString();2479 }24802481 /**2482 * Convert etherium cross account id to substrate cross account id2483 * @param ethCrossAccount etherium cross account2484 * @returns substrate cross account id2485 */2486 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2487 if (ethCrossAccount.sub === '0') {2488 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2489 }2490 2491 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2492 return {Substrate: ss58};2493 }24942495 paraSiblingSovereignAccount(paraid: number) {2496 // We are getting a *sibling* parachain sovereign account,2497 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2498 const siblingPrefix = '0x7369626c';24992500 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2501 const suffix = '000000000000000000000000000000000000000000000000';25022503 return siblingPrefix + encodedParaId + suffix;2504 }2505}25062507class StakingGroup extends HelperGroup<UniqueHelper> {2508 /**2509 * Stake tokens for App Promotion2510 * @param signer keyring of signer2511 * @param amountToStake amount of tokens to stake2512 * @param label extra label for log2513 * @returns2514 */2515 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2516 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2517 const _stakeResult = await this.helper.executeExtrinsic(2518 signer, 'api.tx.appPromotion.stake',2519 [amountToStake], true,2520 );2521 // TODO extract info from stakeResult2522 return true;2523 }25242525 /**2526 * Unstake tokens for App Promotion2527 * @param signer keyring of signer2528 * @param amountToUnstake amount of tokens to unstake2529 * @param label extra label for log2530 * @returns block number where balances will be unlocked2531 */2532 async unstake(signer: TSigner, label?: string): Promise<number> {2533 if(typeof label === 'undefined') label = `${signer.address}`;2534 const _unstakeResult = await this.helper.executeExtrinsic(2535 signer, 'api.tx.appPromotion.unstake',2536 [], true,2537 );2538 // TODO extract block number fron events2539 return 1;2540 }25412542 /**2543 * Get total staked amount for address2544 * @param address substrate or ethereum address2545 * @returns total staked amount2546 */2547 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2548 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2549 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2550 }25512552 /**2553 * Get total staked per block2554 * @param address substrate or ethereum address2555 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2556 */2557 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2558 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2559 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2560 return {2561 block: block.toBigInt(),2562 amount: amount.toBigInt(),2563 };2564 });2565 }25662567 /**2568 * Get total pending unstake amount for address2569 * @param address substrate or ethereum address2570 * @returns total pending unstake amount2571 */2572 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2573 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2574 }25752576 /**2577 * Get pending unstake amount per block for address2578 * @param address substrate or ethereum address2579 * @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 block2580 */2581 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2582 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2583 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2584 return {2585 block: block.toBigInt(),2586 amount: amount.toBigInt(),2587 };2588 });2589 return result;2590 }2591}25922593class SchedulerGroup extends HelperGroup<UniqueHelper> {2594 constructor(helper: UniqueHelper) {2595 super(helper);2596 }25972598 cancelScheduled(signer: TSigner, scheduledId: string) {2599 return this.helper.executeExtrinsic(2600 signer,2601 'api.tx.scheduler.cancelNamed',2602 [scheduledId],2603 true,2604 );2605 }26062607 changePriority(signer: TSigner, scheduledId: string, priority: number) {2608 return this.helper.executeExtrinsic(2609 signer,2610 'api.tx.scheduler.changeNamedPriority',2611 [scheduledId, priority],2612 true,2613 );2614 }26152616 scheduleAt<T extends UniqueHelper>(2617 executionBlockNumber: number,2618 options: ISchedulerOptions = {},2619 ) {2620 return this.schedule<T>('schedule', executionBlockNumber, options);2621 }26222623 scheduleAfter<T extends UniqueHelper>(2624 blocksBeforeExecution: number,2625 options: ISchedulerOptions = {},2626 ) {2627 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2628 }26292630 schedule<T extends UniqueHelper>(2631 scheduleFn: 'schedule' | 'scheduleAfter',2632 blocksNum: number,2633 options: ISchedulerOptions = {},2634 ) {2635 // eslint-disable-next-line @typescript-eslint/naming-convention2636 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2637 return this.helper.clone(ScheduledHelperType, {2638 scheduleFn,2639 blocksNum,2640 options,2641 }) as T;2642 }2643}26442645class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2646 //todo:collator documentation2647 addInvulnerable(signer: TSigner, address: string) {2648 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2649 }26502651 removeInvulnerable(signer: TSigner, address: string) {2652 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2653 }26542655 async getInvulnerables(): Promise<string[]> {2656 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2657 }26582659 /** and also total max invulnerables */2660 maxCollators(): number {2661 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2662 }26632664 async getDesiredCollators(): Promise<number> {2665 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2666 }26672668 setLicenseBond(signer: TSigner, amount: bigint) {2669 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2670 }26712672 async getLicenseBond(): Promise<bigint> {2673 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2674 }26752676 obtainLicense(signer: TSigner) {2677 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2678 }26792680 releaseLicense(signer: TSigner) {2681 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2682 }26832684 forceRevokeLicense(signer: TSigner, released: string) {2685 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceRevokeLicense', [released]);2686 }26872688 async hasLicense(address: string): Promise<bigint> {2689 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2690 }26912692 onboard(signer: TSigner) {2693 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2694 }26952696 offboard(signer: TSigner) {2697 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2698 }26992700 async getCandidates(): Promise<string[]> {2701 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2702 }2703}27042705class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2706 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2707 await this.helper.executeExtrinsic(2708 signer,2709 'api.tx.foreignAssets.registerForeignAsset',2710 [ownerAddress, location, metadata],2711 true,2712 );2713 }27142715 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2716 await this.helper.executeExtrinsic(2717 signer,2718 'api.tx.foreignAssets.updateForeignAsset',2719 [foreignAssetId, location, metadata],2720 true,2721 );2722 }2723}27242725class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2726 palletName: string;27272728 constructor(helper: T, palletName: string) {2729 super(helper);27302731 this.palletName = palletName;2732 }27332734 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2735 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2736 }2737}27382739class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2740 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2741 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2742 }27432744 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2745 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2746 }27472748 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2749 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2750 }2751}27522753class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2754 async accounts(address: string, currencyId: any) {2755 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2756 return BigInt(free);2757 }2758}27592760class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2761 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2762 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2763 }27642765 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2766 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2767 }27682769 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2770 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2771 }27722773 async account(assetId: string | number, address: string) {2774 const accountAsset = (2775 await this.helper.callRpc('api.query.assets.account', [assetId, address])2776 ).toJSON()! as any;27772778 if (accountAsset !== null) {2779 return BigInt(accountAsset['balance']);2780 } else {2781 return null;2782 }2783 }2784}27852786class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2787 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2788 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2789 }2790}27912792class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2793 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2794 const apiPrefix = 'api.tx.assetManager.';27952796 const registerTx = this.helper.constructApiCall(2797 apiPrefix + 'registerForeignAsset',2798 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2799 );28002801 const setUnitsTx = this.helper.constructApiCall(2802 apiPrefix + 'setAssetUnitsPerSecond',2803 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2804 );28052806 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2807 const encodedProposal = batchCall?.method.toHex() || '';2808 return encodedProposal;2809 }28102811 async assetTypeId(location: any) {2812 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2813 }2814}28152816class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2817 async notePreimage(signer: TSigner, encodedProposal: string) {2818 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2819 }28202821 externalProposeMajority(proposalHash: string) {2822 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2823 }28242825 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2826 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2827 }28282829 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2830 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2831 }2832}28332834class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2835 collective: string;28362837 constructor(helper: MoonbeamHelper, collective: string) {2838 super(helper);28392840 this.collective = collective;2841 }28422843 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2844 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2845 }28462847 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2848 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2849 }28502851 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2852 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2853 }28542855 async proposalCount() {2856 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2857 }2858}28592860export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2861export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;28622863export class UniqueHelper extends ChainHelperBase {2864 balance: BalanceGroup<UniqueHelper>;2865 collection: CollectionGroup;2866 nft: NFTGroup;2867 rft: RFTGroup;2868 ft: FTGroup;2869 staking: StakingGroup;2870 scheduler: SchedulerGroup;2871 collatorSelection: CollatorSelectionGroup;2872 foreignAssets: ForeignAssetsGroup;2873 xcm: XcmGroup<UniqueHelper>;2874 xTokens: XTokensGroup<UniqueHelper>;2875 tokens: TokensGroup<UniqueHelper>;28762877 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2878 super(logger, options.helperBase ?? UniqueHelper);28792880 this.balance = new BalanceGroup(this);2881 this.collection = new CollectionGroup(this);2882 this.nft = new NFTGroup(this);2883 this.rft = new RFTGroup(this);2884 this.ft = new FTGroup(this);2885 this.staking = new StakingGroup(this);2886 this.scheduler = new SchedulerGroup(this);2887 this.collatorSelection = new CollatorSelectionGroup(this);2888 this.foreignAssets = new ForeignAssetsGroup(this);2889 this.xcm = new XcmGroup(this, 'polkadotXcm');2890 this.xTokens = new XTokensGroup(this);2891 this.tokens = new TokensGroup(this);2892 }28932894 getSudo<T extends UniqueHelper>() {2895 // eslint-disable-next-line @typescript-eslint/naming-convention2896 const SudoHelperType = SudoHelper(this.helperBase);2897 return this.clone(SudoHelperType) as T;2898 }2899}29002901export class XcmChainHelper extends ChainHelperBase {2902 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2903 const wsProvider = new WsProvider(wsEndpoint);2904 this.api = new ApiPromise({2905 provider: wsProvider,2906 });2907 await this.api.isReadyOrError;2908 this.network = await UniqueHelper.detectNetwork(this.api);2909 }2910}29112912export class RelayHelper extends XcmChainHelper {2913 xcm: XcmGroup<RelayHelper>;29142915 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2916 super(logger, options.helperBase ?? RelayHelper);29172918 this.xcm = new XcmGroup(this, 'xcmPallet');2919 }2920}29212922export class WestmintHelper extends XcmChainHelper {2923 balance: SubstrateBalanceGroup<WestmintHelper>;2924 xcm: XcmGroup<WestmintHelper>;2925 assets: AssetsGroup<WestmintHelper>;2926 xTokens: XTokensGroup<WestmintHelper>;29272928 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2929 super(logger, options.helperBase ?? WestmintHelper);29302931 this.balance = new SubstrateBalanceGroup(this);2932 this.xcm = new XcmGroup(this, 'polkadotXcm');2933 this.assets = new AssetsGroup(this);2934 this.xTokens = new XTokensGroup(this);2935 }2936}29372938export class MoonbeamHelper extends XcmChainHelper {2939 balance: EthereumBalanceGroup<MoonbeamHelper>;2940 assetManager: MoonbeamAssetManagerGroup;2941 assets: AssetsGroup<MoonbeamHelper>;2942 xTokens: XTokensGroup<MoonbeamHelper>;2943 democracy: MoonbeamDemocracyGroup;2944 collective: {2945 council: MoonbeamCollectiveGroup,2946 techCommittee: MoonbeamCollectiveGroup,2947 };29482949 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2950 super(logger, options.helperBase ?? MoonbeamHelper);29512952 this.balance = new EthereumBalanceGroup(this);2953 this.assetManager = new MoonbeamAssetManagerGroup(this);2954 this.assets = new AssetsGroup(this);2955 this.xTokens = new XTokensGroup(this);2956 this.democracy = new MoonbeamDemocracyGroup(this);2957 this.collective = {2958 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2959 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2960 };2961 }2962}29632964export class AcalaHelper extends XcmChainHelper {2965 balance: SubstrateBalanceGroup<AcalaHelper>;2966 assetRegistry: AcalaAssetRegistryGroup;2967 xTokens: XTokensGroup<AcalaHelper>;2968 tokens: TokensGroup<AcalaHelper>;29692970 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2971 super(logger, options.helperBase ?? AcalaHelper);29722973 this.balance = new SubstrateBalanceGroup(this);2974 this.assetRegistry = new AcalaAssetRegistryGroup(this);2975 this.xTokens = new XTokensGroup(this);2976 this.tokens = new TokensGroup(this);2977 }29782979 getSudo<T extends AcalaHelper>() {2980 // eslint-disable-next-line @typescript-eslint/naming-convention2981 const SudoHelperType = SudoHelper(this.helperBase);2982 return this.clone(SudoHelperType) as T;2983 }2984}29852986// eslint-disable-next-line @typescript-eslint/naming-convention2987function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2988 return class extends Base {2989 scheduleFn: 'schedule' | 'scheduleAfter';2990 blocksNum: number;2991 options: ISchedulerOptions;29922993 constructor(...args: any[]) {2994 const logger = args[0] as ILogger;2995 const options = args[1] as {2996 scheduleFn: 'schedule' | 'scheduleAfter',2997 blocksNum: number,2998 options: ISchedulerOptions2999 };30003001 super(logger);30023003 this.scheduleFn = options.scheduleFn;3004 this.blocksNum = options.blocksNum;3005 this.options = options.options;3006 }30073008 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3009 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);3010 3011 const mandatorySchedArgs = [3012 this.blocksNum,3013 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3014 this.options.priority ?? null,3015 scheduledTx,3016 ];3017 3018 let schedArgs;3019 let scheduleFn;30203021 if (this.options.scheduledId) {3022 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];30233024 if (this.scheduleFn == 'schedule') {3025 scheduleFn = 'scheduleNamed';3026 } else if (this.scheduleFn == 'scheduleAfter') {3027 scheduleFn = 'scheduleNamedAfter';3028 }3029 } else {3030 schedArgs = mandatorySchedArgs;3031 scheduleFn = this.scheduleFn;3032 }30333034 const extrinsic = 'api.tx.scheduler.' + scheduleFn;30353036 return super.executeExtrinsic(3037 sender,3038 extrinsic,3039 schedArgs,3040 expectSuccess,3041 );3042 }3043 };3044}30453046// eslint-disable-next-line @typescript-eslint/naming-convention3047function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3048 return class extends Base {3049 constructor(...args: any[]) {3050 super(...args);3051 }30523053 async executeExtrinsic(3054 sender: IKeyringPair,3055 extrinsic: string,3056 params: any[],3057 expectSuccess?: boolean,3058 options: Partial<SignerOptions>|null = null,3059 ): Promise<ITransactionResult> {3060 const call = this.constructApiCall(extrinsic, params);3061 const result = await super.executeExtrinsic(3062 sender,3063 'api.tx.sudo.sudo',3064 [call],3065 expectSuccess,3066 options,3067 );30683069 if (result.status === 'Fail') return result;30703071 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3072 if (data.isErr) {3073 if (data.asErr.isModule) {3074 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3075 const metaError = super.getApi()?.registry.findMetaError(error);3076 throw new Error(`${metaError.section}.${metaError.name}`);3077 } else {3078 throw new Error(data.asErr.toHuman());3079 }3080 }3081 return result;3082 }3083 };3084}30853086export class UniqueBaseCollection {3087 helper: UniqueHelper;3088 collectionId: number;30893090 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3091 this.collectionId = collectionId;3092 this.helper = uniqueHelper;3093 }30943095 async getData() {3096 return await this.helper.collection.getData(this.collectionId);3097 }30983099 async getLastTokenId() {3100 return await this.helper.collection.getLastTokenId(this.collectionId);3101 }31023103 async doesTokenExist(tokenId: number) {3104 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3105 }31063107 async getAdmins() {3108 return await this.helper.collection.getAdmins(this.collectionId);3109 }31103111 async getAllowList() {3112 return await this.helper.collection.getAllowList(this.collectionId);3113 }31143115 async getEffectiveLimits() {3116 return await this.helper.collection.getEffectiveLimits(this.collectionId);3117 }31183119 async getProperties(propertyKeys?: string[] | null) {3120 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3121 }31223123 async getPropertiesConsumedSpace() {3124 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3125 }31263127 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3128 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3129 }31303131 async getOptions() {3132 return await this.helper.collection.getCollectionOptions(this.collectionId);3133 }31343135 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3136 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3137 }31383139 async confirmSponsorship(signer: TSigner) {3140 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3141 }31423143 async removeSponsor(signer: TSigner) {3144 return await this.helper.collection.removeSponsor(signer, this.collectionId);3145 }31463147 async setLimits(signer: TSigner, limits: ICollectionLimits) {3148 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3149 }31503151 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3152 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3153 }31543155 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3156 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3157 }31583159 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3160 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3161 }31623163 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3164 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3165 }31663167 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3168 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3169 }31703171 async setProperties(signer: TSigner, properties: IProperty[]) {3172 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3173 }31743175 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3176 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3177 }31783179 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3180 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3181 }31823183 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3184 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3185 }31863187 async disableNesting(signer: TSigner) {3188 return await this.helper.collection.disableNesting(signer, this.collectionId);3189 }31903191 async burn(signer: TSigner) {3192 return await this.helper.collection.burn(signer, this.collectionId);3193 }31943195 scheduleAt<T extends UniqueHelper>(3196 executionBlockNumber: number,3197 options: ISchedulerOptions = {},3198 ) {3199 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3200 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3201 }32023203 scheduleAfter<T extends UniqueHelper>(3204 blocksBeforeExecution: number,3205 options: ISchedulerOptions = {},3206 ) {3207 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3208 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3209 }32103211 getSudo<T extends UniqueHelper>() {3212 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3213 }3214}321532163217export class UniqueNFTCollection extends UniqueBaseCollection {3218 getTokenObject(tokenId: number) {3219 return new UniqueNFToken(tokenId, this);3220 }32213222 async getTokensByAddress(addressObj: ICrossAccountId) {3223 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3224 }32253226 async getToken(tokenId: number, blockHashAt?: string) {3227 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3228 }32293230 async getTokenOwner(tokenId: number, blockHashAt?: string) {3231 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3232 }32333234 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3235 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3236 }32373238 async getTokenChildren(tokenId: number, blockHashAt?: string) {3239 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3240 }32413242 async getPropertyPermissions(propertyKeys: string[] | null = null) {3243 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3244 }32453246 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3247 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3248 }32493250 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3251 const api = this.helper.getApi();3252 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();3253 3254 return (props! as any).consumedSpace;3255 }32563257 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3258 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3259 }32603261 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3262 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3263 }32643265 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3266 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3267 }32683269 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3270 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3271 }32723273 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3274 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3275 }32763277 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3278 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3279 }32803281 async burnToken(signer: TSigner, tokenId: number) {3282 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3283 }32843285 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3286 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3287 }32883289 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3290 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3291 }32923293 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3294 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3295 }32963297 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3298 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3299 }33003301 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3302 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3303 }33043305 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3306 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3307 }33083309 scheduleAt<T extends UniqueHelper>(3310 executionBlockNumber: number,3311 options: ISchedulerOptions = {},3312 ) {3313 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3314 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3315 }33163317 scheduleAfter<T extends UniqueHelper>(3318 blocksBeforeExecution: number,3319 options: ISchedulerOptions = {},3320 ) {3321 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3322 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3323 }33243325 getSudo<T extends UniqueHelper>() {3326 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3327 }3328}332933303331export class UniqueRFTCollection extends UniqueBaseCollection {3332 getTokenObject(tokenId: number) {3333 return new UniqueRFToken(tokenId, this);3334 }33353336 async getToken(tokenId: number, blockHashAt?: string) {3337 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3338 }33393340 async getTokensByAddress(addressObj: ICrossAccountId) {3341 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3342 }33433344 async getTop10TokenOwners(tokenId: number) {3345 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3346 }33473348 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3349 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3350 }33513352 async getTokenTotalPieces(tokenId: number) {3353 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3354 }33553356 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3357 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3358 }33593360 async getPropertyPermissions(propertyKeys: string[] | null = null) {3361 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3362 }33633364 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3365 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3366 }33673368 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3369 const api = this.helper.getApi();3370 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();3371 3372 return (props! as any).consumedSpace;3373 }33743375 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3376 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3377 }33783379 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3380 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3381 }33823383 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3384 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3385 }33863387 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3388 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3389 }33903391 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3392 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3393 }33943395 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3396 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3397 }33983399 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3400 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3401 }34023403 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3404 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3405 }34063407 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3408 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3409 }34103411 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3412 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3413 }34143415 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3416 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3417 }34183419 scheduleAt<T extends UniqueHelper>(3420 executionBlockNumber: number,3421 options: ISchedulerOptions = {},3422 ) {3423 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3424 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3425 }34263427 scheduleAfter<T extends UniqueHelper>(3428 blocksBeforeExecution: number,3429 options: ISchedulerOptions = {},3430 ) {3431 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3432 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3433 }34343435 getSudo<T extends UniqueHelper>() {3436 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3437 }3438}343934403441export class UniqueFTCollection extends UniqueBaseCollection {3442 async getBalance(addressObj: ICrossAccountId) {3443 return await this.helper.ft.getBalance(this.collectionId, addressObj);3444 }34453446 async getTotalPieces() {3447 return await this.helper.ft.getTotalPieces(this.collectionId);3448 }34493450 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3451 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3452 }34533454 async getTop10Owners() {3455 return await this.helper.ft.getTop10Owners(this.collectionId);3456 }34573458 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3459 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3460 }34613462 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3463 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3464 }34653466 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3467 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3468 }34693470 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3471 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3472 }34733474 async burnTokens(signer: TSigner, amount=1n) {3475 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3476 }34773478 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3479 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3480 }34813482 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3483 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3484 }34853486 scheduleAt<T extends UniqueHelper>(3487 executionBlockNumber: number,3488 options: ISchedulerOptions = {},3489 ) {3490 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3491 return new UniqueFTCollection(this.collectionId, scheduledHelper);3492 }34933494 scheduleAfter<T extends UniqueHelper>(3495 blocksBeforeExecution: number,3496 options: ISchedulerOptions = {},3497 ) {3498 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3499 return new UniqueFTCollection(this.collectionId, scheduledHelper);3500 }35013502 getSudo<T extends UniqueHelper>() {3503 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3504 }3505}350635073508export class UniqueBaseToken {3509 collection: UniqueNFTCollection | UniqueRFTCollection;3510 collectionId: number;3511 tokenId: number;35123513 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3514 this.collection = collection;3515 this.collectionId = collection.collectionId;3516 this.tokenId = tokenId;3517 }35183519 async getNextSponsored(addressObj: ICrossAccountId) {3520 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3521 }35223523 async getProperties(propertyKeys?: string[] | null) {3524 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3525 }35263527 async getTokenPropertiesConsumedSpace() {3528 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3529 }35303531 async setProperties(signer: TSigner, properties: IProperty[]) {3532 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3533 }35343535 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3536 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3537 }35383539 async doesExist() {3540 return await this.collection.doesTokenExist(this.tokenId);3541 }35423543 nestingAccount() {3544 return this.collection.helper.util.getTokenAccount(this);3545 }35463547 scheduleAt<T extends UniqueHelper>(3548 executionBlockNumber: number,3549 options: ISchedulerOptions = {},3550 ) {3551 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3552 return new UniqueBaseToken(this.tokenId, scheduledCollection);3553 }35543555 scheduleAfter<T extends UniqueHelper>(3556 blocksBeforeExecution: number,3557 options: ISchedulerOptions = {},3558 ) {3559 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3560 return new UniqueBaseToken(this.tokenId, scheduledCollection);3561 }35623563 getSudo<T extends UniqueHelper>() {3564 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3565 }3566}356735683569export class UniqueNFToken extends UniqueBaseToken {3570 collection: UniqueNFTCollection;35713572 constructor(tokenId: number, collection: UniqueNFTCollection) {3573 super(tokenId, collection);3574 this.collection = collection;3575 }35763577 async getData(blockHashAt?: string) {3578 return await this.collection.getToken(this.tokenId, blockHashAt);3579 }35803581 async getOwner(blockHashAt?: string) {3582 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3583 }35843585 async getTopmostOwner(blockHashAt?: string) {3586 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3587 }35883589 async getChildren(blockHashAt?: string) {3590 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3591 }35923593 async nest(signer: TSigner, toTokenObj: IToken) {3594 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3595 }35963597 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3598 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3599 }36003601 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3602 return await this.collection.transferToken(signer, this.tokenId, addressObj);3603 }36043605 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3606 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3607 }36083609 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3610 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3611 }36123613 async isApproved(toAddressObj: ICrossAccountId) {3614 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3615 }36163617 async burn(signer: TSigner) {3618 return await this.collection.burnToken(signer, this.tokenId);3619 }36203621 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3622 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3623 }36243625 scheduleAt<T extends UniqueHelper>(3626 executionBlockNumber: number,3627 options: ISchedulerOptions = {},3628 ) {3629 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3630 return new UniqueNFToken(this.tokenId, scheduledCollection);3631 }36323633 scheduleAfter<T extends UniqueHelper>(3634 blocksBeforeExecution: number,3635 options: ISchedulerOptions = {},3636 ) {3637 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3638 return new UniqueNFToken(this.tokenId, scheduledCollection);3639 }36403641 getSudo<T extends UniqueHelper>() {3642 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3643 }3644}36453646export class UniqueRFToken extends UniqueBaseToken {3647 collection: UniqueRFTCollection;36483649 constructor(tokenId: number, collection: UniqueRFTCollection) {3650 super(tokenId, collection);3651 this.collection = collection;3652 }36533654 async getData(blockHashAt?: string) {3655 return await this.collection.getToken(this.tokenId, blockHashAt);3656 }36573658 async getTop10Owners() {3659 return await this.collection.getTop10TokenOwners(this.tokenId);3660 }36613662 async getBalance(addressObj: ICrossAccountId) {3663 return await this.collection.getTokenBalance(this.tokenId, addressObj);3664 }36653666 async getTotalPieces() {3667 return await this.collection.getTokenTotalPieces(this.tokenId);3668 }36693670 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3671 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3672 }36733674 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3675 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3676 }36773678 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3679 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3680 }36813682 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3683 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3684 }36853686 async repartition(signer: TSigner, amount: bigint) {3687 return await this.collection.repartitionToken(signer, this.tokenId, amount);3688 }36893690 async burn(signer: TSigner, amount=1n) {3691 return await this.collection.burnToken(signer, this.tokenId, amount);3692 }36933694 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3695 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3696 }36973698 scheduleAt<T extends UniqueHelper>(3699 executionBlockNumber: number,3700 options: ISchedulerOptions = {},3701 ) {3702 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3703 return new UniqueRFToken(this.tokenId, scheduledCollection);3704 }37053706 scheduleAfter<T extends UniqueHelper>(3707 blocksBeforeExecution: number,3708 options: ISchedulerOptions = {},3709 ) {3710 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3711 return new UniqueRFToken(this.tokenId, scheduledCollection);3712 }37133714 getSudo<T extends UniqueHelper>() {3715 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3716 }3717}