difftreelog
feat Separate rpc calls to own group
in: master
31 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -113,6 +113,20 @@
checksum = "508b352bb5c066aac251f6daf6b36eccd03e8a88e8081cd44959ea277a3af9a8"
[[package]]
+name = "app-promotion-rpc"
+version = "0.1.0"
+dependencies = [
+ "pallet-common",
+ "pallet-evm",
+ "parity-scale-codec 3.1.5",
+ "sp-api",
+ "sp-core",
+ "sp-runtime",
+ "sp-std",
+ "up-data-structs",
+]
+
+[[package]]
name = "approx"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -5127,6 +5141,7 @@
name = "opal-runtime"
version = "0.9.27"
dependencies = [
+ "app-promotion-rpc",
"cumulus-pallet-aura-ext",
"cumulus-pallet-dmp-queue",
"cumulus-pallet-parachain-system",
@@ -8358,6 +8373,7 @@
name = "quartz-runtime"
version = "0.9.27"
dependencies = [
+ "app-promotion-rpc",
"cumulus-pallet-aura-ext",
"cumulus-pallet-dmp-queue",
"cumulus-pallet-parachain-system",
@@ -8381,6 +8397,7 @@
"hex-literal",
"log",
"orml-vesting",
+ "pallet-app-promotion",
"pallet-aura",
"pallet-balances",
"pallet-base-fee",
@@ -12132,6 +12149,7 @@
version = "0.1.3"
dependencies = [
"anyhow",
+ "app-promotion-rpc",
"jsonrpsee",
"pallet-common",
"pallet-evm",
@@ -12210,6 +12228,7 @@
name = "unique-node"
version = "0.9.27"
dependencies = [
+ "app-promotion-rpc",
"clap",
"cumulus-client-cli",
"cumulus-client-collator",
@@ -12298,6 +12317,7 @@
name = "unique-rpc"
version = "0.1.1"
dependencies = [
+ "app-promotion-rpc",
"fc-db",
"fc-mapping-sync",
"fc-rpc",
@@ -12347,6 +12367,7 @@
name = "unique-runtime"
version = "0.9.27"
dependencies = [
+ "app-promotion-rpc",
"cumulus-pallet-aura-ext",
"cumulus-pallet-dmp-queue",
"cumulus-pallet-parachain-system",
@@ -12370,6 +12391,7 @@
"hex-literal",
"log",
"orml-vesting",
+ "pallet-app-promotion",
"pallet-aura",
"pallet-balances",
"pallet-base-fee",
client/rpc/Cargo.tomldiffbeforeafterboth--- a/client/rpc/Cargo.toml
+++ b/client/rpc/Cargo.toml
@@ -8,6 +8,7 @@
pallet-common = { default-features = false, path = '../../pallets/common' }
up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
up-rpc = { path = "../../primitives/rpc" }
+app-promotion-rpc = { path = "../../primitives/app_promotion_rpc"}
rmrk-rpc = { path = "../../primitives/rmrk-rpc" }
codec = { package = "parity-scale-codec", version = "3.1.2" }
jsonrpsee = { version = "0.14.0", features = ["server", "macros"] }
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -31,6 +31,7 @@
use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};
use sp_blockchain::HeaderBackend;
use up_rpc::UniqueApi as UniqueRuntimeApi;
+use app_promotion_rpc::AppPromotionApi as AppPromotionRuntimeApi;
// RMRK
use rmrk_rpc::RmrkApi as RmrkRuntimeApi;
@@ -38,6 +39,7 @@
RmrkCollectionId, RmrkNftId, RmrkBaseId, RmrkNftChild, RmrkThemeName, RmrkResourceId,
};
+pub use app_promotion_unique_rpc::AppPromotionApiServer;
pub use rmrk_unique_rpc::RmrkApiServer;
#[rpc(server)]
@@ -244,39 +246,48 @@
token_id: TokenId,
at: Option<BlockHash>,
) -> Result<Option<String>>;
+}
+
+mod app_promotion_unique_rpc {
+ use super::*;
+
+ #[rpc(server)]
+ #[async_trait]
+ pub trait AppPromotionApi<BlockHash, BlockNumber, CrossAccountId, AccountId> {
+ /// Returns the total amount of staked tokens.
+ #[method(name = "appPromotion_totalStaked")]
+ fn total_staked(&self, staker: Option<CrossAccountId>, at: Option<BlockHash>)
+ -> Result<String>;
- /// Returns the total amount of staked tokens.
- #[method(name = "unique_totalStaked")]
- fn total_staked(&self, staker: Option<CrossAccountId>, at: Option<BlockHash>)
- -> Result<String>;
+ ///Returns the total amount of staked tokens per block when staked.
+ #[method(name = "appPromotion_totalStakedPerBlock")]
+ fn total_staked_per_block(
+ &self,
+ staker: CrossAccountId,
+ at: Option<BlockHash>,
+ ) -> Result<Vec<(BlockNumber, String)>>;
- ///Returns the total amount of staked tokens per block when staked.
- #[method(name = "unique_totalStakedPerBlock")]
- fn total_staked_per_block(
- &self,
- staker: CrossAccountId,
- at: Option<BlockHash>,
- ) -> Result<Vec<(BlockNumber, String)>>;
+ /// Returns the total amount locked by staking tokens.
+ #[method(name = "appPromotion_totalStakingLocked")]
+ fn total_staking_locked(&self, staker: CrossAccountId, at: Option<BlockHash>)
+ -> Result<String>;
- /// Returns the total amount locked by staking tokens.
- #[method(name = "unique_totalStakingLocked")]
- fn total_staking_locked(&self, staker: CrossAccountId, at: Option<BlockHash>)
- -> Result<String>;
+ /// Returns the total amount of tokens pending withdrawal from staking.
+ #[method(name = "appPromotion_pendingUnstake")]
+ fn pending_unstake(
+ &self,
+ staker: Option<CrossAccountId>,
+ at: Option<BlockHash>,
+ ) -> Result<String>;
- /// Returns the total amount of tokens pending withdrawal from staking.
- #[method(name = "unique_pendingUnstake")]
- fn pending_unstake(
- &self,
- staker: Option<CrossAccountId>,
- at: Option<BlockHash>,
- ) -> Result<String>;
- /// Returns the total amount of tokens pending withdrawal from staking per block.
- #[method(name = "unique_pendingUnstakePerBlock")]
- fn pending_unstake_per_block(
- &self,
- staker: CrossAccountId,
- at: Option<BlockHash>,
- ) -> Result<Vec<(BlockNumber, String)>>;
+ /// Returns the total amount of tokens pending withdrawal from staking per block.
+ #[method(name = "appPromotion_pendingUnstakePerBlock")]
+ fn pending_unstake_per_block(
+ &self,
+ staker: CrossAccountId,
+ at: Option<BlockHash>,
+ ) -> Result<Vec<(BlockNumber, String)>>;
+ }
}
mod rmrk_unique_rpc {
@@ -415,6 +426,20 @@
}
}
+pub struct AppPromotion<C, P> {
+ client: Arc<C>,
+ _marker: std::marker::PhantomData<P>,
+}
+
+impl<C, P> AppPromotion<C, P> {
+ pub fn new(client: Arc<C>) -> Self {
+ Self {
+ client,
+ _marker: Default::default(),
+ }
+ }
+}
+
pub struct Rmrk<C, P> {
client: Arc<C>,
_marker: std::marker::PhantomData<P>,
@@ -474,6 +499,12 @@
};
}
+macro_rules! app_promotion_api {
+ () => {
+ dyn AppPromotionRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>
+ };
+}
+
macro_rules! rmrk_api {
() => {
dyn RmrkRuntimeApi<Block, AccountId, CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme>
@@ -556,7 +587,20 @@
pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>, unique_api);
pass_method!(total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<String> => |o| o.map(|number| number.to_string()) , unique_api);
pass_method!(token_owners(collection: CollectionId, token: TokenId) -> Vec<CrossAccountId>, unique_api);
- pass_method!(total_staked(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), unique_api);
+}
+
+impl<C, Block, BlockNumber, CrossAccountId, AccountId>
+ app_promotion_unique_rpc::AppPromotionApiServer<<Block as BlockT>::Hash, BlockNumber, CrossAccountId, AccountId>
+ for AppPromotion<C, Block>
+where
+ Block: BlockT,
+ BlockNumber: Decode + Member + AtLeast32BitUnsigned,
+ AccountId: Decode,
+ C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
+ C::Api: AppPromotionRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>,
+ CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,
+{
+ pass_method!(total_staked(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), app_promotion_api);
pass_method!(total_staked_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>
|v| v
.into_iter()
node/cli/Cargo.tomldiffbeforeafterboth--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -318,6 +318,7 @@
pallet-ethereum = { git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.27" }
unique-rpc = { default-features = false, path = "../rpc" }
+app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false}
rmrk-rpc = { path = "../../primitives/rmrk-rpc" }
[features]
node/cli/src/service.rsdiffbeforeafterboth--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -364,6 +364,7 @@
+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>
+ up_rpc::UniqueApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
+ + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
+ rmrk_rpc::RmrkApi<
Block,
AccountId,
@@ -665,6 +666,7 @@
+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>
+ up_rpc::UniqueApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
+ + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
+ rmrk_rpc::RmrkApi<
Block,
AccountId,
@@ -809,6 +811,7 @@
+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>
+ up_rpc::UniqueApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
+ + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
+ rmrk_rpc::RmrkApi<
Block,
AccountId,
node/rpc/Cargo.tomldiffbeforeafterboth--- a/node/rpc/Cargo.toml
+++ b/node/rpc/Cargo.toml
@@ -53,6 +53,7 @@
pallet-unique = { path = "../../pallets/unique" }
uc-rpc = { path = "../../client/rpc" }
up-rpc = { path = "../../primitives/rpc" }
+app-promotion-rpc = { path = "../../primitives/app_promotion_rpc"}
rmrk-rpc = { path = "../../primitives/rmrk-rpc" }
up-data-structs = { default-features = false, path = "../../primitives/data-structs" }
node/rpc/src/lib.rsdiffbeforeafterboth--- a/node/rpc/src/lib.rs
+++ b/node/rpc/src/lib.rs
@@ -38,6 +38,7 @@
use sp_block_builder::BlockBuilder;
use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
use sc_service::TransactionPool;
+use uc_rpc::AppPromotion;
use std::{collections::BTreeMap, sync::Arc};
use up_common::types::opaque::{Hash, AccountId, RuntimeInstance, Index, Block, BlockNumber, Balance};
@@ -147,6 +148,7 @@
C::Api: fp_rpc::ConvertTransactionRuntimeApi<Block>,
C::Api:
up_rpc::UniqueApi<Block, BlockNumber, <R as RuntimeInstance>::CrossAccountId, AccountId>,
+ C::Api: app_promotion_rpc::AppPromotionApi<Block, BlockNumber, <R as RuntimeInstance>::CrossAccountId, AccountId>,
C::Api: rmrk_rpc::RmrkApi<
Block,
AccountId,
@@ -171,6 +173,7 @@
EthPubSubApiServer, EthSigner, Net, NetApiServer, Web3, Web3ApiServer,
};
use uc_rpc::{UniqueApiServer, Unique};
+ use uc_rpc::{AppPromotionApiServer, AppPromotion};
#[cfg(not(feature = "unique-runtime"))]
use uc_rpc::{RmrkApiServer, Rmrk};
@@ -229,6 +232,9 @@
io.merge(Unique::new(client.clone()).into_rpc())?;
+ // #[cfg(not(feature = "unique-runtime"))]
+ io.merge(AppPromotion::new(client.clone()).into_rpc())?;
+
#[cfg(not(feature = "unique-runtime"))]
io.merge(Rmrk::new(client.clone()).into_rpc())?;
primitives/app_promotion_rpc/CHANGELOG.mddiffbeforeafterboth--- /dev/null
+++ b/primitives/app_promotion_rpc/CHANGELOG.md
@@ -0,0 +1,5 @@
+# Change Log
+
+All notable changes to this project will be documented in this file.
+
+<!-- bureaucrate goes here -->
primitives/app_promotion_rpc/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/primitives/app_promotion_rpc/Cargo.toml
@@ -0,0 +1,29 @@
+[package]
+name = "app-promotion-rpc"
+version = "0.1.0"
+license = "GPLv3"
+edition = "2021"
+
+[dependencies]
+pallet-common = { default-features = false, path = '../../pallets/common' }
+up-data-structs = { default-features = false, path = '../data-structs' }
+codec = { package = "parity-scale-codec", version = "3.1.2", default-features = false, features = [
+ "derive",
+] }
+sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
+sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
+sp-api = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
+sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.27" }
+
+[features]
+default = ["std"]
+std = [
+ "codec/std",
+ "sp-core/std",
+ "sp-std/std",
+ "sp-api/std",
+ "sp-runtime/std",
+ "pallet-common/std",
+ "up-data-structs/std",
+]
primitives/app_promotion_rpc/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/primitives/app_promotion_rpc/src/lib.rs
@@ -0,0 +1,47 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use up_data_structs::{
+ CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits, Property,
+ PropertyKeyPermission, TokenData, TokenChild,
+};
+
+use sp_std::vec::Vec;
+use codec::Decode;
+use sp_runtime::{
+ DispatchError,
+ traits::{AtLeast32BitUnsigned, Member},
+};
+
+type Result<T> = core::result::Result<T, DispatchError>;
+
+sp_api::decl_runtime_apis! {
+ #[api_version(2)]
+ /// Trait for generate rpc.
+ pub trait AppPromotionApi<BlockNumber ,CrossAccountId, AccountId> where
+ BlockNumber: Decode + Member + AtLeast32BitUnsigned,
+ AccountId: Decode,
+ CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,
+ {
+ fn total_staked(staker: Option<CrossAccountId>) -> Result<u128>;
+ fn total_staked_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>>;
+ fn total_staking_locked(staker: CrossAccountId) -> Result<u128>;
+ fn pending_unstake(staker: Option<CrossAccountId>) -> Result<u128>;
+ fn pending_unstake_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>>;
+ }
+}
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -127,11 +127,5 @@
fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Result<Option<u128>>;
fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec<CrossAccountId>>;
- fn total_staked(staker: Option<CrossAccountId>) -> Result<u128>;
- fn total_staked_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>>;
- fn total_staking_locked(staker: CrossAccountId) -> Result<u128>;
- fn pending_unstake(staker: Option<CrossAccountId>) -> Result<u128>;
- fn pending_unstake_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>>;
-
}
}
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -187,25 +187,47 @@
fn total_pieces(collection: CollectionId, token_id: TokenId) -> Result<Option<u128>, DispatchError> {
dispatch_unique_runtime!(collection.total_pieces(token_id))
}
+ }
+ impl app_promotion_rpc::AppPromotionApi<Block, BlockNumber, CrossAccountId, AccountId> for Runtime {
fn total_staked(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {
- Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked(staker).unwrap_or_default())
- }
+ #[cfg(not(feature = "app-promotion"))]
+ return unsupported!();
+ #[cfg(feature = "app-promotion")]
+ return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked(staker).unwrap_or_default());
+ }
+
fn total_staked_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {
- Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked_per_block(staker))
+ #[cfg(not(feature = "app-promotion"))]
+ return unsupported!();
+
+ #[cfg(feature = "app-promotion")]
+ return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked_per_block(staker));
}
fn total_staking_locked(staker: CrossAccountId) -> Result<u128, DispatchError> {
- Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_locked_balance(staker))
+ #[cfg(not(feature = "app-promotion"))]
+ return unsupported!();
+
+ #[cfg(feature = "app-promotion")]
+ return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_locked_balance(staker));
}
fn pending_unstake(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {
- Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake(staker))
+ #[cfg(not(feature = "app-promotion"))]
+ return unsupported!();
+
+ #[cfg(feature = "app-promotion")]
+ return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake(staker));
}
fn pending_unstake_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {
- Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake_per_block(staker))
+ #[cfg(not(feature = "app-promotion"))]
+ return unsupported!();
+
+ #[cfg(feature = "app-promotion")]
+ return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake_per_block(staker))
}
}
runtime/opal/Cargo.tomldiffbeforeafterboth--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -83,6 +83,7 @@
'pallet-base-fee/std',
'fp-rpc/std',
'up-rpc/std',
+ 'app-promotion-rpc/std',
'fp-evm-mapping/std',
'fp-self-contained/std',
'parachain-info/std',
@@ -414,6 +415,7 @@
derivative = "2.2.0"
pallet-unique = { path = '../../pallets/unique', default-features = false }
up-rpc = { path = "../../primitives/rpc", default-features = false }
+app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false}
rmrk-rpc = { path = "../../primitives/rmrk-rpc", default-features = false }
fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.27" }
pallet-inflation = { path = '../../pallets/inflation', default-features = false }
runtime/quartz/Cargo.tomldiffbeforeafterboth--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -82,6 +82,7 @@
'pallet-base-fee/std',
'fp-rpc/std',
'up-rpc/std',
+ 'app-promotion-rpc/std',
'fp-evm-mapping/std',
'fp-self-contained/std',
'parachain-info/std',
@@ -416,8 +417,10 @@
derivative = "2.2.0"
pallet-unique = { path = '../../pallets/unique', default-features = false }
up-rpc = { path = "../../primitives/rpc", default-features = false }
+app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false}
fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.27" }
pallet-inflation = { path = '../../pallets/inflation', default-features = false }
+pallet-app-promotion = { path = '../../pallets/app-promotion', default-features = false }
up-data-structs = { path = '../../primitives/data-structs', default-features = false }
pallet-configuration = { default-features = false, path = "../../pallets/configuration" }
pallet-common = { default-features = false, path = "../../pallets/common" }
runtime/unique/Cargo.tomldiffbeforeafterboth--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -83,6 +83,7 @@
'pallet-base-fee/std',
'fp-rpc/std',
'up-rpc/std',
+ 'app-promotion-rpc/std',
'fp-evm-mapping/std',
'fp-self-contained/std',
'parachain-info/std',
@@ -409,8 +410,10 @@
derivative = "2.2.0"
pallet-unique = { path = '../../pallets/unique', default-features = false }
up-rpc = { path = "../../primitives/rpc", default-features = false }
+app-promotion-rpc = { path = "../../primitives/app_promotion_rpc", default-features = false}
rmrk-rpc = { path = "../../primitives/rmrk-rpc", default-features = false }
pallet-inflation = { path = '../../pallets/inflation', default-features = false }
+pallet-app-promotion = { path = '../../pallets/app-promotion', default-features = false }
up-data-structs = { path = '../../primitives/data-structs', default-features = false }
pallet-configuration = { default-features = false, path = "../../pallets/configuration" }
pallet-common = { default-features = false, path = "../../pallets/common" }
tests/src/interfaces/appPromotion/definitions.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/interfaces/appPromotion/definitions.ts
@@ -0,0 +1,66 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+type RpcParam = {
+ name: string;
+ type: string;
+ isOptional?: true;
+};
+
+const CROSS_ACCOUNT_ID_TYPE = 'PalletEvmAccountBasicCrossAccountIdRepr';
+
+const collectionParam = {name: 'collection', type: 'u32'};
+const tokenParam = {name: 'tokenId', type: 'u32'};
+const propertyKeysParam = {name: 'propertyKeys', type: 'Vec<String>', isOptional: true};
+const crossAccountParam = (name = 'account') => ({name, type: CROSS_ACCOUNT_ID_TYPE});
+const atParam = {name: 'at', type: 'Hash', isOptional: true};
+
+const fun = (description: string, params: RpcParam[], type: string) => ({
+ description,
+ params: [...params, atParam],
+ type,
+});
+
+export default {
+ types: {},
+ rpc: {
+ totalStaked: fun(
+ 'Returns the total amount of staked tokens',
+ [{name: 'staker', type: CROSS_ACCOUNT_ID_TYPE, isOptional: true}],
+ 'u128',
+ ),
+ totalStakedPerBlock: fun(
+ 'Returns the total amount of staked tokens per block when staked',
+ [crossAccountParam('staker')],
+ 'Vec<(u32, u128)>',
+ ),
+ totalStakingLocked: fun(
+ 'Return the total amount locked by staking tokens',
+ [crossAccountParam('staker')],
+ 'u128',
+ ),
+ pendingUnstake: fun(
+ 'Returns the total amount of unstaked tokens',
+ [{name: 'staker', type: CROSS_ACCOUNT_ID_TYPE, isOptional: true}],
+ 'u128',
+ ),
+ pendingUnstakePerBlock: fun(
+ 'Returns the total amount of unstaked tokens per block',
+ [crossAccountParam('staker')],
+ 'Vec<(u32, u128)>',
+ ),
+ },
+};
tests/src/interfaces/appPromotion/index.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/interfaces/appPromotion/index.ts
@@ -0,0 +1,4 @@
+// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
+/* eslint-disable */
+
+export * from './types';
tests/src/interfaces/appPromotion/types.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/interfaces/appPromotion/types.ts
@@ -0,0 +1,4 @@
+// Auto-generated via `yarn polkadot-types-from-defs`, do not edit
+/* eslint-disable */
+
+export type PHANTOM_APPPROMOTION = 'appPromotion';
tests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -269,7 +269,7 @@
**/
NoPendingSponsor: AugmentedError<ApiType>;
/**
- * This method is only executable by owner.
+ * This method is only executable by contract owner
**/
NoPermission: AugmentedError<ApiType>;
/**
@@ -278,7 +278,13 @@
[key: string]: AugmentedError<ApiType>;
};
evmMigration: {
+ /**
+ * Migration of this account is not yet started, or already finished.
+ **/
AccountIsNotMigrating: AugmentedError<ApiType>;
+ /**
+ * Can only migrate to empty address.
+ **/
AccountNotEmpty: AugmentedError<ApiType>;
/**
* Generic error
tests/src/interfaces/augment-api-query.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -335,7 +335,7 @@
*
* Currently used to store RMRK data.
**/
- tokenAuxProperties: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array, arg3: UpDataStructsPropertyScope | 'None' | 'Rmrk' | 'Eth' | number | Uint8Array, arg4: Bytes | string | Uint8Array) => Observable<Option<Bytes>>, [u32, u32, UpDataStructsPropertyScope, Bytes]> & QueryableStorageEntry<ApiType, [u32, u32, UpDataStructsPropertyScope, Bytes]>;
+ tokenAuxProperties: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array, arg3: UpDataStructsPropertyScope | 'None' | 'Rmrk' | number | Uint8Array, arg4: Bytes | string | Uint8Array) => Observable<Option<Bytes>>, [u32, u32, UpDataStructsPropertyScope, Bytes]> & QueryableStorageEntry<ApiType, [u32, u32, UpDataStructsPropertyScope, Bytes]>;
/**
* Used to enumerate token's children.
**/
tests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-rpc.ts
+++ b/tests/src/interfaces/augment-api-rpc.ts
@@ -35,6 +35,28 @@
declare module '@polkadot/rpc-core/types/jsonrpc' {
interface RpcInterface {
+ appPromotion: {
+ /**
+ * Returns the total amount of unstaked tokens
+ **/
+ pendingUnstake: AugmentedRpc<(staker?: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
+ /**
+ * Returns the total amount of unstaked tokens per block
+ **/
+ pendingUnstakePerBlock: AugmentedRpc<(staker: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<ITuple<[u32, u128]>>>>;
+ /**
+ * Returns the total amount of staked tokens
+ **/
+ totalStaked: AugmentedRpc<(staker?: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
+ /**
+ * Returns the total amount of staked tokens per block when staked
+ **/
+ totalStakedPerBlock: AugmentedRpc<(staker: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<ITuple<[u32, u128]>>>>;
+ /**
+ * Return the total amount locked by staking tokens
+ **/
+ totalStakingLocked: AugmentedRpc<(staker: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
+ };
author: {
/**
* Returns true if the keystore has private keys for the given public key and key type.
@@ -702,15 +724,7 @@
* Get the number of blocks until sponsoring a transaction is available
**/
nextSponsored: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, account: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: u32 | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<u64>>>;
- /**
- * Returns the total amount of unstaked tokens
- **/
- pendingUnstake: AugmentedRpc<(staker?: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
/**
- * Returns the total amount of unstaked tokens per block
- **/
- pendingUnstakePerBlock: AugmentedRpc<(staker: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<ITuple<[u32, u128]>>>>;
- /**
* Get property permissions, optionally limited to the provided keys
**/
propertyPermissions: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, propertyKeys?: Vec<Text> | (Text | string)[], at?: Hash | string | Uint8Array) => Observable<Vec<UpDataStructsPropertyKeyPermission>>>;
@@ -746,18 +760,6 @@
* Get the total amount of pieces of an RFT
**/
totalPieces: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, tokenId: u32 | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<u128>>>;
- /**
- * Returns the total amount of staked tokens
- **/
- totalStaked: AugmentedRpc<(staker?: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
- /**
- * Returns the total amount of staked tokens per block when staked
- **/
- totalStakedPerBlock: AugmentedRpc<(staker: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<ITuple<[u32, u128]>>>>;
- /**
- * Return the total amount locked by staking tokens
- **/
- totalStakingLocked: AugmentedRpc<(staker: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
/**
* Get the amount of distinctive tokens present in a collection
**/
tests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -181,8 +181,21 @@
[key: string]: SubmittableExtrinsicFunction<ApiType>;
};
evmMigration: {
+ /**
+ * Start contract migration, inserts contract stub at target address,
+ * and marks account as pending, allowing to insert storage
+ **/
begin: AugmentedSubmittable<(address: H160 | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [H160]>;
+ /**
+ * Finish contract migration, allows it to be called.
+ * It is not possible to alter contract storage via [`Self::set_data`]
+ * after this call.
+ **/
finish: AugmentedSubmittable<(address: H160 | string | Uint8Array, code: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [H160, Bytes]>;
+ /**
+ * Insert items into contract storage, this method can be called
+ * multiple times
+ **/
setData: AugmentedSubmittable<(address: H160 | string | Uint8Array, data: Vec<ITuple<[H256, H256]>> | ([H256 | string | Uint8Array, H256 | string | Uint8Array])[]) => SubmittableExtrinsic<ApiType>, [H160, Vec<ITuple<[H256, H256]>>]>;
/**
* Generic tx
@@ -372,7 +385,7 @@
stopAppPromotion: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
stopSponsoringCollection: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32]>;
stopSponsoringContract: AugmentedSubmittable<(contractId: H160 | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [H160]>;
- unstake: AugmentedSubmittable<(amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u128]>;
+ unstake: AugmentedSubmittable<() => SubmittableExtrinsic<ApiType>, []>;
/**
* Generic tx
**/
tests/src/interfaces/default/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -822,9 +822,6 @@
readonly amount: u128;
} & Struct;
readonly isUnstake: boolean;
- readonly asUnstake: {
- readonly amount: u128;
- } & Struct;
readonly isSponsorCollection: boolean;
readonly asSponsorCollection: {
readonly collectionId: u32;
@@ -2639,8 +2636,7 @@
export interface UpDataStructsPropertyScope extends Enum {
readonly isNone: boolean;
readonly isRmrk: boolean;
- readonly isEth: boolean;
- readonly type: 'None' | 'Rmrk' | 'Eth';
+ readonly type: 'None' | 'Rmrk';
}
/** @name UpDataStructsRpcCollection */
tests/src/interfaces/definitions.tsdiffbeforeafterboth--- a/tests/src/interfaces/definitions.ts
+++ b/tests/src/interfaces/definitions.ts
@@ -15,5 +15,6 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
export {default as unique} from './unique/definitions';
+export {default as appPromotion} from './appPromotion/definitions';
export {default as rmrk} from './rmrk/definitions';
export {default as default} from './default/definitions';
\ No newline at end of file
tests/src/interfaces/lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -2467,9 +2467,7 @@
stake: {
amount: 'u128',
},
- unstake: {
- amount: 'u128',
- },
+ unstake: 'Null',
sponsor_collection: {
collectionId: 'u32',
},
@@ -3078,7 +3076,7 @@
* Lookup403: up_data_structs::PropertyScope
**/
UpDataStructsPropertyScope: {
- _enum: ['None', 'Rmrk', 'Eth']
+ _enum: ['None', 'Rmrk']
},
/**
* Lookup405: pallet_nonfungible::pallet::Error<T>
tests/src/interfaces/types-lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -2675,9 +2675,6 @@
readonly amount: u128;
} & Struct;
readonly isUnstake: boolean;
- readonly asUnstake: {
- readonly amount: u128;
- } & Struct;
readonly isSponsorCollection: boolean;
readonly asSponsorCollection: {
readonly collectionId: u32;
@@ -3238,8 +3235,7 @@
interface UpDataStructsPropertyScope extends Enum {
readonly isNone: boolean;
readonly isRmrk: boolean;
- readonly isEth: boolean;
- readonly type: 'None' | 'Rmrk' | 'Eth';
+ readonly type: 'None' | 'Rmrk';
}
/** @name PalletNonfungibleError (405) */
tests/src/interfaces/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/types.ts
+++ b/tests/src/interfaces/types.ts
@@ -2,5 +2,6 @@
/* eslint-disable */
export * from './unique/types';
+export * from './appPromotion/types';
export * from './rmrk/types';
export * from './default/types';
tests/src/interfaces/unique/definitions.tsdiffbeforeafterboth--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -175,30 +175,5 @@
[collectionParam, tokenParam],
'Option<u128>',
),
- totalStaked: fun(
- 'Returns the total amount of staked tokens',
- [{name: 'staker', type: CROSS_ACCOUNT_ID_TYPE, isOptional: true}],
- 'u128',
- ),
- totalStakedPerBlock: fun(
- 'Returns the total amount of staked tokens per block when staked',
- [crossAccountParam('staker')],
- 'Vec<(u32, u128)>',
- ),
- totalStakingLocked: fun(
- 'Return the total amount locked by staking tokens',
- [crossAccountParam('staker')],
- 'u128',
- ),
- pendingUnstake: fun(
- 'Returns the total amount of unstaked tokens',
- [{name: 'staker', type: CROSS_ACCOUNT_ID_TYPE, isOptional: true}],
- 'u128',
- ),
- pendingUnstakePerBlock: fun(
- 'Returns the total amount of unstaked tokens per block',
- [crossAccountParam('staker')],
- 'Vec<(u32, u128)>',
- ),
},
};
tests/src/substrate/substrate-api.tsdiffbeforeafterboth--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -42,6 +42,7 @@
},
rpc: {
unique: defs.unique.rpc,
+ appPromotion: defs.appPromotion.rpc,
rmrk: defs.rmrk.rpc,
eth: {
feeHistory: {
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -35,6 +35,7 @@
},
rpc: {
unique: defs.unique.rpc,
+ appPromotion: defs.appPromotion.rpc,
rmrk: defs.rmrk.rpc,
eth: {
feeHistory: {
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} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};202122const nesting = {23 toChecksumAddress(address: string): string {24 if (typeof address === 'undefined') return '';2526 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2728 address = address.toLowerCase().replace(/^0x/i,'');29 const addressHash = keccakAsHex(address).replace(/^0x/i,'');30 const checksumAddress = ['0x'];3132 for (let i = 0; i < address.length; i++) {33 // If ith character is 8 to f then make it uppercase34 if (parseInt(addressHash[i], 16) > 7) {35 checksumAddress.push(address[i].toUpperCase());36 } else {37 checksumAddress.push(address[i]);38 }39 }40 return checksumAddress.join('');41 },42 tokenIdToAddress(collectionId: number, tokenId: number) {43 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);44 },45};4647class UniqueUtil {48 static transactionStatus = {49 NOT_READY: 'NotReady',50 FAIL: 'Fail',51 SUCCESS: 'Success',52 };5354 static chainLogType = {55 EXTRINSIC: 'extrinsic',56 RPC: 'rpc',57 };5859 static getNestingTokenAddress(collectionId: number, tokenId: number) {60 return nesting.tokenIdToAddress(collectionId, tokenId);61 }6263 static getDefaultLogger(): ILogger {64 return {65 log(msg: any, level = 'INFO') {66 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));67 },68 level: {69 ERROR: 'ERROR',70 WARNING: 'WARNING',71 INFO: 'INFO',72 },73 };74 }7576 static vec2str(arr: string[] | number[]) {77 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');78 }7980 static str2vec(string: string) {81 if (typeof string !== 'string') return string;82 return Array.from(string).map(x => x.charCodeAt(0));83 }8485 static fromSeed(seed: string, ss58Format = 42) {86 const keyring = new Keyring({type: 'sr25519', ss58Format});87 return keyring.addFromUri(seed);88 }8990 static normalizeSubstrateAddress(address: string, ss58Format = 42) {91 return encodeAddress(decodeAddress(address), ss58Format);92 }9394 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult, label = 'new collection') {95 if (creationResult.status !== this.transactionStatus.SUCCESS) {96 throw Error(`Unable to create collection for ${label}`);97 }9899 let collectionId = null;100 creationResult.result.events.forEach(({event: {data, method, section}}) => {101 if ((section === 'common') && (method === 'CollectionCreated')) {102 collectionId = parseInt(data[0].toString(), 10);103 }104 });105106 if (collectionId === null) {107 throw Error(`No CollectionCreated event for ${label}`);108 }109110 return collectionId;111 }112113 static extractTokensFromCreationResult(creationResult: ITransactionResult, label = 'new tokens') {114 if (creationResult.status !== this.transactionStatus.SUCCESS) {115 throw Error(`Unable to create tokens for ${label}`);116 }117 let success = false;118 const tokens = [] as any;119 creationResult.result.events.forEach(({event: {data, method, section}}) => {120 if (method === 'ExtrinsicSuccess') {121 success = true;122 } else if ((section === 'common') && (method === 'ItemCreated')) {123 tokens.push({124 collectionId: parseInt(data[0].toString(), 10),125 tokenId: parseInt(data[1].toString(), 10),126 owner: data[2].toJSON(),127 });128 }129 });130 return {success, tokens};131 }132133 static extractTokensFromBurnResult(burnResult: ITransactionResult, label = 'burned tokens') {134 if (burnResult.status !== this.transactionStatus.SUCCESS) {135 throw Error(`Unable to burn tokens for ${label}`);136 }137 let success = false;138 const tokens = [] as any;139 burnResult.result.events.forEach(({event: {data, method, section}}) => {140 if (method === 'ExtrinsicSuccess') {141 success = true;142 } else if ((section === 'common') && (method === 'ItemDestroyed')) {143 tokens.push({144 collectionId: parseInt(data[0].toString(), 10),145 tokenId: parseInt(data[1].toString(), 10),146 owner: data[2].toJSON(),147 });148 }149 });150 return {success, tokens};151 }152153 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string, label?: string) {154 let eventId = null;155 events.forEach(({event: {data, method, section}}) => {156 if ((section === expectedSection) && (method === expectedMethod)) {157 eventId = parseInt(data[0].toString(), 10);158 }159 });160161 if (eventId === null) {162 throw Error(`No ${expectedMethod} event for ${label}`);163 }164 return eventId === collectionId;165 }166167 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {168 const normalizeAddress = (address: string | ICrossAccountId) => {169 if(typeof address === 'string') return address;170 const obj = {} as any;171 Object.keys(address).forEach(k => {172 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];173 });174 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};175 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};176 return address;177 };178 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;179 events.forEach(({event: {data, method, section}}) => {180 if ((section === 'common') && (method === 'Transfer')) {181 const hData = (data as any).toJSON();182 transfer = {183 collectionId: hData[0],184 tokenId: hData[1],185 from: normalizeAddress(hData[2]),186 to: normalizeAddress(hData[3]),187 amount: BigInt(hData[4]),188 };189 }190 });191 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);193 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);194 isSuccess = isSuccess && amount === transfer.amount;195 return isSuccess;196 }197}198199200class ChainHelperBase {201 transactionStatus = UniqueUtil.transactionStatus;202 chainLogType = UniqueUtil.chainLogType;203 util: typeof UniqueUtil;204 logger: ILogger;205 api: ApiPromise | null;206 forcedNetwork: TUniqueNetworks | null;207 network: TUniqueNetworks | null;208 chainLog: IUniqueHelperLog[];209210 constructor(logger?: ILogger) {211 this.util = UniqueUtil;212 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();213 this.logger = logger;214 this.api = null;215 this.forcedNetwork = null;216 this.network = null;217 this.chainLog = [];218 }219220 clearChainLog(): void {221 this.chainLog = [];222 }223224 forceNetwork(value: TUniqueNetworks): void {225 this.forcedNetwork = value;226 }227228 async connect(wsEndpoint: string, listeners?: IApiListeners) {229 if (this.api !== null) throw Error('Already connected');230 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);231 this.api = api;232 this.network = network;233 }234235 async disconnect() {236 if (this.api === null) return;237 await this.api.disconnect();238 this.api = null;239 this.network = null;240 }241242 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {243 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;244 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;245 return 'opal';246 }247248 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {249 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});250 await api.isReady;251252 const network = await this.detectNetwork(api);253254 await api.disconnect();255256 return network;257 }258259 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 260 api: ApiPromise; 261 network: TUniqueNetworks; 262 }> {263 if(typeof network === 'undefined' || network === null) network = 'opal';264 const supportedRPC = {265 opal: {266 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,267 },268 quartz: {269 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,270 },271 unique: {272 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,273 },274 };275 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);276 const rpc = supportedRPC[network];277278 // TODO: investigate how to replace rpc in runtime279 // api._rpcCore.addUserInterfaces(rpc);280281 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});282283 await api.isReadyOrError;284285 if (typeof listeners === 'undefined') listeners = {};286 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {287 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;288 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);289 }290291 return {api, network};292 }293294 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {295 const {events, status} = data;296 if (status.isReady) {297 return this.transactionStatus.NOT_READY;298 }299 if (status.isBroadcast) {300 return this.transactionStatus.NOT_READY;301 }302 if (status.isInBlock || status.isFinalized) {303 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');304 if (errors.length > 0) {305 return this.transactionStatus.FAIL;306 }307 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {308 return this.transactionStatus.SUCCESS;309 }310 }311312 return this.transactionStatus.FAIL;313 }314315 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {316 const sign = (callback: any) => {317 if(options !== null) return transaction.signAndSend(sender, options, callback);318 return transaction.signAndSend(sender, callback);319 };320 return new Promise(async (resolve, reject) => {321 try {322 const unsub = await sign((result: any) => {323 const status = this.getTransactionStatus(result);324325 if (status === this.transactionStatus.SUCCESS) {326 this.logger.log(`${label} successful`);327 unsub();328 resolve({result, status});329 } else if (status === this.transactionStatus.FAIL) {330 let moduleError = null;331332 if (result.hasOwnProperty('dispatchError')) {333 const dispatchError = result['dispatchError'];334335 if (dispatchError && dispatchError.isModule) {336 const modErr = dispatchError.asModule;337 const errorMeta = dispatchError.registry.findMetaError(modErr);338339 moduleError = `${errorMeta.section}.${errorMeta.name}`;340 }341 else {342 this.logger.log(result, this.logger.level.ERROR);343 }344 }345346 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);347 unsub();348 reject({status, moduleError, result});349 }350 });351 } catch (e) {352 this.logger.log(e, this.logger.level.ERROR);353 reject(e);354 }355 });356 }357358 constructApiCall(apiCall: string, params: any[]) {359 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);360 let call = this.api as any;361 for(const part of apiCall.slice(4).split('.')) {362 call = call[part];363 }364 return call(...params);365 }366367 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false, failureMessage='expected success') {368 if(this.api === null) throw Error('API not initialized');369 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);370371 const startTime = (new Date()).getTime();372 let result: ITransactionResult;373 let events = [];374 try {375 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;376 events = result.result.events.map((x: any) => x.toHuman());377 }378 catch(e) {379 if(!(e as object).hasOwnProperty('status')) throw e;380 result = e as ITransactionResult;381 }382383 const endTime = (new Date()).getTime();384385 const log = {386 executedAt: endTime,387 executionTime: endTime - startTime,388 type: this.chainLogType.EXTRINSIC,389 status: result.status,390 call: extrinsic,391 params,392 } as IUniqueHelperLog;393394 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;395 if(events.length > 0) log.events = events;396397 this.chainLog.push(log);398399 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(failureMessage);400 return result;401 }402403 async callRpc(rpc: string, params?: any[]) {404 if(typeof params === 'undefined') params = [];405 if(this.api === null) throw Error('API not initialized');406 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);407408 const startTime = (new Date()).getTime();409 let result;410 let error = null;411 const log = {412 type: this.chainLogType.RPC,413 call: rpc,414 params,415 } as IUniqueHelperLog;416417 try {418 result = await this.constructApiCall(rpc, params);419 }420 catch(e) {421 error = e;422 }423424 const endTime = (new Date()).getTime();425426 log.executedAt = endTime;427 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';428 log.executionTime = endTime - startTime;429430 this.chainLog.push(log);431432 if(error !== null) throw error;433434 return result;435 }436437 getSignerAddress(signer: IKeyringPair | string): string {438 if(typeof signer === 'string') return signer;439 return signer.address;440 }441}442443444class HelperGroup {445 helper: UniqueHelper;446447 constructor(uniqueHelper: UniqueHelper) {448 this.helper = uniqueHelper;449 }450}451452453class CollectionGroup extends HelperGroup {454 /**455 * Get number of blocks when sponsored transaction is available.456 *457 * @param collectionId ID of collection458 * @param tokenId ID of token459 * @param addressObj address for which the sponsorship is checked460 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});461 * @returns number of blocks or null if sponsorship hasn't been set462 */463 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {464 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();465 }466467 /**468 * Get the number of created collections.469 * 470 * @returns number of created collections471 */472 async getTotalCount(): Promise<number> {473 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();474 }475476 /**477 * Get information about the collection with additional data, including the number of tokens it contains, its administrators, the normalized address of the collection's owner, and decoded name and description.478 * 479 * @param collectionId ID of collection480 * @example await getData(2)481 * @returns collection information object482 */483 async getData(collectionId: number): Promise<{484 id: number;485 name: string;486 description: string;487 tokensCount: number;488 admins: ICrossAccountId[];489 normalizedOwner: TSubstrateAccount;490 raw: any491 } | null> {492 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);493 const humanCollection = collection.toHuman(), collectionData = {494 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],495 raw: humanCollection,496 } as any, jsonCollection = collection.toJSON();497 if (humanCollection === null) return null;498 collectionData.raw.limits = jsonCollection.limits;499 collectionData.raw.permissions = jsonCollection.permissions;500 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);501 for (const key of ['name', 'description']) {502 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);503 }504505 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;506 collectionData.admins = await this.getAdmins(collectionId);507508 return collectionData;509 }510511 /**512 * Get the normalized addresses of the collection's administrators.513 * 514 * @param collectionId ID of collection515 * @example await getAdmins(1)516 * @returns array of administrators517 */518 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {519 const normalized = [];520 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {521 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});522 else normalized.push(admin);523 }524 return normalized;525 }526527 /**528 * Get the normalized addresses added to the collection allow-list.529 * @param collectionId ID of collection530 * @example await getAllowList(1)531 * @returns array of allow-listed addresses532 */533 async getAllowList(collectionId: number): Promise<ICrossAccountId[]> {534 const normalized = [];535 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();536 for (const address of allowListed) {537 if (address.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(address.Substrate)});538 else normalized.push(address);539 }540 return normalized;541 }542543 /**544 * Get the effective limits of the collection instead of null for default values545 * 546 * @param collectionId ID of collection547 * @example await getEffectiveLimits(2)548 * @returns object of collection limits549 */550 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {551 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();552 }553554 /**555 * Burns the collection if the signer has sufficient permissions and collection is empty.556 * 557 * @param signer keyring of signer558 * @param collectionId ID of collection559 * @param label extra label for log560 * @example await helper.collection.burn(aliceKeyring, 3);561 * @returns ```true``` if extrinsic success, otherwise ```false```562 */563 async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {564 if(typeof label === 'undefined') label = `collection #${collectionId}`;565 const result = await this.helper.executeExtrinsic(566 signer,567 'api.tx.unique.destroyCollection', [collectionId],568 true, `Unable to burn collection for ${label}`,569 );570571 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);572 }573574 /**575 * Sets the sponsor for the collection (Requires the Substrate address).576 * 577 * @param signer keyring of signer578 * @param collectionId ID of collection579 * @param sponsorAddress Sponsor substrate address580 * @param label extra label for log581 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")582 * @returns ```true``` if extrinsic success, otherwise ```false```583 */584 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, label?: string): Promise<boolean> {585 if(typeof label === 'undefined') label = `collection #${collectionId}`;586 const result = await this.helper.executeExtrinsic(587 signer,588 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],589 true, `Unable to set collection sponsor for ${label}`,590 );591592 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);593 }594595 /**596 * Confirms consent to sponsor the collection on behalf of the signer.597 * 598 * @param signer keyring of signer599 * @param collectionId ID of collection600 * @param label extra label for log601 * @example confirmSponsorship(aliceKeyring, 10)602 * @returns ```true``` if extrinsic success, otherwise ```false```603 */604 async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {605 if(typeof label === 'undefined') label = `collection #${collectionId}`;606 const result = await this.helper.executeExtrinsic(607 signer,608 'api.tx.unique.confirmSponsorship', [collectionId],609 true, `Unable to confirm collection sponsorship for ${label}`,610 );611612 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);613 }614615 /**616 * Sets the limits of the collection. At least one limit must be specified for a correct call.617 * 618 * @param signer keyring of signer619 * @param collectionId ID of collection620 * @param limits collection limits object621 * @param label extra label for log622 * @example623 * await setLimits(624 * aliceKeyring,625 * 10,626 * {627 * sponsorTransferTimeout: 0,628 * ownerCanDestroy: false629 * }630 * )631 * @returns ```true``` if extrinsic success, otherwise ```false```632 */633 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {634 if(typeof label === 'undefined') label = `collection #${collectionId}`;635 const result = await this.helper.executeExtrinsic(636 signer,637 'api.tx.unique.setCollectionLimits', [collectionId, limits],638 true, `Unable to set collection limits for ${label}`,639 );640641 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);642 }643644 /**645 * Changes the owner of the collection to the new Substrate address.646 * 647 * @param signer keyring of signer648 * @param collectionId ID of collection649 * @param ownerAddress substrate address of new owner650 * @param label extra label for log651 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")652 * @returns ```true``` if extrinsic success, otherwise ```false```653 */654 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, label?: string): Promise<boolean> {655 if(typeof label === 'undefined') label = `collection #${collectionId}`;656 const result = await this.helper.executeExtrinsic(657 signer,658 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],659 true, `Unable to change collection owner for ${label}`,660 );661662 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);663 }664665 /**666 * Adds a collection administrator. 667 * 668 * @param signer keyring of signer669 * @param collectionId ID of collection670 * @param adminAddressObj Administrator address (substrate or ethereum)671 * @param label extra label for log672 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})673 * @returns ```true``` if extrinsic success, otherwise ```false```674 */675 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {676 if(typeof label === 'undefined') label = `collection #${collectionId}`;677 const result = await this.helper.executeExtrinsic(678 signer,679 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],680 true, `Unable to add collection admin for ${label}`,681 );682683 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);684 }685686 /**687 * Adds an address to allow list 688 * @param signer keyring of signer689 * @param collectionId ID of collection690 * @param addressObj address to add to the allow list691 * @param label extra label for log692 * @returns ```true``` if extrinsic success, otherwise ```false```693 */694 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId, label?: string): Promise<boolean> {695 if(typeof label === 'undefined') label = `collection #${collectionId}`;696 const result = await this.helper.executeExtrinsic(697 signer,698 'api.tx.unique.addToAllowList', [collectionId, addressObj],699 true, `Unable to add address to allow list for ${label}`,700 );701702 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');703 }704705 /**706 * Removes a collection administrator.707 * 708 * @param signer keyring of signer709 * @param collectionId ID of collection710 * @param adminAddressObj Administrator address (substrate or ethereum)711 * @param label extra label for log712 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})713 * @returns ```true``` if extrinsic success, otherwise ```false```714 */715 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {716 if(typeof label === 'undefined') label = `collection #${collectionId}`;717 const result = await this.helper.executeExtrinsic(718 signer,719 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],720 true, `Unable to remove collection admin for ${label}`,721 );722723 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);724 }725726 /**727 * Sets onchain permissions for selected collection.728 * 729 * @param signer keyring of signer730 * @param collectionId ID of collection731 * @param permissions collection permissions object732 * @param label extra label for log733 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});734 * @returns ```true``` if extrinsic success, otherwise ```false```735 */736 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {737 if(typeof label === 'undefined') label = `collection #${collectionId}`;738 const result = await this.helper.executeExtrinsic(739 signer,740 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],741 true, `Unable to set collection permissions for ${label}`,742 );743744 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);745 }746747 /**748 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.749 * 750 * @param signer keyring of signer751 * @param collectionId ID of collection752 * @param permissions nesting permissions object753 * @param label extra label for log754 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});755 * @returns ```true``` if extrinsic success, otherwise ```false```756 */757 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {758 return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);759 }760761 /**762 * Disables nesting for selected collection.763 * 764 * @param signer keyring of signer765 * @param collectionId ID of collection766 * @param label extra label for log767 * @example disableNesting(aliceKeyring, 10);768 * @returns ```true``` if extrinsic success, otherwise ```false```769 */770 async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {771 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);772 }773774 /**775 * Sets onchain properties to the collection.776 * 777 * @param signer keyring of signer778 * @param collectionId ID of collection779 * @param properties array of property objects780 * @param label extra label for log781 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);782 * @returns ```true``` if extrinsic success, otherwise ```false```783 */784 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {785 if(typeof label === 'undefined') label = `collection #${collectionId}`;786 const result = await this.helper.executeExtrinsic(787 signer,788 'api.tx.unique.setCollectionProperties', [collectionId, properties],789 true, `Unable to set collection properties for ${label}`,790 );791792 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);793 }794795 /**796 * Deletes onchain properties from the collection.797 * 798 * @param signer keyring of signer799 * @param collectionId ID of collection800 * @param propertyKeys array of property keys to delete801 * @param label802 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);803 * @returns ```true``` if extrinsic success, otherwise ```false```804 */805 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {806 if(typeof label === 'undefined') label = `collection #${collectionId}`;807 const result = await this.helper.executeExtrinsic(808 signer,809 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],810 true, `Unable to delete collection properties for ${label}`,811 );812813 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);814 }815816 /**817 * Changes the owner of the token.818 * 819 * @param signer keyring of signer820 * @param collectionId ID of collection821 * @param tokenId ID of token822 * @param addressObj address of a new owner823 * @param amount amount of tokens to be transfered. For NFT must be set to 1n824 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})825 * @returns true if the token success, otherwise false826 */827 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {828 const result = await this.helper.executeExtrinsic(829 signer,830 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],831 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,832 );833834 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);835 }836837 /**838 * 839 * Change ownership of a token(s) on behalf of the owner. 840 * 841 * @param signer keyring of signer842 * @param collectionId ID of collection843 * @param tokenId ID of token844 * @param fromAddressObj address on behalf of which the token will be sent845 * @param toAddressObj new token owner846 * @param amount amount of tokens to be transfered. For NFT must be set to 1n847 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})848 * @returns true if the token success, otherwise false849 */850 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {851 const result = await this.helper.executeExtrinsic(852 signer,853 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],854 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,855 );856 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);857 }858859 /**860 * 861 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.862 * 863 * @param signer keyring of signer864 * @param collectionId ID of collection865 * @param tokenId ID of token866 * @param label 867 * @param amount amount of tokens to be burned. For NFT must be set to 1n868 * @example burnToken(aliceKeyring, 10, 5);869 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```870 */871 async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{872 success: boolean,873 token: number | null874 }> {875 if(typeof label === 'undefined') label = `collection #${collectionId}`;876 const burnResult = await this.helper.executeExtrinsic(877 signer,878 'api.tx.unique.burnItem', [collectionId, tokenId, amount],879 true, `Unable to burn token for ${label}`,880 );881 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);882 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');883 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};884 }885886 /**887 * Destroys a concrete instance of NFT on behalf of the owner888 * 889 * @param signer keyring of signer890 * @param collectionId ID of collection891 * @param fromAddressObj address on behalf of which the token will be burnt892 * @param tokenId ID of token893 * @param label 894 * @param amount amount of tokens to be burned. For NFT must be set to 1n895 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})896 * @returns ```true``` if extrinsic success, otherwise ```false```897 */898 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {899 if(typeof label === 'undefined') label = `collection #${collectionId}`;900 const burnResult = await this.helper.executeExtrinsic(901 signer,902 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],903 true, `Unable to burn token from for ${label}`,904 );905 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);906 return burnedTokens.success && burnedTokens.tokens.length > 0;907 }908909 /**910 * Set, change, or remove approved address to transfer the ownership of the NFT.911 * 912 * @param signer keyring of signer913 * @param collectionId ID of collection914 * @param tokenId ID of token915 * @param toAddressObj 916 * @param label 917 * @param amount amount of token to be approved. For NFT must be set to 1n918 * @returns ```true``` if extrinsic success, otherwise ```false```919 */920 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {921 if(typeof label === 'undefined') label = `collection #${collectionId}`;922 const approveResult = await this.helper.executeExtrinsic(923 signer, 924 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],925 true, `Unable to approve token for ${label}`,926 );927928 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);929 }930931 /**932 * Get the amount of token pieces approved to transfer933 * @param collectionId ID of collection934 * @param tokenId ID of token935 * @param toAccountObj 936 * @param fromAccountObj937 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})938 * @returns number of approved to transfer pieces939 */940 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {941 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();942 }943944 /**945 * Get the last created token id946 * @param collectionId ID of collection947 * @example getLastTokenId(10);948 * @returns id of the last created token949 */950 async getLastTokenId(collectionId: number): Promise<number> {951 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();952 }953954 /**955 * Check if token exists956 * @param collectionId ID of collection957 * @param tokenId ID of token958 * @example isTokenExists(10, 20);959 * @returns true if the token exists, otherwise false960 */961 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {962 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();963 }964}965966class NFTnRFT extends CollectionGroup {967 /**968 * Get tokens owned by account969 * 970 * @param collectionId ID of collection971 * @param addressObj tokens owner972 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})973 * @returns array of token ids owned by account974 */975 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {976 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();977 }978979 /**980 * Get token data981 * @param collectionId ID of collection982 * @param tokenId ID of token983 * @param blockHashAt 984 * @param propertyKeys985 * @example getToken(10, 5);986 * @returns human readable token data 987 */988 async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{989 properties: IProperty[];990 owner: ICrossAccountId;991 normalizedOwner: ICrossAccountId;992 }| null> {993 let tokenData;994 if(typeof blockHashAt === 'undefined') {995 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);996 }997 else {998 if(typeof propertyKeys === 'undefined') {999 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1000 if(!collection) return null;1001 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1002 }1003 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1004 }1005 tokenData = tokenData.toHuman();1006 if (tokenData === null || tokenData.owner === null) return null;1007 const owner = {} as any;1008 for (const key of Object.keys(tokenData.owner)) {1009 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1010 }1011 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1012 return tokenData;1013 }10141015 /**1016 * Set permissions to change token properties1017 * @param signer keyring of signer1018 * @param collectionId ID of collection1019 * @param permissions permissions to change a property by the collection owner or admin1020 * @param label 1021 * @example setTokenPropertyPermissions(1022 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1023 * )1024 * @returns true if extrinsic success otherwise false1025 */1026 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {1027 if(typeof label === 'undefined') label = `collection #${collectionId}`;1028 const result = await this.helper.executeExtrinsic(1029 signer,1030 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1031 true, `Unable to set token property permissions for ${label}`,1032 );10331034 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);1035 }10361037 /**1038 * Set token properties1039 * @param signer keyring of signer1040 * @param collectionId ID of collection1041 * @param tokenId ID of token1042 * @param properties 1043 * @param label 1044 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1045 * @returns ```true``` if extrinsic success, otherwise ```false```1046 */1047 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {1048 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1049 const result = await this.helper.executeExtrinsic(1050 signer,1051 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1052 true, `Unable to set token properties for ${label}`,1053 );10541055 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);1056 }10571058 /**1059 * Delete the provided properties of a token1060 * @param signer keyring of signer1061 * @param collectionId ID of collection1062 * @param tokenId ID of token1063 * @param propertyKeys property keys to be deleted 1064 * @param label 1065 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1066 * @returns ```true``` if extrinsic success, otherwise ```false```1067 */1068 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1069 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1070 const result = await this.helper.executeExtrinsic(1071 signer,1072 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1073 true, `Unable to delete token properties for ${label}`,1074 );10751076 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1077 }10781079 /**1080 * Mint new collection1081 * @param signer keyring of signer1082 * @param collectionOptions basic collection options and properties 1083 * @param mode NFT or RFT type of a collection1084 * @param errorLabel 1085 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1086 * @returns object of the created collection1087 */1088 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1089 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1090 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1091 for (const key of ['name', 'description', 'tokenPrefix']) {1092 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);1093 }1094 const creationResult = await this.helper.executeExtrinsic(1095 signer,1096 'api.tx.unique.createCollectionEx', [collectionOptions],1097 true, errorLabel,1098 );1099 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1100 }11011102 getCollectionObject(collectionId: number): any {1103 return null;1104 }11051106 getTokenObject(collectionId: number, tokenId: number): any {1107 return null;1108 }1109}111011111112class NFTGroup extends NFTnRFT {1113 /**1114 * Get collection object1115 * @param collectionId ID of collection1116 * @example getCollectionObject(2);1117 * @returns instance of UniqueNFTCollection1118 */1119 getCollectionObject(collectionId: number): UniqueNFTCollection {1120 return new UniqueNFTCollection(collectionId, this.helper);1121 }11221123 /**1124 * Get token object1125 * @param collectionId ID of collection1126 * @param tokenId ID of token1127 * @example getTokenObject(10, 5);1128 * @returns instance of UniqueNFTToken1129 */1130 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1131 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1132 }11331134 /**1135 * Get token's owner1136 * @param collectionId ID of collection1137 * @param tokenId ID of token1138 * @param blockHashAt 1139 * @example getTokenOwner(10, 5);1140 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1141 */1142 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1143 let owner;1144 if (typeof blockHashAt === 'undefined') {1145 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1146 } else {1147 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1148 }1149 return crossAccountIdFromLower(owner.toJSON());1150 }11511152 /**1153 * Is token approved to transfer1154 * @param collectionId ID of collection1155 * @param tokenId ID of token1156 * @param toAccountObj address to be approved1157 * @returns ```true``` if extrinsic success, otherwise ```false```1158 */1159 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1160 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1161 }11621163 /**1164 * Changes the owner of the token.1165 * 1166 * @param signer keyring of signer1167 * @param collectionId ID of collection1168 * @param tokenId ID of token1169 * @param addressObj address of a new owner1170 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1171 * @returns ```true``` if extrinsic success, otherwise ```false```1172 */1173 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1174 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1175 }11761177 /**1178 * 1179 * Change ownership of a NFT on behalf of the owner. 1180 * 1181 * @param signer keyring of signer1182 * @param collectionId ID of collection1183 * @param tokenId ID of token1184 * @param fromAddressObj address on behalf of which the token will be sent1185 * @param toAddressObj new token owner1186 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1187 * @returns ```true``` if extrinsic success, otherwise ```false```1188 */1189 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1190 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1191 }11921193 /**1194 * Recursively find the address that owns the token1195 * @param collectionId ID of collection1196 * @param tokenId ID of token1197 * @param blockHashAt 1198 * @example getTokenTopmostOwner(10, 5);1199 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1200 */1201 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1202 let owner;1203 if (typeof blockHashAt === 'undefined') {1204 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1205 } else {1206 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1207 }12081209 if (owner === null) return null;12101211 owner = owner.toHuman();12121213 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1214 }12151216 /**1217 * Get tokens nested in the provided token1218 * @param collectionId ID of collection1219 * @param tokenId ID of token1220 * @param blockHashAt 1221 * @example getTokenChildren(10, 5);1222 * @returns tokens whose depth of nesting is <= 5 1223 */1224 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1225 let children;1226 if(typeof blockHashAt === 'undefined') {1227 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1228 } else {1229 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1230 }12311232 return children.toJSON().map((x: any) => {1233 return {collectionId: x.collection, tokenId: x.token};1234 });1235 }12361237 /**1238 * Nest one token into another1239 * @param signer keyring of signer1240 * @param tokenObj token to be nested1241 * @param rootTokenObj token to be parent1242 * @param label 1243 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1244 * @returns ```true``` if extrinsic success, otherwise ```false```1245 */1246 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1247 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1248 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1249 if(!result) {1250 throw Error(`Unable to nest token for ${label}`);1251 }1252 return result;1253 }12541255 /**1256 * Remove token from nested state1257 * @param signer keyring of signer1258 * @param tokenObj token to unnest1259 * @param rootTokenObj parent of a token1260 * @param toAddressObj address of a new token owner 1261 * @param label 1262 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1263 * @returns ```true``` if extrinsic success, otherwise ```false```1264 */1265 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1266 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1267 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1268 if(!result) {1269 throw Error(`Unable to unnest token for ${label}`);1270 }1271 return result;1272 }12731274 /**1275 * Mint new collection1276 * @param signer keyring of signer1277 * @param collectionOptions Collection options1278 * @param label 1279 * @example 1280 * mintCollection(aliceKeyring, {1281 * name: 'New',1282 * description: 'New collection',1283 * tokenPrefix: 'NEW',1284 * })1285 * @returns object of the created collection1286 */1287 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1288 return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1289 }12901291 /**1292 * Mint new token1293 * @param signer keyring of signer1294 * @param data token data1295 * @param label 1296 * @returns created token object1297 */1298 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1299 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1300 const creationResult = await this.helper.executeExtrinsic(1301 signer,1302 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1303 nft: {1304 properties: data.properties,1305 },1306 }],1307 true, `Unable to mint NFT token for ${label}`,1308 );1309 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1310 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1311 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1312 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1313 }13141315 /**1316 * Mint multiple NFT tokens1317 * @param signer keyring of signer1318 * @param collectionId ID of collection1319 * @param tokens array of tokens with owner and properties1320 * @param label 1321 * @example 1322 * mintMultipleTokens(aliceKeyring, 10, [{1323 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1324 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1325 * },{1326 * owner: {Ethereum: "0x9F0583DbB855d..."},1327 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1328 * }]);1329 * @returns ```true``` if extrinsic success, otherwise ```false```1330 */1331 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1332 if(typeof label === 'undefined') label = `collection #${collectionId}`;1333 const creationResult = await this.helper.executeExtrinsic(1334 signer,1335 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1336 true, `Unable to mint NFT tokens for ${label}`,1337 );1338 const collection = this.getCollectionObject(collectionId);1339 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1340 }13411342 /**1343 * Mint multiple NFT tokens with one owner1344 * @param signer keyring of signer1345 * @param collectionId ID of collection1346 * @param owner tokens owner1347 * @param tokens array of tokens with owner and properties1348 * @param label 1349 * @example1350 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1351 * properties: [{1352 * key: "gender",1353 * value: "female",1354 * },{1355 * key: "age",1356 * value: "33",1357 * }],1358 * }]);1359 * @returns array of newly created tokens1360 */1361 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1362 if(typeof label === 'undefined') label = `collection #${collectionId}`;1363 const rawTokens = [];1364 for (const token of tokens) {1365 const raw = {NFT: {properties: token.properties}};1366 rawTokens.push(raw);1367 }1368 const creationResult = await this.helper.executeExtrinsic(1369 signer,1370 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1371 true, `Unable to mint NFT tokens for ${label}`,1372 );1373 const collection = this.getCollectionObject(collectionId);1374 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1375 }13761377 /**1378 * Destroys a concrete instance of NFT.1379 * @param signer keyring of signer1380 * @param collectionId ID of collection1381 * @param tokenId ID of token1382 * @param label 1383 * @example burnToken(aliceKeyring, 10, 5);1384 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1385 */1386 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1387 return await super.burnToken(signer, collectionId, tokenId, label, 1n);1388 }13891390 /**1391 * Set, change, or remove approved address to transfer the ownership of the NFT.1392 * 1393 * @param signer keyring of signer1394 * @param collectionId ID of collection1395 * @param tokenId ID of token1396 * @param toAddressObj address to approve1397 * @param label 1398 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1399 * @returns ```true``` if extrinsic success, otherwise ```false```1400 */1401 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1402 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1403 }1404}140514061407class RFTGroup extends NFTnRFT {1408 /**1409 * Get collection object1410 * @param collectionId ID of collection1411 * @example getCollectionObject(2);1412 * @returns instance of UniqueRFTCollection1413 */1414 getCollectionObject(collectionId: number): UniqueRFTCollection {1415 return new UniqueRFTCollection(collectionId, this.helper);1416 }14171418 /**1419 * Get token object1420 * @param collectionId ID of collection1421 * @param tokenId ID of token1422 * @example getTokenObject(10, 5);1423 * @returns instance of UniqueNFTToken1424 */1425 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1426 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1427 }14281429 /**1430 * Get top 10 token owners with the largest number of pieces 1431 * @param collectionId ID of collection1432 * @param tokenId ID of token1433 * @example getTokenTop10Owners(10, 5);1434 * @returns array of top 10 owners1435 */1436 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1437 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1438 }14391440 /**1441 * Get number of pieces owned by address1442 * @param collectionId ID of collection1443 * @param tokenId ID of token1444 * @param addressObj address token owner1445 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1446 * @returns number of pieces ownerd by address1447 */1448 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1449 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1450 }14511452 /**1453 * Transfer pieces of token to another address1454 * @param signer keyring of signer1455 * @param collectionId ID of collection1456 * @param tokenId ID of token1457 * @param addressObj address of a new owner1458 * @param amount number of pieces to be transfered1459 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1460 * @returns ```true``` if extrinsic success, otherwise ```false```1461 */1462 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1463 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1464 }14651466 /**1467 * Change ownership of some pieces of RFT on behalf of the owner. 1468 * @param signer keyring of signer1469 * @param collectionId ID of collection1470 * @param tokenId ID of token1471 * @param fromAddressObj address on behalf of which the token will be sent1472 * @param toAddressObj new token owner1473 * @param amount number of pieces to be transfered1474 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1475 * @returns ```true``` if extrinsic success, otherwise ```false```1476 */1477 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1478 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1479 }14801481 /**1482 * Mint new collection1483 * @param signer keyring of signer1484 * @param collectionOptions Collection options1485 * @param label 1486 * @example1487 * mintCollection(aliceKeyring, {1488 * name: 'New',1489 * description: 'New collection',1490 * tokenPrefix: 'NEW',1491 * })1492 * @returns object of the created collection1493 */1494 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1495 return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1496 }14971498 /**1499 * Mint new token1500 * @param signer keyring of signer1501 * @param data token data1502 * @param label 1503 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1504 * @returns created token object1505 */1506 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1507 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1508 const creationResult = await this.helper.executeExtrinsic(1509 signer,1510 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1511 refungible: {1512 pieces: data.pieces,1513 properties: data.properties,1514 },1515 }],1516 true, `Unable to mint RFT token for ${label}`,1517 );1518 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1519 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1520 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1521 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1522 }15231524 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1525 throw Error('Not implemented');1526 if(typeof label === 'undefined') label = `collection #${collectionId}`;1527 const creationResult = await this.helper.executeExtrinsic(1528 signer,1529 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1530 true, `Unable to mint RFT tokens for ${label}`,1531 );1532 const collection = this.getCollectionObject(collectionId);1533 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1534 }15351536 /**1537 * Mint multiple RFT tokens with one owner1538 * @param signer keyring of signer1539 * @param collectionId ID of collection1540 * @param owner tokens owner1541 * @param tokens array of tokens with properties and pieces1542 * @param label 1543 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1544 * @returns array of newly created RFT tokens1545 */1546 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1547 if(typeof label === 'undefined') label = `collection #${collectionId}`;1548 const rawTokens = [];1549 for (const token of tokens) {1550 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1551 rawTokens.push(raw);1552 }1553 const creationResult = await this.helper.executeExtrinsic(1554 signer,1555 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1556 true, `Unable to mint RFT tokens for ${label}`,1557 );1558 const collection = this.getCollectionObject(collectionId);1559 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1560 }15611562 /**1563 * Destroys a concrete instance of RFT.1564 * @param signer keyring of signer1565 * @param collectionId ID of collection1566 * @param tokenId ID of token1567 * @param label 1568 * @param amount number of pieces to be burnt1569 * @example burnToken(aliceKeyring, 10, 5);1570 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1571 */1572 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1573 return await super.burnToken(signer, collectionId, tokenId, label, amount);1574 }15751576 /**1577 * Set, change, or remove approved address to transfer the ownership of the RFT.1578 * 1579 * @param signer keyring of signer1580 * @param collectionId ID of collection1581 * @param tokenId ID of token1582 * @param toAddressObj address to approve1583 * @param label 1584 * @param amount number of pieces to be approved1585 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1586 * @returns true if the token success, otherwise false1587 */1588 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1589 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1590 }15911592 /**1593 * Get total number of pieces1594 * @param collectionId ID of collection1595 * @param tokenId ID of token1596 * @example getTokenTotalPieces(10, 5);1597 * @returns number of pieces1598 */1599 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1600 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1601 }16021603 /**1604 * Change number of token pieces. Signer must be the owner of all token pieces.1605 * @param signer keyring of signer1606 * @param collectionId ID of collection1607 * @param tokenId ID of token1608 * @param amount new number of pieces1609 * @param label 1610 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1611 * @returns true if the repartion was success, otherwise false1612 */1613 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1614 if(typeof label === 'undefined') label = `collection #${collectionId}`;1615 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1616 const repartitionResult = await this.helper.executeExtrinsic(1617 signer,1618 'api.tx.unique.repartition', [collectionId, tokenId, amount],1619 true, `Unable to repartition RFT token for ${label}`,1620 );1621 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1622 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1623 }1624}162516261627class FTGroup extends CollectionGroup {1628 /**1629 * Get collection object1630 * @param collectionId ID of collection1631 * @example getCollectionObject(2);1632 * @returns instance of UniqueFTCollection1633 */1634 getCollectionObject(collectionId: number): UniqueFTCollection {1635 return new UniqueFTCollection(collectionId, this.helper);1636 }16371638 /**1639 * Mint new fungible collection1640 * @param signer keyring of signer1641 * @param collectionOptions Collection options1642 * @param decimalPoints number of token decimals 1643 * @param errorLabel 1644 * @example1645 * mintCollection(aliceKeyring, {1646 * name: 'New',1647 * description: 'New collection',1648 * tokenPrefix: 'NEW',1649 * }, 18)1650 * @returns newly created fungible collection1651 */1652 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1653 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1654 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1655 collectionOptions.mode = {fungible: decimalPoints};1656 for (const key of ['name', 'description', 'tokenPrefix']) {1657 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);1658 }1659 const creationResult = await this.helper.executeExtrinsic(1660 signer,1661 'api.tx.unique.createCollectionEx', [collectionOptions],1662 true, errorLabel,1663 );1664 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1665 }16661667 /**1668 * Mint tokens1669 * @param signer keyring of signer1670 * @param collectionId ID of collection1671 * @param owner address owner of new tokens1672 * @param amount amount of tokens to be meanted1673 * @param label 1674 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1675 * @returns ```true``` if extrinsic success, otherwise ```false``` 1676 */1677 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1678 if(typeof label === 'undefined') label = `collection #${collectionId}`;1679 const creationResult = await this.helper.executeExtrinsic(1680 signer,1681 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1682 fungible: {1683 value: amount,1684 },1685 }],1686 true, `Unable to mint fungible tokens for ${label}`,1687 );1688 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1689 }16901691 /**1692 * Mint multiple Fungible tokens with one owner1693 * @param signer keyring of signer1694 * @param collectionId ID of collection1695 * @param owner tokens owner1696 * @param tokens array of tokens with properties and pieces1697 * @param label 1698 * @returns ```true``` if extrinsic success, otherwise ```false``` 1699 */1700 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1701 if(typeof label === 'undefined') label = `collection #${collectionId}`;1702 const rawTokens = [];1703 for (const token of tokens) {1704 const raw = {Fungible: {Value: token.value}};1705 rawTokens.push(raw);1706 }1707 const creationResult = await this.helper.executeExtrinsic(1708 signer,1709 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1710 true, `Unable to mint RFT tokens for ${label}`,1711 );1712 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1713 }17141715 /**1716 * Get the top 10 owners with the largest balance for the Fungible collection 1717 * @param collectionId ID of collection1718 * @example getTop10Owners(10);1719 * @returns array of ```ICrossAccountId```1720 */1721 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1722 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1723 }17241725 /**1726 * Get account balance1727 * @param collectionId ID of collection1728 * @param addressObj address of owner1729 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1730 * @returns amount of fungible tokens owned by address1731 */1732 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1733 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1734 }17351736 /**1737 * Transfer tokens to address1738 * @param signer keyring of signer1739 * @param collectionId ID of collection1740 * @param toAddressObj address recepient1741 * @param amount amount of tokens to be sent1742 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1743 * @returns ```true``` if extrinsic success, otherwise ```false``` 1744 */1745 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1746 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1747 }17481749 /**1750 * Transfer some tokens on behalf of the owner.1751 * @param signer keyring of signer1752 * @param collectionId ID of collection1753 * @param fromAddressObj address on behalf of which tokens will be sent1754 * @param toAddressObj address where token to be sent1755 * @param amount number of tokens to be sent1756 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1757 * @returns ```true``` if extrinsic success, otherwise ```false``` 1758 */1759 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1760 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1761 }17621763 /**1764 * Destroy some amount of tokens1765 * @param signer keyring of signer1766 * @param collectionId ID of collection1767 * @param amount amount of tokens to be destroyed1768 * @param label 1769 * @example burnTokens(aliceKeyring, 10, 1000n);1770 * @returns ```true``` if extrinsic success, otherwise ```false``` 1771 */1772 async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1773 return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1774 }17751776 /**1777 * Burn some tokens on behalf of the owner.1778 * @param signer keyring of signer1779 * @param collectionId ID of collection1780 * @param fromAddressObj address on behalf of which tokens will be burnt1781 * @param amount amount of tokens to be burnt1782 * @param label 1783 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1784 * @returns ```true``` if extrinsic success, otherwise ```false``` 1785 */1786 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1787 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1788 }17891790 /**1791 * Get total collection supply1792 * @param collectionId 1793 * @returns 1794 */1795 async getTotalPieces(collectionId: number): Promise<bigint> {1796 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1797 }17981799 /**1800 * Set, change, or remove approved address to transfer tokens.1801 * 1802 * @param signer keyring of signer1803 * @param collectionId ID of collection1804 * @param toAddressObj address to be approved1805 * @param amount amount of tokens to be approved1806 * @param label 1807 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1808 * @returns ```true``` if extrinsic success, otherwise ```false``` 1809 */1810 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1811 return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1812 }18131814 /**1815 * Get amount of fungible tokens approved to transfer1816 * @param collectionId ID of collection1817 * @param fromAddressObj owner of tokens1818 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1819 * @returns number of tokens approved for the transfer1820 */1821 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1822 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1823 }1824}182518261827class ChainGroup extends HelperGroup {1828 /**1829 * Get system properties of a chain1830 * @example getChainProperties();1831 * @returns ss58Format, token decimals, and token symbol1832 */1833 getChainProperties(): IChainProperties {1834 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1835 return {1836 ss58Format: properties.ss58Format.toJSON(),1837 tokenDecimals: properties.tokenDecimals.toJSON(),1838 tokenSymbol: properties.tokenSymbol.toJSON(),1839 };1840 }18411842 /**1843 * Get chain header1844 * @example getLatestBlockNumber();1845 * @returns the number of the last block1846 */1847 async getLatestBlockNumber(): Promise<number> {1848 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1849 }18501851 /**1852 * Get block hash by block number1853 * @param blockNumber number of block1854 * @example getBlockHashByNumber(12345);1855 * @returns hash of a block1856 */1857 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1858 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1859 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1860 return blockHash;1861 }18621863 /**1864 * Get account nonce1865 * @param address substrate address1866 * @example getNonce("5GrwvaEF5zXb26Fz...");1867 * @returns number, account's nonce1868 */1869 async getNonce(address: TSubstrateAccount): Promise<number> {1870 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1871 }1872}187318741875class BalanceGroup extends HelperGroup {1876 /**1877 * Representation of the native token in the smallest unit1878 * @example getOneTokenNominal()1879 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1880 */1881 getOneTokenNominal(): bigint {1882 const chainProperties = this.helper.chain.getChainProperties();1883 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1884 }18851886 /**1887 * Get substrate address balance1888 * @param address substrate address1889 * @example getSubstrate("5GrwvaEF5zXb26Fz...")1890 * @returns amount of tokens on address1891 */1892 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1893 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1894 }18951896 /**1897 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved1898 * @param address substrate address1899 * @returns 1900 */1901 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {1902 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;1903 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};1904 }19051906 /**1907 * Get ethereum address balance1908 * @param address ethereum address1909 * @example getEthereum("0x9F0583DbB855d...")1910 * @returns amount of tokens on address1911 */1912 async getEthereum(address: TEthereumAccount): Promise<bigint> {1913 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1914 }19151916 /**1917 * Transfer tokens to substrate address1918 * @param signer keyring of signer1919 * @param address substrate address of a recepient1920 * @param amount amount of tokens to be transfered1921 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);1922 * @returns ```true``` if extrinsic success, otherwise ```false```1923 */1924 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1925 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}`);19261927 let transfer = {from: null, to: null, amount: 0n} as any;1928 result.result.events.forEach(({event: {data, method, section}}) => {1929 if ((section === 'balances') && (method === 'Transfer')) {1930 transfer = {1931 from: this.helper.address.normalizeSubstrate(data[0]),1932 to: this.helper.address.normalizeSubstrate(data[1]),1933 amount: BigInt(data[2]),1934 };1935 }1936 });1937 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1938 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1939 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1940 return isSuccess;1941 }1942}194319441945class AddressGroup extends HelperGroup {1946 /**1947 * Normalizes the address to the specified ss58 format, by default ```42```.1948 * @param address substrate address1949 * @param ss58Format format for address conversion, by default ```42```1950 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY1951 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation1952 */1953 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1954 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1955 }19561957 /**1958 * Get address in the connected chain format1959 * @param address substrate address1960 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network1961 * @returns address in chain format1962 */1963 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1964 const info = this.helper.chain.getChainProperties();1965 return encodeAddress(decodeAddress(address), info.ss58Format);1966 }19671968 /**1969 * Get substrate mirror of an ethereum address1970 * @param ethAddress ethereum address1971 * @param toChainFormat false for normalized account1972 * @example ethToSubstrate('0x9F0583DbB855d...')1973 * @returns substrate mirror of a provided ethereum address1974 */1975 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1976 if(!toChainFormat) return evmToAddress(ethAddress);1977 const info = this.helper.chain.getChainProperties();1978 return evmToAddress(ethAddress, info.ss58Format);1979 }19801981 /**1982 * Get ethereum mirror of a substrate address1983 * @param subAddress substrate account1984 * @example substrateToEth("5DnSF6RRjwteE3BrC...")1985 * @returns ethereum mirror of a provided substrate address1986 */1987 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1988 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1989 }1990}19911992class StakingGroup extends HelperGroup {1993 /**1994 * Stake tokens for App Promotion1995 * @param signer keyring of signer1996 * @param amountToStake amount of tokens to stake1997 * @param label extra label for log1998 * @returns1999 */2000 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2001 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2002 const stakeResult = await this.helper.executeExtrinsic(2003 signer,2004 'api.tx.promotion.stake', [amountToStake],2005 true, `stake failed for ${label}`,2006 );2007 // TODO extract info from stakeResult2008 return true;2009 }20102011 /**2012 * Unstake tokens for App Promotion2013 * @param signer keyring of signer2014 * @param amountToUnstake amount of tokens to unstake2015 * @param label extra label for log2016 * @returns 2017 */2018 async unstake(signer: TSigner, label?: string): Promise<boolean> {2019 if(typeof label === 'undefined') label = `${signer.address}`;2020 const unstakeResult = await this.helper.executeExtrinsic(2021 signer,2022 'api.tx.promotion.unstake', [],2023 true, `unstake failed for ${label}`,2024 );2025 // TODO extract info from unstakeResult2026 return true;2027 }20282029 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2030 if (address) return (await this.helper.callRpc('api.rpc.unique.totalStaked', [address])).toBigInt();2031 return (await this.helper.callRpc('api.rpc.unique.totalStaked')).toBigInt();2032 }20332034 async getTotalStakingLocked(address: ICrossAccountId): Promise<bigint> {2035 return (await this.helper.callRpc('api.rpc.unique.totalStakingLocked', [address])).toBigInt();2036 }20372038 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {2039 return (await this.helper.callRpc('api.rpc.unique.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2040 }20412042 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2043 return (await this.helper.callRpc('api.rpc.unique.pendingUnstake', [address])).toBigInt();2044 }2045 2046 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<bigint[][]> {2047 return (await this.helper.callRpc('api.rpc.unique.pendingUnstakePerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2048 }2049}20502051export class UniqueHelper extends ChainHelperBase {2052 chain: ChainGroup;2053 balance: BalanceGroup;2054 address: AddressGroup;2055 collection: CollectionGroup;2056 nft: NFTGroup;2057 rft: RFTGroup;2058 ft: FTGroup;2059 staking: StakingGroup;20602061 constructor(logger?: ILogger) {2062 super(logger);2063 this.chain = new ChainGroup(this);2064 this.balance = new BalanceGroup(this);2065 this.address = new AddressGroup(this);2066 this.collection = new CollectionGroup(this);2067 this.nft = new NFTGroup(this);2068 this.rft = new RFTGroup(this);2069 this.ft = new FTGroup(this);2070 this.staking = new StakingGroup(this);2071 } 2072}207320742075class UniqueCollectionBase {2076 helper: UniqueHelper;2077 collectionId: number;20782079 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2080 this.collectionId = collectionId;2081 this.helper = uniqueHelper;2082 }20832084 async getData() {2085 return await this.helper.collection.getData(this.collectionId);2086 }20872088 async getLastTokenId() {2089 return await this.helper.collection.getLastTokenId(this.collectionId);2090 }20912092 async isTokenExists(tokenId: number) {2093 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2094 }20952096 async getAdmins() {2097 return await this.helper.collection.getAdmins(this.collectionId);2098 }20992100 async getAllowList() {2101 return await this.helper.collection.getAllowList(this.collectionId);2102 }21032104 async getEffectiveLimits() {2105 return await this.helper.collection.getEffectiveLimits(this.collectionId);2106 }21072108 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {2109 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);2110 }21112112 async confirmSponsorship(signer: TSigner, label?: string) {2113 return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);2114 }21152116 async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {2117 return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);2118 }21192120 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {2121 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);2122 }21232124 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2125 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);2126 }21272128 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId, label?: string) {2129 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj, label);2130 }21312132 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2133 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);2134 }21352136 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2137 return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);2138 }21392140 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2141 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);2142 }21432144 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2145 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2146 }21472148 async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {2149 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);2150 }21512152 async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {2153 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);2154 }21552156 async disableNesting(signer: TSigner, label?: string) {2157 return await this.helper.collection.disableNesting(signer, this.collectionId, label);2158 }21592160 async burn(signer: TSigner, label?: string) {2161 return await this.helper.collection.burn(signer, this.collectionId, label);2162 }2163}216421652166class UniqueNFTCollection extends UniqueCollectionBase {2167 getTokenObject(tokenId: number) {2168 return new UniqueNFTToken(tokenId, this);2169 }21702171 async getTokensByAddress(addressObj: ICrossAccountId) {2172 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2173 }21742175 async getToken(tokenId: number, blockHashAt?: string) {2176 return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);2177 }21782179 async getTokenOwner(tokenId: number, blockHashAt?: string) {2180 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2181 }21822183 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2184 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2185 }21862187 async getTokenChildren(tokenId: number, blockHashAt?: string) {2188 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2189 }21902191 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2192 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2193 }21942195 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2196 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2197 }21982199 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {2200 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);2201 }22022203 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2204 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2205 }22062207 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {2208 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);2209 }22102211 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {2212 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);2213 }22142215 async burnToken(signer: TSigner, tokenId: number, label?: string) {2216 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);2217 }22182219 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2220 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2221 }22222223 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2224 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2225 }22262227 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2228 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2229 }22302231 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {2232 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);2233 }22342235 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2236 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);2237 }2238}223922402241class UniqueRFTCollection extends UniqueCollectionBase {2242 getTokenObject(tokenId: number) {2243 return new UniqueRFTToken(tokenId, this);2244 }22452246 async getTokensByAddress(addressObj: ICrossAccountId) {2247 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2248 }22492250 async getTop10TokenOwners(tokenId: number) {2251 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2252 }22532254 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2255 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2256 }22572258 async getTokenTotalPieces(tokenId: number) {2259 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2260 }22612262 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {2263 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2264 }22652266 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2267 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2268 }22692270 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2271 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);2272 }22732274 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2275 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2276 }22772278 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {2279 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);2280 }22812282 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {2283 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);2284 }22852286 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {2287 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);2288 }22892290 async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {2291 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);2292 }22932294 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2295 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2296 }22972298 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2299 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2300 }23012302 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2303 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2304 }2305}230623072308class UniqueFTCollection extends UniqueCollectionBase {2309 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {2310 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);2311 }23122313 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {2314 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);2315 }23162317 async getBalance(addressObj: ICrossAccountId) {2318 return await this.helper.ft.getBalance(this.collectionId, addressObj);2319 }23202321 async getTop10Owners() {2322 return await this.helper.ft.getTop10Owners(this.collectionId);2323 }23242325 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {2326 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2327 }23282329 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {2330 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2331 }23322333 async burnTokens(signer: TSigner, amount: bigint, label?: string) {2334 return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);2335 }23362337 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {2338 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);2339 }23402341 async getTotalPieces() {2342 return await this.helper.ft.getTotalPieces(this.collectionId);2343 }23442345 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2346 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);2347 }23482349 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2350 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2351 }2352}235323542355class UniqueTokenBase implements IToken {2356 collection: UniqueNFTCollection | UniqueRFTCollection;2357 collectionId: number;2358 tokenId: number;23592360 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2361 this.collection = collection;2362 this.collectionId = collection.collectionId;2363 this.tokenId = tokenId;2364 }23652366 async getNextSponsored(addressObj: ICrossAccountId) {2367 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2368 }23692370 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2371 return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);2372 }23732374 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2375 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);2376 }2377}237823792380class UniqueNFTToken extends UniqueTokenBase {2381 collection: UniqueNFTCollection;23822383 constructor(tokenId: number, collection: UniqueNFTCollection) {2384 super(tokenId, collection);2385 this.collection = collection;2386 }23872388 async getData(blockHashAt?: string) {2389 return await this.collection.getToken(this.tokenId, blockHashAt);2390 }23912392 async getOwner(blockHashAt?: string) {2393 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2394 }23952396 async getTopmostOwner(blockHashAt?: string) {2397 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2398 }23992400 async getChildren(blockHashAt?: string) {2401 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2402 }24032404 async nest(signer: TSigner, toTokenObj: IToken, label?: string) {2405 return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);2406 }24072408 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2409 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);2410 }24112412 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2413 return await this.collection.transferToken(signer, this.tokenId, addressObj);2414 }24152416 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2417 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2418 }24192420 async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {2421 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);2422 }24232424 async isApproved(toAddressObj: ICrossAccountId) {2425 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2426 }24272428 async burn(signer: TSigner, label?: string) {2429 return await this.collection.burnToken(signer, this.tokenId, label);2430 }2431}24322433class UniqueRFTToken extends UniqueTokenBase {2434 collection: UniqueRFTCollection;24352436 constructor(tokenId: number, collection: UniqueRFTCollection) {2437 super(tokenId, collection);2438 this.collection = collection;2439 }24402441 async getTop10Owners() {2442 return await this.collection.getTop10TokenOwners(this.tokenId);2443 }24442445 async getBalance(addressObj: ICrossAccountId) {2446 return await this.collection.getTokenBalance(this.tokenId, addressObj);2447 }24482449 async getTotalPieces() {2450 return await this.collection.getTokenTotalPieces(this.tokenId);2451 }24522453 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {2454 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2455 }24562457 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2458 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2459 }24602461 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2462 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);2463 }24642465 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2466 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2467 }24682469 async repartition(signer: TSigner, amount: bigint, label?: string) {2470 return await this.collection.repartitionToken(signer, this.tokenId, amount, label);2471 }24722473 async burn(signer: TSigner, amount=100n, label?: string) {2474 return await this.collection.burnToken(signer, this.tokenId, amount, label);2475 }2476}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} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};202122const nesting = {23 toChecksumAddress(address: string): string {24 if (typeof address === 'undefined') return '';2526 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2728 address = address.toLowerCase().replace(/^0x/i,'');29 const addressHash = keccakAsHex(address).replace(/^0x/i,'');30 const checksumAddress = ['0x'];3132 for (let i = 0; i < address.length; i++) {33 // If ith character is 8 to f then make it uppercase34 if (parseInt(addressHash[i], 16) > 7) {35 checksumAddress.push(address[i].toUpperCase());36 } else {37 checksumAddress.push(address[i]);38 }39 }40 return checksumAddress.join('');41 },42 tokenIdToAddress(collectionId: number, tokenId: number) {43 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);44 },45};4647class UniqueUtil {48 static transactionStatus = {49 NOT_READY: 'NotReady',50 FAIL: 'Fail',51 SUCCESS: 'Success',52 };5354 static chainLogType = {55 EXTRINSIC: 'extrinsic',56 RPC: 'rpc',57 };5859 static getNestingTokenAddress(collectionId: number, tokenId: number) {60 return nesting.tokenIdToAddress(collectionId, tokenId);61 }6263 static getDefaultLogger(): ILogger {64 return {65 log(msg: any, level = 'INFO') {66 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));67 },68 level: {69 ERROR: 'ERROR',70 WARNING: 'WARNING',71 INFO: 'INFO',72 },73 };74 }7576 static vec2str(arr: string[] | number[]) {77 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');78 }7980 static str2vec(string: string) {81 if (typeof string !== 'string') return string;82 return Array.from(string).map(x => x.charCodeAt(0));83 }8485 static fromSeed(seed: string, ss58Format = 42) {86 const keyring = new Keyring({type: 'sr25519', ss58Format});87 return keyring.addFromUri(seed);88 }8990 static normalizeSubstrateAddress(address: string, ss58Format = 42) {91 return encodeAddress(decodeAddress(address), ss58Format);92 }9394 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult, label = 'new collection') {95 if (creationResult.status !== this.transactionStatus.SUCCESS) {96 throw Error(`Unable to create collection for ${label}`);97 }9899 let collectionId = null;100 creationResult.result.events.forEach(({event: {data, method, section}}) => {101 if ((section === 'common') && (method === 'CollectionCreated')) {102 collectionId = parseInt(data[0].toString(), 10);103 }104 });105106 if (collectionId === null) {107 throw Error(`No CollectionCreated event for ${label}`);108 }109110 return collectionId;111 }112113 static extractTokensFromCreationResult(creationResult: ITransactionResult, label = 'new tokens') {114 if (creationResult.status !== this.transactionStatus.SUCCESS) {115 throw Error(`Unable to create tokens for ${label}`);116 }117 let success = false;118 const tokens = [] as any;119 creationResult.result.events.forEach(({event: {data, method, section}}) => {120 if (method === 'ExtrinsicSuccess') {121 success = true;122 } else if ((section === 'common') && (method === 'ItemCreated')) {123 tokens.push({124 collectionId: parseInt(data[0].toString(), 10),125 tokenId: parseInt(data[1].toString(), 10),126 owner: data[2].toJSON(),127 });128 }129 });130 return {success, tokens};131 }132133 static extractTokensFromBurnResult(burnResult: ITransactionResult, label = 'burned tokens') {134 if (burnResult.status !== this.transactionStatus.SUCCESS) {135 throw Error(`Unable to burn tokens for ${label}`);136 }137 let success = false;138 const tokens = [] as any;139 burnResult.result.events.forEach(({event: {data, method, section}}) => {140 if (method === 'ExtrinsicSuccess') {141 success = true;142 } else if ((section === 'common') && (method === 'ItemDestroyed')) {143 tokens.push({144 collectionId: parseInt(data[0].toString(), 10),145 tokenId: parseInt(data[1].toString(), 10),146 owner: data[2].toJSON(),147 });148 }149 });150 return {success, tokens};151 }152153 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string, label?: string) {154 let eventId = null;155 events.forEach(({event: {data, method, section}}) => {156 if ((section === expectedSection) && (method === expectedMethod)) {157 eventId = parseInt(data[0].toString(), 10);158 }159 });160161 if (eventId === null) {162 throw Error(`No ${expectedMethod} event for ${label}`);163 }164 return eventId === collectionId;165 }166167 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {168 const normalizeAddress = (address: string | ICrossAccountId) => {169 if(typeof address === 'string') return address;170 const obj = {} as any;171 Object.keys(address).forEach(k => {172 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];173 });174 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};175 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};176 return address;177 };178 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;179 events.forEach(({event: {data, method, section}}) => {180 if ((section === 'common') && (method === 'Transfer')) {181 const hData = (data as any).toJSON();182 transfer = {183 collectionId: hData[0],184 tokenId: hData[1],185 from: normalizeAddress(hData[2]),186 to: normalizeAddress(hData[3]),187 amount: BigInt(hData[4]),188 };189 }190 });191 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);193 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);194 isSuccess = isSuccess && amount === transfer.amount;195 return isSuccess;196 }197}198199200class ChainHelperBase {201 transactionStatus = UniqueUtil.transactionStatus;202 chainLogType = UniqueUtil.chainLogType;203 util: typeof UniqueUtil;204 logger: ILogger;205 api: ApiPromise | null;206 forcedNetwork: TUniqueNetworks | null;207 network: TUniqueNetworks | null;208 chainLog: IUniqueHelperLog[];209210 constructor(logger?: ILogger) {211 this.util = UniqueUtil;212 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();213 this.logger = logger;214 this.api = null;215 this.forcedNetwork = null;216 this.network = null;217 this.chainLog = [];218 }219220 clearChainLog(): void {221 this.chainLog = [];222 }223224 forceNetwork(value: TUniqueNetworks): void {225 this.forcedNetwork = value;226 }227228 async connect(wsEndpoint: string, listeners?: IApiListeners) {229 if (this.api !== null) throw Error('Already connected');230 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);231 this.api = api;232 this.network = network;233 }234235 async disconnect() {236 if (this.api === null) return;237 await this.api.disconnect();238 this.api = null;239 this.network = null;240 }241242 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {243 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;244 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;245 return 'opal';246 }247248 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {249 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});250 await api.isReady;251252 const network = await this.detectNetwork(api);253254 await api.disconnect();255256 return network;257 }258259 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 260 api: ApiPromise; 261 network: TUniqueNetworks; 262 }> {263 if(typeof network === 'undefined' || network === null) network = 'opal';264 const supportedRPC = {265 opal: {266 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,267 },268 quartz: {269 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,270 },271 unique: {272 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,273 },274 };275 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);276 const rpc = supportedRPC[network];277278 // TODO: investigate how to replace rpc in runtime279 // api._rpcCore.addUserInterfaces(rpc);280281 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});282283 await api.isReadyOrError;284285 if (typeof listeners === 'undefined') listeners = {};286 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {287 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;288 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);289 }290291 return {api, network};292 }293294 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {295 const {events, status} = data;296 if (status.isReady) {297 return this.transactionStatus.NOT_READY;298 }299 if (status.isBroadcast) {300 return this.transactionStatus.NOT_READY;301 }302 if (status.isInBlock || status.isFinalized) {303 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');304 if (errors.length > 0) {305 return this.transactionStatus.FAIL;306 }307 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {308 return this.transactionStatus.SUCCESS;309 }310 }311312 return this.transactionStatus.FAIL;313 }314315 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {316 const sign = (callback: any) => {317 if(options !== null) return transaction.signAndSend(sender, options, callback);318 return transaction.signAndSend(sender, callback);319 };320 return new Promise(async (resolve, reject) => {321 try {322 const unsub = await sign((result: any) => {323 const status = this.getTransactionStatus(result);324325 if (status === this.transactionStatus.SUCCESS) {326 this.logger.log(`${label} successful`);327 unsub();328 resolve({result, status});329 } else if (status === this.transactionStatus.FAIL) {330 let moduleError = null;331332 if (result.hasOwnProperty('dispatchError')) {333 const dispatchError = result['dispatchError'];334335 if (dispatchError && dispatchError.isModule) {336 const modErr = dispatchError.asModule;337 const errorMeta = dispatchError.registry.findMetaError(modErr);338339 moduleError = `${errorMeta.section}.${errorMeta.name}`;340 }341 else {342 this.logger.log(result, this.logger.level.ERROR);343 }344 }345346 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);347 unsub();348 reject({status, moduleError, result});349 }350 });351 } catch (e) {352 this.logger.log(e, this.logger.level.ERROR);353 reject(e);354 }355 });356 }357358 constructApiCall(apiCall: string, params: any[]) {359 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);360 let call = this.api as any;361 for(const part of apiCall.slice(4).split('.')) {362 call = call[part];363 }364 return call(...params);365 }366367 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false, failureMessage='expected success') {368 if(this.api === null) throw Error('API not initialized');369 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);370371 const startTime = (new Date()).getTime();372 let result: ITransactionResult;373 let events = [];374 try {375 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;376 events = result.result.events.map((x: any) => x.toHuman());377 }378 catch(e) {379 if(!(e as object).hasOwnProperty('status')) throw e;380 result = e as ITransactionResult;381 }382383 const endTime = (new Date()).getTime();384385 const log = {386 executedAt: endTime,387 executionTime: endTime - startTime,388 type: this.chainLogType.EXTRINSIC,389 status: result.status,390 call: extrinsic,391 params,392 } as IUniqueHelperLog;393394 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;395 if(events.length > 0) log.events = events;396397 this.chainLog.push(log);398399 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(failureMessage);400 return result;401 }402403 async callRpc(rpc: string, params?: any[]) {404 if(typeof params === 'undefined') params = [];405 if(this.api === null) throw Error('API not initialized');406 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);407408 const startTime = (new Date()).getTime();409 let result;410 let error = null;411 const log = {412 type: this.chainLogType.RPC,413 call: rpc,414 params,415 } as IUniqueHelperLog;416417 try {418 result = await this.constructApiCall(rpc, params);419 }420 catch(e) {421 error = e;422 }423424 const endTime = (new Date()).getTime();425426 log.executedAt = endTime;427 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';428 log.executionTime = endTime - startTime;429430 this.chainLog.push(log);431432 if(error !== null) throw error;433434 return result;435 }436437 getSignerAddress(signer: IKeyringPair | string): string {438 if(typeof signer === 'string') return signer;439 return signer.address;440 }441}442443444class HelperGroup {445 helper: UniqueHelper;446447 constructor(uniqueHelper: UniqueHelper) {448 this.helper = uniqueHelper;449 }450}451452453class CollectionGroup extends HelperGroup {454 /**455 * Get number of blocks when sponsored transaction is available.456 *457 * @param collectionId ID of collection458 * @param tokenId ID of token459 * @param addressObj address for which the sponsorship is checked460 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});461 * @returns number of blocks or null if sponsorship hasn't been set462 */463 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {464 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();465 }466467 /**468 * Get the number of created collections.469 * 470 * @returns number of created collections471 */472 async getTotalCount(): Promise<number> {473 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();474 }475476 /**477 * Get information about the collection with additional data, including the number of tokens it contains, its administrators, the normalized address of the collection's owner, and decoded name and description.478 * 479 * @param collectionId ID of collection480 * @example await getData(2)481 * @returns collection information object482 */483 async getData(collectionId: number): Promise<{484 id: number;485 name: string;486 description: string;487 tokensCount: number;488 admins: ICrossAccountId[];489 normalizedOwner: TSubstrateAccount;490 raw: any491 } | null> {492 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);493 const humanCollection = collection.toHuman(), collectionData = {494 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],495 raw: humanCollection,496 } as any, jsonCollection = collection.toJSON();497 if (humanCollection === null) return null;498 collectionData.raw.limits = jsonCollection.limits;499 collectionData.raw.permissions = jsonCollection.permissions;500 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);501 for (const key of ['name', 'description']) {502 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);503 }504505 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;506 collectionData.admins = await this.getAdmins(collectionId);507508 return collectionData;509 }510511 /**512 * Get the normalized addresses of the collection's administrators.513 * 514 * @param collectionId ID of collection515 * @example await getAdmins(1)516 * @returns array of administrators517 */518 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {519 const normalized = [];520 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {521 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});522 else normalized.push(admin);523 }524 return normalized;525 }526527 /**528 * Get the normalized addresses added to the collection allow-list.529 * @param collectionId ID of collection530 * @example await getAllowList(1)531 * @returns array of allow-listed addresses532 */533 async getAllowList(collectionId: number): Promise<ICrossAccountId[]> {534 const normalized = [];535 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();536 for (const address of allowListed) {537 if (address.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(address.Substrate)});538 else normalized.push(address);539 }540 return normalized;541 }542543 /**544 * Get the effective limits of the collection instead of null for default values545 * 546 * @param collectionId ID of collection547 * @example await getEffectiveLimits(2)548 * @returns object of collection limits549 */550 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {551 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();552 }553554 /**555 * Burns the collection if the signer has sufficient permissions and collection is empty.556 * 557 * @param signer keyring of signer558 * @param collectionId ID of collection559 * @param label extra label for log560 * @example await helper.collection.burn(aliceKeyring, 3);561 * @returns ```true``` if extrinsic success, otherwise ```false```562 */563 async burn(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {564 if(typeof label === 'undefined') label = `collection #${collectionId}`;565 const result = await this.helper.executeExtrinsic(566 signer,567 'api.tx.unique.destroyCollection', [collectionId],568 true, `Unable to burn collection for ${label}`,569 );570571 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed', label);572 }573574 /**575 * Sets the sponsor for the collection (Requires the Substrate address).576 * 577 * @param signer keyring of signer578 * @param collectionId ID of collection579 * @param sponsorAddress Sponsor substrate address580 * @param label extra label for log581 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")582 * @returns ```true``` if extrinsic success, otherwise ```false```583 */584 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount, label?: string): Promise<boolean> {585 if(typeof label === 'undefined') label = `collection #${collectionId}`;586 const result = await this.helper.executeExtrinsic(587 signer,588 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],589 true, `Unable to set collection sponsor for ${label}`,590 );591592 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet', label);593 }594595 /**596 * Confirms consent to sponsor the collection on behalf of the signer.597 * 598 * @param signer keyring of signer599 * @param collectionId ID of collection600 * @param label extra label for log601 * @example confirmSponsorship(aliceKeyring, 10)602 * @returns ```true``` if extrinsic success, otherwise ```false```603 */604 async confirmSponsorship(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {605 if(typeof label === 'undefined') label = `collection #${collectionId}`;606 const result = await this.helper.executeExtrinsic(607 signer,608 'api.tx.unique.confirmSponsorship', [collectionId],609 true, `Unable to confirm collection sponsorship for ${label}`,610 );611612 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed', label);613 }614615 /**616 * Sets the limits of the collection. At least one limit must be specified for a correct call.617 * 618 * @param signer keyring of signer619 * @param collectionId ID of collection620 * @param limits collection limits object621 * @param label extra label for log622 * @example623 * await setLimits(624 * aliceKeyring,625 * 10,626 * {627 * sponsorTransferTimeout: 0,628 * ownerCanDestroy: false629 * }630 * )631 * @returns ```true``` if extrinsic success, otherwise ```false```632 */633 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits, label?: string): Promise<boolean> {634 if(typeof label === 'undefined') label = `collection #${collectionId}`;635 const result = await this.helper.executeExtrinsic(636 signer,637 'api.tx.unique.setCollectionLimits', [collectionId, limits],638 true, `Unable to set collection limits for ${label}`,639 );640641 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet', label);642 }643644 /**645 * Changes the owner of the collection to the new Substrate address.646 * 647 * @param signer keyring of signer648 * @param collectionId ID of collection649 * @param ownerAddress substrate address of new owner650 * @param label extra label for log651 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")652 * @returns ```true``` if extrinsic success, otherwise ```false```653 */654 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount, label?: string): Promise<boolean> {655 if(typeof label === 'undefined') label = `collection #${collectionId}`;656 const result = await this.helper.executeExtrinsic(657 signer,658 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],659 true, `Unable to change collection owner for ${label}`,660 );661662 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged', label);663 }664665 /**666 * Adds a collection administrator. 667 * 668 * @param signer keyring of signer669 * @param collectionId ID of collection670 * @param adminAddressObj Administrator address (substrate or ethereum)671 * @param label extra label for log672 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})673 * @returns ```true``` if extrinsic success, otherwise ```false```674 */675 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {676 if(typeof label === 'undefined') label = `collection #${collectionId}`;677 const result = await this.helper.executeExtrinsic(678 signer,679 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],680 true, `Unable to add collection admin for ${label}`,681 );682683 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded', label);684 }685686 /**687 * Adds an address to allow list 688 * @param signer keyring of signer689 * @param collectionId ID of collection690 * @param addressObj address to add to the allow list691 * @param label extra label for log692 * @returns ```true``` if extrinsic success, otherwise ```false```693 */694 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId, label?: string): Promise<boolean> {695 if(typeof label === 'undefined') label = `collection #${collectionId}`;696 const result = await this.helper.executeExtrinsic(697 signer,698 'api.tx.unique.addToAllowList', [collectionId, addressObj],699 true, `Unable to add address to allow list for ${label}`,700 );701702 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');703 }704705 /**706 * Removes a collection administrator.707 * 708 * @param signer keyring of signer709 * @param collectionId ID of collection710 * @param adminAddressObj Administrator address (substrate or ethereum)711 * @param label extra label for log712 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})713 * @returns ```true``` if extrinsic success, otherwise ```false```714 */715 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId, label?: string): Promise<boolean> {716 if(typeof label === 'undefined') label = `collection #${collectionId}`;717 const result = await this.helper.executeExtrinsic(718 signer,719 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],720 true, `Unable to remove collection admin for ${label}`,721 );722723 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved', label);724 }725726 /**727 * Sets onchain permissions for selected collection.728 * 729 * @param signer keyring of signer730 * @param collectionId ID of collection731 * @param permissions collection permissions object732 * @param label extra label for log733 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});734 * @returns ```true``` if extrinsic success, otherwise ```false```735 */736 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions, label?: string): Promise<boolean> {737 if(typeof label === 'undefined') label = `collection #${collectionId}`;738 const result = await this.helper.executeExtrinsic(739 signer,740 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],741 true, `Unable to set collection permissions for ${label}`,742 );743744 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet', label);745 }746747 /**748 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.749 * 750 * @param signer keyring of signer751 * @param collectionId ID of collection752 * @param permissions nesting permissions object753 * @param label extra label for log754 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});755 * @returns ```true``` if extrinsic success, otherwise ```false```756 */757 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions, label?: string): Promise<boolean> {758 return await this.setPermissions(signer, collectionId, {nesting: permissions}, label);759 }760761 /**762 * Disables nesting for selected collection.763 * 764 * @param signer keyring of signer765 * @param collectionId ID of collection766 * @param label extra label for log767 * @example disableNesting(aliceKeyring, 10);768 * @returns ```true``` if extrinsic success, otherwise ```false```769 */770 async disableNesting(signer: TSigner, collectionId: number, label?: string): Promise<boolean> {771 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}}, label);772 }773774 /**775 * Sets onchain properties to the collection.776 * 777 * @param signer keyring of signer778 * @param collectionId ID of collection779 * @param properties array of property objects780 * @param label extra label for log781 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);782 * @returns ```true``` if extrinsic success, otherwise ```false```783 */784 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[], label?: string): Promise<boolean> {785 if(typeof label === 'undefined') label = `collection #${collectionId}`;786 const result = await this.helper.executeExtrinsic(787 signer,788 'api.tx.unique.setCollectionProperties', [collectionId, properties],789 true, `Unable to set collection properties for ${label}`,790 );791792 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet', label);793 }794795 /**796 * Deletes onchain properties from the collection.797 * 798 * @param signer keyring of signer799 * @param collectionId ID of collection800 * @param propertyKeys array of property keys to delete801 * @param label802 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);803 * @returns ```true``` if extrinsic success, otherwise ```false```804 */805 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[], label?: string): Promise<boolean> {806 if(typeof label === 'undefined') label = `collection #${collectionId}`;807 const result = await this.helper.executeExtrinsic(808 signer,809 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],810 true, `Unable to delete collection properties for ${label}`,811 );812813 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted', label);814 }815816 /**817 * Changes the owner of the token.818 * 819 * @param signer keyring of signer820 * @param collectionId ID of collection821 * @param tokenId ID of token822 * @param addressObj address of a new owner823 * @param amount amount of tokens to be transfered. For NFT must be set to 1n824 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})825 * @returns true if the token success, otherwise false826 */827 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {828 const result = await this.helper.executeExtrinsic(829 signer,830 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],831 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,832 );833834 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);835 }836837 /**838 * 839 * Change ownership of a token(s) on behalf of the owner. 840 * 841 * @param signer keyring of signer842 * @param collectionId ID of collection843 * @param tokenId ID of token844 * @param fromAddressObj address on behalf of which the token will be sent845 * @param toAddressObj new token owner846 * @param amount amount of tokens to be transfered. For NFT must be set to 1n847 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})848 * @returns true if the token success, otherwise false849 */850 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {851 const result = await this.helper.executeExtrinsic(852 signer,853 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],854 true, `Unable to transfer token #${tokenId} from collection #${collectionId}`,855 );856 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);857 }858859 /**860 * 861 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.862 * 863 * @param signer keyring of signer864 * @param collectionId ID of collection865 * @param tokenId ID of token866 * @param label 867 * @param amount amount of tokens to be burned. For NFT must be set to 1n868 * @example burnToken(aliceKeyring, 10, 5);869 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```870 */871 async burnToken(signer: TSigner, collectionId: number, tokenId: number, label?: string, amount=1n): Promise<{872 success: boolean,873 token: number | null874 }> {875 if(typeof label === 'undefined') label = `collection #${collectionId}`;876 const burnResult = await this.helper.executeExtrinsic(877 signer,878 'api.tx.unique.burnItem', [collectionId, tokenId, amount],879 true, `Unable to burn token for ${label}`,880 );881 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);882 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');883 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};884 }885886 /**887 * Destroys a concrete instance of NFT on behalf of the owner888 * 889 * @param signer keyring of signer890 * @param collectionId ID of collection891 * @param fromAddressObj address on behalf of which the token will be burnt892 * @param tokenId ID of token893 * @param label 894 * @param amount amount of tokens to be burned. For NFT must be set to 1n895 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})896 * @returns ```true``` if extrinsic success, otherwise ```false```897 */898 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, label?: string, amount=1n): Promise<boolean> {899 if(typeof label === 'undefined') label = `collection #${collectionId}`;900 const burnResult = await this.helper.executeExtrinsic(901 signer,902 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],903 true, `Unable to burn token from for ${label}`,904 );905 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult, label);906 return burnedTokens.success && burnedTokens.tokens.length > 0;907 }908909 /**910 * Set, change, or remove approved address to transfer the ownership of the NFT.911 * 912 * @param signer keyring of signer913 * @param collectionId ID of collection914 * @param tokenId ID of token915 * @param toAddressObj 916 * @param label 917 * @param amount amount of token to be approved. For NFT must be set to 1n918 * @returns ```true``` if extrinsic success, otherwise ```false```919 */920 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=1n) {921 if(typeof label === 'undefined') label = `collection #${collectionId}`;922 const approveResult = await this.helper.executeExtrinsic(923 signer, 924 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],925 true, `Unable to approve token for ${label}`,926 );927928 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved', label);929 }930931 /**932 * Get the amount of token pieces approved to transfer933 * @param collectionId ID of collection934 * @param tokenId ID of token935 * @param toAccountObj 936 * @param fromAccountObj937 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})938 * @returns number of approved to transfer pieces939 */940 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {941 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();942 }943944 /**945 * Get the last created token id946 * @param collectionId ID of collection947 * @example getLastTokenId(10);948 * @returns id of the last created token949 */950 async getLastTokenId(collectionId: number): Promise<number> {951 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();952 }953954 /**955 * Check if token exists956 * @param collectionId ID of collection957 * @param tokenId ID of token958 * @example isTokenExists(10, 20);959 * @returns true if the token exists, otherwise false960 */961 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {962 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();963 }964}965966class NFTnRFT extends CollectionGroup {967 /**968 * Get tokens owned by account969 * 970 * @param collectionId ID of collection971 * @param addressObj tokens owner972 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})973 * @returns array of token ids owned by account974 */975 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {976 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();977 }978979 /**980 * Get token data981 * @param collectionId ID of collection982 * @param tokenId ID of token983 * @param blockHashAt 984 * @param propertyKeys985 * @example getToken(10, 5);986 * @returns human readable token data 987 */988 async getToken(collectionId: number, tokenId: number, blockHashAt?: string, propertyKeys?: string[]): Promise<{989 properties: IProperty[];990 owner: ICrossAccountId;991 normalizedOwner: ICrossAccountId;992 }| null> {993 let tokenData;994 if(typeof blockHashAt === 'undefined') {995 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);996 }997 else {998 if(typeof propertyKeys === 'undefined') {999 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1000 if(!collection) return null;1001 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1002 }1003 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1004 }1005 tokenData = tokenData.toHuman();1006 if (tokenData === null || tokenData.owner === null) return null;1007 const owner = {} as any;1008 for (const key of Object.keys(tokenData.owner)) {1009 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1010 }1011 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1012 return tokenData;1013 }10141015 /**1016 * Set permissions to change token properties1017 * @param signer keyring of signer1018 * @param collectionId ID of collection1019 * @param permissions permissions to change a property by the collection owner or admin1020 * @param label 1021 * @example setTokenPropertyPermissions(1022 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1023 * )1024 * @returns true if extrinsic success otherwise false1025 */1026 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[], label?: string): Promise<boolean> {1027 if(typeof label === 'undefined') label = `collection #${collectionId}`;1028 const result = await this.helper.executeExtrinsic(1029 signer,1030 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1031 true, `Unable to set token property permissions for ${label}`,1032 );10331034 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet', label);1035 }10361037 /**1038 * Set token properties1039 * @param signer keyring of signer1040 * @param collectionId ID of collection1041 * @param tokenId ID of token1042 * @param properties 1043 * @param label 1044 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1045 * @returns ```true``` if extrinsic success, otherwise ```false```1046 */1047 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[], label?: string): Promise<boolean> {1048 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1049 const result = await this.helper.executeExtrinsic(1050 signer,1051 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1052 true, `Unable to set token properties for ${label}`,1053 );10541055 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet', label);1056 }10571058 /**1059 * Delete the provided properties of a token1060 * @param signer keyring of signer1061 * @param collectionId ID of collection1062 * @param tokenId ID of token1063 * @param propertyKeys property keys to be deleted 1064 * @param label 1065 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1066 * @returns ```true``` if extrinsic success, otherwise ```false```1067 */1068 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[], label?: string): Promise<boolean> {1069 if(typeof label === 'undefined') label = `token #${tokenId} from collection #${collectionId}`;1070 const result = await this.helper.executeExtrinsic(1071 signer,1072 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1073 true, `Unable to delete token properties for ${label}`,1074 );10751076 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted', label);1077 }10781079 /**1080 * Mint new collection1081 * @param signer keyring of signer1082 * @param collectionOptions basic collection options and properties 1083 * @param mode NFT or RFT type of a collection1084 * @param errorLabel 1085 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1086 * @returns object of the created collection1087 */1088 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT', errorLabel = 'Unable to mint collection'): Promise<UniqueCollectionBase> {1089 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1090 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1091 for (const key of ['name', 'description', 'tokenPrefix']) {1092 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);1093 }1094 const creationResult = await this.helper.executeExtrinsic(1095 signer,1096 'api.tx.unique.createCollectionEx', [collectionOptions],1097 true, errorLabel,1098 );1099 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1100 }11011102 getCollectionObject(collectionId: number): any {1103 return null;1104 }11051106 getTokenObject(collectionId: number, tokenId: number): any {1107 return null;1108 }1109}111011111112class NFTGroup extends NFTnRFT {1113 /**1114 * Get collection object1115 * @param collectionId ID of collection1116 * @example getCollectionObject(2);1117 * @returns instance of UniqueNFTCollection1118 */1119 getCollectionObject(collectionId: number): UniqueNFTCollection {1120 return new UniqueNFTCollection(collectionId, this.helper);1121 }11221123 /**1124 * Get token object1125 * @param collectionId ID of collection1126 * @param tokenId ID of token1127 * @example getTokenObject(10, 5);1128 * @returns instance of UniqueNFTToken1129 */1130 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1131 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1132 }11331134 /**1135 * Get token's owner1136 * @param collectionId ID of collection1137 * @param tokenId ID of token1138 * @param blockHashAt 1139 * @example getTokenOwner(10, 5);1140 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1141 */1142 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1143 let owner;1144 if (typeof blockHashAt === 'undefined') {1145 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1146 } else {1147 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1148 }1149 return crossAccountIdFromLower(owner.toJSON());1150 }11511152 /**1153 * Is token approved to transfer1154 * @param collectionId ID of collection1155 * @param tokenId ID of token1156 * @param toAccountObj address to be approved1157 * @returns ```true``` if extrinsic success, otherwise ```false```1158 */1159 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1160 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1161 }11621163 /**1164 * Changes the owner of the token.1165 * 1166 * @param signer keyring of signer1167 * @param collectionId ID of collection1168 * @param tokenId ID of token1169 * @param addressObj address of a new owner1170 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1171 * @returns ```true``` if extrinsic success, otherwise ```false```1172 */1173 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1174 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1175 }11761177 /**1178 * 1179 * Change ownership of a NFT on behalf of the owner. 1180 * 1181 * @param signer keyring of signer1182 * @param collectionId ID of collection1183 * @param tokenId ID of token1184 * @param fromAddressObj address on behalf of which the token will be sent1185 * @param toAddressObj new token owner1186 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1187 * @returns ```true``` if extrinsic success, otherwise ```false```1188 */1189 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1190 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1191 }11921193 /**1194 * Recursively find the address that owns the token1195 * @param collectionId ID of collection1196 * @param tokenId ID of token1197 * @param blockHashAt 1198 * @example getTokenTopmostOwner(10, 5);1199 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1200 */1201 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1202 let owner;1203 if (typeof blockHashAt === 'undefined') {1204 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1205 } else {1206 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1207 }12081209 if (owner === null) return null;12101211 owner = owner.toHuman();12121213 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1214 }12151216 /**1217 * Get tokens nested in the provided token1218 * @param collectionId ID of collection1219 * @param tokenId ID of token1220 * @param blockHashAt 1221 * @example getTokenChildren(10, 5);1222 * @returns tokens whose depth of nesting is <= 5 1223 */1224 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1225 let children;1226 if(typeof blockHashAt === 'undefined') {1227 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1228 } else {1229 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1230 }12311232 return children.toJSON().map((x: any) => {1233 return {collectionId: x.collection, tokenId: x.token};1234 });1235 }12361237 /**1238 * Nest one token into another1239 * @param signer keyring of signer1240 * @param tokenObj token to be nested1241 * @param rootTokenObj token to be parent1242 * @param label 1243 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1244 * @returns ```true``` if extrinsic success, otherwise ```false```1245 */1246 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, label='nest token'): Promise<boolean> {1247 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1248 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1249 if(!result) {1250 throw Error(`Unable to nest token for ${label}`);1251 }1252 return result;1253 }12541255 /**1256 * Remove token from nested state1257 * @param signer keyring of signer1258 * @param tokenObj token to unnest1259 * @param rootTokenObj parent of a token1260 * @param toAddressObj address of a new token owner 1261 * @param label 1262 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1263 * @returns ```true``` if extrinsic success, otherwise ```false```1264 */1265 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId, label='unnest token'): Promise<boolean> {1266 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1267 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1268 if(!result) {1269 throw Error(`Unable to unnest token for ${label}`);1270 }1271 return result;1272 }12731274 /**1275 * Mint new collection1276 * @param signer keyring of signer1277 * @param collectionOptions Collection options1278 * @param label 1279 * @example 1280 * mintCollection(aliceKeyring, {1281 * name: 'New',1282 * description: 'New collection',1283 * tokenPrefix: 'NEW',1284 * })1285 * @returns object of the created collection1286 */1287 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueNFTCollection> {1288 return await super.mintCollection(signer, collectionOptions, 'NFT', `Unable to mint NFT collection for ${label}`) as UniqueNFTCollection;1289 }12901291 /**1292 * Mint new token1293 * @param signer keyring of signer1294 * @param data token data1295 * @param label 1296 * @returns created token object1297 */1298 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }, label?: string): Promise<UniqueNFTToken> {1299 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1300 const creationResult = await this.helper.executeExtrinsic(1301 signer,1302 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1303 nft: {1304 properties: data.properties,1305 },1306 }],1307 true, `Unable to mint NFT token for ${label}`,1308 );1309 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1310 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1311 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1312 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1313 }13141315 /**1316 * Mint multiple NFT tokens1317 * @param signer keyring of signer1318 * @param collectionId ID of collection1319 * @param tokens array of tokens with owner and properties1320 * @param label 1321 * @example 1322 * mintMultipleTokens(aliceKeyring, 10, [{1323 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1324 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1325 * },{1326 * owner: {Ethereum: "0x9F0583DbB855d..."},1327 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1328 * }]);1329 * @returns ```true``` if extrinsic success, otherwise ```false```1330 */1331 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1332 if(typeof label === 'undefined') label = `collection #${collectionId}`;1333 const creationResult = await this.helper.executeExtrinsic(1334 signer,1335 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1336 true, `Unable to mint NFT tokens for ${label}`,1337 );1338 const collection = this.getCollectionObject(collectionId);1339 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1340 }13411342 /**1343 * Mint multiple NFT tokens with one owner1344 * @param signer keyring of signer1345 * @param collectionId ID of collection1346 * @param owner tokens owner1347 * @param tokens array of tokens with owner and properties1348 * @param label 1349 * @example1350 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1351 * properties: [{1352 * key: "gender",1353 * value: "female",1354 * },{1355 * key: "age",1356 * value: "33",1357 * }],1358 * }]);1359 * @returns array of newly created tokens1360 */1361 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[], label?: string): Promise<UniqueNFTToken[]> {1362 if(typeof label === 'undefined') label = `collection #${collectionId}`;1363 const rawTokens = [];1364 for (const token of tokens) {1365 const raw = {NFT: {properties: token.properties}};1366 rawTokens.push(raw);1367 }1368 const creationResult = await this.helper.executeExtrinsic(1369 signer,1370 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1371 true, `Unable to mint NFT tokens for ${label}`,1372 );1373 const collection = this.getCollectionObject(collectionId);1374 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1375 }13761377 /**1378 * Destroys a concrete instance of NFT.1379 * @param signer keyring of signer1380 * @param collectionId ID of collection1381 * @param tokenId ID of token1382 * @param label 1383 * @example burnToken(aliceKeyring, 10, 5);1384 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1385 */1386 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string): Promise<{ success: boolean; token: number | null; }> {1387 return await super.burnToken(signer, collectionId, tokenId, label, 1n);1388 }13891390 /**1391 * Set, change, or remove approved address to transfer the ownership of the NFT.1392 * 1393 * @param signer keyring of signer1394 * @param collectionId ID of collection1395 * @param tokenId ID of token1396 * @param toAddressObj address to approve1397 * @param label 1398 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1399 * @returns ```true``` if extrinsic success, otherwise ```false```1400 */1401 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {1402 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, 1n);1403 }1404}140514061407class RFTGroup extends NFTnRFT {1408 /**1409 * Get collection object1410 * @param collectionId ID of collection1411 * @example getCollectionObject(2);1412 * @returns instance of UniqueRFTCollection1413 */1414 getCollectionObject(collectionId: number): UniqueRFTCollection {1415 return new UniqueRFTCollection(collectionId, this.helper);1416 }14171418 /**1419 * Get token object1420 * @param collectionId ID of collection1421 * @param tokenId ID of token1422 * @example getTokenObject(10, 5);1423 * @returns instance of UniqueNFTToken1424 */1425 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1426 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1427 }14281429 /**1430 * Get top 10 token owners with the largest number of pieces 1431 * @param collectionId ID of collection1432 * @param tokenId ID of token1433 * @example getTokenTop10Owners(10, 5);1434 * @returns array of top 10 owners1435 */1436 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1437 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1438 }14391440 /**1441 * Get number of pieces owned by address1442 * @param collectionId ID of collection1443 * @param tokenId ID of token1444 * @param addressObj address token owner1445 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1446 * @returns number of pieces ownerd by address1447 */1448 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1449 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1450 }14511452 /**1453 * Transfer pieces of token to another address1454 * @param signer keyring of signer1455 * @param collectionId ID of collection1456 * @param tokenId ID of token1457 * @param addressObj address of a new owner1458 * @param amount number of pieces to be transfered1459 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1460 * @returns ```true``` if extrinsic success, otherwise ```false```1461 */1462 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=100n): Promise<boolean> {1463 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1464 }14651466 /**1467 * Change ownership of some pieces of RFT on behalf of the owner. 1468 * @param signer keyring of signer1469 * @param collectionId ID of collection1470 * @param tokenId ID of token1471 * @param fromAddressObj address on behalf of which the token will be sent1472 * @param toAddressObj new token owner1473 * @param amount number of pieces to be transfered1474 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1475 * @returns ```true``` if extrinsic success, otherwise ```false```1476 */1477 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n): Promise<boolean> {1478 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1479 }14801481 /**1482 * Mint new collection1483 * @param signer keyring of signer1484 * @param collectionOptions Collection options1485 * @param label 1486 * @example1487 * mintCollection(aliceKeyring, {1488 * name: 'New',1489 * description: 'New collection',1490 * tokenPrefix: 'NEW',1491 * })1492 * @returns object of the created collection1493 */1494 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, label = 'new collection'): Promise<UniqueRFTCollection> {1495 return await super.mintCollection(signer, collectionOptions, 'RFT', `Unable to mint RFT collection for ${label}`) as UniqueRFTCollection;1496 }14971498 /**1499 * Mint new token1500 * @param signer keyring of signer1501 * @param data token data1502 * @param label 1503 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1504 * @returns created token object1505 */1506 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }, label?: string): Promise<UniqueRFTToken> {1507 if(typeof label === 'undefined') label = `collection #${data.collectionId}`;1508 const creationResult = await this.helper.executeExtrinsic(1509 signer,1510 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1511 refungible: {1512 pieces: data.pieces,1513 properties: data.properties,1514 },1515 }],1516 true, `Unable to mint RFT token for ${label}`,1517 );1518 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult, label);1519 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1520 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1521 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1522 }15231524 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1525 throw Error('Not implemented');1526 if(typeof label === 'undefined') label = `collection #${collectionId}`;1527 const creationResult = await this.helper.executeExtrinsic(1528 signer,1529 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1530 true, `Unable to mint RFT tokens for ${label}`,1531 );1532 const collection = this.getCollectionObject(collectionId);1533 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1534 }15351536 /**1537 * Mint multiple RFT tokens with one owner1538 * @param signer keyring of signer1539 * @param collectionId ID of collection1540 * @param owner tokens owner1541 * @param tokens array of tokens with properties and pieces1542 * @param label 1543 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1544 * @returns array of newly created RFT tokens1545 */1546 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[], label?: string): Promise<UniqueRFTToken[]> {1547 if(typeof label === 'undefined') label = `collection #${collectionId}`;1548 const rawTokens = [];1549 for (const token of tokens) {1550 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1551 rawTokens.push(raw);1552 }1553 const creationResult = await this.helper.executeExtrinsic(1554 signer,1555 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1556 true, `Unable to mint RFT tokens for ${label}`,1557 );1558 const collection = this.getCollectionObject(collectionId);1559 return this.helper.util.extractTokensFromCreationResult(creationResult, label).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1560 }15611562 /**1563 * Destroys a concrete instance of RFT.1564 * @param signer keyring of signer1565 * @param collectionId ID of collection1566 * @param tokenId ID of token1567 * @param label 1568 * @param amount number of pieces to be burnt1569 * @example burnToken(aliceKeyring, 10, 5);1570 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1571 */1572 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, label?: string, amount=100n): Promise<{ success: boolean; token: number | null; }> {1573 return await super.burnToken(signer, collectionId, tokenId, label, amount);1574 }15751576 /**1577 * Set, change, or remove approved address to transfer the ownership of the RFT.1578 * 1579 * @param signer keyring of signer1580 * @param collectionId ID of collection1581 * @param tokenId ID of token1582 * @param toAddressObj address to approve1583 * @param label 1584 * @param amount number of pieces to be approved1585 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1586 * @returns true if the token success, otherwise false1587 */1588 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, label?: string, amount=100n) {1589 return super.approveToken(signer, collectionId, tokenId, toAddressObj, label, amount);1590 }15911592 /**1593 * Get total number of pieces1594 * @param collectionId ID of collection1595 * @param tokenId ID of token1596 * @example getTokenTotalPieces(10, 5);1597 * @returns number of pieces1598 */1599 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1600 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1601 }16021603 /**1604 * Change number of token pieces. Signer must be the owner of all token pieces.1605 * @param signer keyring of signer1606 * @param collectionId ID of collection1607 * @param tokenId ID of token1608 * @param amount new number of pieces1609 * @param label 1610 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1611 * @returns true if the repartion was success, otherwise false1612 */1613 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint, label?: string): Promise<boolean> {1614 if(typeof label === 'undefined') label = `collection #${collectionId}`;1615 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1616 const repartitionResult = await this.helper.executeExtrinsic(1617 signer,1618 'api.tx.unique.repartition', [collectionId, tokenId, amount],1619 true, `Unable to repartition RFT token for ${label}`,1620 );1621 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated', label);1622 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed', label);1623 }1624}162516261627class FTGroup extends CollectionGroup {1628 /**1629 * Get collection object1630 * @param collectionId ID of collection1631 * @example getCollectionObject(2);1632 * @returns instance of UniqueFTCollection1633 */1634 getCollectionObject(collectionId: number): UniqueFTCollection {1635 return new UniqueFTCollection(collectionId, this.helper);1636 }16371638 /**1639 * Mint new fungible collection1640 * @param signer keyring of signer1641 * @param collectionOptions Collection options1642 * @param decimalPoints number of token decimals 1643 * @param errorLabel 1644 * @example1645 * mintCollection(aliceKeyring, {1646 * name: 'New',1647 * description: 'New collection',1648 * tokenPrefix: 'NEW',1649 * }, 18)1650 * @returns newly created fungible collection1651 */1652 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0, errorLabel = 'Unable to mint collection'): Promise<UniqueFTCollection> {1653 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1654 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1655 collectionOptions.mode = {fungible: decimalPoints};1656 for (const key of ['name', 'description', 'tokenPrefix']) {1657 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);1658 }1659 const creationResult = await this.helper.executeExtrinsic(1660 signer,1661 'api.tx.unique.createCollectionEx', [collectionOptions],1662 true, errorLabel,1663 );1664 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult, errorLabel));1665 }16661667 /**1668 * Mint tokens1669 * @param signer keyring of signer1670 * @param collectionId ID of collection1671 * @param owner address owner of new tokens1672 * @param amount amount of tokens to be meanted1673 * @param label 1674 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1675 * @returns ```true``` if extrinsic success, otherwise ```false``` 1676 */1677 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint, label?: string): Promise<boolean> {1678 if(typeof label === 'undefined') label = `collection #${collectionId}`;1679 const creationResult = await this.helper.executeExtrinsic(1680 signer,1681 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1682 fungible: {1683 value: amount,1684 },1685 }],1686 true, `Unable to mint fungible tokens for ${label}`,1687 );1688 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1689 }16901691 /**1692 * Mint multiple Fungible tokens with one owner1693 * @param signer keyring of signer1694 * @param collectionId ID of collection1695 * @param owner tokens owner1696 * @param tokens array of tokens with properties and pieces1697 * @param label 1698 * @returns ```true``` if extrinsic success, otherwise ```false``` 1699 */1700 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string): Promise<boolean> {1701 if(typeof label === 'undefined') label = `collection #${collectionId}`;1702 const rawTokens = [];1703 for (const token of tokens) {1704 const raw = {Fungible: {Value: token.value}};1705 rawTokens.push(raw);1706 }1707 const creationResult = await this.helper.executeExtrinsic(1708 signer,1709 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1710 true, `Unable to mint RFT tokens for ${label}`,1711 );1712 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated', label);1713 }17141715 /**1716 * Get the top 10 owners with the largest balance for the Fungible collection 1717 * @param collectionId ID of collection1718 * @example getTop10Owners(10);1719 * @returns array of ```ICrossAccountId```1720 */1721 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1722 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1723 }17241725 /**1726 * Get account balance1727 * @param collectionId ID of collection1728 * @param addressObj address of owner1729 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1730 * @returns amount of fungible tokens owned by address1731 */1732 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1733 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1734 }17351736 /**1737 * Transfer tokens to address1738 * @param signer keyring of signer1739 * @param collectionId ID of collection1740 * @param toAddressObj address recepient1741 * @param amount amount of tokens to be sent1742 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1743 * @returns ```true``` if extrinsic success, otherwise ```false``` 1744 */1745 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount: bigint) {1746 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1747 }17481749 /**1750 * Transfer some tokens on behalf of the owner.1751 * @param signer keyring of signer1752 * @param collectionId ID of collection1753 * @param fromAddressObj address on behalf of which tokens will be sent1754 * @param toAddressObj address where token to be sent1755 * @param amount number of tokens to be sent1756 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1757 * @returns ```true``` if extrinsic success, otherwise ```false``` 1758 */1759 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {1760 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1761 }17621763 /**1764 * Destroy some amount of tokens1765 * @param signer keyring of signer1766 * @param collectionId ID of collection1767 * @param amount amount of tokens to be destroyed1768 * @param label 1769 * @example burnTokens(aliceKeyring, 10, 1000n);1770 * @returns ```true``` if extrinsic success, otherwise ```false``` 1771 */1772 async burnTokens(signer: IKeyringPair, collectionId: number, amount=100n, label?: string): Promise<boolean> {1773 return (await super.burnToken(signer, collectionId, 0, label, amount)).success;1774 }17751776 /**1777 * Burn some tokens on behalf of the owner.1778 * @param signer keyring of signer1779 * @param collectionId ID of collection1780 * @param fromAddressObj address on behalf of which tokens will be burnt1781 * @param amount amount of tokens to be burnt1782 * @param label 1783 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1784 * @returns ```true``` if extrinsic success, otherwise ```false``` 1785 */1786 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=100n, label?: string): Promise<boolean> {1787 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, label, amount);1788 }17891790 /**1791 * Get total collection supply1792 * @param collectionId 1793 * @returns 1794 */1795 async getTotalPieces(collectionId: number): Promise<bigint> {1796 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1797 }17981799 /**1800 * Set, change, or remove approved address to transfer tokens.1801 * 1802 * @param signer keyring of signer1803 * @param collectionId ID of collection1804 * @param toAddressObj address to be approved1805 * @param amount amount of tokens to be approved1806 * @param label 1807 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1808 * @returns ```true``` if extrinsic success, otherwise ```false``` 1809 */1810 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {1811 return super.approveToken(signer, collectionId, 0, toAddressObj, label, amount);1812 }18131814 /**1815 * Get amount of fungible tokens approved to transfer1816 * @param collectionId ID of collection1817 * @param fromAddressObj owner of tokens1818 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1819 * @returns number of tokens approved for the transfer1820 */1821 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1822 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1823 }1824}182518261827class ChainGroup extends HelperGroup {1828 /**1829 * Get system properties of a chain1830 * @example getChainProperties();1831 * @returns ss58Format, token decimals, and token symbol1832 */1833 getChainProperties(): IChainProperties {1834 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1835 return {1836 ss58Format: properties.ss58Format.toJSON(),1837 tokenDecimals: properties.tokenDecimals.toJSON(),1838 tokenSymbol: properties.tokenSymbol.toJSON(),1839 };1840 }18411842 /**1843 * Get chain header1844 * @example getLatestBlockNumber();1845 * @returns the number of the last block1846 */1847 async getLatestBlockNumber(): Promise<number> {1848 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1849 }18501851 /**1852 * Get block hash by block number1853 * @param blockNumber number of block1854 * @example getBlockHashByNumber(12345);1855 * @returns hash of a block1856 */1857 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1858 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1859 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1860 return blockHash;1861 }18621863 /**1864 * Get account nonce1865 * @param address substrate address1866 * @example getNonce("5GrwvaEF5zXb26Fz...");1867 * @returns number, account's nonce1868 */1869 async getNonce(address: TSubstrateAccount): Promise<number> {1870 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1871 }1872}187318741875class BalanceGroup extends HelperGroup {1876 /**1877 * Representation of the native token in the smallest unit1878 * @example getOneTokenNominal()1879 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1880 */1881 getOneTokenNominal(): bigint {1882 const chainProperties = this.helper.chain.getChainProperties();1883 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1884 }18851886 /**1887 * Get substrate address balance1888 * @param address substrate address1889 * @example getSubstrate("5GrwvaEF5zXb26Fz...")1890 * @returns amount of tokens on address1891 */1892 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1893 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1894 }18951896 /**1897 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved1898 * @param address substrate address1899 * @returns 1900 */1901 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {1902 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;1903 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};1904 }19051906 /**1907 * Get ethereum address balance1908 * @param address ethereum address1909 * @example getEthereum("0x9F0583DbB855d...")1910 * @returns amount of tokens on address1911 */1912 async getEthereum(address: TEthereumAccount): Promise<bigint> {1913 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1914 }19151916 /**1917 * Transfer tokens to substrate address1918 * @param signer keyring of signer1919 * @param address substrate address of a recepient1920 * @param amount amount of tokens to be transfered1921 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);1922 * @returns ```true``` if extrinsic success, otherwise ```false```1923 */1924 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1925 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}`);19261927 let transfer = {from: null, to: null, amount: 0n} as any;1928 result.result.events.forEach(({event: {data, method, section}}) => {1929 if ((section === 'balances') && (method === 'Transfer')) {1930 transfer = {1931 from: this.helper.address.normalizeSubstrate(data[0]),1932 to: this.helper.address.normalizeSubstrate(data[1]),1933 amount: BigInt(data[2]),1934 };1935 }1936 });1937 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1938 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1939 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1940 return isSuccess;1941 }1942}194319441945class AddressGroup extends HelperGroup {1946 /**1947 * Normalizes the address to the specified ss58 format, by default ```42```.1948 * @param address substrate address1949 * @param ss58Format format for address conversion, by default ```42```1950 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY1951 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation1952 */1953 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1954 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1955 }19561957 /**1958 * Get address in the connected chain format1959 * @param address substrate address1960 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network1961 * @returns address in chain format1962 */1963 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1964 const info = this.helper.chain.getChainProperties();1965 return encodeAddress(decodeAddress(address), info.ss58Format);1966 }19671968 /**1969 * Get substrate mirror of an ethereum address1970 * @param ethAddress ethereum address1971 * @param toChainFormat false for normalized account1972 * @example ethToSubstrate('0x9F0583DbB855d...')1973 * @returns substrate mirror of a provided ethereum address1974 */1975 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1976 if(!toChainFormat) return evmToAddress(ethAddress);1977 const info = this.helper.chain.getChainProperties();1978 return evmToAddress(ethAddress, info.ss58Format);1979 }19801981 /**1982 * Get ethereum mirror of a substrate address1983 * @param subAddress substrate account1984 * @example substrateToEth("5DnSF6RRjwteE3BrC...")1985 * @returns ethereum mirror of a provided substrate address1986 */1987 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1988 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1989 }1990}19911992class StakingGroup extends HelperGroup {1993 /**1994 * Stake tokens for App Promotion1995 * @param signer keyring of signer1996 * @param amountToStake amount of tokens to stake1997 * @param label extra label for log1998 * @returns1999 */2000 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2001 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2002 const stakeResult = await this.helper.executeExtrinsic(2003 signer,2004 'api.tx.promotion.stake', [amountToStake],2005 true, `stake failed for ${label}`,2006 );2007 // TODO extract info from stakeResult2008 return true;2009 }20102011 /**2012 * Unstake tokens for App Promotion2013 * @param signer keyring of signer2014 * @param amountToUnstake amount of tokens to unstake2015 * @param label extra label for log2016 * @returns 2017 */2018 async unstake(signer: TSigner, label?: string): Promise<boolean> {2019 if(typeof label === 'undefined') label = `${signer.address}`;2020 const unstakeResult = await this.helper.executeExtrinsic(2021 signer,2022 'api.tx.promotion.unstake', [],2023 true, `unstake failed for ${label}`,2024 );2025 // TODO extract info from unstakeResult2026 return true;2027 }20282029 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2030 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2031 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2032 }20332034 async getTotalStakingLocked(address: ICrossAccountId): Promise<bigint> {2035 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakingLocked', [address])).toBigInt();2036 }20372038 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {2039 return (await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2040 }20412042 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2043 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2044 }2045 2046 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<bigint[][]> {2047 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);2048 }2049}20502051export class UniqueHelper extends ChainHelperBase {2052 chain: ChainGroup;2053 balance: BalanceGroup;2054 address: AddressGroup;2055 collection: CollectionGroup;2056 nft: NFTGroup;2057 rft: RFTGroup;2058 ft: FTGroup;2059 staking: StakingGroup;20602061 constructor(logger?: ILogger) {2062 super(logger);2063 this.chain = new ChainGroup(this);2064 this.balance = new BalanceGroup(this);2065 this.address = new AddressGroup(this);2066 this.collection = new CollectionGroup(this);2067 this.nft = new NFTGroup(this);2068 this.rft = new RFTGroup(this);2069 this.ft = new FTGroup(this);2070 this.staking = new StakingGroup(this);2071 } 2072}207320742075class UniqueCollectionBase {2076 helper: UniqueHelper;2077 collectionId: number;20782079 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2080 this.collectionId = collectionId;2081 this.helper = uniqueHelper;2082 }20832084 async getData() {2085 return await this.helper.collection.getData(this.collectionId);2086 }20872088 async getLastTokenId() {2089 return await this.helper.collection.getLastTokenId(this.collectionId);2090 }20912092 async isTokenExists(tokenId: number) {2093 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2094 }20952096 async getAdmins() {2097 return await this.helper.collection.getAdmins(this.collectionId);2098 }20992100 async getAllowList() {2101 return await this.helper.collection.getAllowList(this.collectionId);2102 }21032104 async getEffectiveLimits() {2105 return await this.helper.collection.getEffectiveLimits(this.collectionId);2106 }21072108 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount, label?: string) {2109 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress, label);2110 }21112112 async confirmSponsorship(signer: TSigner, label?: string) {2113 return await this.helper.collection.confirmSponsorship(signer, this.collectionId, label);2114 }21152116 async setLimits(signer: TSigner, limits: ICollectionLimits, label?: string) {2117 return await this.helper.collection.setLimits(signer, this.collectionId, limits, label);2118 }21192120 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount, label?: string) {2121 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress, label);2122 }21232124 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2125 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj, label);2126 }21272128 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId, label?: string) {2129 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj, label);2130 }21312132 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId, label?: string) {2133 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj, label);2134 }21352136 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2137 return await this.helper.collection.setProperties(signer, this.collectionId, properties, label);2138 }21392140 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2141 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys, label);2142 }21432144 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2145 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2146 }21472148 async setPermissions(signer: TSigner, permissions: ICollectionPermissions, label?: string) {2149 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions, label);2150 }21512152 async enableNesting(signer: TSigner, permissions: INestingPermissions, label?: string) {2153 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions, label);2154 }21552156 async disableNesting(signer: TSigner, label?: string) {2157 return await this.helper.collection.disableNesting(signer, this.collectionId, label);2158 }21592160 async burn(signer: TSigner, label?: string) {2161 return await this.helper.collection.burn(signer, this.collectionId, label);2162 }2163}216421652166class UniqueNFTCollection extends UniqueCollectionBase {2167 getTokenObject(tokenId: number) {2168 return new UniqueNFTToken(tokenId, this);2169 }21702171 async getTokensByAddress(addressObj: ICrossAccountId) {2172 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2173 }21742175 async getToken(tokenId: number, blockHashAt?: string) {2176 return await this.helper.nft.getToken(this.collectionId, tokenId, blockHashAt);2177 }21782179 async getTokenOwner(tokenId: number, blockHashAt?: string) {2180 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2181 }21822183 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2184 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2185 }21862187 async getTokenChildren(tokenId: number, blockHashAt?: string) {2188 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2189 }21902191 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2192 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2193 }21942195 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2196 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2197 }21982199 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, label?: string) {2200 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label);2201 }22022203 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2204 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2205 }22062207 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[], label?: string) {2208 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties}, label);2209 }22102211 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[], label?: string) {2212 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens, label);2213 }22142215 async burnToken(signer: TSigner, tokenId: number, label?: string) {2216 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId, label);2217 }22182219 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2220 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2221 }22222223 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2224 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2225 }22262227 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2228 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2229 }22302231 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken, label?: string) {2232 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj, label);2233 }22342235 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2236 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj, label);2237 }2238}223922402241class UniqueRFTCollection extends UniqueCollectionBase {2242 getTokenObject(tokenId: number) {2243 return new UniqueRFTToken(tokenId, this);2244 }22452246 async getTokensByAddress(addressObj: ICrossAccountId) {2247 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2248 }22492250 async getTop10TokenOwners(tokenId: number) {2251 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2252 }22532254 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2255 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2256 }22572258 async getTokenTotalPieces(tokenId: number) {2259 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2260 }22612262 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=100n) {2263 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2264 }22652266 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2267 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2268 }22692270 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2271 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, label, amount);2272 }22732274 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2275 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2276 }22772278 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint, label?: string) {2279 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount, label);2280 }22812282 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[], label?: string) {2283 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties}, label);2284 }22852286 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[], label?: string) {2287 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens, label);2288 }22892290 async burnToken(signer: TSigner, tokenId: number, amount=100n, label?: string) {2291 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, label, amount);2292 }22932294 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[], label?: string) {2295 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties, label);2296 }22972298 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[], label?: string) {2299 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys, label);2300 }23012302 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[], label?: string) {2303 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions, label);2304 }2305}230623072308class UniqueFTCollection extends UniqueCollectionBase {2309 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint, label?: string) {2310 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount, label);2311 }23122313 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[], label?: string) {2314 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens, label);2315 }23162317 async getBalance(addressObj: ICrossAccountId) {2318 return await this.helper.ft.getBalance(this.collectionId, addressObj);2319 }23202321 async getTop10Owners() {2322 return await this.helper.ft.getTop10Owners(this.collectionId);2323 }23242325 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) {2326 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2327 }23282329 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) {2330 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2331 }23322333 async burnTokens(signer: TSigner, amount: bigint, label?: string) {2334 return await this.helper.ft.burnTokens(signer, this.collectionId, amount, label);2335 }23362337 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint, label?: string) {2338 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount, label);2339 }23402341 async getTotalPieces() {2342 return await this.helper.ft.getTotalPieces(this.collectionId);2343 }23442345 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2346 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount, label);2347 }23482349 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2350 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2351 }2352}235323542355class UniqueTokenBase implements IToken {2356 collection: UniqueNFTCollection | UniqueRFTCollection;2357 collectionId: number;2358 tokenId: number;23592360 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2361 this.collection = collection;2362 this.collectionId = collection.collectionId;2363 this.tokenId = tokenId;2364 }23652366 async getNextSponsored(addressObj: ICrossAccountId) {2367 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2368 }23692370 async setProperties(signer: TSigner, properties: IProperty[], label?: string) {2371 return await this.collection.setTokenProperties(signer, this.tokenId, properties, label);2372 }23732374 async deleteProperties(signer: TSigner, propertyKeys: string[], label?: string) {2375 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys, label);2376 }2377}237823792380class UniqueNFTToken extends UniqueTokenBase {2381 collection: UniqueNFTCollection;23822383 constructor(tokenId: number, collection: UniqueNFTCollection) {2384 super(tokenId, collection);2385 this.collection = collection;2386 }23872388 async getData(blockHashAt?: string) {2389 return await this.collection.getToken(this.tokenId, blockHashAt);2390 }23912392 async getOwner(blockHashAt?: string) {2393 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2394 }23952396 async getTopmostOwner(blockHashAt?: string) {2397 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2398 }23992400 async getChildren(blockHashAt?: string) {2401 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2402 }24032404 async nest(signer: TSigner, toTokenObj: IToken, label?: string) {2405 return await this.collection.nestToken(signer, this.tokenId, toTokenObj, label);2406 }24072408 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId, label?: string) {2409 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj, label);2410 }24112412 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2413 return await this.collection.transferToken(signer, this.tokenId, addressObj);2414 }24152416 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2417 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2418 }24192420 async approve(signer: TSigner, toAddressObj: ICrossAccountId, label?: string) {2421 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, label);2422 }24232424 async isApproved(toAddressObj: ICrossAccountId) {2425 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2426 }24272428 async burn(signer: TSigner, label?: string) {2429 return await this.collection.burnToken(signer, this.tokenId, label);2430 }2431}24322433class UniqueRFTToken extends UniqueTokenBase {2434 collection: UniqueRFTCollection;24352436 constructor(tokenId: number, collection: UniqueRFTCollection) {2437 super(tokenId, collection);2438 this.collection = collection;2439 }24402441 async getTop10Owners() {2442 return await this.collection.getTop10TokenOwners(this.tokenId);2443 }24442445 async getBalance(addressObj: ICrossAccountId) {2446 return await this.collection.getTokenBalance(this.tokenId, addressObj);2447 }24482449 async getTotalPieces() {2450 return await this.collection.getTokenTotalPieces(this.tokenId);2451 }24522453 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=100n) {2454 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2455 }24562457 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=100n) {2458 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2459 }24602461 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=100n, label?: string) {2462 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount, label);2463 }24642465 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2466 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2467 }24682469 async repartition(signer: TSigner, amount: bigint, label?: string) {2470 return await this.collection.repartitionToken(signer, this.tokenId, amount, label);2471 }24722473 async burn(signer: TSigner, amount=100n, label?: string) {2474 return await this.collection.burnToken(signer, this.tokenId, amount, label);2475 }2476}