difftreelog
Merge branch 'develop' into chore/fix-warnings
in: master
76 files changed
.docker/Dockerfile-try-runtimediffbeforeafterboth--- a/.docker/Dockerfile-try-runtime
+++ b/.docker/Dockerfile-try-runtime
@@ -46,4 +46,4 @@
echo "Fork from: $REPLICA_FROM\n" && \
cargo build --features=try-runtime,${NETWORK}-runtime --release
-CMD cargo run --features=try-runtime,${NETWORK}-runtime --release -- try-runtime -ltry-runtime::cli=debug --no-spec-check-panic on-runtime-upgrade live --uri $REPLICA_FROM
+CMD cargo run --release --features ${NETWORK}-runtime,try-runtime -- try-runtime --runtime target/release/wbuild/${NETWORK}-runtime/${NETWORK}_runtime.compact.compressed.wasm -lruntime=debug -ltry-runtime::cli=debug on-runtime-upgrade --checks live --uri $REPLICA_FROM
.envdiffbeforeafterboth--- a/.env
+++ b/.env
@@ -5,19 +5,19 @@
STATEMINT_BUILD_BRANCH=release-parachains-v9320
ACALA_BUILD_BRANCH=2.11.0
MOONBEAM_BUILD_BRANCH=runtime-1901
-UNIQUE_MAINNET_BRANCH=release-v930033
+UNIQUE_MAINNET_BRANCH=release-v930033-fix-gas-price
UNIQUE_REPLICA_FROM=wss://eu-ws.unique.network:443
KUSAMA_MAINNET_BRANCH=release-v0.9.35
STATEMINE_BUILD_BRANCH=release-parachains-v9330
KARURA_BUILD_BRANCH=release-karura-2.11.0
MOONRIVER_BUILD_BRANCH=runtime-2000
-QUARTZ_MAINNET_BRANCH=release-v930034
+QUARTZ_MAINNET_BRANCH=release-v930034-fix-gas-price
QUARTZ_REPLICA_FROM=wss://eu-ws-quartz.unique.network:443
UNQWND_MAINNET_BRANCH=release-v0.9.30
WESTMINT_BUILD_BRANCH=parachains-v9330
-OPAL_MAINNET_BRANCH=release-v930034
+OPAL_MAINNET_BRANCH=release-v930034-fix-gas-price
OPAL_REPLICA_FROM=wss://eu-ws-opal.unique.network:443
POLKADOT_LAUNCH_BRANCH=unique-network
.github/workflows/ci-master.ymldiffbeforeafterboth--- a/.github/workflows/ci-master.yml
+++ b/.github/workflows/ci-master.yml
@@ -42,3 +42,6 @@
codestyle:
uses: ./.github/workflows/codestyle.yml
+
+ polkadot-types:
+ uses: ./.github/workflows/polkadot-types.yml
\ No newline at end of file
.github/workflows/polkadot-types.ymldiffbeforeafterboth--- /dev/null
+++ b/.github/workflows/polkadot-types.yml
@@ -0,0 +1,96 @@
+# Integration test in --dev mode
+# https://cryptousetech.atlassian.net/wiki/spaces/CI/pages/2586411104/Integration+tests
+name: Polkadot types
+
+# Triger: only call from main workflow(re-usable workflows)
+on:
+ workflow_call:
+ # Allows you to run this workflow manually from the Actions tab
+ workflow_dispatch:
+
+# on:
+# pull_request:
+# branches: [ 'develop' ]
+# types: [ opened, reopened, synchronize, ready_for_review, converted_to_draft ]
+
+
+# A workflow run is made up of one or more jobs that can run sequentially or in parallel
+jobs:
+
+ polkadot_generate_types:
+ # The type of runner that the job will run on
+ runs-on: [self-hosted-ci,medium]
+ timeout-minutes: 1380
+
+ name: ${{ matrix.network }}
+
+ continue-on-error: true #Do not stop testing of matrix runs failed. As it decided during PR review - it required 50/50& Let's check it with false.
+
+ strategy:
+ matrix:
+ include:
+ - network: sapphire
+ usage: "--sapphire"
+ - network: "opal"
+ usage: ""
+ - network: "quartz"
+ usage: ""
+ - network: "unique"
+ usage: ""
+
+ steps:
+
+ - name: Clean Workspace
+ uses: AutoModality/action-clean@v1.1.0
+
+ # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
+ - uses: actions/checkout@v3
+ with:
+ ref: ${{ github.head_ref }} #Checking out head commit
+
+ - name: Read .env file
+ uses: xom9ikk/dotenv@v2
+
+ - name: Generate ENV related extend file for docker-compose
+ uses: cuchi/jinja2-action@v1.2.0
+ with:
+ template: .docker/docker-compose.tmp-dev.j2
+ output_file: .docker/docker-compose.${{ matrix.network }}.yml
+ variables: |
+ RUST_TOOLCHAIN=${{ env.RUST_TOOLCHAIN }}
+ NETWORK=${{ matrix.network }}
+
+ - name: Show build configuration
+ run: cat .docker/docker-compose.${{ matrix.network }}.yml
+
+ - name: Build the stack
+ run: docker-compose -f ".docker/docker-compose.${{ matrix.network }}.yml" up -d --build --remove-orphans
+
+ - uses: actions/setup-node@v3
+ with:
+ node-version: 16
+
+ - name: Install jq
+ run: sudo apt install jq -y
+
+ - name: Run generate_types_package script
+ working-directory: tests
+ run: |
+ yarn install
+ /bin/bash ./scripts/wait_for_first_block.sh
+ git config --global user.name "Unique"
+ git config --global user.email github-actions@usetech.com
+ /bin/bash ./scripts/generate_types_package.sh --release ${{ matrix.usage }} --push
+ env:
+ RPC_URL: http://127.0.0.1:9933/
+
+ - name: Stop running containers
+ if: always() # run this step always
+ run: docker-compose -f ".docker/docker-compose.${{ matrix.network }}.yml" down
+
+ - name: Remove builder cache
+ if: always() # run this step always
+ run: |
+ docker builder prune -f -a
+ docker system prune -f
+ docker image prune -f -a
.github/workflows/schedule-trigger-for-develop-build.ymldiffbeforeafterboth--- a/.github/workflows/schedule-trigger-for-develop-build.yml
+++ b/.github/workflows/schedule-trigger-for-develop-build.yml
@@ -1,8 +1,8 @@
name: schedule-trigger-for-develop-build
on:
# update the branch ci/develop-scheduler every night
- schedule:
- - cron: '0 1 * * *'
+ # schedule:
+ # - cron: '0 1 * * *'
# or update the branch manually
workflow_dispatch:
# pull_request:
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2467,7 +2467,7 @@
[[package]]
name = "fc-consensus"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"async-trait",
"fc-db",
@@ -2486,7 +2486,7 @@
[[package]]
name = "fc-db"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"fp-storage",
"kvdb-rocksdb",
@@ -2505,7 +2505,7 @@
[[package]]
name = "fc-mapping-sync"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"fc-db",
"fp-consensus",
@@ -2522,7 +2522,7 @@
[[package]]
name = "fc-rpc"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"ethereum 0.14.0",
"ethereum-types 0.14.1",
@@ -2565,7 +2565,7 @@
[[package]]
name = "fc-rpc-core"
version = "1.1.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"ethereum 0.14.0",
"ethereum-types 0.14.1",
@@ -2730,7 +2730,7 @@
[[package]]
name = "fp-consensus"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"ethereum 0.14.0",
"parity-scale-codec 3.2.1",
@@ -2742,7 +2742,7 @@
[[package]]
name = "fp-ethereum"
version = "1.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"ethereum 0.14.0",
"ethereum-types 0.14.1",
@@ -2757,7 +2757,7 @@
[[package]]
name = "fp-evm"
version = "3.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"evm",
"frame-support",
@@ -2771,7 +2771,7 @@
[[package]]
name = "fp-evm-mapping"
version = "0.1.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"frame-support",
"sp-core",
@@ -2780,7 +2780,7 @@
[[package]]
name = "fp-rpc"
version = "3.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"ethereum 0.14.0",
"ethereum-types 0.14.1",
@@ -2797,7 +2797,7 @@
[[package]]
name = "fp-self-contained"
version = "1.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"ethereum 0.14.0",
"frame-support",
@@ -2810,7 +2810,7 @@
[[package]]
name = "fp-storage"
version = "2.0.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"parity-scale-codec 3.2.1",
"serde",
@@ -5682,7 +5682,7 @@
[[package]]
name = "pallet-base-fee"
version = "1.0.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"fp-evm",
"frame-support",
@@ -5918,7 +5918,7 @@
[[package]]
name = "pallet-ethereum"
version = "4.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"ethereum 0.14.0",
"ethereum-types 0.14.1",
@@ -5946,7 +5946,7 @@
[[package]]
name = "pallet-evm"
version = "6.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"environmental",
"evm",
@@ -6032,7 +6032,7 @@
[[package]]
name = "pallet-evm-precompile-simple"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
dependencies = [
"fp-evm",
"ripemd",
@@ -12965,6 +12965,7 @@
"sp-core",
"sp-finality-grandpa",
"sp-inherents",
+ "sp-io",
"sp-keystore",
"sp-offchain",
"sp-runtime",
crates/evm-coder/procedural/src/abi_derive/derive_enum.rsdiffbeforeafterboth--- a/crates/evm-coder/procedural/src/abi_derive/derive_enum.rs
+++ b/crates/evm-coder/procedural/src/abi_derive/derive_enum.rs
@@ -143,8 +143,7 @@
)
}
-pub fn check_and_count_options(de: &syn::DataEnum) -> syn::Result<usize> {
- let mut count = 0;
+pub fn check_enum_fields(de: &syn::DataEnum) -> syn::Result<()> {
for v in de.variants.iter() {
if !v.fields.is_empty() {
return Err(syn::Error::new(
@@ -156,12 +155,10 @@
v.ident.span(),
"Enumeration options should not have an explicit specified value",
));
- } else {
- count += 1;
}
}
- Ok(count)
+ Ok(())
}
pub fn check_repr_u8(name: &syn::Ident, attrs: &[syn::Attribute]) -> syn::Result<()> {
crates/evm-coder/procedural/src/abi_derive/mod.rsdiffbeforeafterboth--- a/crates/evm-coder/procedural/src/abi_derive/mod.rs
+++ b/crates/evm-coder/procedural/src/abi_derive/mod.rs
@@ -70,6 +70,7 @@
) -> syn::Result<proc_macro2::TokenStream> {
let name = &ast.ident;
check_repr_u8(name, &ast.attrs)?;
+ check_enum_fields(de)?;
let docs = extract_docs(&ast.attrs)?;
let enum_options = de.variants.iter();
node/cli/Cargo.tomldiffbeforeafterboth--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -122,6 +122,10 @@
git = "https://github.com/paritytech/substrate"
branch = "polkadot-v0.9.36"
+[dependencies.sp-io]
+git = "https://github.com/paritytech/substrate"
+branch = "polkadot-v0.9.36"
+
[dependencies.sp-finality-grandpa]
git = "https://github.com/paritytech/substrate"
branch = "polkadot-v0.9.36"
node/cli/src/command.rsdiffbeforeafterboth--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -412,6 +412,7 @@
#[cfg(feature = "try-runtime")]
Some(Subcommand::TryRuntime(cmd)) => {
use std::{future::Future, pin::Pin};
+ use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch};
let runner = cli.create_runner(cmd)?;
@@ -429,12 +430,21 @@
Ok((
match config.chain_spec.runtime_id() {
#[cfg(feature = "unique-runtime")]
- RuntimeId::Unique => Box::pin(cmd.run::<Block, UniqueRuntimeExecutor>(config)),
+ RuntimeId::Unique => Box::pin(cmd.run::<Block, ExtendedHostFunctions<
+ sp_io::SubstrateHostFunctions,
+ <UniqueRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,
+ >>()),
#[cfg(feature = "quartz-runtime")]
- RuntimeId::Quartz => Box::pin(cmd.run::<Block, QuartzRuntimeExecutor>(config)),
+ RuntimeId::Quartz => Box::pin(cmd.run::<Block, ExtendedHostFunctions<
+ sp_io::SubstrateHostFunctions,
+ <QuartzRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,
+ >>()),
- RuntimeId::Opal => Box::pin(cmd.run::<Block, OpalRuntimeExecutor>(config)),
+ RuntimeId::Opal => Box::pin(cmd.run::<Block, ExtendedHostFunctions<
+ sp_io::SubstrateHostFunctions,
+ <OpalRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,
+ >>()),
RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain).into()),
},
task_manager,
node/cli/src/service.rsdiffbeforeafterboth--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -106,7 +106,12 @@
#[cfg(feature = "unique-runtime")]
impl NativeExecutionDispatch for UniqueRuntimeExecutor {
+ /// Only enable the benchmarking host functions when we actually want to benchmark.
+ #[cfg(feature = "runtime-benchmarks")]
type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
+ /// Otherwise we only use the default Substrate host functions.
+ #[cfg(not(feature = "runtime-benchmarks"))]
+ type ExtendHostFunctions = ();
fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
unique_runtime::api::dispatch(method, data)
@@ -119,7 +124,12 @@
#[cfg(feature = "quartz-runtime")]
impl NativeExecutionDispatch for QuartzRuntimeExecutor {
+ /// Only enable the benchmarking host functions when we actually want to benchmark.
+ #[cfg(feature = "runtime-benchmarks")]
type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
+ /// Otherwise we only use the default Substrate host functions.
+ #[cfg(not(feature = "runtime-benchmarks"))]
+ type ExtendHostFunctions = ();
fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
quartz_runtime::api::dispatch(method, data)
@@ -131,7 +141,12 @@
}
impl NativeExecutionDispatch for OpalRuntimeExecutor {
+ /// Only enable the benchmarking host functions when we actually want to benchmark.
+ #[cfg(feature = "runtime-benchmarks")]
type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
+ /// Otherwise we only use the default Substrate host functions.
+ #[cfg(not(feature = "runtime-benchmarks"))]
+ type ExtendHostFunctions = ();
fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {
opal_runtime::api::dispatch(method, data)
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -127,7 +127,7 @@
pub struct OptionCrossAddress {
/// Whether or not this CrossAdress is valid and has meaning.
pub status: bool,
- /// The underlying CrossAddress. If the status is false, can be set to whatever.
+ /// The underlying CrossAddress value. If the status is false, can be set to whatever.
pub value: CrossAddress,
}
pallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/evm-contract-helpers/src/stubs/ContractHelpers.soldiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
+++ b/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
@@ -283,6 +283,8 @@
/// Ethereum representation of Optional value with CrossAddress.
struct OptionCrossAddress {
+ /// TODO: field description
bool status;
+ /// TODO: field description
CrossAddress value;
}
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -228,7 +228,7 @@
owner: sub; collection: collection(owner); owner: cross_from_sub;
operator: cross_sub;
};
- }: {<Pallet<T>>::set_allowance_for_all(&collection, &owner, &operator, true)}
+ }: {<Pallet<T>>::set_allowance_for_all(&collection, &owner, &operator, true)?}
allowance_for_all {
bench_init!{
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -22,21 +22,17 @@
use frame_benchmarking::{benchmarks, account};
use pallet_common::{
bench_init,
- benchmarking::{create_collection_raw, property_key, property_value, create_data},
+ benchmarking::{create_collection_raw, property_key, property_value},
};
-use sp_core::H160;
use sp_std::prelude::*;
-use up_data_structs::{
- CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, CUSTOM_DATA_LIMIT,
- budget::Unlimited,
-};
+use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, budget::Unlimited};
const SEED: u32 = 1;
-fn create_max_item_data<CrossAccountId: Ord>(
- users: impl IntoIterator<Item = (CrossAccountId, u128)>,
-) -> CreateItemData<CrossAccountId> {
- CreateItemData {
+fn create_max_item_data<T: Config>(
+ users: impl IntoIterator<Item = (T::CrossAccountId, u128)>,
+) -> CreateItemData<T> {
+ CreateItemData::<T> {
users: users
.into_iter()
.collect::<BTreeMap<_, _>>()
@@ -51,7 +47,7 @@
sender: &T::CrossAccountId,
users: impl IntoIterator<Item = (T::CrossAccountId, u128)>,
) -> Result<TokenId, DispatchError> {
- let data: CreateItemData<T::CrossAccountId> = create_max_item_data(users);
+ let data: CreateItemData<T> = create_max_item_data::<T>(users);
<Pallet<T>>::create_item(&collection, sender, data, &Unlimited)?;
Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))
}
@@ -83,7 +79,7 @@
owner: sub; collection: collection(owner);
sender: cross_from_sub(owner); to: cross_sub;
};
- let data = (0..b).map(|_| create_max_item_data([(to.clone(), 200)])).collect();
+ let data = (0..b).map(|_| create_max_item_data::<T>([(to.clone(), 200)])).collect();
}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}
create_multiple_items_ex_multiple_items {
@@ -94,7 +90,7 @@
};
let data = (0..b).map(|t| {
bench_init!(to: cross_sub(t););
- create_max_item_data([(to, 200)])
+ create_max_item_data::<T>([(to, 200)])
}).collect();
}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}
@@ -104,7 +100,7 @@
owner: sub; collection: collection(owner);
sender: cross_from_sub(owner);
};
- let data = vec![create_max_item_data((0..b).map(|u| {
+ let data = vec![create_max_item_data::<T>((0..b).map(|u| {
bench_init!(to: cross_sub(u););
(to, 200)
}))].try_into().unwrap();
@@ -296,7 +292,7 @@
owner: sub; collection: collection(owner); owner: cross_from_sub;
operator: cross_sub;
};
- }: {<Pallet<T>>::set_allowance_for_all(&collection, &owner, &operator, true)}
+ }: {<Pallet<T>>::set_allowance_for_all(&collection, &owner, &operator, true)?}
allowance_for_all {
bench_init!{
pallets/refungible/src/erc_token.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -43,6 +43,9 @@
TotalSupply, weights::WeightInfo,
};
+/// Refungible token handle contains information about token's collection and id
+///
+/// RefungibleTokenHandle doesn't check token's existance upon creation
pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);
#[solidity_interface(name = ERC1633)]
runtime/common/ethereum/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -32,14 +32,22 @@
Config as FungibleConfig,
erc::{UniqueFungibleCall, ERC20Call},
};
-use pallet_refungible::Config as RefungibleConfig;
+use pallet_refungible::{
+ Config as RefungibleConfig,
+ erc::UniqueRefungibleCall,
+ erc_token::{RefungibleTokenHandle, UniqueRefungibleTokenCall},
+ RefungibleHandle,
+};
use pallet_unique::Config as UniqueConfig;
use sp_std::prelude::*;
-use up_data_structs::{CollectionMode, CreateItemData, CreateNftData, TokenId};
+use up_data_structs::{
+ CollectionMode, CreateItemData, CreateNftData, mapping::TokenAddressMapping, TokenId,
+};
use up_sponsorship::SponsorshipHandler;
-
use crate::{Runtime, runtime_common::sponsoring::*};
+mod refungible;
+
pub type EvmSponsorshipHandler = (
UniqueEthSponsorshipHandler<Runtime>,
pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
@@ -53,80 +61,163 @@
who: &T::CrossAccountId,
call_context: &CallContext,
) -> Option<T::CrossAccountId> {
- let collection_id = map_eth_to_id(&call_context.contract_address)?;
- let collection = <CollectionHandle<T>>::new(collection_id)?;
- let sponsor = collection.sponsorship.sponsor()?.clone();
- let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;
- Some(T::CrossAccountId::from_sub(match &collection.mode {
- CollectionMode::NFT => {
- let call = <UniqueNFTCall<T>>::parse(method_id, &mut reader).ok()??;
- match call {
- UniqueNFTCall::TokenProperties(TokenPropertiesCall::SetProperty {
- token_id,
- key,
- value,
- ..
- }) => {
- let token_id: TokenId = token_id.try_into().ok()?;
- withdraw_set_token_property::<T>(
+ if let Some(collection_id) = map_eth_to_id(&call_context.contract_address) {
+ let collection = <CollectionHandle<T>>::new(collection_id)?;
+ let sponsor = collection.sponsorship.sponsor()?.clone();
+ let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;
+ Some(T::CrossAccountId::from_sub(match &collection.mode {
+ CollectionMode::NFT => {
+ let call = <UniqueNFTCall<T>>::parse(method_id, &mut reader).ok()??;
+ match call {
+ UniqueNFTCall::TokenProperties(TokenPropertiesCall::SetProperty {
+ token_id,
+ key,
+ value,
+ ..
+ }) => {
+ let token_id: TokenId = token_id.try_into().ok()?;
+ withdraw_set_token_property::<T>(
+ &collection,
+ &who,
+ &token_id,
+ key.len() + value.len(),
+ )
+ .map(|()| sponsor)
+ }
+ UniqueNFTCall::ERC721UniqueExtensions(
+ ERC721UniqueExtensionsCall::Transfer { token_id, .. },
+ ) => {
+ let token_id: TokenId = token_id.try_into().ok()?;
+ withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)
+ }
+ UniqueNFTCall::ERC721UniqueMintable(
+ ERC721UniqueMintableCall::Mint { .. }
+ | ERC721UniqueMintableCall::MintCheckId { .. }
+ | ERC721UniqueMintableCall::MintWithTokenUri { .. }
+ | ERC721UniqueMintableCall::MintWithTokenUriCheckId { .. },
+ ) => withdraw_create_item::<T>(
&collection,
&who,
- &token_id,
- key.len() + value.len(),
+ &CreateItemData::NFT(CreateNftData::default()),
)
- .map(|()| sponsor)
- }
- UniqueNFTCall::ERC721UniqueExtensions(
- ERC721UniqueExtensionsCall::Transfer { token_id, .. },
- ) => {
- let token_id: TokenId = token_id.try_into().ok()?;
- withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)
+ .map(|()| sponsor),
+ UniqueNFTCall::ERC721(ERC721Call::TransferFrom {
+ token_id, from, ..
+ }) => {
+ let token_id: TokenId = token_id.try_into().ok()?;
+ let from = T::CrossAccountId::from_eth(from);
+ withdraw_transfer::<T>(&collection, &from, &token_id).map(|()| sponsor)
+ }
+ UniqueNFTCall::ERC721(ERC721Call::Approve { token_id, .. }) => {
+ let token_id: TokenId = token_id.try_into().ok()?;
+ withdraw_approve::<T>(&collection, who.as_sub(), &token_id)
+ .map(|()| sponsor)
+ }
+ _ => None,
}
- UniqueNFTCall::ERC721UniqueMintable(
- ERC721UniqueMintableCall::Mint { .. }
- | ERC721UniqueMintableCall::MintCheckId { .. }
- | ERC721UniqueMintableCall::MintWithTokenUri { .. }
- | ERC721UniqueMintableCall::MintWithTokenUriCheckId { .. },
- ) => withdraw_create_item::<T>(
- &collection,
- &who,
- &CreateItemData::NFT(CreateNftData::default()),
- )
- .map(|()| sponsor),
- UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, from, .. }) => {
- let token_id: TokenId = token_id.try_into().ok()?;
- let from = T::CrossAccountId::from_eth(from);
- withdraw_transfer::<T>(&collection, &from, &token_id).map(|()| sponsor)
- }
- UniqueNFTCall::ERC721(ERC721Call::Approve { token_id, .. }) => {
- let token_id: TokenId = token_id.try_into().ok()?;
- withdraw_approve::<T>(&collection, who.as_sub(), &token_id)
- .map(|()| sponsor)
- }
- _ => None,
}
- }
- CollectionMode::Fungible(_) => {
- let call = <UniqueFungibleCall<T>>::parse(method_id, &mut reader).ok()??;
- #[allow(clippy::single_match)]
- match call {
- UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {
- withdraw_transfer::<T>(&collection, who, &TokenId::default())
- .map(|()| sponsor)
- }
- UniqueFungibleCall::ERC20(ERC20Call::TransferFrom { from, .. }) => {
- let from = T::CrossAccountId::from_eth(from);
- withdraw_transfer::<T>(&collection, &from, &TokenId::default())
- .map(|()| sponsor)
+ CollectionMode::ReFungible => {
+ let call = <UniqueRefungibleCall<T>>::parse(method_id, &mut reader).ok()??;
+ refungible::call_sponsor(call, collection, who).map(|()| sponsor)
+ }
+ CollectionMode::Fungible(_) => {
+ let call = <UniqueFungibleCall<T>>::parse(method_id, &mut reader).ok()??;
+ match call {
+ UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {
+ withdraw_transfer::<T>(&collection, who, &TokenId::default())
+ .map(|()| sponsor)
+ }
+ UniqueFungibleCall::ERC20(ERC20Call::TransferFrom { from, .. }) => {
+ let from = T::CrossAccountId::from_eth(from);
+ withdraw_transfer::<T>(&collection, &from, &TokenId::default())
+ .map(|()| sponsor)
+ }
+ UniqueFungibleCall::ERC20(ERC20Call::Approve { .. }) => {
+ withdraw_approve::<T>(&collection, who.as_sub(), &TokenId::default())
+ .map(|()| sponsor)
+ }
+ _ => None,
}
- UniqueFungibleCall::ERC20(ERC20Call::Approve { .. }) => {
- withdraw_approve::<T>(&collection, who.as_sub(), &TokenId::default())
- .map(|()| sponsor)
- }
- _ => None,
}
+ }?))
+ } else {
+ let (collection_id, token_id) =
+ T::EvmTokenAddressMapping::address_to_token(&call_context.contract_address)?;
+ let collection = <CollectionHandle<T>>::new(collection_id)?;
+ if collection.mode != CollectionMode::ReFungible {
+ return None;
}
- _ => None,
- }?))
+ let sponsor = collection.sponsorship.sponsor()?.clone();
+ let rft_collection = RefungibleHandle::cast(collection);
+ // Token existance isn't checked at this point and should be checked in `withdraw` method.
+ let token = RefungibleTokenHandle(rft_collection, token_id);
+
+ let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;
+ let call = <UniqueRefungibleTokenCall<T>>::parse(method_id, &mut reader).ok()??;
+ Some(T::CrossAccountId::from_sub(
+ refungible::token_call_sponsor(call, token, who).map(|()| sponsor)?,
+ ))
+ }
+ }
+}
+
+mod common {
+ use super::*;
+
+ use pallet_common::erc::{CollectionCall};
+
+ pub fn collection_call_sponsor<T>(
+ call: CollectionCall<T>,
+ _collection: CollectionHandle<T>,
+ _who: &T::CrossAccountId,
+ ) -> Option<()>
+ where
+ T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,
+ {
+ use CollectionCall::*;
+
+ match call {
+ // Readonly
+ ERC165Call(_, _)
+ | CollectionProperty { .. }
+ | CollectionProperties { .. }
+ | HasCollectionPendingSponsor
+ | CollectionSponsor
+ | ContractAddress
+ | AllowlistedCross { .. }
+ | IsOwnerOrAdminEth { .. }
+ | IsOwnerOrAdminCross { .. }
+ | CollectionOwner
+ | CollectionAdmins
+ | CollectionLimits
+ | CollectionNestingRestrictedIds
+ | CollectionNestingPermissions
+ | UniqueCollectionType => None,
+
+ // Not sponsored
+ AddToCollectionAllowList { .. }
+ | AddToCollectionAllowListCross { .. }
+ | RemoveFromCollectionAllowList { .. }
+ | RemoveFromCollectionAllowListCross { .. }
+ | AddCollectionAdminCross { .. }
+ | RemoveCollectionAdminCross { .. }
+ | AddCollectionAdmin { .. }
+ | RemoveCollectionAdmin { .. }
+ | SetNestingBool { .. }
+ | SetNesting { .. }
+ | SetCollectionAccess { .. }
+ | SetCollectionMintMode { .. }
+ | SetOwner { .. }
+ | ChangeCollectionOwnerCross { .. }
+ | SetCollectionProperty { .. }
+ | SetCollectionProperties { .. }
+ | DeleteCollectionProperty { .. }
+ | DeleteCollectionProperties { .. }
+ | SetCollectionSponsor { .. }
+ | SetCollectionSponsorCross { .. }
+ | SetCollectionLimit { .. }
+ | ConfirmCollectionSponsorship
+ | RemoveCollectionSponsor => None,
+ }
}
}
runtime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/ethereum/sponsoring/refungible.rs
@@ -0,0 +1,381 @@
+// 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/>.
+
+//! Implements EVM sponsoring logic via TransactionValidityHack
+
+use core::convert::TryInto;
+use pallet_common::CollectionHandle;
+use pallet_evm::account::CrossAccountId;
+use pallet_fungible::Config as FungibleConfig;
+use pallet_refungible::Config as RefungibleConfig;
+use pallet_nonfungible::Config as NonfungibleConfig;
+use pallet_unique::Config as UniqueConfig;
+use up_data_structs::{CreateItemData, CreateNftData, TokenId};
+
+use super::common;
+use crate::runtime_common::sponsoring::*;
+
+use pallet_refungible::{
+ erc::{
+ ERC721BurnableCall, ERC721Call, ERC721EnumerableCall, ERC721MetadataCall,
+ ERC721UniqueExtensionsCall, ERC721UniqueMintableCall, TokenPropertiesCall,
+ UniqueRefungibleCall,
+ },
+ erc_token::{
+ ERC1633Call, ERC20Call, ERC20UniqueExtensionsCall, RefungibleTokenHandle,
+ UniqueRefungibleTokenCall,
+ },
+};
+
+pub fn call_sponsor<T>(
+ call: UniqueRefungibleCall<T>,
+ collection: CollectionHandle<T>,
+ who: &T::CrossAccountId,
+) -> Option<()>
+where
+ T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,
+{
+ use UniqueRefungibleCall::*;
+
+ match call {
+ // Readonly
+ ERC165Call(_, _) => None,
+
+ ERC721Enumerable(call) => erc721::enumerable_call_sponsor(call, collection, who),
+ ERC721Burnable(call) => erc721::burnable_call_sponsor(call, collection, who),
+ ERC721Metadata(call) => erc721::metadata_call_sponsor(call, collection, who),
+ Collection(call) => common::collection_call_sponsor(call, collection, who),
+ ERC721(call) => erc721::call_sponsor(call, collection, who),
+ ERC721UniqueExtensions(call) => {
+ erc721::unique_extensions_call_sponsor(call, collection, who)
+ }
+ ERC721UniqueMintable(call) => erc721::unique_mintable_call_sponsor(call, collection, who),
+ TokenProperties(call) => token_properties_call_sponsor(call, collection, who),
+ }
+}
+
+pub fn token_properties_call_sponsor<T>(
+ call: TokenPropertiesCall<T>,
+ collection: CollectionHandle<T>,
+ who: &T::CrossAccountId,
+) -> Option<()>
+where
+ T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,
+{
+ use TokenPropertiesCall::*;
+
+ match call {
+ // Readonly
+ ERC165Call(_, _) | Property { .. } | TokenPropertyPermissions => None,
+
+ // Not sponsored
+ SetTokenPropertyPermission { .. }
+ | SetTokenPropertyPermissions { .. }
+ | SetProperties { .. }
+ | DeleteProperty { .. }
+ | DeleteProperties { .. } => None,
+
+ SetProperty {
+ token_id,
+ key,
+ value,
+ ..
+ } => {
+ let token_id = TokenId::try_from(token_id).ok()?;
+ withdraw_set_token_property::<T>(&collection, &who, &token_id, key.len() + value.len())
+ }
+ }
+}
+
+pub fn token_call_sponsor<T>(
+ call: UniqueRefungibleTokenCall<T>,
+ token: RefungibleTokenHandle<T>,
+ who: &T::CrossAccountId,
+) -> Option<()>
+where
+ T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,
+{
+ use UniqueRefungibleTokenCall::*;
+
+ match call {
+ // Readonly
+ ERC165Call(_, _) => None,
+
+ ERC20(call) => erc20::call_sponsor(call, token, who),
+ ERC20UniqueExtensions(call) => erc20::unique_extensions_call_sponsor(call, token, who),
+ ERC1633(call) => erc1633::call_sponsor(call, token, who),
+ }
+}
+
+mod erc721 {
+ use super::*;
+
+ pub fn call_sponsor<T>(
+ call: ERC721Call<T>,
+ collection: CollectionHandle<T>,
+ _who: &T::CrossAccountId,
+ ) -> Option<()>
+ where
+ T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,
+ {
+ use ERC721Call::*;
+
+ match call {
+ // Readonly
+ ERC165Call(_, _)
+ | BalanceOf { .. }
+ | OwnerOf { .. }
+ | GetApproved { .. }
+ | IsApprovedForAll { .. }
+ | CollectionHelperAddress => None,
+
+ // Not sponsored
+ SafeTransferFromWithData { .. }
+ | SafeTransferFrom { .. }
+ | SetApprovalForAll { .. } => None,
+
+ TransferFrom { token_id, from, .. } => {
+ let token_id = TokenId::try_from(token_id).ok()?;
+ let from = T::CrossAccountId::from_eth(from);
+ withdraw_transfer::<T>(&collection, &from, &token_id)
+ }
+
+ // Not supported
+ Approve { .. } => None,
+ }
+ }
+
+ pub fn enumerable_call_sponsor<T>(
+ call: ERC721EnumerableCall<T>,
+ _collection: CollectionHandle<T>,
+ _who: &T::CrossAccountId,
+ ) -> Option<()>
+ where
+ T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,
+ {
+ use ERC721EnumerableCall::*;
+
+ match call {
+ // Readonly
+ ERC165Call(_, _) | TokenByIndex { .. } | TokenOfOwnerByIndex { .. } | TotalSupply => {
+ None
+ }
+ }
+ }
+
+ pub fn burnable_call_sponsor<T>(
+ call: ERC721BurnableCall<T>,
+ _collection: CollectionHandle<T>,
+ _who: &T::CrossAccountId,
+ ) -> Option<()>
+ where
+ T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,
+ {
+ use ERC721BurnableCall::*;
+
+ match call {
+ // Readonly
+ ERC165Call(_, _) => None,
+
+ // Not sponsored
+ Burn { .. } => None,
+ }
+ }
+
+ pub fn metadata_call_sponsor<T>(
+ call: ERC721MetadataCall<T>,
+ _collection: CollectionHandle<T>,
+ _who: &T::CrossAccountId,
+ ) -> Option<()>
+ where
+ T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,
+ {
+ use ERC721MetadataCall::*;
+
+ match call {
+ // Readonly
+ ERC165Call(_, _) | NameProxy | SymbolProxy | TokenUri { .. } => None,
+ }
+ }
+
+ pub fn unique_extensions_call_sponsor<T>(
+ call: ERC721UniqueExtensionsCall<T>,
+ collection: CollectionHandle<T>,
+ who: &T::CrossAccountId,
+ ) -> Option<()>
+ where
+ T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,
+ {
+ use ERC721UniqueExtensionsCall::*;
+
+ match call {
+ // Readonly
+ ERC165Call(_, _)
+ | Name
+ | Symbol
+ | Description
+ | CrossOwnerOf { .. }
+ | Properties { .. }
+ | NextTokenId
+ | TokenContractAddress { .. } => None,
+
+ // Not sponsored
+ BurnFrom { .. }
+ | BurnFromCross { .. }
+ | MintBulk { .. }
+ | MintBulkWithTokenUri { .. } => None,
+
+ MintCross { .. } => withdraw_create_item::<T>(
+ &collection,
+ &who,
+ &CreateItemData::NFT(CreateNftData::default()),
+ ),
+
+ TransferCross { token_id, .. }
+ | TransferFromCross { token_id, .. }
+ | Transfer { token_id, .. } => {
+ let token_id = TokenId::try_from(token_id).ok()?;
+ withdraw_transfer::<T>(&collection, &who, &token_id)
+ }
+ }
+ }
+
+ pub fn unique_mintable_call_sponsor<T>(
+ call: ERC721UniqueMintableCall<T>,
+ collection: CollectionHandle<T>,
+ who: &T::CrossAccountId,
+ ) -> Option<()>
+ where
+ T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,
+ {
+ use ERC721UniqueMintableCall::*;
+
+ match call {
+ // Readonly
+ ERC165Call(_, _) | MintingFinished => None,
+
+ // Not sponsored
+ FinishMinting => None,
+
+ Mint { .. }
+ | MintCheckId { .. }
+ | MintWithTokenUri { .. }
+ | MintWithTokenUriCheckId { .. } => withdraw_create_item::<T>(
+ &collection,
+ &who,
+ &CreateItemData::NFT(CreateNftData::default()),
+ ),
+ }
+ }
+}
+
+/// Module for methods of refungible token
+///
+/// Existance of token should be checked before searching for sponsor
+/// because RefungibleTokenHandle doesn't check token's existence upon creation
+mod erc20 {
+ use super::*;
+
+ pub fn call_sponsor<T>(
+ call: ERC20Call<T>,
+ token: RefungibleTokenHandle<T>,
+ who: &T::CrossAccountId,
+ ) -> Option<()>
+ where
+ T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,
+ {
+ use ERC20Call::*;
+
+ match call {
+ // Readonly
+ ERC165Call(_, _)
+ | Name
+ | Symbol
+ | TotalSupply
+ | Decimals
+ | BalanceOf { .. }
+ | Allowance { .. } => None,
+
+ Transfer { .. } => {
+ let RefungibleTokenHandle(handle, token_id) = token;
+ let token_id = token_id.try_into().ok()?;
+ withdraw_transfer::<T>(&handle, &who, &token_id)
+ }
+ TransferFrom { from, .. } => {
+ let RefungibleTokenHandle(handle, token_id) = token;
+ let token_id = token_id.try_into().ok()?;
+ let from = T::CrossAccountId::from_eth(from);
+ withdraw_transfer::<T>(&handle, &from, &token_id)
+ }
+ Approve { .. } => {
+ let RefungibleTokenHandle(handle, token_id) = token;
+ let token_id = token_id.try_into().ok()?;
+ withdraw_approve::<T>(&handle, who.as_sub(), &token_id)
+ }
+ }
+ }
+
+ pub fn unique_extensions_call_sponsor<T>(
+ call: ERC20UniqueExtensionsCall<T>,
+ token: RefungibleTokenHandle<T>,
+ who: &T::CrossAccountId,
+ ) -> Option<()>
+ where
+ T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,
+ {
+ use ERC20UniqueExtensionsCall::*;
+
+ match call {
+ // Readonly
+ ERC165Call(_, _) => None,
+
+ // Not sponsored
+ BurnFrom { .. } | BurnFromCross { .. } | Repartition { .. } => None,
+
+ TransferCross { .. } | TransferFromCross { .. } => {
+ let RefungibleTokenHandle(handle, token_id) = token;
+ let token_id = token_id.try_into().ok()?;
+ withdraw_transfer::<T>(&handle, &who, &token_id)
+ }
+
+ ApproveCross { .. } => {
+ let RefungibleTokenHandle(handle, token_id) = token;
+ let token_id = token_id.try_into().ok()?;
+ withdraw_approve::<T>(&handle, who.as_sub(), &token_id)
+ }
+ }
+ }
+}
+
+mod erc1633 {
+ use super::*;
+
+ pub fn call_sponsor<T>(
+ call: ERC1633Call<T>,
+ _token: RefungibleTokenHandle<T>,
+ _who: &T::CrossAccountId,
+ ) -> Option<()>
+ where
+ T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig,
+ {
+ use ERC1633Call::*;
+
+ match call {
+ // Readonly
+ ERC165Call(_, _) | ParentToken | ParentTokenId => None,
+ }
+ }
+}
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -780,15 +780,16 @@
#[cfg(feature = "try-runtime")]
impl frame_try_runtime::TryRuntime<Block> for Runtime {
- fn on_runtime_upgrade() -> (frame_support::pallet_prelude::Weight, frame_support::pallet_prelude::Weight) {
+ fn on_runtime_upgrade(checks: bool) -> (frame_support::pallet_prelude::Weight, frame_support::pallet_prelude::Weight) {
log::info!("try-runtime::on_runtime_upgrade unique-chain.");
- let weight = Executive::try_runtime_upgrade().unwrap();
+ let weight = Executive::try_runtime_upgrade(checks).unwrap();
(weight, crate::config::substrate::RuntimeBlockWeights::get().max_block)
}
fn execute_block(
block: Block,
state_root_check: bool,
+ signature_check: bool,
select: frame_try_runtime::TryStateSelect
) -> frame_support::pallet_prelude::Weight {
log::info!(
@@ -799,7 +800,7 @@
select,
);
- Executive::try_execute_block(block, state_root_check, select).unwrap()
+ Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
}
}
}
runtime/opal/Cargo.tomldiffbeforeafterboth--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -91,6 +91,7 @@
'pallet-unique-scheduler-v2/try-runtime',
'pallet-maintenance/try-runtime',
'pallet-test-utils?/try-runtime',
+ 'fp-self-contained/try-runtime',
]
std = [
'codec/std',
runtime/quartz/Cargo.tomldiffbeforeafterboth--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -86,6 +86,7 @@
'pallet-evm-transaction-payment/try-runtime',
'pallet-evm-migration/try-runtime',
'pallet-maintenance/try-runtime',
+ 'fp-self-contained/try-runtime',
]
std = [
'codec/std',
runtime/unique/Cargo.tomldiffbeforeafterboth--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -87,6 +87,7 @@
'pallet-evm-transaction-payment/try-runtime',
'pallet-evm-migration/try-runtime',
'pallet-maintenance/try-runtime',
+ 'fp-self-contained/try-runtime',
]
std = [
'codec/std',
tests/.eslintrc.jsondiffbeforeafterboth--- a/tests/.eslintrc.json
+++ b/tests/.eslintrc.json
@@ -18,6 +18,9 @@
"mocha"
],
"rules": {
+ "@typescript-eslint/no-floating-promises": [
+ "error"
+ ],
"indent": [
"error",
2,
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -11,8 +11,8 @@
"@types/chai-subset": "^1.3.3",
"@types/mocha": "^10.0.0",
"@types/node": "^18.11.2",
- "@typescript-eslint/eslint-plugin": "^5.40.1",
- "@typescript-eslint/parser": "^5.40.1",
+ "@typescript-eslint/eslint-plugin": "^5.47.0",
+ "@typescript-eslint/parser": "^5.47.0",
"chai": "^4.3.6",
"chai-subset": "^1.6.0",
"eslint": "^8.25.0",
tests/src/apiConsts.test.tsdiffbeforeafterboth--- a/tests/src/apiConsts.test.ts
+++ b/tests/src/apiConsts.test.ts
@@ -46,33 +46,33 @@
describe('integration test: API UNIQUE consts', () => {
let api: ApiPromise;
-
+
before(async () => {
await usingPlaygrounds(async (helper) => {
api = await helper.getApi();
});
});
-
+
itSub('DEFAULT_NFT_COLLECTION_LIMITS', () => {
expect(api.consts.unique.nftDefaultCollectionLimits.toHuman()).to.deep.equal(DEFAULT_COLLETCTION_LIMIT);
});
-
+
itSub('DEFAULT_RFT_COLLECTION_LIMITS', () => {
expect(api.consts.unique.rftDefaultCollectionLimits.toHuman()).to.deep.equal(DEFAULT_COLLETCTION_LIMIT);
});
-
+
itSub('DEFAULT_FT_COLLECTION_LIMITS', () => {
expect(api.consts.unique.ftDefaultCollectionLimits.toHuman()).to.deep.equal(DEFAULT_COLLETCTION_LIMIT);
});
-
+
itSub('MAX_COLLECTION_NAME_LENGTH', () => {
checkConst(api.consts.unique.maxCollectionNameLength, MAX_COLLECTION_NAME_LENGTH);
});
-
+
itSub('MAX_COLLECTION_DESCRIPTION_LENGTH', () => {
checkConst(api.consts.unique.maxCollectionDescriptionLength, MAX_COLLECTION_DESCRIPTION_LENGTH);
});
-
+
itSub('MAX_COLLECTION_PROPERTIES_SIZE', () => {
checkConst(api.consts.unique.maxCollectionPropertiesSize, MAX_COLLECTION_PROPERTIES_SIZE);
});
@@ -84,31 +84,31 @@
itSub('MAX_PROPERTY_KEY_LENGTH', () => {
checkConst(api.consts.unique.maxPropertyKeyLength, MAX_PROPERTY_KEY_LENGTH);
});
-
+
itSub('MAX_PROPERTY_VALUE_LENGTH', () => {
checkConst(api.consts.unique.maxPropertyValueLength, MAX_PROPERTY_VALUE_LENGTH);
});
-
+
itSub('MAX_PROPERTIES_PER_ITEM', () => {
checkConst(api.consts.unique.maxPropertiesPerItem, MAX_PROPERTIES_PER_ITEM);
});
-
+
itSub('NESTING_BUDGET', () => {
checkConst(api.consts.unique.nestingBudget, NESTING_BUDGET);
});
-
+
itSub('MAX_TOKEN_PROPERTIES_SIZE', () => {
checkConst(api.consts.unique.maxTokenPropertiesSize, MAX_TOKEN_PROPERTIES_SIZE);
});
-
+
itSub('COLLECTION_ADMINS_LIMIT', () => {
checkConst(api.consts.unique.collectionAdminsLimit, COLLECTION_ADMINS_LIMIT);
});
-
+
itSub('HELPERS_CONTRACT_ADDRESS', () => {
expect(api.consts.evmContractHelpers.contractAddress.toString().toLowerCase()).to.be.equal(HELPERS_CONTRACT_ADDRESS.toLowerCase());
});
-
+
itSub('EVM_COLLECTION_HELPERS_ADDRESS', () => {
expect(api.consts.common.contractAddress.toString().toLowerCase()).to.be.equal(EVM_COLLECTION_HELPERS_ADDRESS.toLowerCase());
});
tests/src/app-promotion.seqtest.tsdiffbeforeafterboth--- a/tests/src/app-promotion.seqtest.ts
+++ b/tests/src/app-promotion.seqtest.ts
@@ -50,31 +50,31 @@
await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;
await expect(helper.signTransaction(nonAdmin, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;
});
-
+
itSub('can be any valid CrossAccountId', async ({helper}) => {
// We are not going to set an eth address as a sponsor,
// but we do want to check, it doesn't break anything;
const api = helper.getApi();
const [account] = await helper.arrange.createAccounts([10n], donor);
- const ethAccount = helper.address.substrateToEth(account.address);
+ const ethAccount = helper.address.substrateToEth(account.address);
// Alice sets Ethereum address as a sudo. Then Substrate address back...
await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;
await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
-
+
// ...It doesn't break anything;
const collection = await helper.nft.mintCollection(account, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
await expect(helper.signTransaction(account, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
});
-
+
itSub('can be reassigned', async ({helper}) => {
const api = helper.getApi();
const [oldAdmin, newAdmin, collectionOwner] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
-
+
await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: oldAdmin.address})))).to.be.fulfilled;
await expect(helper.signTransaction(superuser, api.tx.sudo.sudo(api.tx.appPromotion.setAdminAddress({Substrate: newAdmin.address})))).to.be.fulfilled;
await expect(helper.signTransaction(oldAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
-
+
await expect(helper.signTransaction(newAdmin, api.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
});
});
tests/src/approve.test.tsdiffbeforeafterboth--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -538,7 +538,7 @@
const approveTx = () => helper.rft.approveToken(alice, collectionId, 1, {Substrate: bob.address});
await expect(approveTx()).to.be.rejected;
});
-
+
itSub('[nft] Approve transfer of a token that does not exist', async ({helper}) => {
const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
const approveTx = () => helper.nft.approveToken(alice, collectionId, 2, {Substrate: bob.address});
@@ -639,7 +639,7 @@
await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);
const checkAfterApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
expect(checkAfterApproval).to.be.true;
-
+
await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);
const checkAfterDisapproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
expect(checkAfterDisapproval).to.be.false;
tests/src/burnItem.test.tsdiffbeforeafterboth--- a/tests/src/burnItem.test.ts
+++ b/tests/src/burnItem.test.ts
@@ -185,7 +185,7 @@
const collection = await helper.nft.mintCollection(alice, {name: 'Coll', description: 'Desc', tokenPrefix: 'T'});
const tokenAlice = await collection.mintToken(alice, {Substrate: alice.address});
const tokenBob = await collection.mintToken(alice, {Substrate: bob.address});
-
+
// 1. Zero burn of own tokens allowed:
await helper.executeExtrinsic(alice, 'api.tx.unique.burnItem', [collection.collectionId, tokenAlice.tokenId, 0]);
// 2. Zero burn of non-owned tokens not allowed:
tests/src/calibrate.tsdiffbeforeafterboth--- a/tests/src/calibrate.ts
+++ b/tests/src/calibrate.ts
@@ -295,6 +295,7 @@
}
}
+// eslint-disable-next-line @typescript-eslint/no-floating-promises
(async () => {
await usingEthPlaygrounds(async (helper: EthUniqueHelper, privateKey) => {
// Subsequent runs reduce error, as price line is not actually straight, this is a curve
tests/src/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -127,7 +127,7 @@
const mintCollectionTx = () => helper.nft.mintCollection(alice, {name: 'name', description: 'descr', tokenPrefix: 'A'.repeat(17)});
await expect(mintCollectionTx()).to.be.rejectedWith('Verification Error');
});
-
+
itSub('(!negative test!) fails when bad limits are set', async ({helper}) => {
const mintCollectionTx = () => helper.nft.mintCollection(alice, {name: 'name', description: 'descr', tokenPrefix: 'COL', limits: {tokenLimit: 0}});
await expect(mintCollectionTx()).to.be.rejectedWith(/common\.CollectionTokenLimitExceeded/);
tests/src/createMultipleItems.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -272,8 +272,8 @@
const types = ['NFT', 'Fungible', 'ReFungible'];
await expect(helper.executeExtrinsic(
- alice,
- 'api.tx.unique.createMultipleItems',
+ alice,
+ 'api.tx.unique.createMultipleItems',
[collectionId, {Substrate: alice.address}, types],
)).to.be.rejectedWith(/nonfungible\.NotNonfungibleDataUsedToMintFungibleCollectionToken/);
});
tests/src/eth/abi/reFungibleDeprecated.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungibleDeprecated.json
+++ b/tests/src/eth/abi/reFungibleDeprecated.json
@@ -98,5 +98,33 @@
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256[]", "name": "tokenIds", "type": "uint256[]" }
+ ],
+ "name": "mintBulk",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ {
+ "components": [
+ { "internalType": "uint256", "name": "field_0", "type": "uint256" },
+ { "internalType": "string", "name": "field_1", "type": "string" }
+ ],
+ "internalType": "struct Tuple0[]",
+ "name": "tokens",
+ "type": "tuple[]"
+ }
+ ],
+ "name": "mintBulkWithTokenURI",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
}
]
tests/src/eth/api/ContractHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/ContractHelpers.sol
+++ b/tests/src/eth/api/ContractHelpers.sol
@@ -183,7 +183,9 @@
/// Ethereum representation of Optional value with CrossAddress.
struct OptionCrossAddress {
+ /// TODO: field description
bool status;
+ /// TODO: field description
CrossAddress value;
}
tests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -15,10 +15,10 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {usingPlaygrounds} from '../util/index';
+import {Pallets, requirePalletsOrSkip, usingPlaygrounds} from '../util/index';
import {itEth, expect} from './util';
-describe('evm collection sponsoring', () => {
+describe('evm nft collection sponsoring', () => {
let donor: IKeyringPair;
let alice: IKeyringPair;
let nominal: bigint;
@@ -101,12 +101,14 @@
expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
+ let sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});
+ expect(helper.address.restoreCrossAccountFromBigInt(BigInt(sponsorStruct.sub))).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
await collectionEvm.methods.removeCollectionSponsor().send({from: owner});
- const sponsorTuple = await collectionEvm.methods.collectionSponsor().call({from: owner});
- expect(sponsorTuple.eth).to.be.eq('0x0000000000000000000000000000000000000000');
+ sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});
+ expect(sponsorStruct.eth).to.be.eq('0x0000000000000000000000000000000000000000');
}));
[
@@ -142,7 +144,7 @@
expect(nextTokenId).to.be.equal('1');
// Set collection permissions:
- const oldPermissions = (await collectionSub.getData())!.raw.permissions; // (await getDetailedCollectionInfo(api, collectionId))!.permissions.toHuman();
+ const oldPermissions = (await collectionSub.getData())!.raw.permissions;
expect(oldPermissions.mintMode).to.be.false;
expect(oldPermissions.access).to.be.equal('Normal');
@@ -150,12 +152,13 @@
await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});
await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
- const newPermissions = (await collectionSub.getData())!.raw.permissions; // (await getDetailedCollectionInfo(api, collectionId))!.permissions.toHuman();
+ const newPermissions = (await collectionSub.getData())!.raw.permissions;
expect(newPermissions.mintMode).to.be.true;
expect(newPermissions.access).to.be.equal('AllowList');
const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
+ const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
// User can mint token without balance:
{
@@ -179,7 +182,7 @@
expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
- expect(userBalanceAfter).to.be.eq(0n);
+ expect(userBalanceAfter).to.be.eq(userBalanceBefore);
expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;
}
}));
@@ -315,3 +318,531 @@
expect(collectionSponsor).to.deep.eq({Unconfirmed: sponsorSub.address});
});
});
+
+describe('evm RFT collection sponsoring', () => {
+ let donor: IKeyringPair;
+ let alice: IKeyringPair;
+ let nominal: bigint;
+
+ before(async function() {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+ donor = await privateKey({filename: __filename});
+ [alice] = await helper.arrange.createAccounts([100n], donor);
+ nominal = helper.balance.getOneTokenNominal();
+ });
+ });
+
+ [
+ 'mintCross',
+ 'mintWithTokenURI',
+ ].map(testCase =>
+ itEth(`[${testCase}] sponsors mint transactions`, async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'spnr', permissions: {mintMode: true}, tokenPropertyPermissions: [
+ {key: 'URI', permission: {tokenOwner: true, mutable: true, collectionAdmin: true}},
+ ]});
+
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ await collection.setSponsor(alice, alice.address);
+ await collection.confirmSponsorship(alice);
+
+ const minter = helper.eth.createAccount();
+ const minterCross = helper.ethCrossAccount.fromAddress(minter);
+ expect(await helper.balance.getEthereum(minter)).to.equal(0n);
+
+ const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', minter, true);
+
+ await collection.addToAllowList(alice, {Ethereum: minter});
+ await collection.addAdmin(alice, {Ethereum: owner});
+ const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);
+ await collectionHelpers.methods.makeCollectionERC721MetadataCompatible(collectionAddress, 'base/')
+ .send();
+
+ let mintingResult;
+ let tokenId;
+ switch (testCase) {
+ case 'mintCross':
+ mintingResult = await contract.methods.mintCross(minterCross, []).send();
+ break;
+ case 'mintWithTokenURI':
+ mintingResult = await contract.methods.mintWithTokenURI(minter, 'Test URI').send();
+ tokenId = mintingResult.events.Transfer.returnValues.tokenId;
+ expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
+ break;
+ }
+
+ const events = helper.eth.normalizeEvents(mintingResult.events);
+ expect(events).to.deep.include({
+ address: collectionAddress,
+ event: 'Transfer',
+ args: {
+ from: '0x0000000000000000000000000000000000000000',
+ to: minter,
+ tokenId: '1',
+ },
+ });
+ }));
+
+ [
+ 'setCollectionSponsorCross',
+ 'setCollectionSponsor', // Soft-deprecated
+ ].map(testCase =>
+ itEth(`[${testCase}] can remove collection sponsor`, async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);
+
+ let result = await collectionHelpers.methods.createRFTCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
+ const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);
+ const collectionEvm = await helper.ethNativeContract.collection(collectionIdAddress, 'rft', owner, testCase === 'setCollectionSponsor');
+
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
+ result = await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsor : sponsorCross).send({from: owner});
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
+
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
+
+ await collectionEvm.methods.removeCollectionSponsor().send({from: owner});
+
+ const sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});
+ expect(sponsorStruct.eth).to.be.eq('0x0000000000000000000000000000000000000000');
+ }));
+
+ [
+ 'setCollectionSponsorCross',
+ 'setCollectionSponsor', // Soft-deprecated
+ ].map(testCase =>
+ itEth(`[${testCase}] Can sponsor from evm address via access list`, async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsorEth = await helper.eth.createAccountWithBalance(donor);
+ const sponsorCrossEth = helper.ethCrossAccount.fromAddress(sponsorEth);
+
+ const {collectionId, collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Sponsor collection', '1', '1', '');
+
+ const collectionSub = helper.rft.getCollectionObject(collectionId);
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner, testCase === 'setCollectionSponsor');
+
+ // Set collection sponsor:
+ await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsorEth : sponsorCrossEth).send({from: owner});
+ let sponsorship = (await collectionSub.getData())!.raw.sponsorship;
+ expect(sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));
+ // Account cannot confirm sponsorship if it is not set as a sponsor
+ await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');
+
+ // Sponsor can confirm sponsorship:
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});
+ sponsorship = (await collectionSub.getData())!.raw.sponsorship;
+ expect(sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));
+
+ // Create user with no balance:
+ const user = helper.eth.createAccount();
+ const userCross = helper.ethCrossAccount.fromAddress(user);
+ const nextTokenId = await collectionEvm.methods.nextTokenId().call();
+ expect(nextTokenId).to.be.equal('1');
+
+ // Set collection permissions:
+ const oldPermissions = (await collectionSub.getData())!.raw.permissions;
+ expect(oldPermissions.mintMode).to.be.false;
+ expect(oldPermissions.access).to.be.equal('Normal');
+
+ await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});
+ await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});
+ await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
+
+ const newPermissions = (await collectionSub.getData())!.raw.permissions;
+ expect(newPermissions.mintMode).to.be.true;
+ expect(newPermissions.access).to.be.equal('AllowList');
+
+ const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
+ const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+
+ // User can mint token without balance:
+ {
+ const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
+ const events = helper.eth.normalizeEvents(result.events);
+
+ expect(events).to.deep.include({
+ address: collectionAddress,
+ event: 'Transfer',
+ args: {
+ from: '0x0000000000000000000000000000000000000000',
+ to: user,
+ tokenId: '1',
+ },
+ });
+
+ const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
+ const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+
+ expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+ expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
+ expect(userBalanceAfter).to.be.eq(userBalanceBefore);
+ expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;
+ }
+ }));
+
+ [
+ 'setCollectionSponsorCross',
+ 'setCollectionSponsor', // Soft-deprecated
+ ].map(testCase =>
+ itEth(`[${testCase}] Check that collection admin EVM transaction spend money from sponsor eth address`, async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);
+
+ const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');
+
+ const collectionSub = helper.rft.getCollectionObject(collectionId);
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner, testCase === 'setCollectionSponsor');
+ // Set collection sponsor:
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.false;
+ await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsor : sponsorCross).send();
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.true;
+ let collectionData = (await collectionSub.getData())!;
+ expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
+ await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.true;
+
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
+ collectionData = (await collectionSub.getData())!;
+ expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.false;
+ const sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});
+ const sponsorSubAddress = helper.address.normalizeSubstrateToChainFormat(helper.address.ethToSubstrate(sponsor));
+ const actualSubAddress = helper.address.normalizeSubstrateToChainFormat(helper.address.restoreCrossAccountFromBigInt(BigInt(sponsorStruct.sub)));
+ expect(actualSubAddress).to.be.equal(sponsorSubAddress);
+
+ const user = helper.eth.createAccount();
+ const userCross = helper.ethCrossAccount.fromAddress(user);
+ await collectionEvm.methods.addCollectionAdminCross(userCross).send();
+
+ const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+
+ const mintingResult = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
+ const tokenId = mintingResult.events.Transfer.returnValues.tokenId;
+
+ const events = helper.eth.normalizeEvents(mintingResult.events);
+ const address = helper.ethAddress.fromCollectionId(collectionId);
+
+ expect(events).to.deep.include({
+ address,
+ event: 'Transfer',
+ args: {
+ from: '0x0000000000000000000000000000000000000000',
+ to: user,
+ tokenId: '1',
+ },
+ });
+ expect(await collectionEvm.methods.tokenURI(tokenId).call({from: user})).to.be.equal('Test URI');
+
+ const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+ expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
+ }));
+
+ itEth('Check that collection admin EVM transaction spend money from sponsor sub address', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = alice;
+ const sponsorCross = helper.ethCrossAccount.fromKeyringPair(sponsor);
+
+ const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');
+
+ const collectionSub = helper.rft.getCollectionObject(collectionId);
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner, false);
+ // Set collection sponsor:
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.false;
+ await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send();
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.true;
+ let collectionData = (await collectionSub.getData())!;
+ expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(sponsor.address);
+ await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');
+
+ await collectionSub.confirmSponsorship(sponsor);
+ collectionData = (await collectionSub.getData())!;
+ expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(sponsor.address);
+ expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.false;
+ const sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});
+ expect(BigInt(sponsorStruct.sub)).to.be.equal(BigInt('0x' + Buffer.from(sponsor.addressRaw).toString('hex')));
+
+ const user = helper.eth.createAccount();
+ const userCross = helper.ethCrossAccount.fromAddress(user);
+ await collectionEvm.methods.addCollectionAdminCross(userCross).send();
+
+ const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(sponsor.address);
+
+ const mintingResult = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
+ const tokenId = mintingResult.events.Transfer.returnValues.tokenId;
+
+ const events = helper.eth.normalizeEvents(mintingResult.events);
+
+ expect(events).to.deep.include({
+ address: collectionAddress,
+ event: 'Transfer',
+ args: {
+ from: '0x0000000000000000000000000000000000000000',
+ to: user,
+ tokenId: '1',
+ },
+ });
+ expect(await collectionEvm.methods.tokenURI(tokenId).call({from: user})).to.be.equal('Test URI');
+
+ const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(sponsor.address);
+ expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
+ });
+
+ itEth('Sponsoring collection from substrate address via access list', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const user = helper.eth.createAccount();
+ const userCross = helper.ethCrossAccount.fromAddress(user);
+ const sponsor = alice;
+ const sponsorCross = helper.ethCrossAccount.fromKeyringPair(sponsor);
+
+ const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner, false);
+
+ await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send({from: owner});
+
+ const collectionSub = helper.rft.getCollectionObject(collectionId);
+ await collectionSub.confirmSponsorship(sponsor);
+
+ const nextTokenId = await collectionEvm.methods.nextTokenId().call();
+ expect(nextTokenId).to.be.equal('1');
+
+ await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});
+
+ await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});
+ await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
+
+ const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(sponsor.address);
+ const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+
+ {
+ const nextTokenId = await collectionEvm.methods.nextTokenId().call();
+ expect(nextTokenId).to.be.equal('1');
+ const mintingResult = await collectionEvm.methods.mintWithTokenURI(
+ user,
+ 'Test URI',
+ ).send({from: user});
+
+ const events = helper.eth.normalizeEvents(mintingResult.events);
+
+
+ expect(events).to.deep.include({
+ address: collectionAddress,
+ event: 'Transfer',
+ args: {
+ from: '0x0000000000000000000000000000000000000000',
+ to: user,
+ tokenId: nextTokenId,
+ },
+ });
+
+ const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(sponsor.address);
+ const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+
+ expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+ expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
+ expect(userBalanceAfter).to.be.eq(userBalanceBefore);
+ expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;
+ }
+ });
+
+ itEth('Can reassign collection sponsor', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsorEth = await helper.eth.createAccountWithBalance(donor);
+ const sponsorCrossEth = helper.ethCrossAccount.fromAddress(sponsorEth);
+ const [sponsorSub] = await helper.arrange.createAccounts([100n], donor);
+ const sponsorCrossSub = helper.ethCrossAccount.fromKeyringPair(sponsorSub);
+
+ const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');
+ const collectionSub = helper.rft.getCollectionObject(collectionId);
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+
+ // Set and confirm sponsor:
+ await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossEth).send({from: owner});
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});
+
+ // Can reassign sponsor:
+ await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossSub).send({from: owner});
+ const collectionSponsor = (await collectionSub.getData())?.raw.sponsorship;
+ expect(collectionSponsor).to.deep.eq({Unconfirmed: sponsorSub.address});
+ });
+
+ [
+ 'transfer',
+ 'transferCross',
+ 'transferFrom',
+ 'transferFromCross',
+ ].map(testCase =>
+ itEth(`[${testCase}] Check that transfer via EVM spend money from sponsor address`, async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);
+ const receiver = await helper.eth.createAccountWithBalance(donor);
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+
+ await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send();
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
+
+ const user = await helper.eth.createAccountWithBalance(donor);
+ const userCross = helper.ethCrossAccount.fromAddress(user);
+ await collectionEvm.methods.addCollectionAdminCross(userCross).send();
+
+ const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+
+ const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+ const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+
+ switch (testCase) {
+ case 'transfer':
+ await collectionEvm.methods.transfer(receiver, tokenId).send({from: user});
+ break;
+ case 'transferCross':
+ await collectionEvm.methods.transferCross(helper.ethCrossAccount.fromAddress(receiver), tokenId).send({from: user});
+ break;
+ case 'transferFrom':
+ await collectionEvm.methods.transferFrom(user, receiver, tokenId).send({from: user});
+ break;
+ case 'transferFromCross':
+ await collectionEvm.methods.transferFromCross(helper.ethCrossAccount.fromAddress(user), helper.ethCrossAccount.fromAddress(receiver), tokenId).send({from: user});
+ break;
+ }
+
+ const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+ expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
+ const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+ expect(userBalanceAfter).to.be.eq(userBalanceBefore);
+ }));
+});
+
+describe('evm RFT token sponsoring', () => {
+ let donor: IKeyringPair;
+
+ before(async function() {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+ donor = await privateKey({filename: __filename});
+ });
+ });
+
+ [
+ 'transfer',
+ 'transferCross',
+ 'transferFrom',
+ 'transferFromCross',
+ ].map(testCase =>
+ itEth(`[${testCase}] Check that token piece transfer via EVM spend money from sponsor address`, async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);
+ const receiver = await helper.eth.createAccountWithBalance(donor);
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+
+ await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send();
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
+
+ const user = await helper.eth.createAccountWithBalance(donor);
+ const userCross = helper.ethCrossAccount.fromAddress(user);
+ await collectionEvm.methods.addCollectionAdminCross(userCross).send();
+
+ const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+
+ const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, user);
+ await tokenContract.methods.repartition(2).send();
+
+ const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+ const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+
+ switch (testCase) {
+ case 'transfer':
+ await tokenContract.methods.transfer(receiver, 1).send();
+ break;
+ case 'transferCross':
+ await tokenContract.methods.transferCross(helper.ethCrossAccount.fromAddress(receiver), 1).send();
+ break;
+ case 'transferFrom':
+ await tokenContract.methods.transferFrom(user, receiver, 1).send();
+ break;
+ case 'transferFromCross':
+ await tokenContract.methods.transferFromCross(helper.ethCrossAccount.fromAddress(user), helper.ethCrossAccount.fromAddress(receiver), 1).send();
+ break;
+ }
+
+ const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+ expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
+ const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+ expect(userBalanceAfter).to.be.eq(userBalanceBefore);
+ }));
+
+ [
+ 'approve',
+ 'approveCross',
+ ].map(testCase =>
+ itEth(`[${testCase}] Check that approve via EVM spend money from sponsor address`, async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);
+ const receiver = await helper.eth.createAccountWithBalance(donor);
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+
+ await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send();
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
+
+ const user = await helper.eth.createAccountWithBalance(donor);
+ const userCross = helper.ethCrossAccount.fromAddress(user);
+ await collectionEvm.methods.addCollectionAdminCross(userCross).send();
+
+ const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
+ const tokenId = result.events.Transfer.returnValues.tokenId;
+
+ const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, user);
+ await tokenContract.methods.repartition(2).send();
+
+ const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+ const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+
+ switch (testCase) {
+ case 'approve':
+ await tokenContract.methods.approve(receiver, 1).send();
+ break;
+ case 'approveCross':
+ await tokenContract.methods.approveCross(helper.ethCrossAccount.fromAddress(receiver), 1).send();
+ break;
+ }
+
+ const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
+ expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;
+ const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+ expect(userBalanceAfter).to.be.eq(userBalanceBefore);
+ }));
+});
+
tests/src/eth/createFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createFTCollection.test.ts
+++ b/tests/src/eth/createFTCollection.test.ts
@@ -32,6 +32,7 @@
});
});
+ // TODO move sponsorship tests to another file:
// Soft-deprecated
itEth('[eth] Set sponsorship', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
@@ -93,6 +94,11 @@
expect(await collectionHelpers
.methods.isCollectionExist(collectionAddress).call())
.to.be.true;
+
+ // check collectionOwner:
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner, true);
+ const collectionOwner = await collectionEvm.methods.collectionOwner().call();
+ expect(helper.address.restoreCrossAccountFromBigInt(BigInt(collectionOwner.sub))).to.eq(helper.address.ethToSubstrate(owner, true));
});
itEth('destroyCollection', async ({helper}) => {
tests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -134,6 +134,11 @@
expect(await collectionHelpers
.methods.isCollectionExist(collectionAddress).call())
.to.be.true;
+
+ // check collectionOwner:
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner, true);
+ const collectionOwner = await collectionEvm.methods.collectionOwner().call();
+ expect(helper.address.restoreCrossAccountFromBigInt(BigInt(collectionOwner.sub))).to.eq(helper.address.ethToSubstrate(owner, true));
});
});
tests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -88,27 +88,6 @@
]);
});
- // this test will occasionally fail when in async environment.
- itEth.skip('Check collection address exist', async ({helper}) => {
- const owner = await helper.eth.createAccountWithBalance(donor);
-
- const expectedCollectionId = +(await helper.callRpc('api.rpc.unique.collectionStats')).created + 1;
- const expectedCollectionAddress = helper.ethAddress.fromCollectionId(expectedCollectionId);
- const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);
-
- expect(await collectionHelpers.methods
- .isCollectionExist(expectedCollectionAddress)
- .call()).to.be.false;
-
- await collectionHelpers.methods
- .createRFTCollection('A', 'A', 'A')
- .send({value: Number(2n * helper.balance.getOneTokenNominal())});
-
- expect(await collectionHelpers.methods
- .isCollectionExist(expectedCollectionAddress)
- .call()).to.be.true;
- });
-
// Soft-deprecated
itEth('[eth] Set sponsorship', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
@@ -166,6 +145,11 @@
expect(await collectionHelpers
.methods.isCollectionExist(collectionAddress).call())
.to.be.true;
+
+ // check collectionOwner:
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner, true);
+ const collectionOwner = await collectionEvm.methods.collectionOwner().call();
+ expect(helper.address.restoreCrossAccountFromBigInt(BigInt(collectionOwner.sub))).to.eq(helper.address.ethToSubstrate(owner, true));
});
});
tests/src/eth/evmCoder.test.tsdiffbeforeafterboth--- a/tests/src/eth/evmCoder.test.ts
+++ b/tests/src/eth/evmCoder.test.ts
@@ -62,7 +62,7 @@
donor = await privateKey({filename: __filename});
});
});
-
+
itEth('Call non-existing function', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const collection = await helper.eth.createNFTCollection(owner, 'EVMCODER', '', 'TEST');
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -167,7 +167,6 @@
expect(event.returnValues.to).to.be.equal(receiver);
expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
- console.log(await contract.methods.crossOwnerOf(tokenId).call());
expect(await contract.methods.crossOwnerOf(tokenId).call()).to.be.like([receiver, '0']);
// TODO: this wont work right now, need release 919000 first
// await helper.methods.setOffchainSchema(collectionIdAddress, 'https://offchain-service.local/token-info/{id}').send();
@@ -200,7 +199,6 @@
},
};
});
-
const collection = await helper.nft.mintCollection(minter, {
tokenPrefix: 'ethp',
tests/src/eth/proxyContract.test.tsdiffbeforeafterboth--- a/tests/src/eth/proxyContract.test.ts
+++ b/tests/src/eth/proxyContract.test.ts
@@ -31,11 +31,11 @@
const deployer = await helper.eth.createAccountWithBalance(donor);
const caller = await helper.eth.createAccountWithBalance(donor);
const proxyContract = await deployProxyContract(helper, deployer);
-
+
const realContractV1 = await deployRealContractV1(helper, deployer);
const realContractV1proxy = new helper.web3!.eth.Contract(realContractV1.options.jsonInterface, proxyContract.options.address, {from: caller, gas: helper.eth.DEFAULT_GAS});
await proxyContract.methods.updateVersion(realContractV1.options.address).send();
-
+
await realContractV1proxy.methods.flip().send();
await realContractV1proxy.methods.flip().send();
await realContractV1proxy.methods.flip().send();
tests/src/eth/scheduling.test.tsdiffbeforeafterboth--- a/tests/src/eth/scheduling.test.ts
+++ b/tests/src/eth/scheduling.test.ts
@@ -53,7 +53,7 @@
);
expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
-
+
await helper.wait.newBlocks(waitForBlocks + 1);
expect(await flipper.methods.getValue().call()).to.be.not.equal(initialValue);
tests/src/eth/util/index.tsdiffbeforeafterboth--- a/tests/src/eth/util/index.ts
+++ b/tests/src/eth/util/index.ts
@@ -58,9 +58,9 @@
silentConsole.disable();
}
};
-
+
export function itEth(name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {
- (opts.only ? it.only :
+ (opts.only ? it.only :
opts.skip ? it.skip : it)(name, async function() {
await usingEthPlaygrounds(async (helper, privateKey) => {
if (opts.requiredPallets) {
tests/src/fungible.test.tsdiffbeforeafterboth--- a/tests/src/fungible.test.ts
+++ b/tests/src/fungible.test.ts
@@ -43,7 +43,7 @@
expect(itemCountAfter).to.be.equal(defaultTokenId);
expect(aliceBalance).to.be.equal(U128_MAX);
});
-
+
itSub('RPC method tokenOnewrs for fungible collection and token', async ({helper}) => {
const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
const facelessCrowd = (await helper.arrange.createAccounts(Array(7).fill(0n), donor)).map(keyring => {return {Substrate: keyring.address};});
@@ -54,22 +54,22 @@
await collection.transfer(alice, {Substrate: bob.address}, 1000n);
await collection.transfer(alice, ethAcc, 900n);
-
+
for (let i = 0; i < 7; i++) {
await collection.transfer(alice, facelessCrowd[i], 1n);
- }
+ }
const owners = await collection.getTop10Owners();
// What to expect
expect(owners).to.deep.include.members([{Substrate: alice.address}, ethAcc, {Substrate: bob.address}, ...facelessCrowd]);
expect(owners.length).to.be.equal(10);
-
+
const [eleven] = await helper.arrange.createAccounts([0n], donor);
expect(await collection.transfer(alice, {Substrate: eleven.address}, 10n)).to.be.true;
expect((await collection.getTop10Owners()).length).to.be.equal(10);
});
-
+
itSub('Transfer token', async ({helper}) => {
const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
@@ -108,7 +108,7 @@
expect(await collection.doesTokenExist(0)).to.be.true;
expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(1n);
});
-
+
itSub('Burn all tokens ', async ({helper}) => {
const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
await collection.mint(alice, 500n);
@@ -127,7 +127,7 @@
await collection.mint(alice, 100n);
expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(100n);
-
+
expect(await collection.approveTokens(alice, {Substrate: bob.address}, 60n)).to.be.true;
expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(60n);
expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(0n);
@@ -169,11 +169,11 @@
// 1. Alice cannot transfer more than 0 tokens if balance low:
await expect(collection.transfer(alice, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
await expect(collection.transfer(alice, {Substrate: charlie.address}, 100n)).to.be.rejectedWith('common.TokenValueTooLow');
-
+
// 2. Alice cannot transfer non-existing token:
await expect(nonExistingCollection.transfer(alice, {Substrate: charlie.address}, 0n)).to.be.rejectedWith('common.CollectionNotFound');
await expect(nonExistingCollection.transfer(alice, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.CollectionNotFound');
-
+
// 3. Zero transfer allowed (EIP-20):
await collection.transfer(bob, {Substrate: charlie.address}, 0n);
// 3.1 even if the balance = 0
tests/src/inflation.seqtest.tsdiffbeforeafterboth--- a/tests/src/inflation.seqtest.ts
+++ b/tests/src/inflation.seqtest.ts
@@ -26,7 +26,7 @@
superuser = await privateKey('//Alice');
});
});
-
+
itSub('First year inflation is 10%', async ({helper}) => {
// Make sure non-sudo can't start inflation
const [bob] = await helper.arrange.createAccounts([10n], superuser);
tests/src/interfaces/unique/definitions.tsdiffbeforeafterboth--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -38,39 +38,39 @@
types: {},
rpc: {
accountTokens: fun(
- 'Get tokens owned by an account in a collection',
- [collectionParam, crossAccountParam()],
+ 'Get tokens owned by an account in a collection',
+ [collectionParam, crossAccountParam()],
'Vec<u32>',
),
collectionTokens: fun(
- 'Get tokens contained within a collection',
- [collectionParam],
+ 'Get tokens contained within a collection',
+ [collectionParam],
'Vec<u32>',
),
tokenExists: fun(
- 'Check if the token exists',
- [collectionParam, tokenParam],
+ 'Check if the token exists',
+ [collectionParam, tokenParam],
'bool',
),
tokenOwner: fun(
- 'Get the token owner',
- [collectionParam, tokenParam],
+ 'Get the token owner',
+ [collectionParam, tokenParam],
`Option<${CROSS_ACCOUNT_ID_TYPE}>`,
),
topmostTokenOwner: fun(
- 'Get the topmost token owner in the hierarchy of a possibly nested token',
- [collectionParam, tokenParam],
+ 'Get the topmost token owner in the hierarchy of a possibly nested token',
+ [collectionParam, tokenParam],
`Option<${CROSS_ACCOUNT_ID_TYPE}>`,
),
tokenOwners: fun(
- 'Returns 10 tokens owners in no particular order',
- [collectionParam, tokenParam],
+ 'Returns 10 tokens owners in no particular order',
+ [collectionParam, tokenParam],
`Vec<${CROSS_ACCOUNT_ID_TYPE}>`,
),
tokenChildren: fun(
- 'Get tokens nested directly into the token',
- [collectionParam, tokenParam],
+ 'Get tokens nested directly into the token',
+ [collectionParam, tokenParam],
'Vec<UpDataStructsTokenChild>',
),
@@ -91,13 +91,13 @@
),
constMetadata: fun(
- 'Get token constant metadata',
- [collectionParam, tokenParam],
+ 'Get token constant metadata',
+ [collectionParam, tokenParam],
'Vec<u8>',
),
variableMetadata: fun(
- 'Get token variable metadata',
- [collectionParam, tokenParam],
+ 'Get token variable metadata',
+ [collectionParam, tokenParam],
'Vec<u8>',
),
@@ -107,77 +107,77 @@
'UpDataStructsTokenData',
),
totalSupply: fun(
- 'Get the amount of distinctive tokens present in a collection',
- [collectionParam],
+ 'Get the amount of distinctive tokens present in a collection',
+ [collectionParam],
'u32',
),
accountBalance: fun(
- 'Get the amount of any user tokens owned by an account',
- [collectionParam, crossAccountParam()],
+ 'Get the amount of any user tokens owned by an account',
+ [collectionParam, crossAccountParam()],
'u32',
),
balance: fun(
- 'Get the amount of a specific token owned by an account',
- [collectionParam, crossAccountParam(), tokenParam],
+ 'Get the amount of a specific token owned by an account',
+ [collectionParam, crossAccountParam(), tokenParam],
'u128',
),
allowance: fun(
- 'Get the amount of currently possible sponsored transactions on a token for the fee to be taken off a sponsor',
- [collectionParam, crossAccountParam('sender'), crossAccountParam('spender'), tokenParam],
+ 'Get the amount of currently possible sponsored transactions on a token for the fee to be taken off a sponsor',
+ [collectionParam, crossAccountParam('sender'), crossAccountParam('spender'), tokenParam],
'u128',
),
adminlist: fun(
- 'Get the list of admin accounts of a collection',
- [collectionParam],
+ 'Get the list of admin accounts of a collection',
+ [collectionParam],
'Vec<PalletEvmAccountBasicCrossAccountIdRepr>',
),
allowlist: fun(
- 'Get the list of accounts allowed to operate within a collection',
- [collectionParam],
+ 'Get the list of accounts allowed to operate within a collection',
+ [collectionParam],
'Vec<PalletEvmAccountBasicCrossAccountIdRepr>',
),
allowed: fun(
- 'Check if a user is allowed to operate within a collection',
- [collectionParam, crossAccountParam()],
+ 'Check if a user is allowed to operate within a collection',
+ [collectionParam, crossAccountParam()],
'bool',
),
lastTokenId: fun(
- 'Get the last token ID created in a collection',
- [collectionParam],
+ 'Get the last token ID created in a collection',
+ [collectionParam],
'u32',
),
collectionById: fun(
- 'Get a collection by the specified ID',
- [collectionParam],
+ 'Get a collection by the specified ID',
+ [collectionParam],
'Option<UpDataStructsRpcCollection>',
),
collectionStats: fun(
- 'Get chain stats about collections',
- [],
+ 'Get chain stats about collections',
+ [],
'UpDataStructsCollectionStats',
),
nextSponsored: fun(
- 'Get the number of blocks until sponsoring a transaction is available',
- [collectionParam, crossAccountParam(), tokenParam],
+ 'Get the number of blocks until sponsoring a transaction is available',
+ [collectionParam, crossAccountParam(), tokenParam],
'Option<u64>',
),
effectiveCollectionLimits: fun(
- 'Get effective collection limits',
- [collectionParam],
+ 'Get effective collection limits',
+ [collectionParam],
'Option<UpDataStructsCollectionLimits>',
),
totalPieces: fun(
- 'Get the total amount of pieces of an RFT',
- [collectionParam, tokenParam],
+ 'Get the total amount of pieces of an RFT',
+ [collectionParam, tokenParam],
'Option<u128>',
),
allowanceForAll: fun(
- 'Tells whether the given `owner` approves the `operator`.',
- [collectionParam, crossAccountParam('owner'), crossAccountParam('operator')],
+ 'Tells whether the given `owner` approves the `operator`.',
+ [collectionParam, crossAccountParam('owner'), crossAccountParam('operator')],
'Option<bool>',
),
},
tests/src/limits.test.tsdiffbeforeafterboth--- a/tests/src/limits.test.ts
+++ b/tests/src/limits.test.ts
@@ -30,7 +30,7 @@
itSub.skip('Collection limits allow greater number than chain limits, chain limits are enforced', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {});
await collection.setLimits(alice, {accountTokenOwnershipLimit: 20});
-
+
for(let i = 0; i < 10; i++){
await expect(collection.mintToken(alice)).to.be.not.rejected;
}
@@ -40,14 +40,14 @@
}
await collection.burn(alice);
});
-
+
itSub('Collection limits allow lower number than chain limits, collection limits are enforced', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {});
await collection.setLimits(alice, {accountTokenOwnershipLimit: 1});
await collection.mintToken(alice);
await expect(collection.mintToken(alice)).to.be.rejectedWith(/common\.AccountTokenLimitExceeded/);
-
+
await collection.burnToken(alice, 1);
await expect(collection.burn(alice)).to.be.not.rejected;
});
@@ -68,7 +68,7 @@
itSub.skip('Collection limits allow greater number than chain limits, chain limits are enforced', async ({helper}) => {
const collection = await helper.rft.mintCollection(alice, {});
await collection.setLimits(alice, {accountTokenOwnershipLimit: 20});
-
+
for(let i = 0; i < 10; i++){
await expect(collection.mintToken(alice, 10n)).to.be.not.rejected;
}
@@ -85,7 +85,7 @@
await collection.mintToken(alice);
await expect(collection.mintToken(alice)).to.be.rejectedWith(/common\.AccountTokenLimitExceeded/);
-
+
await collection.burnToken(alice, 1);
await expect(collection.burn(alice)).to.be.not.rejected;
});
@@ -314,7 +314,7 @@
await collection.setSponsor(alice, alice.address);
await collection.confirmSponsorship(alice);
-
+
await token.transfer(alice, {Substrate: bob.address});
const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
@@ -345,7 +345,7 @@
await collection.setSponsor(alice, alice.address);
await collection.confirmSponsorship(alice);
-
+
await collection.transfer(alice, {Substrate: bob.address}, 2n);
const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
@@ -387,7 +387,7 @@
await collection.setSponsor(alice, alice.address);
await collection.confirmSponsorship(alice);
-
+
await token.transfer(alice, {Substrate: bob.address}, 2n);
const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
@@ -408,17 +408,17 @@
[alice] = await helper.arrange.createAccounts([10n], donor);
});
});
-
+
itSub('Effective collection limits', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {});
- await collection.setLimits(alice, {ownerCanTransfer: true});
-
- {
+ await collection.setLimits(alice, {ownerCanTransfer: true});
+
+ {
// Check that limits are undefined
const collectionInfo = await collection.getData();
const limits = collectionInfo?.raw.limits;
expect(limits).to.be.any;
-
+
expect(limits.accountTokenOwnershipLimit).to.be.null;
expect(limits.sponsoredDataSize).to.be.null;
expect(limits.sponsoredDataRateLimit).to.be.null;
@@ -449,7 +449,7 @@
expect(limits.transfersEnabled).to.be.true;
}
- {
+ {
// Check the values for collection limits
await collection.setLimits(alice, {
accountTokenOwnershipLimit: 99_999,
tests/src/nesting/collectionProperties.seqtest.tsdiffbeforeafterboth--- a/tests/src/nesting/collectionProperties.seqtest.ts
+++ b/tests/src/nesting/collectionProperties.seqtest.ts
@@ -20,7 +20,7 @@
describe('Integration Test: Collection Properties with sudo', () => {
let superuser: IKeyringPair;
let alice: IKeyringPair;
-
+
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
superuser = await privateKey('//Alice');
@@ -32,7 +32,7 @@
[
{mode: 'nft' as const, requiredPallets: []},
{mode: 'ft' as const, requiredPallets: []},
- {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
].map(testSuite => describe(`${testSuite.mode.toUpperCase()}`, () => {
before(async function() {
// eslint-disable-next-line require-await
tests/src/nesting/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/collectionProperties.test.ts
+++ b/tests/src/nesting/collectionProperties.test.ts
@@ -20,14 +20,14 @@
describe('Integration Test: Collection Properties', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
-
+
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({filename: __filename});
[alice, bob] = await helper.arrange.createAccounts([200n, 10n], donor);
});
});
-
+
itSub('Properties are initially empty', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice);
expect(await collection.getProperties()).to.be.empty;
@@ -36,7 +36,7 @@
[
{mode: 'nft' as const, requiredPallets: []},
{mode: 'ft' as const, requiredPallets: []},
- {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
].map(testSuite => describe(`${testSuite.mode.toUpperCase()}`, () => {
before(async function() {
// eslint-disable-next-line require-await
@@ -50,37 +50,37 @@
// As owner
await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;
-
+
await collection.addAdmin(alice, {Substrate: bob.address});
-
+
// As administrator
await expect(collection.setProperties(bob, [{key: 'black_hole'}])).to.be.fulfilled;
-
+
const properties = await collection.getProperties();
expect(properties).to.include.deep.members([
{key: 'electron', value: 'come bond'},
{key: 'black_hole', value: ''},
]);
});
-
+
itSub('Check valid names for collection properties keys', async ({helper}) => {
const collection = await helper[testSuite.mode].mintCollection(alice);
// alpha symbols
await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;
-
+
// numeric symbols
await expect(collection.setProperties(alice, [{key: '451'}])).to.be.fulfilled;
-
+
// underscore symbol
await expect(collection.setProperties(alice, [{key: 'black_hole'}])).to.be.fulfilled;
-
+
// dash symbol
await expect(collection.setProperties(alice, [{key: '-'}])).to.be.fulfilled;
-
+
// dot symbol
await expect(collection.setProperties(alice, [{key: 'once.in.a.long.long.while...', value: 'you get a little lost'}])).to.be.fulfilled;
-
+
const properties = await collection.getProperties();
expect(properties).to.include.deep.members([
{key: 'answer', value: ''},
@@ -90,29 +90,29 @@
{key: 'once.in.a.long.long.while...', value: 'you get a little lost'},
]);
});
-
+
itSub('Changes properties of a collection', async ({helper}) => {
const collection = await helper[testSuite.mode].mintCollection(alice);
await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;
-
+
// Mutate the properties
await expect(collection.setProperties(alice, [{key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
-
+
const properties = await collection.getProperties();
expect(properties).to.include.deep.members([
{key: 'electron', value: 'come bond'},
{key: 'black_hole', value: 'LIGO'},
]);
});
-
+
itSub('Deletes properties of a collection', async ({helper}) => {
const collection = await helper[testSuite.mode].mintCollection(alice);
await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
-
+
await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;
-
+
const properties = await collection.getProperties(['black_hole', 'electron']);
expect(properties).to.be.deep.equal([
{key: 'black_hole', value: 'LIGO'},
@@ -201,11 +201,11 @@
});
}));
});
-
+
describe('Negative Integration Test: Collection Properties', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
-
+
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({filename: __filename});
@@ -216,7 +216,7 @@
[
{mode: 'nft' as const, requiredPallets: []},
{mode: 'ft' as const, requiredPallets: []},
- {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
].map(testSuite => describe(`${testSuite.mode.toUpperCase()}`, () => {
before(async function() {
// eslint-disable-next-line require-await
@@ -224,21 +224,21 @@
requirePalletsOrSkip(this, helper, testSuite.requiredPallets);
});
});
-
+
itSub('Fails to set properties in a collection if not its onwer/administrator', async ({helper}) => {
const collection = await helper[testSuite.mode].mintCollection(alice);
await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))
.to.be.rejectedWith(/common\.NoPermission/);
-
+
expect(await collection.getProperties()).to.be.empty;
});
-
+
itSub('Fails to set properties that exceed the limits', async ({helper}) => {
const collection = await helper[testSuite.mode].mintCollection(alice);
const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();
-
+
// Mute the general tx parsing error, too many bytes to process
{
console.error = () => {};
@@ -246,17 +246,17 @@
{key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))},
])).to.be.rejected;
}
-
+
expect(await collection.getProperties(['electron'])).to.be.empty;
-
+
await expect(collection.setProperties(alice, [
- {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))},
- {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))},
+ {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))},
+ {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))},
])).to.be.rejectedWith(/common\.NoSpaceForProperty/);
-
+
expect(await collection.getProperties(['electron', 'black_hole'])).to.be.empty;
});
-
+
itSub('Fails to set more properties than it is allowed', async ({helper}) => {
const collection = await helper[testSuite.mode].mintCollection(alice);
@@ -267,10 +267,10 @@
value: Math.random() > 0.5 ? 'high' : 'low',
});
}
-
+
await expect(collection.setProperties(alice, propertiesToBeSet)).
to.be.rejectedWith(/common\.PropertyLimitReached/);
-
+
expect(await collection.getProperties()).to.be.empty;
});
@@ -282,34 +282,34 @@
[{key: 'Mr/Sandman', value: 'Bring me a gene'}],
[{key: 'déjà vu', value: 'hmm...'}],
];
-
+
for (let i = 0; i < invalidProperties.length; i++) {
await expect(
- collection.setProperties(alice, invalidProperties[i]),
+ collection.setProperties(alice, invalidProperties[i]),
`on rejecting the new badly-named property #${i}`,
).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
}
-
+
await expect(
- collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]),
+ collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]),
'on rejecting an unnamed property',
).to.be.rejectedWith(/common\.EmptyPropertyKey/);
-
+
await expect(
- collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]),
+ collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]),
'on setting the correctly-but-still-badly-named property',
).to.be.fulfilled;
-
+
const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');
-
+
const properties = await collection.getProperties(keys);
expect(properties).to.be.deep.equal([
{key: 'CRISPR-Cas9', value: 'rewriting nature!'},
]);
-
+
for (let i = 0; i < invalidProperties.length; i++) {
await expect(
- collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)),
+ collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)),
`on trying to delete the non-existent badly-named property #${i}`,
).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
}
@@ -326,4 +326,3 @@
});
}));
});
-
\ No newline at end of file
tests/src/nesting/graphs.test.tsdiffbeforeafterboth--- a/tests/src/nesting/graphs.test.ts
+++ b/tests/src/nesting/graphs.test.ts
@@ -56,7 +56,7 @@
// to self
await expect(
tokens[0].nest(alice, tokens[0]),
- 'first transaction',
+ 'first transaction',
).to.be.rejectedWith(/structure\.OuroborosDetected/);
// to nested part of graph
await expect(
tests/src/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -36,7 +36,7 @@
const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());
expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
-
+
// Create a token to be nested
const newToken = await collection.mintToken(alice);
@@ -66,7 +66,7 @@
// Create a nested token
const tokenC = await collection.mintToken(alice, tokenA.nestingAccount());
expect(await tokenC.getOwner()).to.be.deep.equal(tokenA.nestingAccount().toLowerCase());
-
+
// Transfer the nested token to another token
await expect(tokenC.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount())).to.be.fulfilled;
expect(await tokenC.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
@@ -76,7 +76,7 @@
itSub('Checks token children', async ({helper}) => {
const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
const collectionB = await helper.ft.mintCollection(alice);
-
+
const targetToken = await collectionA.mintToken(alice);
expect((await targetToken.getChildren()).length).to.be.equal(0, 'Children length check at creation');
@@ -108,7 +108,7 @@
{tokenId: 0, collectionId: collectionB.collectionId},
], 'Children contents check at nesting #4 (from another collection)')
.and.be.length(2, 'Children length check at nesting #4 (from another collection)');
-
+
// Move part of the fungible token inside token A deeper in the nesting tree
await collectionB.transferFrom(alice, targetToken.nestingAccount(), tokenA.nestingAccount(), 1n);
expect(await targetToken.getChildren()).to.be.have.deep.members([
tests/src/nesting/propertyPermissions.test.tsdiffbeforeafterboth--- a/tests/src/nesting/propertyPermissions.test.ts
+++ b/tests/src/nesting/propertyPermissions.test.ts
@@ -21,94 +21,94 @@
describe('Integration Test: Access Rights to Token Properties', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
-
+
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({filename: __filename});
[alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
});
});
-
+
itSub('Reads access rights to properties of a collection', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice);
const propertyRights = (await helper.callRpc('api.query.common.collectionPropertyPermissions', [collection.collectionId])).toJSON();
expect(propertyRights).to.be.empty;
});
-
- async function testSetsAccessRightsToProperties(collection: UniqueNFTCollection | UniqueRFTCollection) {
+
+ async function testSetsAccessRightsToProperties(collection: UniqueNFTCollection | UniqueRFTCollection) {
await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: true}}]))
.to.be.fulfilled;
-
+
await collection.addAdmin(alice, {Substrate: bob.address});
-
+
await expect(collection.setTokenPropertyPermissions(bob, [{key: 'mindgame', permission: {collectionAdmin: true, tokenOwner: false}}]))
.to.be.fulfilled;
-
+
const propertyRights = await collection.getPropertyPermissions(['skullduggery', 'mindgame']);
expect(propertyRights).to.include.deep.members([
{key: 'skullduggery', permission: {mutable: true, collectionAdmin: false, tokenOwner: false}},
{key: 'mindgame', permission: {mutable: false, collectionAdmin: true, tokenOwner: false}},
]);
}
-
+
itSub('Sets access rights to properties of a collection (NFT)', async ({helper}) => {
await testSetsAccessRightsToProperties(await helper.nft.mintCollection(alice));
});
-
+
itSub.ifWithPallets('Sets access rights to properties of a collection (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
await testSetsAccessRightsToProperties(await helper.rft.mintCollection(alice));
});
-
+
async function testChangesAccessRightsToProperty(collection: UniqueNFTCollection | UniqueRFTCollection) {
await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: true, collectionAdmin: true}}]))
.to.be.fulfilled;
-
+
await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]))
.to.be.fulfilled;
-
+
const propertyRights = await collection.getPropertyPermissions();
expect(propertyRights).to.be.deep.equal([
{key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},
]);
}
-
+
itSub('Changes access rights to properties of a NFT collection', async ({helper}) => {
await testChangesAccessRightsToProperty(await helper.nft.mintCollection(alice));
});
-
+
itSub.ifWithPallets('Changes access rights to properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
await testChangesAccessRightsToProperty(await helper.rft.mintCollection(alice));
});
});
-
+
describe('Negative Integration Test: Access Rights to Token Properties', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
-
+
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({filename: __filename});
[alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);
});
});
-
+
async function testPreventsFromSettingAccessRightsNotAdminOrOwner(collection: UniqueNFTCollection | UniqueRFTCollection) {
await expect(collection.setTokenPropertyPermissions(bob, [{key: 'skullduggery', permission: {mutable: true, tokenOwner: true}}]))
.to.be.rejectedWith(/common\.NoPermission/);
-
+
const propertyRights = await collection.getPropertyPermissions(['skullduggery']);
expect(propertyRights).to.be.empty;
}
-
+
itSub('Prevents from setting access rights to properties of a NFT collection if not an onwer/admin', async ({helper}) => {
await testPreventsFromSettingAccessRightsNotAdminOrOwner(await helper.nft.mintCollection(alice));
});
-
+
itSub.ifWithPallets('Prevents from setting access rights to properties of a ReFungible collection if not an onwer/admin', [Pallets.ReFungible], async ({helper}) => {
await testPreventsFromSettingAccessRightsNotAdminOrOwner(await helper.rft.mintCollection(alice));
});
-
- async function testPreventFromAddingTooManyPossibleProperties(collection: UniqueNFTCollection | UniqueRFTCollection) {
+
+ async function testPreventFromAddingTooManyPossibleProperties(collection: UniqueNFTCollection | UniqueRFTCollection) {
const constitution = [];
for (let i = 0; i < 65; i++) {
constitution.push({
@@ -116,82 +116,82 @@
permission: Math.random() > 0.5 ? {mutable: true, collectionAdmin: true, tokenOwner: true} : {},
});
}
-
+
await expect(collection.setTokenPropertyPermissions(alice, constitution))
.to.be.rejectedWith(/common\.PropertyLimitReached/);
-
+
const propertyRights = await collection.getPropertyPermissions();
expect(propertyRights).to.be.empty;
}
-
+
itSub('Prevents from adding too many possible properties (NFT)', async ({helper}) => {
await testPreventFromAddingTooManyPossibleProperties(await helper.nft.mintCollection(alice));
});
-
+
itSub.ifWithPallets('Prevents from adding too many possible properties (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
await testPreventFromAddingTooManyPossibleProperties(await helper.rft.mintCollection(alice));
});
-
+
async function testPreventAccessRightsModifiedIfConstant(collection: UniqueNFTCollection | UniqueRFTCollection) {
await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]))
.to.be.fulfilled;
-
+
await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {collectionAdmin: true}}]))
.to.be.rejectedWith(/common\.NoPermission/);
-
+
const propertyRights = await collection.getPropertyPermissions(['skullduggery']);
expect(propertyRights).to.deep.equal([
{key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},
]);
}
-
+
itSub('Prevents access rights to be modified if constant (NFT)', async ({helper}) => {
await testPreventAccessRightsModifiedIfConstant(await helper.nft.mintCollection(alice));
});
-
+
itSub.ifWithPallets('Prevents access rights to be modified if constant (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
await testPreventAccessRightsModifiedIfConstant(await helper.rft.mintCollection(alice));
});
-
+
async function testPreventsAddingPropertiesWithInvalidNames(collection: UniqueNFTCollection | UniqueRFTCollection) {
const invalidProperties = [
[{key: 'skullduggery', permission: {tokenOwner: true}}, {key: 'im possible', permission: {collectionAdmin: true}}],
[{key: 'G#4', permission: {tokenOwner: true}}],
[{key: 'HÆMILTON', permission: {mutable: false, collectionAdmin: true, tokenOwner: true}}],
];
-
+
for (let i = 0; i < invalidProperties.length; i++) {
await expect(
- collection.setTokenPropertyPermissions(alice, invalidProperties[i]),
+ collection.setTokenPropertyPermissions(alice, invalidProperties[i]),
`on setting the new badly-named property #${i}`,
).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
}
-
+
await expect(
- collection.setTokenPropertyPermissions(alice, [{key: '', permission: {}}]),
+ collection.setTokenPropertyPermissions(alice, [{key: '', permission: {}}]),
'on rejecting an unnamed property',
).to.be.rejectedWith(/common\.EmptyPropertyKey/);
-
+
const correctKey = '--0x03116e387820CA05'; // PolkadotJS would parse this as an already encoded hex-string
await expect(
collection.setTokenPropertyPermissions(alice, [
{key: correctKey, permission: {collectionAdmin: true}},
- ]),
+ ]),
'on setting the correctly-but-still-badly-named property',
).to.be.fulfilled;
-
+
const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat(correctKey).concat('');
-
+
const propertyRights = await collection.getPropertyPermissions(keys);
expect(propertyRights).to.be.deep.equal([
{key: correctKey, permission: {mutable: false, collectionAdmin: true, tokenOwner: false}},
]);
}
-
+
itSub('Prevents adding properties with invalid names (NFT)', async ({helper}) => {
await testPreventsAddingPropertiesWithInvalidNames(await helper.nft.mintCollection(alice));
});
-
+
itSub.ifWithPallets('Prevents adding properties with invalid names (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
await testPreventsAddingPropertiesWithInvalidNames(await helper.rft.mintCollection(alice));
});
tests/src/nesting/tokenProperties.seqtest.tsdiffbeforeafterboth--- a/tests/src/nesting/tokenProperties.seqtest.ts
+++ b/tests/src/nesting/tokenProperties.seqtest.ts
@@ -31,7 +31,7 @@
[
{mode: 'nft' as const, pieces: undefined, requiredPallets: []},
- {mode: 'rft' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
+ {mode: 'rft' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
].map(testSuite => describe(`${testSuite.mode.toUpperCase()}`, () => {
before(async function() {
// eslint-disable-next-line require-await
@@ -39,7 +39,7 @@
requirePalletsOrSkip(this, helper, testSuite.requiredPallets);
});
});
-
+
itSub('force_repair_item preserves valid consumed space', async({helper}) => {
const propKey = 'tok-prop';
tests/src/nesting/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/tokenProperties.test.ts
+++ b/tests/src/nesting/tokenProperties.test.ts
@@ -43,12 +43,12 @@
async function mintCollectionWithAllPermissionsAndToken(helper: UniqueHelper, mode: 'NFT' | 'RFT'): Promise<[UniqueNFToken | UniqueRFToken, bigint]> {
const collection = await (mode == 'NFT' ? helper.nft : helper.rft).mintCollection(alice, {
- tokenPropertyPermissions: permissions.flatMap(({permission, signers}, i) =>
+ tokenPropertyPermissions: permissions.flatMap(({permission, signers}, i) =>
signers.map(signer => {return {key: `${i+1}_${signer.address}`, permission};})),
});
return mode == 'NFT' ? [await collection.mintToken(alice), 1n] : [await collection.mintToken(alice, 100n), 100n];
}
-
+
async function testReadsYetEmptyProperties(token: UniqueNFToken | UniqueRFToken) {
const properties = await token.getProperties();
expect(properties).to.be.empty;
@@ -84,7 +84,7 @@
propertyKeys.push(key);
await expect(
- token.setProperties(signer, [{key: key, value: 'Serotonin increase'}]),
+ token.setProperties(signer, [{key: key, value: 'Serotonin increase'}]),
`on adding property #${i} by signer #${j}`,
).to.be.fulfilled;
}
@@ -117,7 +117,7 @@
for (const permission of permissions) {
i++;
if (!permission.permission.mutable) continue;
-
+
let j = 0;
for (const signer of permission.signers) {
j++;
@@ -125,12 +125,12 @@
propertyKeys.push(key);
await expect(
- token.setProperties(signer, [{key, value: 'Serotonin increase'}]),
+ token.setProperties(signer, [{key, value: 'Serotonin increase'}]),
`on adding property #${i} by signer #${j}`,
).to.be.fulfilled;
await expect(
- token.setProperties(signer, [{key, value: 'Serotonin stable'}]),
+ token.setProperties(signer, [{key, value: 'Serotonin stable'}]),
`on changing property #${i} by signer #${j}`,
).to.be.fulfilled;
}
@@ -164,7 +164,7 @@
for (const permission of permissions) {
i++;
if (!permission.permission.mutable) continue;
-
+
let j = 0;
for (const signer of permission.signers) {
j++;
@@ -172,12 +172,12 @@
propertyKeys.push(key);
await expect(
- token.setProperties(signer, [{key, value: 'Serotonin increase'}]),
+ token.setProperties(signer, [{key, value: 'Serotonin increase'}]),
`on adding property #${i} by signer #${j}`,
).to.be.fulfilled;
await expect(
- token.deleteProperties(signer, [key]),
+ token.deleteProperties(signer, [key]),
`on deleting property #${i} by signer #${j}`,
).to.be.fulfilled;
}
@@ -186,7 +186,7 @@
expect(await token.getProperties(propertyKeys)).to.be.empty;
expect((await token.getData())!.properties).to.be.empty;
}
-
+
itSub('Deletes properties of a token according to permissions (NFT)', async ({helper}) => {
const [token, amount] = await mintCollectionWithAllPermissionsAndToken(helper, 'NFT');
await testDeletePropertiesAccordingPermission(token, amount);
@@ -200,7 +200,7 @@
itSub('Assigns properties to a nested token according to permissions', async ({helper}) => {
const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
const collectionB = await helper.nft.mintCollection(alice, {
- tokenPropertyPermissions: permissions.flatMap(({permission, signers}, i) =>
+ tokenPropertyPermissions: permissions.flatMap(({permission, signers}, i) =>
signers.map(signer => {return {key: `${i+1}_${signer.address}`, permission};})),
});
const targetToken = await collectionA.mintToken(alice);
@@ -220,7 +220,7 @@
propertyKeys.push(key);
await expect(
- nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]),
+ nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]),
`on adding property #${i} by signer #${j}`,
).to.be.fulfilled;
}
@@ -238,7 +238,7 @@
itSub('Changes properties of a nested token according to permissions', async ({helper}) => {
const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
const collectionB = await helper.nft.mintCollection(alice, {
- tokenPropertyPermissions: permissions.flatMap(({permission, signers}, i) =>
+ tokenPropertyPermissions: permissions.flatMap(({permission, signers}, i) =>
signers.map(signer => {return {key: `${i+1}_${signer.address}`, permission};})),
});
const targetToken = await collectionA.mintToken(alice);
@@ -252,7 +252,7 @@
for (const permission of permissions) {
i++;
if (!permission.permission.mutable) continue;
-
+
let j = 0;
for (const signer of permission.signers) {
j++;
@@ -260,12 +260,12 @@
propertyKeys.push(key);
await expect(
- nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]),
+ nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]),
`on adding property #${i} by signer #${j}`,
).to.be.fulfilled;
await expect(
- nestedToken.setProperties(signer, [{key, value: 'Serotonin stable'}]),
+ nestedToken.setProperties(signer, [{key, value: 'Serotonin stable'}]),
`on changing property #${i} by signer #${j}`,
).to.be.fulfilled;
}
@@ -283,7 +283,7 @@
itSub('Deletes properties of a nested token according to permissions', async ({helper}) => {
const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
const collectionB = await helper.nft.mintCollection(alice, {
- tokenPropertyPermissions: permissions.flatMap(({permission, signers}, i) =>
+ tokenPropertyPermissions: permissions.flatMap(({permission, signers}, i) =>
signers.map(signer => {return {key: `${i+1}_${signer.address}`, permission};})),
});
const targetToken = await collectionA.mintToken(alice);
@@ -297,7 +297,7 @@
for (const permission of permissions) {
i++;
if (!permission.permission.mutable) continue;
-
+
let j = 0;
for (const signer of permission.signers) {
j++;
@@ -305,12 +305,12 @@
propertyKeys.push(key);
await expect(
- nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]),
+ nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]),
`on adding property #${i} by signer #${j}`,
).to.be.fulfilled;
await expect(
- nestedToken.deleteProperties(signer, [key]),
+ nestedToken.deleteProperties(signer, [key]),
`on deleting property #${i} by signer #${j}`,
).to.be.fulfilled;
}
@@ -323,7 +323,7 @@
[
{mode: 'nft' as const, storage: 'nonfungible' as const, pieces: undefined, requiredPallets: []},
- {mode: 'rft' as const, storage: 'refungible' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
+ {mode: 'rft' as const, storage: 'refungible' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
].map(testCase =>
itSub.ifWithPallets(`Allows modifying a token property multiple times with the same size (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
const propKey = 'tok-prop';
@@ -370,7 +370,7 @@
[
{mode: 'nft' as const, pieces: undefined, requiredPallets: []},
- {mode: 'rft' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
+ {mode: 'rft' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
].map(testCase =>
itSub.ifWithPallets(`Adding then removing a token property doesn't change the consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
const propKey = 'tok-prop';
@@ -404,7 +404,7 @@
[
{mode: 'nft' as const, pieces: undefined, requiredPallets: []},
- {mode: 'rft' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
+ {mode: 'rft' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
].map(testCase =>
itSub.ifWithPallets(`Modifying a token property with different sizes correctly changes the consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
const propKey = 'tok-prop';
@@ -497,12 +497,12 @@
i++;
const signer = passage.signers[0];
await expect(
- token.setProperties(signer, [{key: `${i}`, value: 'Serotonin increase'}]),
+ token.setProperties(signer, [{key: `${i}`, value: 'Serotonin increase'}]),
`on adding property ${i} by ${signer.address}`,
).to.be.fulfilled;
}
- const originalSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const originalSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
return originalSpace;
}
@@ -515,17 +515,17 @@
if (!forbiddance.permission.mutable) continue;
await expect(
- token.setProperties(forbiddance.sinner, [{key: `${i}`, value: 'Serotonin down'}]),
+ token.setProperties(forbiddance.sinner, [{key: `${i}`, value: 'Serotonin down'}]),
`on failing to change property ${i} by the malefactor`,
).to.be.rejectedWith(/common\.NoPermission/);
await expect(
- token.deleteProperties(forbiddance.sinner, [`${i}`]),
+ token.deleteProperties(forbiddance.sinner, [`${i}`]),
`on failing to delete property ${i} by the malefactor`,
).to.be.rejectedWith(/common\.NoPermission/);
}
- const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
@@ -548,17 +548,17 @@
if (permission.permission.mutable) continue;
await expect(
- token.setProperties(permission.signers[0], [{key: `${i}`, value: 'Serotonin down'}]),
+ token.setProperties(permission.signers[0], [{key: `${i}`, value: 'Serotonin down'}]),
`on failing to change property ${i} by signer #0`,
).to.be.rejectedWith(/common\.NoPermission/);
await expect(
- token.deleteProperties(permission.signers[0], [i.toString()]),
+ token.deleteProperties(permission.signers[0], [i.toString()]),
`on failing to delete property ${i} by signer #0`,
).to.be.rejectedWith(/common\.NoPermission/);
}
-
- const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
@@ -576,23 +576,23 @@
const originalSpace = await prepare(token, pieces);
await expect(
- token.setProperties(alice, [{key: 'non-existent', value: 'I exist!'}]),
+ token.setProperties(alice, [{key: 'non-existent', value: 'I exist!'}]),
'on failing to add a previously non-existent property',
).to.be.rejectedWith(/common\.NoPermission/);
-
+
await expect(
- token.collection.setTokenPropertyPermissions(alice, [{key: 'now-existent', permission: {}}]),
+ token.collection.setTokenPropertyPermissions(alice, [{key: 'now-existent', permission: {}}]),
'on setting a new non-permitted property',
).to.be.fulfilled;
await expect(
- token.setProperties(alice, [{key: 'now-existent', value: 'I exist!'}]),
+ token.setProperties(alice, [{key: 'now-existent', value: 'I exist!'}]),
'on failing to add a property forbidden by the \'None\' permission',
).to.be.rejectedWith(/common\.NoPermission/);
expect(await token.getProperties(['non-existent', 'now-existent'])).to.be.empty;
-
- const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
@@ -611,9 +611,9 @@
await expect(
token.collection.setTokenPropertyPermissions(alice, [
- {key: 'a_holy_book', permission: {collectionAdmin: true, tokenOwner: true}},
+ {key: 'a_holy_book', permission: {collectionAdmin: true, tokenOwner: true}},
{key: 'young_years', permission: {collectionAdmin: true, tokenOwner: true}},
- ]),
+ ]),
'on setting new permissions for properties',
).to.be.fulfilled;
@@ -625,12 +625,12 @@
}
await expect(token.setProperties(alice, [
- {key: 'a_holy_book', value: 'word '.repeat(3277)},
+ {key: 'a_holy_book', value: 'word '.repeat(3277)},
{key: 'young_years', value: 'neverending'.repeat(1490)},
])).to.be.rejectedWith(/common\.NoSpaceForProperty/);
-
+
expect(await token.getProperties(['a_holy_book', 'young_years'])).to.be.empty;
- const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
@@ -646,7 +646,7 @@
[
{mode: 'nft' as const, requiredPallets: []},
- {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
].map(testCase =>
itSub.ifWithPallets(`Forbids adding too many propeties to a token (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
const collection = await helper[testCase.mode].mintCollection(alice);
@@ -667,7 +667,7 @@
[
{mode: 'nft' as const, pieces: undefined, requiredPallets: []},
- {mode: 'rft' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
+ {mode: 'rft' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
].map(testCase =>
itSub.ifWithPallets(`Forbids force_repair_item from non-sudo (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
const propKey = 'tok-prop';
@@ -712,10 +712,10 @@
async function prepare(helper: UniqueHelper): Promise<UniqueRFToken> {
const collection = await helper.rft.mintCollection(alice);
const token = await collection.mintToken(alice, 100n);
-
+
await collection.addAdmin(alice, {Substrate: bob.address});
await collection.setTokenPropertyPermissions(alice, [{key: 'fractals', permission: {mutable: true, tokenOwner: true}}]);
-
+
return token;
}
@@ -725,7 +725,7 @@
await token.transfer(alice, {Substrate: charlie.address}, 33n);
await expect(token.setProperties(alice, [
- {key: 'fractals', value: 'multiverse'},
+ {key: 'fractals', value: 'multiverse'},
])).to.be.rejectedWith(/common\.NoPermission/);
});
@@ -736,13 +736,13 @@
.to.be.fulfilled;
await expect(token.setProperties(alice, [
- {key: 'fractals', value: 'multiverse'},
+ {key: 'fractals', value: 'multiverse'},
])).to.be.fulfilled;
await token.transfer(alice, {Substrate: charlie.address}, 33n);
await expect(token.setProperties(alice, [
- {key: 'fractals', value: 'want to rule the world'},
+ {key: 'fractals', value: 'want to rule the world'},
])).to.be.rejectedWith(/common\.NoPermission/);
});
@@ -750,7 +750,7 @@
const token = await prepare(helper);
await expect(token.setProperties(alice, [
- {key: 'fractals', value: 'one headline - why believe it'},
+ {key: 'fractals', value: 'one headline - why believe it'},
])).to.be.fulfilled;
await token.transfer(alice, {Substrate: charlie.address}, 33n);
@@ -768,7 +768,7 @@
.to.be.fulfilled;
await expect(token.setProperties(alice, [
- {key: 'fractals', value: 'multiverse'},
+ {key: 'fractals', value: 'multiverse'},
])).to.be.fulfilled;
});
});
tests/src/nesting/unnest.test.tsdiffbeforeafterboth--- a/tests/src/nesting/unnest.test.ts
+++ b/tests/src/nesting/unnest.test.ts
@@ -30,7 +30,7 @@
itSub('NFT: allows the owner to successfully unnest a token', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
const targetToken = await collection.mintToken(alice);
-
+
// Create a nested token
const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());
@@ -49,7 +49,7 @@
const targetToken = await collection.mintToken(alice);
const collectionFT = await helper.ft.mintCollection(alice);
-
+
// Nest and unnest
await collectionFT.mint(alice, 10n, targetToken.nestingAccount());
await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 9n), 'while unnesting').to.be.fulfilled;
@@ -69,7 +69,7 @@
const targetToken = await collection.mintToken(alice);
const collectionRFT = await helper.rft.mintCollection(alice);
-
+
// Nest and unnest
const token = await collectionRFT.mintToken(alice, 10n, targetToken.nestingAccount());
await expect(token.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 9n), 'while unnesting').to.be.fulfilled;
tests/src/nextSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/nextSponsoring.test.ts
+++ b/tests/src/nextSponsoring.test.ts
@@ -39,7 +39,7 @@
// Check with Disabled sponsoring state
expect(await token.getNextSponsored({Substrate: alice.address})).to.be.null;
-
+
// Check with Unconfirmed sponsoring state
await collection.setSponsor(alice, bob.address);
expect(await token.getNextSponsored({Substrate: alice.address})).to.be.null;
@@ -52,7 +52,7 @@
await token.transfer(alice, {Substrate: bob.address});
expect(await token.getNextSponsored({Substrate: alice.address})).to.be.lessThanOrEqual(SPONSORING_TIMEOUT);
- // Non-existing token
+ // Non-existing token
expect(await collection.getTokenNextSponsored(0, {Substrate: alice.address})).to.be.null;
});
@@ -65,7 +65,7 @@
await collection.setSponsor(alice, bob.address);
await collection.confirmSponsorship(bob);
-
+
// Check with Confirmed sponsoring state
expect(await collection.getTokenNextSponsored(0, {Substrate: alice.address})).to.be.equal(0);
@@ -91,7 +91,7 @@
await token.transfer(alice, {Substrate: bob.address});
expect(await token.getNextSponsored({Substrate: alice.address})).to.be.lessThanOrEqual(SPONSORING_TIMEOUT);
- // Non-existing token
+ // Non-existing token
expect(await collection.getTokenNextSponsored(0, {Substrate: alice.address})).to.be.null;
});
});
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -32,36 +32,36 @@
[alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
});
});
-
+
itSub('Create refungible collection and token', async ({helper}) => {
const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
const itemCountBefore = await collection.getLastTokenId();
const token = await collection.mintToken(alice, 100n);
-
+
const itemCountAfter = await collection.getLastTokenId();
-
+
// What to expect
expect(token?.tokenId).to.be.gte(itemCountBefore);
expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
expect(itemCountAfter.toString()).to.be.equal(token?.tokenId.toString());
});
-
+
itSub('Checking RPC methods when interacting with maximum allowed values (MAX_REFUNGIBLE_PIECES)', async ({helper}) => {
const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
-
+
const token = await collection.mintToken(alice, MAX_REFUNGIBLE_PIECES);
-
+
expect(await collection.getTokenBalance(token.tokenId, {Substrate: alice.address})).to.be.equal(MAX_REFUNGIBLE_PIECES);
-
+
await collection.transferToken(alice, token.tokenId, {Substrate: bob.address}, MAX_REFUNGIBLE_PIECES);
expect(await collection.getTokenBalance(token.tokenId, {Substrate: bob.address})).to.be.equal(MAX_REFUNGIBLE_PIECES);
expect(await token.getTotalPieces()).to.be.equal(MAX_REFUNGIBLE_PIECES);
-
+
await expect(collection.mintToken(alice, MAX_REFUNGIBLE_PIECES + 1n))
.to.eventually.be.rejectedWith(/refungible\.WrongRefungiblePieces/);
});
-
+
itSub('RPC method tokenOwners for refungible collection and token', async ({helper}) => {
const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
const facelessCrowd = (await helper.arrange.createAccounts(Array(7).fill(0n), donor)).map(keyring => {return {Substrate: keyring.address};});
@@ -72,32 +72,32 @@
await token.transfer(alice, {Substrate: bob.address}, 1000n);
await token.transfer(alice, ethAcc, 900n);
-
+
for (let i = 0; i < 7; i++) {
await token.transfer(alice, facelessCrowd[i], 50n * BigInt(i + 1));
- }
+ }
const owners = await token.getTop10Owners();
// What to expect
expect(owners).to.deep.include.members([{Substrate: alice.address}, ethAcc, {Substrate: bob.address}, ...facelessCrowd]);
expect(owners.length).to.be.equal(10);
-
+
const [eleven] = await helper.arrange.createAccounts([0n], donor);
expect(await token.transfer(alice, {Substrate: eleven.address}, 10n)).to.be.true;
expect((await token.getTop10Owners()).length).to.be.equal(10);
});
-
+
itSub('Transfer token pieces', async ({helper}) => {
const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
const token = await collection.mintToken(alice, 100n);
expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
expect(await token.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;
-
+
expect(await token.getBalance({Substrate: alice.address})).to.be.equal(40n);
expect(await token.getBalance({Substrate: bob.address})).to.be.equal(60n);
-
+
await expect(token.transfer(alice, {Substrate: bob.address}, 41n))
.to.eventually.be.rejectedWith(/common\.TokenValueTooLow/);
});
@@ -111,8 +111,8 @@
// {owner: {Substrate: alice.address}, pieces: 100n},
// ]);
await helper.rft.mintMultipleTokensWithOneOwner(alice, collection.collectionId, {Substrate: alice.address}, [
- {pieces: 1n},
- {pieces: 2n},
+ {pieces: 1n},
+ {pieces: 2n},
{pieces: 100n},
]);
const lastTokenId = await collection.getLastTokenId();
@@ -133,7 +133,7 @@
itSub('Burn all pieces', async ({helper}) => {
const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
const token = await collection.mintToken(alice, 100n);
-
+
expect(await collection.doesTokenExist(token.tokenId)).to.be.true;
expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
@@ -146,7 +146,7 @@
const token = await collection.mintToken(alice, 100n);
expect(await collection.doesTokenExist(token.tokenId)).to.be.true;
-
+
expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
expect(await token.transfer(alice, {Substrate: bob.address}, 60n)).to.be.true;
@@ -171,7 +171,7 @@
itSub('Set allowance for token', async ({helper}) => {
const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
const token = await collection.mintToken(alice, 100n);
-
+
expect(await token.getBalance({Substrate: alice.address})).to.be.equal(100n);
expect(await token.approve(alice, {Substrate: bob.address}, 60n)).to.be.true;
@@ -190,14 +190,14 @@
expect(await token.repartition(alice, 200n)).to.be.true;
expect(await token.getBalance({Substrate: alice.address})).to.be.equal(200n);
expect(await token.getTotalPieces()).to.be.equal(200n);
-
+
expect(await token.transfer(alice, {Substrate: bob.address}, 110n)).to.be.true;
expect(await token.getBalance({Substrate: alice.address})).to.be.equal(90n);
expect(await token.getBalance({Substrate: bob.address})).to.be.equal(110n);
-
+
await expect(token.repartition(alice, 80n))
.to.eventually.be.rejectedWith(/refungible\.RepartitionWhileNotOwningAllPieces/);
-
+
expect(await token.transfer(alice, {Substrate: bob.address}, 90n)).to.be.true;
expect(await token.getBalance({Substrate: alice.address})).to.be.equal(0n);
expect(await token.getBalance({Substrate: bob.address})).to.be.equal(200n);
@@ -220,7 +220,7 @@
data: [
collection.collectionId,
token.tokenId,
- {substrate: alice.address},
+ {substrate: alice.address},
100n,
],
});
@@ -239,12 +239,12 @@
data: [
collection.collectionId,
token.tokenId,
- {substrate: alice.address},
+ {substrate: alice.address},
50n,
],
});
});
-
+
itSub('Create new collection with properties', async ({helper}) => {
const properties = [{key: 'key1', value: 'val1'}];
const tokenPropertyPermissions = [{key: 'key1', permission: {tokenOwner: true, mutable: false, collectionAdmin: true}}];
@@ -280,7 +280,7 @@
await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 10n)).to.be.rejectedWith('common.TokenValueTooLow');
await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 100n)).to.be.rejectedWith('common.TokenValueTooLow');
-
+
// 2. Alice cannot transfer non-existing token:
await expect(collection.transferToken(alice, 100, {Substrate: charlie.address}, 0n)).to.be.rejectedWith('common.TokenValueTooLow');
await expect(collection.transferToken(alice, 100, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
tests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionAdmin.test.ts
+++ b/tests/src/removeCollectionAdmin.test.ts
@@ -94,7 +94,7 @@
itSub('Admin can\'t remove collection admin.', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionAdmin-Neg-4', tokenPrefix: 'RCA'});
-
+
await collection.addAdmin(alice, {Substrate: bob.address});
await collection.addAdmin(alice, {Substrate: charlie.address});
tests/src/rpc.test.tsdiffbeforeafterboth--- a/tests/src/rpc.test.ts
+++ b/tests/src/rpc.test.ts
@@ -35,20 +35,20 @@
const owner = (await helper.callRpc('api.rpc.unique.tokenOwner', [collection.collectionId, 0])).toJSON() as any;
expect(owner).to.be.null;
});
-
+
itSub('RPC method tokenOwners for fungible collection and token', async ({helper}) => {
// Set-up a few token owners of all stripes
const ethAcc = {Ethereum: '0x67fb3503a61b284dc83fa96dceec4192db47dc7c'};
const facelessCrowd = (await helper.arrange.createAccounts([0n, 0n, 0n, 0n, 0n, 0n, 0n], donor))
.map(i => {return {Substrate: i.address};});
-
+
const collection = await helper.ft.mintCollection(alice, {name: 'RPC-2', tokenPrefix: 'RPC'});
// mint some maximum (u128) amounts of tokens possible
await collection.mint(alice, (1n << 128n) - 1n);
-
+
await collection.transfer(alice, {Substrate: bob.address}, 1000n);
await collection.transfer(alice, ethAcc, 900n);
-
+
for (let i = 0; i < facelessCrowd.length; i++) {
await collection.transfer(alice, facelessCrowd[i], 1n);
}
@@ -59,7 +59,7 @@
expect(ids).to.deep.include.members([{Substrate: alice.address}, ethAcc, {Substrate: bob.address}, ...facelessCrowd]);
expect(owners.length == 10).to.be.true;
-
+
// Make sure only 10 results are returned with this RPC
const [eleven] = await helper.arrange.createAccounts([0n], donor);
expect(await collection.transfer(alice, {Substrate: eleven.address}, 10n)).to.be.true;
tests/src/scheduler.seqtest.tsdiffbeforeafterboth--- a/tests/src/scheduler.seqtest.ts
+++ b/tests/src/scheduler.seqtest.ts
@@ -47,7 +47,7 @@
const token = await collection.mintToken(alice);
const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
const blocksBeforeExecution = 4;
-
+
await token.scheduleAfter(blocksBeforeExecution, {scheduledId})
.transfer(alice, {Substrate: bob.address});
const executionBlock = await helper.chain.getLatestBlockNumber() + blocksBeforeExecution + 1;
@@ -156,7 +156,7 @@
const maxScheduledPerBlock = 50;
let fillScheduledIds = new Array(maxScheduledPerBlock);
let extraScheduledId = undefined;
-
+
if (scheduleKind == 'named') {
const scheduledIds = helper.arrange.makeScheduledIds(maxScheduledPerBlock + 1);
fillScheduledIds = scheduledIds.slice(0, maxScheduledPerBlock);
@@ -641,7 +641,7 @@
const balanceBefore = await helper.balance.getSubstrate(bob.address);
const scheduled = helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId, priority: 42});
-
+
await expect(scheduled.balance.transferToSubstrate(alice, bob.address, amount))
.to.be.rejectedWith(/BadOrigin/);
tests/src/setCollectionLimits.test.tsdiffbeforeafterboth--- a/tests/src/setCollectionLimits.test.ts
+++ b/tests/src/setCollectionLimits.test.ts
@@ -75,7 +75,7 @@
await collection.setLimits(alice, collectionLimits);
const collectionInfo1 = await collection.getEffectiveLimits();
-
+
expect(collectionInfo1.tokenLimit).to.be.equal(tokenLimit);
await collection.setLimits(alice, collectionLimits);
@@ -108,7 +108,7 @@
[alice, bob] = await helper.arrange.createAccounts([20n, 10n], donor);
});
});
-
+
itSub('execute setCollectionLimits for not exists collection', async ({helper}) => {
const nonExistentCollectionId = (1 << 32) - 1;
await expect(helper.collection.setLimits(
@@ -180,7 +180,7 @@
itSub('Setting the higher token limit fails', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionLimits-Neg-4', tokenPrefix: 'SCL'});
-
+
const collectionLimits = {
accountTokenOwnershipLimit: accountTokenOwnershipLimit,
sponsoredMintSize: sponsoredDataSize,
tests/src/setCollectionSponsor.test.tsdiffbeforeafterboth--- a/tests/src/setCollectionSponsor.test.ts
+++ b/tests/src/setCollectionSponsor.test.ts
@@ -37,7 +37,7 @@
Unconfirmed: bob.address,
});
});
-
+
itSub('Set Fungible collection sponsor', async ({helper}) => {
const collection = await helper.ft.mintCollection(alice, {name: 'SetCollectionSponsor-1-FT', tokenPrefix: 'SCS'});
await expect(collection.setSponsor(alice, bob.address)).to.be.not.rejected;
@@ -75,7 +75,7 @@
Unconfirmed: charlie.address,
});
});
-
+
itSub('Collection admin add sponsor', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {name: 'SetCollectionSponsor-4', tokenPrefix: 'SCS'});
await collection.addAdmin(alice, {Substrate: bob.address});
tests/src/setPermissions.test.tsdiffbeforeafterboth--- a/tests/src/setPermissions.test.ts
+++ b/tests/src/setPermissions.test.ts
@@ -34,11 +34,11 @@
await collection.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true, restricted: [1, 2]}});
await collection.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true, restricted: [1, 2]}});
-
+
const permissions = (await collection.getData())?.raw.permissions;
expect(permissions).to.be.deep.equal({
- access: 'AllowList',
- mintMode: true,
+ access: 'AllowList',
+ mintMode: true,
nesting: {collectionAdmin: true, tokenOwner: true, restricted: [1, 2]},
});
});
@@ -49,16 +49,16 @@
await collection.setPermissions(alice, {access: 'AllowList', nesting: {collectionAdmin: false, tokenOwner: true, restricted: [1, 2]}});
expect((await collection.getData())?.raw.permissions).to.be.deep.equal({
- access: 'AllowList',
- mintMode: false,
+ access: 'AllowList',
+ mintMode: false,
nesting: {collectionAdmin: false, tokenOwner: true, restricted: [1, 2]},
});
await collection.setPermissions(alice, {access: 'Normal', mintMode: false, nesting: {}});
await collection.setPermissions(alice, {access: 'Normal', mintMode: false, nesting: {}});
expect((await collection.getData())?.raw.permissions).to.be.deep.equal({
- access: 'Normal',
- mintMode: false,
+ access: 'Normal',
+ mintMode: false,
nesting: {collectionAdmin: false, tokenOwner: false, restricted: null},
});
});
@@ -67,7 +67,7 @@
const collection = await helper.nft.mintCollection(alice, {name: 'SetPermissions-2', tokenPrefix: 'SP'});
await collection.addAdmin(alice, {Substrate: bob.address});
await collection.setPermissions(bob, {access: 'AllowList', mintMode: true});
-
+
expect((await collection.getData())?.raw.permissions.access).to.equal('AllowList');
expect((await collection.getData())?.raw.permissions.mintMode).to.equal(true);
});
tests/src/transfer.nload.tsdiffbeforeafterboth--- a/tests/src/transfer.nload.ts
+++ b/tests/src/transfer.nload.ts
@@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+/* eslint-disable @typescript-eslint/no-floating-promises */
import os from 'os';
import {IKeyringPair} from '@polkadot/types/types';
import {usingPlaygrounds} from './util';
tests/src/transfer.test.tsdiffbeforeafterboth--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -29,7 +29,7 @@
[alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);
});
});
-
+
itSub('Balance transfers and check balance', async ({helper}) => {
const alicesBalanceBefore = await helper.balance.getSubstrate(alice.address);
const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
@@ -162,7 +162,7 @@
await expect(collection.transfer(alice, {Substrate: bob.address}))
.to.be.rejectedWith(/common\.CollectionNotFound/);
});
-
+
itSub.ifWithPallets('[refungible] Transfer with deleted collection_id', [Pallets.ReFungible], async ({helper}) => {
const collection = await helper.rft.mintCollection(alice, {name: 'Transfer-Neg-1-RFT', description: '', tokenPrefix: 'T'});
const rft = await collection.mintToken(alice, 10n);
@@ -279,7 +279,7 @@
donor = await privateKey({filename: __filename});
});
});
-
+
itEth('Transfers to self. In case of same frontend', async ({helper}) => {
const [owner] = await helper.arrange.createAccounts([10n], donor);
const collection = await helper.ft.mintCollection(owner, {});
tests/src/transferFrom.test.tsdiffbeforeafterboth--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -44,7 +44,7 @@
await collection.mint(alice, 10n);
await collection.approveTokens(alice, {Substrate: bob.address}, 7n);
expect(await collection.getApprovedTokens({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(7n);
-
+
await collection.transferFrom(bob, {Substrate: alice.address}, {Substrate: charlie.address}, 6n);
expect(await collection.getBalance({Substrate: charlie.address})).to.be.equal(6n);
expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(4n);
@@ -56,7 +56,7 @@
const rft = await collection.mintToken(alice, 10n);
await rft.approve(alice, {Substrate: bob.address}, 7n);
expect(await rft.getApprovedPieces({Substrate: alice.address}, {Substrate: bob.address})).to.be.equal(7n);
-
+
await rft.transferFrom(bob, {Substrate: alice.address}, {Substrate: charlie.address}, 6n);
expect(await rft.getBalance({Substrate: charlie.address})).to.be.equal(6n);
expect(await rft.getBalance({Substrate: alice.address})).to.be.equal(4n);
@@ -155,11 +155,11 @@
expect(await nft.isApproved({Substrate: bob.address})).to.be.true;
await expect(helper.collection.transferTokenFrom(
- bob,
- collection.collectionId,
- nft.tokenId,
- {Substrate: alice.address},
- {Substrate: charlie.address},
+ bob,
+ collection.collectionId,
+ nft.tokenId,
+ {Substrate: alice.address},
+ {Substrate: charlie.address},
2n,
)).to.be.rejectedWith(/nonfungible\.NonfungibleItemsHaveNoAmount/);
expect(await nft.getOwner()).to.be.deep.equal({Substrate: alice.address});
@@ -202,7 +202,7 @@
await expect(nft.transferFrom(
charlie,
- {Substrate: alice.address},
+ {Substrate: alice.address},
{Substrate: charlie.address},
)).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
expect(await nft.getOwner()).to.be.deep.equal({Substrate: alice.address});
@@ -218,7 +218,7 @@
await expect(collection.transferFrom(
charlie,
- {Substrate: alice.address},
+ {Substrate: alice.address},
{Substrate: charlie.address},
)).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
expect(await collection.getBalance({Substrate: alice.address})).to.be.deep.equal(10000n);
@@ -236,7 +236,7 @@
await expect(rft.transferFrom(
charlie,
- {Substrate: alice.address},
+ {Substrate: alice.address},
{Substrate: charlie.address},
)).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
expect(await rft.getBalance({Substrate: alice.address})).to.be.deep.equal(10000n);
@@ -254,7 +254,7 @@
await expect(nft.transferFrom(
bob,
- {Substrate: alice.address},
+ {Substrate: alice.address},
{Substrate: charlie.address},
)).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
});
@@ -269,7 +269,7 @@
await expect(collection.transferFrom(
alice,
- {Substrate: alice.address},
+ {Substrate: alice.address},
{Substrate: charlie.address},
)).to.be.rejectedWith(/common\.TokenValueTooLow/);
});
@@ -284,7 +284,7 @@
await expect(rft.transferFrom(
alice,
- {Substrate: alice.address},
+ {Substrate: alice.address},
{Substrate: charlie.address},
)).to.be.rejectedWith(/common\.TokenValueTooLow/);
});
@@ -300,7 +300,7 @@
await expect(nft.transferFrom(
bob,
- {Substrate: alice.address},
+ {Substrate: alice.address},
{Substrate: charlie.address},
)).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
});
@@ -316,7 +316,7 @@
await expect(collection.transferFrom(
bob,
- {Substrate: alice.address},
+ {Substrate: alice.address},
{Substrate: charlie.address},
)).to.be.rejectedWith(/common\.TokenValueTooLow/);
});
@@ -332,7 +332,7 @@
await expect(rft.transferFrom(
bob,
- {Substrate: alice.address},
+ {Substrate: alice.address},
{Substrate: charlie.address},
)).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
});
@@ -345,7 +345,7 @@
await expect(nft.transferFrom(
alice,
- {Substrate: bob.address},
+ {Substrate: bob.address},
{Substrate: charlie.address},
)).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
});
tests/src/util/globalSetup.tsdiffbeforeafterboth--- a/tests/src/util/globalSetup.ts
+++ b/tests/src/util/globalSetup.ts
@@ -17,10 +17,10 @@
// 2. Create donors for test files
await fundFilenamesWithRetries(3)
.then((result) => {
- if (!result) Promise.reject();
+ if (!result) throw Error('Some problems with fundFilenamesWithRetries');
});
- // 3. Configure App Promotion
+ // 3. Configure App Promotion
const missingPallets = helper.fetchMissingPalletNames([Pallets.AppPromotion]);
if (missingPallets.length === 0) {
const superuser = await privateKey('//Alice');
@@ -38,7 +38,7 @@
}
} catch (error) {
console.error(error);
- Promise.reject();
+ throw Error('Error during globalSetup');
}
});
};
@@ -78,7 +78,7 @@
if (aliceBalance < MINIMUM_DONOR_FUND * oneToken) {
tx.push(helper.executeExtrinsic(
- alice,
+ alice,
'api.tx.balances.transfer',
[account.address, DONOR_FUNDING * oneToken],
true,
tests/src/util/index.tsdiffbeforeafterboth--- a/tests/src/util/index.ts
+++ b/tests/src/util/index.ts
@@ -41,7 +41,7 @@
else {
const actualSeed = getTestSeed(seed.filename);
let account = helper.util.fromSeed(actualSeed, ss58Format);
- // here's to hoping that no
+ // here's to hoping that no
if (!seed.ignoreFundsPresence && ((helper as any)['balance'] == undefined || await (helper as any).balance.getSubstrate(account.address) < MINIMUM_DONOR_FUND)) {
console.warn(`${path.basename(seed.filename)}: Not enough funds present on the filename account. Using the default one as the donor instead.`);
account = helper.util.fromSeed('//Alice', ss58Format);
@@ -115,7 +115,7 @@
export function requirePalletsOrSkip(test: Context, helper: DevUniqueHelper, requiredPallets: string[]) {
const missingPallets = helper.fetchMissingPalletNames(requiredPallets);
-
+
if (missingPallets.length > 0) {
const skipMsg = `\tSkipping test '${test.test?.title}'.\n\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;
console.warn('\x1b[38:5:208m%s\x1b[0m', skipMsg);
@@ -124,13 +124,13 @@
}
export function itSub(name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {
- (opts.only ? it.only :
+ (opts.only ? it.only :
opts.skip ? it.skip : it)(name, async function () {
await usingPlaygrounds(async (helper, privateKey) => {
if (opts.requiredPallets) {
requirePalletsOrSkip(this, helper, opts.requiredPallets);
}
-
+
await cb({helper, privateKey});
});
});
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -26,7 +26,7 @@
export interface ISubscribeBlockEventsData {
number: number;
hash: string;
- timestamp: number;
+ timestamp: number;
events: IEvent[];
}
@@ -56,7 +56,7 @@
connected?: (...args: any[]) => any;
disconnected?: (...args: any[]) => any;
error?: (...args: any[]) => any;
- ready?: (...args: any[]) => any;
+ ready?: (...args: any[]) => any;
decorated?: (...args: any[]) => any;
}
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -35,7 +35,7 @@
this.consoleWarn = console.warn;
}
- enable() {
+ enable() {
const outFn = (printer: any) => (...args: any[]) => {
for (const arg of args) {
if (typeof arg !== 'string')
@@ -45,7 +45,7 @@
}
printer(...args);
};
-
+
console.error = outFn(this.consoleErr.bind(console));
console.log = outFn(this.consoleLog.bind(console));
console.warn = outFn(this.consoleWarn.bind(console));
@@ -188,11 +188,11 @@
}
/**
- * Generates accounts with the specified UNQ token balance
+ * Generates accounts with the specified UNQ token balance
* @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.
* @param donor donor account for balances
* @returns array of newly created accounts
- * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor);
+ * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor);
*/
createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {
let nonce = await this.helper.chain.getNonce(donor.address);
@@ -212,7 +212,7 @@
}
await Promise.all(transactions).catch(_e => {});
-
+
//#region TODO remove this region, when nonce problem will be solved
const checkBalances = async () => {
let isSuccess = true;
@@ -242,7 +242,7 @@
};
// TODO combine this method and createAccounts into one
- createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {
+ createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {
const createAsManyAsCan = async () => {
let transactions: any = [];
const accounts: IKeyringPair[] = [];
@@ -250,9 +250,9 @@
const tokenNominal = this.helper.balance.getOneTokenNominal();
for (let i = 0; i < accountsToCreate; i++) {
if (i === 500) { // if there are too many accounts to create
- await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled
+ await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled
transactions = []; //
- nonce = await this.helper.chain.getNonce(donor.address); // update nonce
+ nonce = await this.helper.chain.getNonce(donor.address); // update nonce
}
const recepient = this.helper.util.fromSeed(mnemonicGenerate());
accounts.push(recepient);
@@ -262,7 +262,7 @@
nonce++;
}
}
-
+
const fullfilledAccounts = [];
await Promise.allSettled(transactions);
for (const account of accounts) {
@@ -274,7 +274,7 @@
return fullfilledAccounts;
};
-
+
const crowd: IKeyringPair[] = [];
// do up to 5 retries
for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {
@@ -291,7 +291,7 @@
isDevNode = async () => {
let blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();
if (blockNumber == 0) {
- await this.helper.wait.newBlocks(1);
+ await this.helper.wait.newBlocks(1);
blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();
}
const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])]);
@@ -310,15 +310,15 @@
const block2date = await findCreationDate(block2);
if(block2date! - block1date! < 9000) return true;
};
-
+
async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {
const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);
- let balance = await this.helper.balance.getSubstrate(address);
-
+ let balance = await this.helper.balance.getSubstrate(address);
+
await promise();
-
+
balance -= await this.helper.balance.getSubstrate(address);
-
+
return balance;
}
@@ -335,7 +335,7 @@
const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;
- return scheduledId;
+ return scheduledId;
}
const ids = [];
@@ -424,7 +424,7 @@
/**
* Wait for specified number of blocks
* @param blocksCount number of blocks to wait
- * @returns
+ * @returns
*/
async newBlocks(blocksCount = 1, timeout?: number): Promise<void> {
timeout = timeout ?? blocksCount * 60_000;
@@ -457,7 +457,7 @@
await this.waitWithTimeout(promise, timeout);
return promise;
}
-
+
async forRelayBlockNumber(blockNumber: bigint | number, timeout?: number) {
timeout = timeout ?? 30 * 60 * 1000;
// eslint-disable-next-line no-async-promise-executor
@@ -476,7 +476,7 @@
noScheduledTasks() {
const api = this.helper.getApi();
-
+
// eslint-disable-next-line no-async-promise-executor
const promise = new Promise<void>(async resolve => {
const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {
@@ -486,7 +486,7 @@
unsubscribe();
resolve();
}
- });
+ });
});
return promise;
@@ -500,16 +500,16 @@
const blockHash = header.hash;
const eventIdStr = `${eventSection}.${eventMethod}`;
const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;
-
+
this.helper.logger.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);
-
+
const apiAt = await this.helper.getApi().at(blockHash);
const eventRecords = (await apiAt.query.system.events()) as any;
-
+
const neededEvent = eventRecords.toArray().find((r: FrameSystemEventRecord) => {
return r.event.section == eventSection && r.event.method == eventMethod;
});
-
+
if (neededEvent) {
unsubscribe();
resolve(neededEvent);
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15 IApiListeners,16 IBlock,17 IEvent,18 IChainProperties,19 ICollectionCreationOptions,20 ICollectionLimits,21 ICollectionPermissions,22 ICrossAccountId,23 ICrossAccountIdLower,24 ILogger,25 INestingPermissions,26 IProperty,27 IStakingInfo,28 ISchedulerOptions,29 ISubstrateBalance,30 IToken,31 ITokenPropertyPermission,32 ITransactionResult,33 IUniqueHelperLog,34 TApiAllowedListeners,35 TEthereumAccount,36 TSigner,37 TSubstrateAccount,38 TNetworks,39 IForeignAssetMetadata,40 AcalaAssetMetadata,41 MoonbeamAssetInfo,42 DemocracyStandardAccountVote,43 IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50 Substrate?: TSubstrateAccount;51 Ethereum?: TEthereumAccount;5253 constructor(account: ICrossAccountId) {54 if (account.Substrate) this.Substrate = account.Substrate;55 if (account.Ethereum) this.Ethereum = account.Ethereum;56 }5758 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59 switch (domain) {60 case 'Substrate': return new CrossAccountId({Substrate: account.address});61 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62 }63 }6465 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67 }6869 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70 return encodeAddress(decodeAddress(address), ss58Format);71 }7273 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75 }7677 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79 return this;80 }8182 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84 }8586 toEthereum(): CrossAccountId {87 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88 return this;89 }9091 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92 return evmToAddress(address, ss58Format);93 }9495 toSubstrate(ss58Format?: number): CrossAccountId {96 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97 return this;98 }99100 toLowerCase(): CrossAccountId {101 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103 return this;104 }105}106107const nesting = {108 toChecksumAddress(address: string): string {109 if (typeof address === 'undefined') return '';110111 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113 address = address.toLowerCase().replace(/^0x/i,'');114 const addressHash = keccakAsHex(address).replace(/^0x/i,'');115 const checksumAddress = ['0x'];116117 for (let i = 0; i < address.length; i++) {118 // If ith character is 8 to f then make it uppercase119 if (parseInt(addressHash[i], 16) > 7) {120 checksumAddress.push(address[i].toUpperCase());121 } else {122 checksumAddress.push(address[i]);123 }124 }125 return checksumAddress.join('');126 },127 tokenIdToAddress(collectionId: number, tokenId: number) {128 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);129 },130};131132class UniqueUtil {133 static transactionStatus = {134 NOT_READY: 'NotReady',135 FAIL: 'Fail',136 SUCCESS: 'Success',137 };138139 static chainLogType = {140 EXTRINSIC: 'extrinsic',141 RPC: 'rpc',142 };143144 static getTokenAccount(token: IToken): CrossAccountId {145 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146 }147148 static getTokenAddress(token: IToken): string {149 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150 }151152 static getDefaultLogger(): ILogger {153 return {154 log(msg: any, level = 'INFO') {155 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156 },157 level: {158 ERROR: 'ERROR',159 WARNING: 'WARNING',160 INFO: 'INFO',161 },162 };163 }164165 static vec2str(arr: string[] | number[]) {166 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167 }168169 static str2vec(string: string) {170 if (typeof string !== 'string') return string;171 return Array.from(string).map(x => x.charCodeAt(0));172 }173174 static fromSeed(seed: string, ss58Format = 42) {175 const keyring = new Keyring({type: 'sr25519', ss58Format});176 return keyring.addFromUri(seed);177 }178179 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180 if (creationResult.status !== this.transactionStatus.SUCCESS) {181 throw Error('Unable to create collection!');182 }183184 let collectionId = null;185 creationResult.result.events.forEach(({event: {data, method, section}}) => {186 if ((section === 'common') && (method === 'CollectionCreated')) {187 collectionId = parseInt(data[0].toString(), 10);188 }189 });190191 if (collectionId === null) {192 throw Error('No CollectionCreated event was found!');193 }194195 return collectionId;196 }197198 static extractTokensFromCreationResult(creationResult: ITransactionResult): {199 success: boolean,200 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201 } {202 if (creationResult.status !== this.transactionStatus.SUCCESS) {203 throw Error('Unable to create tokens!');204 }205 let success = false;206 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207 creationResult.result.events.forEach(({event: {data, method, section}}) => {208 if (method === 'ExtrinsicSuccess') {209 success = true;210 } else if ((section === 'common') && (method === 'ItemCreated')) {211 tokens.push({212 collectionId: parseInt(data[0].toString(), 10),213 tokenId: parseInt(data[1].toString(), 10),214 owner: data[2].toHuman(),215 amount: data[3].toBigInt(),216 });217 }218 });219 return {success, tokens};220 }221222 static extractTokensFromBurnResult(burnResult: ITransactionResult): {223 success: boolean,224 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225 } {226 if (burnResult.status !== this.transactionStatus.SUCCESS) {227 throw Error('Unable to burn tokens!');228 }229 let success = false;230 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231 burnResult.result.events.forEach(({event: {data, method, section}}) => {232 if (method === 'ExtrinsicSuccess') {233 success = true;234 } else if ((section === 'common') && (method === 'ItemDestroyed')) {235 tokens.push({236 collectionId: parseInt(data[0].toString(), 10),237 tokenId: parseInt(data[1].toString(), 10),238 owner: data[2].toHuman(),239 amount: data[3].toBigInt(),240 });241 }242 });243 return {success, tokens};244 }245246 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247 let eventId = null;248 events.forEach(({event: {data, method, section}}) => {249 if ((section === expectedSection) && (method === expectedMethod)) {250 eventId = parseInt(data[0].toString(), 10);251 }252 });253254 if (eventId === null) {255 throw Error(`No ${expectedMethod} event was found!`);256 }257 return eventId === collectionId;258 }259260 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261 const normalizeAddress = (address: string | ICrossAccountId) => {262 if(typeof address === 'string') return address;263 const obj = {} as any;264 Object.keys(address).forEach(k => {265 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266 });267 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269 return address;270 };271 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272 events.forEach(({event: {data, method, section}}) => {273 if ((section === 'common') && (method === 'Transfer')) {274 const hData = (data as any).toJSON();275 transfer = {276 collectionId: hData[0],277 tokenId: hData[1],278 from: normalizeAddress(hData[2]),279 to: normalizeAddress(hData[3]),280 amount: BigInt(hData[4]),281 };282 }283 });284 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287 isSuccess = isSuccess && amount === transfer.amount;288 return isSuccess;289 }290291 static bigIntToDecimals(number: bigint, decimals = 18) {292 const numberStr = number.toString();293 const dotPos = numberStr.length - decimals;294295 if (dotPos <= 0) {296 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297 } else {298 const intPart = numberStr.substring(0, dotPos);299 const fractPart = numberStr.substring(dotPos);300 return intPart + '.' + fractPart;301 }302 }303}304305class UniqueEventHelper {306 private static extractIndex(index: any): [number, number] | string {307 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308 return index.toJSON();309 }310311 private static extractSub(data: any, subTypes: any): {[key: string]: any} {312 let obj: any = {};313 let index = 0;314315 if (data.entries) {316 for(const [key, value] of data.entries()) {317 obj[key] = this.extractData(value, subTypes[index]);318 index++;319 }320 } else obj = data.toJSON();321322 return obj;323 }324325 private static toHuman(data: any) {326 return data && data.toHuman ? data.toHuman() : `${data}`;327 }328329 private static extractData(data: any, type: any): any {330 if(!type) return this.toHuman(data);331 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334 return this.toHuman(data);335 }336337 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338 const parsedEvents: IEvent[] = [];339340 events.forEach((record) => {341 const {event, phase} = record;342 const types = event.typeDef;343344 const eventData: IEvent = {345 section: event.section.toString(),346 method: event.method.toString(),347 index: this.extractIndex(event.index),348 data: [],349 phase: phase.toJSON(),350 };351352 event.data.forEach((val: any, index: number) => {353 eventData.data.push(this.extractData(val, types[index]));354 });355356 parsedEvents.push(eventData);357 });358359 return parsedEvents;360 }361}362363export class ChainHelperBase {364 helperBase: any;365366 transactionStatus = UniqueUtil.transactionStatus;367 chainLogType = UniqueUtil.chainLogType;368 util: typeof UniqueUtil;369 eventHelper: typeof UniqueEventHelper;370 logger: ILogger;371 api: ApiPromise | null;372 forcedNetwork: TNetworks | null;373 network: TNetworks | null;374 chainLog: IUniqueHelperLog[];375 children: ChainHelperBase[];376 address: AddressGroup;377 chain: ChainGroup;378379 constructor(logger?: ILogger, helperBase?: any) {380 this.helperBase = helperBase;381382 this.util = UniqueUtil;383 this.eventHelper = UniqueEventHelper;384 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();385 this.logger = logger;386 this.api = null;387 this.forcedNetwork = null;388 this.network = null;389 this.chainLog = [];390 this.children = [];391 this.address = new AddressGroup(this);392 this.chain = new ChainGroup(this);393 }394395 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {396 Object.setPrototypeOf(helperCls.prototype, this);397 const newHelper = new helperCls(this.logger, options);398399 newHelper.api = this.api;400 newHelper.network = this.network;401 newHelper.forceNetwork = this.forceNetwork;402403 this.children.push(newHelper);404405 return newHelper;406 }407408 getApi(): ApiPromise {409 if(this.api === null) throw Error('API not initialized');410 return this.api;411 }412413 async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {414 const collectedEvents: IEvent[] = [];415 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {416 const ievents = this.eventHelper.extractEvents(events);417 ievents.forEach((event) => {418 expectedEvents.forEach((e => {419 if (event.section === e.section && e.names.includes(event.method)) {420 collectedEvents.push(event);421 }422 }));423 });424 });425 return {unsubscribe: unsubscribe as any, collectedEvents};426 }427428 clearChainLog(): void {429 this.chainLog = [];430 }431432 forceNetwork(value: TNetworks): void {433 this.forcedNetwork = value;434 }435436 async connect(wsEndpoint: string, listeners?: IApiListeners) {437 if (this.api !== null) throw Error('Already connected');438 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);439 this.api = api;440 this.network = network;441 }442443 async disconnect() {444 for (const child of this.children) {445 child.clearApi();446 }447448 if (this.api === null) return;449 await this.api.disconnect();450 this.clearApi();451 }452453 clearApi() {454 this.api = null;455 this.network = null;456 }457458 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {459 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;460 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];461462 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;463464 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;465 return 'opal';466 }467468 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {469 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});470 await api.isReady;471472 const network = await this.detectNetwork(api);473474 await api.disconnect();475476 return network;477 }478479 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{480 api: ApiPromise;481 network: TNetworks;482 }> {483 if(typeof network === 'undefined' || network === null) network = 'opal';484 const supportedRPC = {485 opal: {486 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,487 },488 quartz: {489 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,490 },491 unique: {492 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,493 },494 rococo: {},495 westend: {},496 moonbeam: {},497 moonriver: {},498 acala: {},499 karura: {},500 westmint: {},501 };502 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);503 const rpc = supportedRPC[network];504505 // TODO: investigate how to replace rpc in runtime506 // api._rpcCore.addUserInterfaces(rpc);507508 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});509510 await api.isReadyOrError;511512 if (typeof listeners === 'undefined') listeners = {};513 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {514 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;515 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);516 }517518 return {api, network};519 }520521 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {522 const {events, status} = data;523 if (status.isReady) {524 return this.transactionStatus.NOT_READY;525 }526 if (status.isBroadcast) {527 return this.transactionStatus.NOT_READY;528 }529 if (status.isInBlock || status.isFinalized) {530 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');531 if (errors.length > 0) {532 return this.transactionStatus.FAIL;533 }534 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {535 return this.transactionStatus.SUCCESS;536 }537 }538539 return this.transactionStatus.FAIL;540 }541542 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {543 const sign = (callback: any) => {544 if(options !== null) return transaction.signAndSend(sender, options, callback);545 return transaction.signAndSend(sender, callback);546 };547 // eslint-disable-next-line no-async-promise-executor548 return new Promise(async (resolve, reject) => {549 try {550 const unsub = await sign((result: any) => {551 const status = this.getTransactionStatus(result);552553 if (status === this.transactionStatus.SUCCESS) {554 this.logger.log(`${label} successful`);555 unsub();556 resolve({result, status});557 } else if (status === this.transactionStatus.FAIL) {558 let moduleError = null;559560 if (result.hasOwnProperty('dispatchError')) {561 const dispatchError = result['dispatchError'];562563 if (dispatchError) {564 if (dispatchError.isModule) {565 const modErr = dispatchError.asModule;566 const errorMeta = dispatchError.registry.findMetaError(modErr);567568 moduleError = `${errorMeta.section}.${errorMeta.name}`;569 } else {570 moduleError = dispatchError.toHuman();571 }572 } else {573 this.logger.log(result, this.logger.level.ERROR);574 }575 }576577 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);578 unsub();579 reject({status, moduleError, result});580 }581 });582 } catch (e) {583 this.logger.log(e, this.logger.level.ERROR);584 reject(e);585 }586 });587 }588589 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {590 const api = this.getApi();591 const signingInfo = await api.derive.tx.signingInfo(signer.address);592593 // We need to sign the tx because594 // unsigned transactions does not have an inclusion fee595 tx.sign(signer, {596 blockHash: api.genesisHash,597 genesisHash: api.genesisHash,598 runtimeVersion: api.runtimeVersion,599 nonce: signingInfo.nonce,600 });601602 if (len === null) {603 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;604 } else {605 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;606 }607 }608609 constructApiCall(apiCall: string, params: any[]) {610 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);611 let call = this.getApi() as any;612 for(const part of apiCall.slice(4).split('.')) {613 call = call[part];614 }615 return call(...params);616 }617618 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {619 if(this.api === null) throw Error('API not initialized');620 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);621622 const startTime = (new Date()).getTime();623 let result: ITransactionResult;624 let events: IEvent[] = [];625 try {626 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;627 events = this.eventHelper.extractEvents(result.result.events);628 }629 catch(e) {630 if(!(e as object).hasOwnProperty('status')) throw e;631 result = e as ITransactionResult;632 }633634 const endTime = (new Date()).getTime();635636 const log = {637 executedAt: endTime,638 executionTime: endTime - startTime,639 type: this.chainLogType.EXTRINSIC,640 status: result.status,641 call: extrinsic,642 signer: this.getSignerAddress(sender),643 params,644 } as IUniqueHelperLog;645646 if(result.status !== this.transactionStatus.SUCCESS) {647 if (result.moduleError) log.moduleError = result.moduleError;648 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;649 }650 if(events.length > 0) log.events = events;651652 this.chainLog.push(log);653654 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {655 if (result.moduleError) throw Error(`${result.moduleError}`);656 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));657 }658 return result;659 }660661 async callRpc(rpc: string, params?: any[]) {662 if(typeof params === 'undefined') params = [];663 if(this.api === null) throw Error('API not initialized');664 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);665666 const startTime = (new Date()).getTime();667 let result;668 let error = null;669 const log = {670 type: this.chainLogType.RPC,671 call: rpc,672 params,673 } as IUniqueHelperLog;674675 try {676 result = await this.constructApiCall(rpc, params);677 }678 catch(e) {679 error = e;680 }681682 const endTime = (new Date()).getTime();683684 log.executedAt = endTime;685 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';686 log.executionTime = endTime - startTime;687688 this.chainLog.push(log);689690 if(error !== null) throw error;691692 return result;693 }694695 getSignerAddress(signer: IKeyringPair | string): string {696 if(typeof signer === 'string') return signer;697 return signer.address;698 }699700 fetchAllPalletNames(): string[] {701 if(this.api === null) throw Error('API not initialized');702 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());703 }704705 fetchMissingPalletNames(requiredPallets: string[]): string[] {706 const palletNames = this.fetchAllPalletNames();707 return requiredPallets.filter(p => !palletNames.includes(p));708 }709}710711712class HelperGroup<T extends ChainHelperBase> {713 helper: T;714715 constructor(uniqueHelper: T) {716 this.helper = uniqueHelper;717 }718}719720721class CollectionGroup extends HelperGroup<UniqueHelper> {722 /**723 * Get number of blocks when sponsored transaction is available.724 *725 * @param collectionId ID of collection726 * @param tokenId ID of token727 * @param addressObj address for which the sponsorship is checked728 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});729 * @returns number of blocks or null if sponsorship hasn't been set730 */731 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {732 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();733 }734735 /**736 * Get the number of created collections.737 *738 * @returns number of created collections739 */740 async getTotalCount(): Promise<number> {741 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();742 }743744 /**745 * Get information about the collection with additional data,746 * including the number of tokens it contains, its administrators,747 * the normalized address of the collection's owner, and decoded name and description.748 *749 * @param collectionId ID of collection750 * @example await getData(2)751 * @returns collection information object752 */753 async getData(collectionId: number): Promise<{754 id: number;755 name: string;756 description: string;757 tokensCount: number;758 admins: CrossAccountId[];759 normalizedOwner: TSubstrateAccount;760 raw: any761 } | null> {762 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);763 const humanCollection = collection.toHuman(), collectionData = {764 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],765 raw: humanCollection,766 } as any, jsonCollection = collection.toJSON();767 if (humanCollection === null) return null;768 collectionData.raw.limits = jsonCollection.limits;769 collectionData.raw.permissions = jsonCollection.permissions;770 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);771 for (const key of ['name', 'description']) {772 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);773 }774775 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))776 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)777 : 0;778 collectionData.admins = await this.getAdmins(collectionId);779780 return collectionData;781 }782783 /**784 * Get the addresses of the collection's administrators, optionally normalized.785 *786 * @param collectionId ID of collection787 * @param normalize whether to normalize the addresses to the default ss58 format788 * @example await getAdmins(1)789 * @returns array of administrators790 */791 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {792 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();793794 return normalize795 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())796 : admins;797 }798799 /**800 * Get the addresses added to the collection allow-list, optionally normalized.801 * @param collectionId ID of collection802 * @param normalize whether to normalize the addresses to the default ss58 format803 * @example await getAllowList(1)804 * @returns array of allow-listed addresses805 */806 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {807 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();808 return normalize809 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())810 : allowListed;811 }812813 /**814 * Get the effective limits of the collection instead of null for default values815 *816 * @param collectionId ID of collection817 * @example await getEffectiveLimits(2)818 * @returns object of collection limits819 */820 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {821 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();822 }823824 /**825 * Burns the collection if the signer has sufficient permissions and collection is empty.826 *827 * @param signer keyring of signer828 * @param collectionId ID of collection829 * @example await helper.collection.burn(aliceKeyring, 3);830 * @returns ```true``` if extrinsic success, otherwise ```false```831 */832 async burn(signer: TSigner, collectionId: number): Promise<boolean> {833 const result = await this.helper.executeExtrinsic(834 signer,835 'api.tx.unique.destroyCollection', [collectionId],836 true,837 );838839 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');840 }841842 /**843 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.844 *845 * @param signer keyring of signer846 * @param collectionId ID of collection847 * @param sponsorAddress Sponsor substrate address848 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")849 * @returns ```true``` if extrinsic success, otherwise ```false```850 */851 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {852 const result = await this.helper.executeExtrinsic(853 signer,854 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],855 true,856 );857858 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');859 }860861 /**862 * Confirms consent to sponsor the collection on behalf of the signer.863 *864 * @param signer keyring of signer865 * @param collectionId ID of collection866 * @example confirmSponsorship(aliceKeyring, 10)867 * @returns ```true``` if extrinsic success, otherwise ```false```868 */869 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {870 const result = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.confirmSponsorship', [collectionId],873 true,874 );875876 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');877 }878879 /**880 * Removes the sponsor of a collection, regardless if it consented or not.881 *882 * @param signer keyring of signer883 * @param collectionId ID of collection884 * @example removeSponsor(aliceKeyring, 10)885 * @returns ```true``` if extrinsic success, otherwise ```false```886 */887 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {888 const result = await this.helper.executeExtrinsic(889 signer,890 'api.tx.unique.removeCollectionSponsor', [collectionId],891 true,892 );893894 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');895 }896897 /**898 * Sets the limits of the collection. At least one limit must be specified for a correct call.899 *900 * @param signer keyring of signer901 * @param collectionId ID of collection902 * @param limits collection limits object903 * @example904 * await setLimits(905 * aliceKeyring,906 * 10,907 * {908 * sponsorTransferTimeout: 0,909 * ownerCanDestroy: false910 * }911 * )912 * @returns ```true``` if extrinsic success, otherwise ```false```913 */914 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {915 const result = await this.helper.executeExtrinsic(916 signer,917 'api.tx.unique.setCollectionLimits', [collectionId, limits],918 true,919 );920921 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');922 }923924 /**925 * Changes the owner of the collection to the new Substrate address.926 *927 * @param signer keyring of signer928 * @param collectionId ID of collection929 * @param ownerAddress substrate address of new owner930 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")931 * @returns ```true``` if extrinsic success, otherwise ```false```932 */933 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {934 const result = await this.helper.executeExtrinsic(935 signer,936 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],937 true,938 );939940 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');941 }942943 /**944 * Adds a collection administrator.945 *946 * @param signer keyring of signer947 * @param collectionId ID of collection948 * @param adminAddressObj Administrator address (substrate or ethereum)949 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})950 * @returns ```true``` if extrinsic success, otherwise ```false```951 */952 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {953 const result = await this.helper.executeExtrinsic(954 signer,955 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],956 true,957 );958959 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');960 }961962 /**963 * Removes a collection administrator.964 *965 * @param signer keyring of signer966 * @param collectionId ID of collection967 * @param adminAddressObj Administrator address (substrate or ethereum)968 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})969 * @returns ```true``` if extrinsic success, otherwise ```false```970 */971 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {972 const result = await this.helper.executeExtrinsic(973 signer,974 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],975 true,976 );977978 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');979 }980981 /**982 * Check if user is in allow list.983 *984 * @param collectionId ID of collection985 * @param user Account to check986 * @example await getAdmins(1)987 * @returns is user in allow list988 */989 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {990 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();991 }992993 /**994 * Adds an address to allow list995 * @param signer keyring of signer996 * @param collectionId ID of collection997 * @param addressObj address to add to the allow list998 * @returns ```true``` if extrinsic success, otherwise ```false```999 */1000 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1001 const result = await this.helper.executeExtrinsic(1002 signer,1003 'api.tx.unique.addToAllowList', [collectionId, addressObj],1004 true,1005 );10061007 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1008 }10091010 /**1011 * Removes an address from allow list1012 *1013 * @param signer keyring of signer1014 * @param collectionId ID of collection1015 * @param addressObj address to remove from the allow list1016 * @returns ```true``` if extrinsic success, otherwise ```false```1017 */1018 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1019 const result = await this.helper.executeExtrinsic(1020 signer,1021 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1022 true,1023 );10241025 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1026 }10271028 /**1029 * Sets onchain permissions for selected collection.1030 *1031 * @param signer keyring of signer1032 * @param collectionId ID of collection1033 * @param permissions collection permissions object1034 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1035 * @returns ```true``` if extrinsic success, otherwise ```false```1036 */1037 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1038 const result = await this.helper.executeExtrinsic(1039 signer,1040 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1041 true,1042 );10431044 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1045 }10461047 /**1048 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1049 *1050 * @param signer keyring of signer1051 * @param collectionId ID of collection1052 * @param permissions nesting permissions object1053 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1054 * @returns ```true``` if extrinsic success, otherwise ```false```1055 */1056 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1057 return await this.setPermissions(signer, collectionId, {nesting: permissions});1058 }10591060 /**1061 * Disables nesting for selected collection.1062 *1063 * @param signer keyring of signer1064 * @param collectionId ID of collection1065 * @example disableNesting(aliceKeyring, 10);1066 * @returns ```true``` if extrinsic success, otherwise ```false```1067 */1068 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1069 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1070 }10711072 /**1073 * Sets onchain properties to the collection.1074 *1075 * @param signer keyring of signer1076 * @param collectionId ID of collection1077 * @param properties array of property objects1078 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1079 * @returns ```true``` if extrinsic success, otherwise ```false```1080 */1081 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1082 const result = await this.helper.executeExtrinsic(1083 signer,1084 'api.tx.unique.setCollectionProperties', [collectionId, properties],1085 true,1086 );10871088 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1089 }10901091 /**1092 * Get collection properties.1093 *1094 * @param collectionId ID of collection1095 * @param propertyKeys optionally filter the returned properties to only these keys1096 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1097 * @returns array of key-value pairs1098 */1099 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1100 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1101 }11021103 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1104 const api = this.helper.getApi();1105 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();1106 1107 return (props! as any).consumedSpace;1108 }11091110 async getCollectionOptions(collectionId: number) {1111 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1112 }11131114 /**1115 * Deletes onchain properties from the collection.1116 *1117 * @param signer keyring of signer1118 * @param collectionId ID of collection1119 * @param propertyKeys array of property keys to delete1120 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1121 * @returns ```true``` if extrinsic success, otherwise ```false```1122 */1123 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1124 const result = await this.helper.executeExtrinsic(1125 signer,1126 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1127 true,1128 );11291130 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1131 }11321133 /**1134 * Changes the owner of the token.1135 *1136 * @param signer keyring of signer1137 * @param collectionId ID of collection1138 * @param tokenId ID of token1139 * @param addressObj address of a new owner1140 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1141 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1142 * @returns true if the token success, otherwise false1143 */1144 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1145 const result = await this.helper.executeExtrinsic(1146 signer,1147 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1148 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1149 );11501151 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1152 }11531154 /**1155 *1156 * Change ownership of a token(s) on behalf of the owner.1157 *1158 * @param signer keyring of signer1159 * @param collectionId ID of collection1160 * @param tokenId ID of token1161 * @param fromAddressObj address on behalf of which the token will be sent1162 * @param toAddressObj new token owner1163 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1164 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1165 * @returns true if the token success, otherwise false1166 */1167 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1168 const result = await this.helper.executeExtrinsic(1169 signer,1170 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1171 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1172 );1173 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1174 }11751176 /**1177 *1178 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1179 *1180 * @param signer keyring of signer1181 * @param collectionId ID of collection1182 * @param tokenId ID of token1183 * @param amount amount of tokens to be burned. For NFT must be set to 1n1184 * @example burnToken(aliceKeyring, 10, 5);1185 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1186 */1187 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1188 const burnResult = await this.helper.executeExtrinsic(1189 signer,1190 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1191 true, // `Unable to burn token for ${label}`,1192 );1193 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1194 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1195 return burnedTokens.success;1196 }11971198 /**1199 * Destroys a concrete instance of NFT on behalf of the owner1200 *1201 * @param signer keyring of signer1202 * @param collectionId ID of collection1203 * @param tokenId ID of token1204 * @param fromAddressObj address on behalf of which the token will be burnt1205 * @param amount amount of tokens to be burned. For NFT must be set to 1n1206 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1207 * @returns ```true``` if extrinsic success, otherwise ```false```1208 */1209 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1210 const burnResult = await this.helper.executeExtrinsic(1211 signer,1212 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1213 true, // `Unable to burn token from for ${label}`,1214 );1215 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1216 return burnedTokens.success && burnedTokens.tokens.length > 0;1217 }12181219 /**1220 * Set, change, or remove approved address to transfer the ownership of the NFT.1221 *1222 * @param signer keyring of signer1223 * @param collectionId ID of collection1224 * @param tokenId ID of token1225 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1226 * @param amount amount of token to be approved. For NFT must be set to 1n1227 * @returns ```true``` if extrinsic success, otherwise ```false```1228 */1229 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1230 const approveResult = await this.helper.executeExtrinsic(1231 signer,1232 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1233 true, // `Unable to approve token for ${label}`,1234 );12351236 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1237 }12381239 /**1240 * Get the amount of token pieces approved to transfer or burn. Normally 0.1241 *1242 * @param collectionId ID of collection1243 * @param tokenId ID of token1244 * @param toAccountObj address which is approved to use token pieces1245 * @param fromAccountObj address which may have allowed the use of its owned tokens1246 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1247 * @returns number of approved to transfer pieces1248 */1249 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1250 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1251 }12521253 /**1254 * Get the last created token ID in a collection1255 *1256 * @param collectionId ID of collection1257 * @example getLastTokenId(10);1258 * @returns id of the last created token1259 */1260 async getLastTokenId(collectionId: number): Promise<number> {1261 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1262 }12631264 /**1265 * Check if token exists1266 *1267 * @param collectionId ID of collection1268 * @param tokenId ID of token1269 * @example doesTokenExist(10, 20);1270 * @returns true if the token exists, otherwise false1271 */1272 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1273 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1274 }1275}12761277class NFTnRFT extends CollectionGroup {1278 /**1279 * Get tokens owned by account1280 *1281 * @param collectionId ID of collection1282 * @param addressObj tokens owner1283 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1284 * @returns array of token ids owned by account1285 */1286 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1287 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1288 }12891290 /**1291 * Get token data1292 *1293 * @param collectionId ID of collection1294 * @param tokenId ID of token1295 * @param propertyKeys optionally filter the token properties to only these keys1296 * @param blockHashAt optionally query the data at some block with this hash1297 * @example getToken(10, 5);1298 * @returns human readable token data1299 */1300 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1301 properties: IProperty[];1302 owner: CrossAccountId;1303 normalizedOwner: CrossAccountId;1304 }| null> {1305 let tokenData;1306 if(typeof blockHashAt === 'undefined') {1307 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1308 }1309 else {1310 if(propertyKeys.length == 0) {1311 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1312 if(!collection) return null;1313 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1314 }1315 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1316 }1317 tokenData = tokenData.toHuman();1318 if (tokenData === null || tokenData.owner === null) return null;1319 const owner = {} as any;1320 for (const key of Object.keys(tokenData.owner)) {1321 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1322 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1323 : tokenData.owner[key];1324 }1325 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1326 return tokenData;1327 }13281329 /**1330 * Set permissions to change token properties1331 *1332 * @param signer keyring of signer1333 * @param collectionId ID of collection1334 * @param permissions permissions to change a property by the collection admin or token owner1335 * @example setTokenPropertyPermissions(1336 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1337 * )1338 * @returns true if extrinsic success otherwise false1339 */1340 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1341 const result = await this.helper.executeExtrinsic(1342 signer,1343 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1344 true,1345 );13461347 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1348 }13491350 /**1351 * Get token property permissions.1352 *1353 * @param collectionId ID of collection1354 * @param propertyKeys optionally filter the returned property permissions to only these keys1355 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1356 * @returns array of key-permission pairs1357 */1358 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1359 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1360 }13611362 /**1363 * Set token properties1364 *1365 * @param signer keyring of signer1366 * @param collectionId ID of collection1367 * @param tokenId ID of token1368 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1369 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1370 * @returns ```true``` if extrinsic success, otherwise ```false```1371 */1372 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1373 const result = await this.helper.executeExtrinsic(1374 signer,1375 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1376 true,1377 );13781379 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1380 }13811382 /**1383 * Get properties, metadata assigned to a token.1384 *1385 * @param collectionId ID of collection1386 * @param tokenId ID of token1387 * @param propertyKeys optionally filter the returned properties to only these keys1388 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1389 * @returns array of key-value pairs1390 */1391 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1392 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1393 }13941395 /**1396 * Delete the provided properties of a token1397 * @param signer keyring of signer1398 * @param collectionId ID of collection1399 * @param tokenId ID of token1400 * @param propertyKeys property keys to be deleted1401 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1402 * @returns ```true``` if extrinsic success, otherwise ```false```1403 */1404 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1405 const result = await this.helper.executeExtrinsic(1406 signer,1407 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1408 true,1409 );14101411 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1412 }14131414 /**1415 * Mint new collection1416 *1417 * @param signer keyring of signer1418 * @param collectionOptions basic collection options and properties1419 * @param mode NFT or RFT type of a collection1420 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1421 * @returns object of the created collection1422 */1423 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1424 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1425 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1426 for (const key of ['name', 'description', 'tokenPrefix']) {1427 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1428 }1429 const creationResult = await this.helper.executeExtrinsic(1430 signer,1431 'api.tx.unique.createCollectionEx', [collectionOptions],1432 true, // errorLabel,1433 );1434 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1435 }14361437 getCollectionObject(_collectionId: number): any {1438 return null;1439 }14401441 getTokenObject(_collectionId: number, _tokenId: number): any {1442 return null;1443 }14441445 /**1446 * Tells whether the given `owner` approves the `operator`.1447 * @param collectionId ID of collection1448 * @param owner owner address1449 * @param operator operator addrees1450 * @returns true if operator is enabled1451 */1452 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1453 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1454 }14551456 /** Sets or unsets the approval of a given operator.1457 * The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1458 * @param operator Operator1459 * @param approved Should operator status be granted or revoked?1460 * @returns ```true``` if extrinsic success, otherwise ```false```1461 */1462 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1463 const result = await this.helper.executeExtrinsic(1464 signer,1465 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1466 true,1467 );1468 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1469 }1470}147114721473class NFTGroup extends NFTnRFT {1474 /**1475 * Get collection object1476 * @param collectionId ID of collection1477 * @example getCollectionObject(2);1478 * @returns instance of UniqueNFTCollection1479 */1480 getCollectionObject(collectionId: number): UniqueNFTCollection {1481 return new UniqueNFTCollection(collectionId, this.helper);1482 }14831484 /**1485 * Get token object1486 * @param collectionId ID of collection1487 * @param tokenId ID of token1488 * @example getTokenObject(10, 5);1489 * @returns instance of UniqueNFTToken1490 */1491 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1492 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1493 }14941495 /**1496 * Get token's owner1497 * @param collectionId ID of collection1498 * @param tokenId ID of token1499 * @param blockHashAt optionally query the data at the block with this hash1500 * @example getTokenOwner(10, 5);1501 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1502 */1503 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1504 let owner;1505 if (typeof blockHashAt === 'undefined') {1506 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1507 } else {1508 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1509 }1510 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1511 }15121513 /**1514 * Is token approved to transfer1515 * @param collectionId ID of collection1516 * @param tokenId ID of token1517 * @param toAccountObj address to be approved1518 * @returns ```true``` if extrinsic success, otherwise ```false```1519 */1520 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1521 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1522 }15231524 /**1525 * Changes the owner of the token.1526 *1527 * @param signer keyring of signer1528 * @param collectionId ID of collection1529 * @param tokenId ID of token1530 * @param addressObj address of a new owner1531 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1532 * @returns ```true``` if extrinsic success, otherwise ```false```1533 */1534 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1535 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1536 }15371538 /**1539 *1540 * Change ownership of a NFT on behalf of the owner.1541 *1542 * @param signer keyring of signer1543 * @param collectionId ID of collection1544 * @param tokenId ID of token1545 * @param fromAddressObj address on behalf of which the token will be sent1546 * @param toAddressObj new token owner1547 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1548 * @returns ```true``` if extrinsic success, otherwise ```false```1549 */1550 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1551 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1552 }15531554 /**1555 * Recursively find the address that owns the token1556 * @param collectionId ID of collection1557 * @param tokenId ID of token1558 * @param blockHashAt1559 * @example getTokenTopmostOwner(10, 5);1560 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1561 */1562 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1563 let owner;1564 if (typeof blockHashAt === 'undefined') {1565 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1566 } else {1567 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1568 }15691570 if (owner === null) return null;15711572 return owner.toHuman();1573 }15741575 /**1576 * Get tokens nested in the provided token1577 * @param collectionId ID of collection1578 * @param tokenId ID of token1579 * @param blockHashAt optionally query the data at the block with this hash1580 * @example getTokenChildren(10, 5);1581 * @returns tokens whose depth of nesting is <= 51582 */1583 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1584 let children;1585 if(typeof blockHashAt === 'undefined') {1586 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1587 } else {1588 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1589 }15901591 return children.toJSON().map((x: any) => {1592 return {collectionId: x.collection, tokenId: x.token};1593 });1594 }15951596 /**1597 * Nest one token into another1598 * @param signer keyring of signer1599 * @param tokenObj token to be nested1600 * @param rootTokenObj token to be parent1601 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1602 * @returns ```true``` if extrinsic success, otherwise ```false```1603 */1604 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1605 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1606 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1607 if(!result) {1608 throw Error('Unable to nest token!');1609 }1610 return result;1611 }16121613 /**1614 * Remove token from nested state1615 * @param signer keyring of signer1616 * @param tokenObj token to unnest1617 * @param rootTokenObj parent of a token1618 * @param toAddressObj address of a new token owner1619 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1620 * @returns ```true``` if extrinsic success, otherwise ```false```1621 */1622 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1623 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1624 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1625 if(!result) {1626 throw Error('Unable to unnest token!');1627 }1628 return result;1629 }16301631 /**1632 * Mint new collection1633 * @param signer keyring of signer1634 * @param collectionOptions Collection options1635 * @example1636 * mintCollection(aliceKeyring, {1637 * name: 'New',1638 * description: 'New collection',1639 * tokenPrefix: 'NEW',1640 * })1641 * @returns object of the created collection1642 */1643 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1644 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1645 }16461647 /**1648 * Mint new token1649 * @param signer keyring of signer1650 * @param data token data1651 * @returns created token object1652 */1653 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1654 const creationResult = await this.helper.executeExtrinsic(1655 signer,1656 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1657 nft: {1658 properties: data.properties,1659 },1660 }],1661 true,1662 );1663 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1664 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1665 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1666 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1667 }16681669 /**1670 * Mint multiple NFT tokens1671 * @param signer keyring of signer1672 * @param collectionId ID of collection1673 * @param tokens array of tokens with owner and properties1674 * @example1675 * mintMultipleTokens(aliceKeyring, 10, [{1676 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1677 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1678 * },{1679 * owner: {Ethereum: "0x9F0583DbB855d..."},1680 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1681 * }]);1682 * @returns ```true``` if extrinsic success, otherwise ```false```1683 */1684 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1685 const creationResult = await this.helper.executeExtrinsic(1686 signer,1687 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1688 true,1689 );1690 const collection = this.getCollectionObject(collectionId);1691 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1692 }16931694 /**1695 * Mint multiple NFT tokens with one owner1696 * @param signer keyring of signer1697 * @param collectionId ID of collection1698 * @param owner tokens owner1699 * @param tokens array of tokens with owner and properties1700 * @example1701 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1702 * properties: [{1703 * key: "gender",1704 * value: "female",1705 * },{1706 * key: "age",1707 * value: "33",1708 * }],1709 * }]);1710 * @returns array of newly created tokens1711 */1712 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1713 const rawTokens = [];1714 for (const token of tokens) {1715 const raw = {NFT: {properties: token.properties}};1716 rawTokens.push(raw);1717 }1718 const creationResult = await this.helper.executeExtrinsic(1719 signer,1720 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1721 true,1722 );1723 const collection = this.getCollectionObject(collectionId);1724 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1725 }17261727 /**1728 * Set, change, or remove approved address to transfer the ownership of the NFT.1729 *1730 * @param signer keyring of signer1731 * @param collectionId ID of collection1732 * @param tokenId ID of token1733 * @param toAddressObj address to approve1734 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1735 * @returns ```true``` if extrinsic success, otherwise ```false```1736 */1737 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1738 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1739 }1740}174117421743class RFTGroup extends NFTnRFT {1744 /**1745 * Get collection object1746 * @param collectionId ID of collection1747 * @example getCollectionObject(2);1748 * @returns instance of UniqueRFTCollection1749 */1750 getCollectionObject(collectionId: number): UniqueRFTCollection {1751 return new UniqueRFTCollection(collectionId, this.helper);1752 }17531754 /**1755 * Get token object1756 * @param collectionId ID of collection1757 * @param tokenId ID of token1758 * @example getTokenObject(10, 5);1759 * @returns instance of UniqueNFTToken1760 */1761 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1762 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1763 }17641765 /**1766 * Get top 10 token owners with the largest number of pieces1767 * @param collectionId ID of collection1768 * @param tokenId ID of token1769 * @example getTokenTop10Owners(10, 5);1770 * @returns array of top 10 owners1771 */1772 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1773 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1774 }17751776 /**1777 * Get number of pieces owned by address1778 * @param collectionId ID of collection1779 * @param tokenId ID of token1780 * @param addressObj address token owner1781 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1782 * @returns number of pieces ownerd by address1783 */1784 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1785 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1786 }17871788 /**1789 * Transfer pieces of token to another address1790 * @param signer keyring of signer1791 * @param collectionId ID of collection1792 * @param tokenId ID of token1793 * @param addressObj address of a new owner1794 * @param amount number of pieces to be transfered1795 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1796 * @returns ```true``` if extrinsic success, otherwise ```false```1797 */1798 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1799 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1800 }18011802 /**1803 * Change ownership of some pieces of RFT on behalf of the owner.1804 * @param signer keyring of signer1805 * @param collectionId ID of collection1806 * @param tokenId ID of token1807 * @param fromAddressObj address on behalf of which the token will be sent1808 * @param toAddressObj new token owner1809 * @param amount number of pieces to be transfered1810 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1811 * @returns ```true``` if extrinsic success, otherwise ```false```1812 */1813 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1814 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1815 }18161817 /**1818 * Mint new collection1819 * @param signer keyring of signer1820 * @param collectionOptions Collection options1821 * @example1822 * mintCollection(aliceKeyring, {1823 * name: 'New',1824 * description: 'New collection',1825 * tokenPrefix: 'NEW',1826 * })1827 * @returns object of the created collection1828 */1829 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1830 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1831 }18321833 /**1834 * Mint new token1835 * @param signer keyring of signer1836 * @param data token data1837 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1838 * @returns created token object1839 */1840 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1841 const creationResult = await this.helper.executeExtrinsic(1842 signer,1843 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1844 refungible: {1845 pieces: data.pieces,1846 properties: data.properties,1847 },1848 }],1849 true,1850 );1851 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1852 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1853 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1854 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1855 }18561857 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1858 throw Error('Not implemented');1859 const creationResult = await this.helper.executeExtrinsic(1860 signer,1861 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1862 true, // `Unable to mint RFT tokens for ${label}`,1863 );1864 const collection = this.getCollectionObject(collectionId);1865 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1866 }18671868 /**1869 * Mint multiple RFT tokens with one owner1870 * @param signer keyring of signer1871 * @param collectionId ID of collection1872 * @param owner tokens owner1873 * @param tokens array of tokens with properties and pieces1874 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1875 * @returns array of newly created RFT tokens1876 */1877 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1878 const rawTokens = [];1879 for (const token of tokens) {1880 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1881 rawTokens.push(raw);1882 }1883 const creationResult = await this.helper.executeExtrinsic(1884 signer,1885 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1886 true,1887 );1888 const collection = this.getCollectionObject(collectionId);1889 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1890 }18911892 /**1893 * Destroys a concrete instance of RFT.1894 * @param signer keyring of signer1895 * @param collectionId ID of collection1896 * @param tokenId ID of token1897 * @param amount number of pieces to be burnt1898 * @example burnToken(aliceKeyring, 10, 5);1899 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1900 */1901 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1902 return await super.burnToken(signer, collectionId, tokenId, amount);1903 }19041905 /**1906 * Destroys a concrete instance of RFT on behalf of the owner.1907 * @param signer keyring of signer1908 * @param collectionId ID of collection1909 * @param tokenId ID of token1910 * @param fromAddressObj address on behalf of which the token will be burnt1911 * @param amount number of pieces to be burnt1912 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1913 * @returns ```true``` if extrinsic success, otherwise ```false```1914 */1915 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1916 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1917 }19181919 /**1920 * Set, change, or remove approved address to transfer the ownership of the RFT.1921 *1922 * @param signer keyring of signer1923 * @param collectionId ID of collection1924 * @param tokenId ID of token1925 * @param toAddressObj address to approve1926 * @param amount number of pieces to be approved1927 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1928 * @returns true if the token success, otherwise false1929 */1930 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1931 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1932 }19331934 /**1935 * Get total number of pieces1936 * @param collectionId ID of collection1937 * @param tokenId ID of token1938 * @example getTokenTotalPieces(10, 5);1939 * @returns number of pieces1940 */1941 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1942 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1943 }19441945 /**1946 * Change number of token pieces. Signer must be the owner of all token pieces.1947 * @param signer keyring of signer1948 * @param collectionId ID of collection1949 * @param tokenId ID of token1950 * @param amount new number of pieces1951 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1952 * @returns true if the repartion was success, otherwise false1953 */1954 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1955 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1956 const repartitionResult = await this.helper.executeExtrinsic(1957 signer,1958 'api.tx.unique.repartition', [collectionId, tokenId, amount],1959 true,1960 );1961 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1962 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1963 }1964}196519661967class FTGroup extends CollectionGroup {1968 /**1969 * Get collection object1970 * @param collectionId ID of collection1971 * @example getCollectionObject(2);1972 * @returns instance of UniqueFTCollection1973 */1974 getCollectionObject(collectionId: number): UniqueFTCollection {1975 return new UniqueFTCollection(collectionId, this.helper);1976 }19771978 /**1979 * Mint new fungible collection1980 * @param signer keyring of signer1981 * @param collectionOptions Collection options1982 * @param decimalPoints number of token decimals1983 * @example1984 * mintCollection(aliceKeyring, {1985 * name: 'New',1986 * description: 'New collection',1987 * tokenPrefix: 'NEW',1988 * }, 18)1989 * @returns newly created fungible collection1990 */1991 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1992 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1993 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1994 collectionOptions.mode = {fungible: decimalPoints};1995 for (const key of ['name', 'description', 'tokenPrefix']) {1996 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1997 }1998 const creationResult = await this.helper.executeExtrinsic(1999 signer,2000 'api.tx.unique.createCollectionEx', [collectionOptions],2001 true,2002 );2003 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2004 }20052006 /**2007 * Mint tokens2008 * @param signer keyring of signer2009 * @param collectionId ID of collection2010 * @param owner address owner of new tokens2011 * @param amount amount of tokens to be meanted2012 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2013 * @returns ```true``` if extrinsic success, otherwise ```false```2014 */2015 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2016 const creationResult = await this.helper.executeExtrinsic(2017 signer,2018 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2019 fungible: {2020 value: amount,2021 },2022 }],2023 true, // `Unable to mint fungible tokens for ${label}`,2024 );2025 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2026 }20272028 /**2029 * Mint multiple Fungible tokens with one owner2030 * @param signer keyring of signer2031 * @param collectionId ID of collection2032 * @param owner tokens owner2033 * @param tokens array of tokens with properties and pieces2034 * @returns ```true``` if extrinsic success, otherwise ```false```2035 */2036 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2037 const rawTokens = [];2038 for (const token of tokens) {2039 const raw = {Fungible: {Value: token.value}};2040 rawTokens.push(raw);2041 }2042 const creationResult = await this.helper.executeExtrinsic(2043 signer,2044 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2045 true,2046 );2047 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2048 }20492050 /**2051 * Get the top 10 owners with the largest balance for the Fungible collection2052 * @param collectionId ID of collection2053 * @example getTop10Owners(10);2054 * @returns array of ```ICrossAccountId```2055 */2056 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2057 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2058 }20592060 /**2061 * Get account balance2062 * @param collectionId ID of collection2063 * @param addressObj address of owner2064 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2065 * @returns amount of fungible tokens owned by address2066 */2067 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2068 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2069 }20702071 /**2072 * Transfer tokens to address2073 * @param signer keyring of signer2074 * @param collectionId ID of collection2075 * @param toAddressObj address recipient2076 * @param amount amount of tokens to be sent2077 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2078 * @returns ```true``` if extrinsic success, otherwise ```false```2079 */2080 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2081 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2082 }20832084 /**2085 * Transfer some tokens on behalf of the owner.2086 * @param signer keyring of signer2087 * @param collectionId ID of collection2088 * @param fromAddressObj address on behalf of which tokens will be sent2089 * @param toAddressObj address where token to be sent2090 * @param amount number of tokens to be sent2091 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2092 * @returns ```true``` if extrinsic success, otherwise ```false```2093 */2094 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2095 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2096 }20972098 /**2099 * Destroy some amount of tokens2100 * @param signer keyring of signer2101 * @param collectionId ID of collection2102 * @param amount amount of tokens to be destroyed2103 * @example burnTokens(aliceKeyring, 10, 1000n);2104 * @returns ```true``` if extrinsic success, otherwise ```false```2105 */2106 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2107 return await super.burnToken(signer, collectionId, 0, amount);2108 }21092110 /**2111 * Burn some tokens on behalf of the owner.2112 * @param signer keyring of signer2113 * @param collectionId ID of collection2114 * @param fromAddressObj address on behalf of which tokens will be burnt2115 * @param amount amount of tokens to be burnt2116 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2117 * @returns ```true``` if extrinsic success, otherwise ```false```2118 */2119 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2120 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2121 }21222123 /**2124 * Get total collection supply2125 * @param collectionId2126 * @returns2127 */2128 async getTotalPieces(collectionId: number): Promise<bigint> {2129 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2130 }21312132 /**2133 * Set, change, or remove approved address to transfer tokens.2134 *2135 * @param signer keyring of signer2136 * @param collectionId ID of collection2137 * @param toAddressObj address to be approved2138 * @param amount amount of tokens to be approved2139 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2140 * @returns ```true``` if extrinsic success, otherwise ```false```2141 */2142 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2143 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2144 }21452146 /**2147 * Get amount of fungible tokens approved to transfer2148 * @param collectionId ID of collection2149 * @param fromAddressObj owner of tokens2150 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2151 * @returns number of tokens approved for the transfer2152 */2153 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2154 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2155 }2156}215721582159class ChainGroup extends HelperGroup<ChainHelperBase> {2160 /**2161 * Get system properties of a chain2162 * @example getChainProperties();2163 * @returns ss58Format, token decimals, and token symbol2164 */2165 getChainProperties(): IChainProperties {2166 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2167 return {2168 ss58Format: properties.ss58Format.toJSON(),2169 tokenDecimals: properties.tokenDecimals.toJSON(),2170 tokenSymbol: properties.tokenSymbol.toJSON(),2171 };2172 }21732174 /**2175 * Get chain header2176 * @example getLatestBlockNumber();2177 * @returns the number of the last block2178 */2179 async getLatestBlockNumber(): Promise<number> {2180 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2181 }21822183 /**2184 * Get block hash by block number2185 * @param blockNumber number of block2186 * @example getBlockHashByNumber(12345);2187 * @returns hash of a block2188 */2189 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2190 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2191 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2192 return blockHash;2193 }21942195 // TODO add docs2196 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2197 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2198 if (!blockHash) return null;2199 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2200 }22012202 /**2203 * Get latest relay block2204 * @returns {number} relay block2205 */2206 async getRelayBlockNumber(): Promise<bigint> {2207 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2208 return BigInt(blockNumber);2209 }22102211 /**2212 * Get account nonce2213 * @param address substrate address2214 * @example getNonce("5GrwvaEF5zXb26Fz...");2215 * @returns number, account's nonce2216 */2217 async getNonce(address: TSubstrateAccount): Promise<number> {2218 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2219 }2220}22212222class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2223 /**2224 * Get substrate address balance2225 * @param address substrate address2226 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2227 * @returns amount of tokens on address2228 */2229 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2230 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2231 }22322233 /**2234 * Transfer tokens to substrate address2235 * @param signer keyring of signer2236 * @param address substrate address of a recipient2237 * @param amount amount of tokens to be transfered2238 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2239 * @returns ```true``` if extrinsic success, otherwise ```false```2240 */2241 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2242 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}`*/);22432244 let transfer = {from: null, to: null, amount: 0n} as any;2245 result.result.events.forEach(({event: {data, method, section}}) => {2246 if ((section === 'balances') && (method === 'Transfer')) {2247 transfer = {2248 from: this.helper.address.normalizeSubstrate(data[0]),2249 to: this.helper.address.normalizeSubstrate(data[1]),2250 amount: BigInt(data[2]),2251 };2252 }2253 });2254 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2255 && this.helper.address.normalizeSubstrate(address) === transfer.to2256 && BigInt(amount) === transfer.amount;2257 return isSuccess;2258 }22592260 /**2261 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2262 * @param address substrate address2263 * @returns2264 */2265 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2266 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2267 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2268 }22692270 async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2271 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2272 return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2273 }2274}22752276class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2277 /**2278 * Get ethereum address balance2279 * @param address ethereum address2280 * @example getEthereum("0x9F0583DbB855d...")2281 * @returns amount of tokens on address2282 */2283 async getEthereum(address: TEthereumAccount): Promise<bigint> {2284 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2285 }22862287 /**2288 * Transfer tokens to address2289 * @param signer keyring of signer2290 * @param address Ethereum address of a recipient2291 * @param amount amount of tokens to be transfered2292 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2293 * @returns ```true``` if extrinsic success, otherwise ```false```2294 */2295 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2296 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22972298 let transfer = {from: null, to: null, amount: 0n} as any;2299 result.result.events.forEach(({event: {data, method, section}}) => {2300 if ((section === 'balances') && (method === 'Transfer')) {2301 transfer = {2302 from: data[0].toString(),2303 to: data[1].toString(),2304 amount: BigInt(data[2]),2305 };2306 }2307 });2308 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2309 && address === transfer.to2310 && BigInt(amount) === transfer.amount;2311 return isSuccess;2312 }2313}23142315class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2316 subBalanceGroup: SubstrateBalanceGroup<T>;2317 ethBalanceGroup: EthereumBalanceGroup<T>;23182319 constructor(helper: T) {2320 super(helper);2321 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2322 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2323 }23242325 getCollectionCreationPrice(): bigint {2326 return 2n * this.getOneTokenNominal();2327 }2328 /**2329 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2330 * @example getOneTokenNominal()2331 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2332 */2333 getOneTokenNominal(): bigint {2334 const chainProperties = this.helper.chain.getChainProperties();2335 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2336 }23372338 /**2339 * Get substrate address balance2340 * @param address substrate address2341 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2342 * @returns amount of tokens on address2343 */2344 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2345 return this.subBalanceGroup.getSubstrate(address);2346 }23472348 /**2349 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2350 * @param address substrate address2351 * @returns2352 */2353 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2354 return this.subBalanceGroup.getSubstrateFull(address);2355 }23562357 /**2358 * Get locked balances2359 * @param address substrate address2360 * @returns locked balances with reason via api.query.balances.locks2361 */2362 getLocked(address: TSubstrateAccount) {2363 return this.subBalanceGroup.getLocked(address);2364 }23652366 /**2367 * Get ethereum address balance2368 * @param address ethereum address2369 * @example getEthereum("0x9F0583DbB855d...")2370 * @returns amount of tokens on address2371 */2372 getEthereum(address: TEthereumAccount): Promise<bigint> {2373 return this.ethBalanceGroup.getEthereum(address);2374 }23752376 /**2377 * Transfer tokens to substrate address2378 * @param signer keyring of signer2379 * @param address substrate address of a recipient2380 * @param amount amount of tokens to be transfered2381 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2382 * @returns ```true``` if extrinsic success, otherwise ```false```2383 */2384 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2385 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2386 }23872388 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2389 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);23902391 let transfer = {from: null, to: null, amount: 0n} as any;2392 result.result.events.forEach(({event: {data, method, section}}) => {2393 if ((section === 'balances') && (method === 'Transfer')) {2394 transfer = {2395 from: this.helper.address.normalizeSubstrate(data[0]),2396 to: this.helper.address.normalizeSubstrate(data[1]),2397 amount: BigInt(data[2]),2398 };2399 }2400 });2401 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2402 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2403 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2404 return isSuccess;2405 }24062407 /**2408 * Transfer tokens with the unlock period2409 * @param signer signers Keyring2410 * @param address Substrate address of recipient2411 * @param schedule Schedule params2412 * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002413 */2414 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2415 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2416 const event = result.result.events2417 .find(e => e.event.section === 'vesting' &&2418 e.event.method === 'VestingScheduleAdded' &&2419 e.event.data[0].toHuman() === signer.address);2420 if (!event) throw Error('Cannot find transfer in events');2421 }24222423 /**2424 * Get schedule for recepient of vested transfer2425 * @param address Substrate address of recipient2426 * @returns 2427 */2428 async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2429 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2430 return schedule.map((schedule: any) => {2431 return {2432 start: BigInt(schedule.start),2433 period: BigInt(schedule.period),2434 periodCount: BigInt(schedule.periodCount),2435 perPeriod: BigInt(schedule.perPeriod),2436 };2437 });2438 }24392440 /**2441 * Claim vested tokens2442 * @param signer signers Keyring2443 */2444 async claim(signer: TSigner) {2445 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2446 const event = result.result.events2447 .find(e => e.event.section === 'vesting' &&2448 e.event.method === 'Claimed' &&2449 e.event.data[0].toHuman() === signer.address);2450 if (!event) throw Error('Cannot find claim in events');2451 }2452}24532454class AddressGroup extends HelperGroup<ChainHelperBase> {2455 /**2456 * Normalizes the address to the specified ss58 format, by default ```42```.2457 * @param address substrate address2458 * @param ss58Format format for address conversion, by default ```42```2459 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2460 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2461 */2462 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2463 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2464 }24652466 /**2467 * Get address in the connected chain format2468 * @param address substrate address2469 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2470 * @returns address in chain format2471 */2472 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2473 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2474 }24752476 /**2477 * Get substrate mirror of an ethereum address2478 * @param ethAddress ethereum address2479 * @param toChainFormat false for normalized account2480 * @example ethToSubstrate('0x9F0583DbB855d...')2481 * @returns substrate mirror of a provided ethereum address2482 */2483 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2484 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2485 }24862487 /**2488 * Get ethereum mirror of a substrate address2489 * @param subAddress substrate account2490 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2491 * @returns ethereum mirror of a provided substrate address2492 */2493 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2494 return CrossAccountId.translateSubToEth(subAddress);2495 }24962497 /**2498 * Encode key to substrate address2499 * @param key key for encoding address2500 * @param ss58Format prefix for encoding to the address of the corresponding network2501 * @returns encoded substrate address2502 */2503 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2504 const u8a :Uint8Array = typeof key === 'string'2505 ? hexToU8a(key)2506 : typeof key === 'bigint'2507 ? hexToU8a(key.toString(16))2508 : key;2509 2510 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2511 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2512 }2513 2514 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2515 if (!allowedDecodedLengths.includes(u8a.length)) {2516 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2517 }2518 2519 const u8aPrefix = ss58Format < 642520 ? new Uint8Array([ss58Format])2521 : new Uint8Array([2522 ((ss58Format & 0xfc) >> 2) | 0x40,2523 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2524 ]);25252526 const input = u8aConcat(u8aPrefix, u8a);2527 2528 return base58Encode(u8aConcat(2529 input,2530 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2531 ));2532 }25332534 /**2535 * Restore substrate address from bigint representation2536 * @param number decimal representation of substrate address2537 * @returns substrate address2538 */2539 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2540 if (this.helper.api === null) {2541 throw 'Not connected';2542 }2543 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2544 if (res === undefined || res === null) {2545 throw 'Restore address error';2546 }2547 return res.toString();2548 }25492550 /**2551 * Convert etherium cross account id to substrate cross account id2552 * @param ethCrossAccount etherium cross account2553 * @returns substrate cross account id2554 */2555 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2556 if (ethCrossAccount.sub === '0') {2557 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2558 }2559 2560 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2561 return {Substrate: ss58};2562 }25632564 paraSiblingSovereignAccount(paraid: number) {2565 // We are getting a *sibling* parachain sovereign account,2566 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2567 const siblingPrefix = '0x7369626c';25682569 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2570 const suffix = '000000000000000000000000000000000000000000000000';25712572 return siblingPrefix + encodedParaId + suffix;2573 }2574}25752576class StakingGroup extends HelperGroup<UniqueHelper> {2577 /**2578 * Stake tokens for App Promotion2579 * @param signer keyring of signer2580 * @param amountToStake amount of tokens to stake2581 * @param label extra label for log2582 * @returns2583 */2584 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2585 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2586 const _stakeResult = await this.helper.executeExtrinsic(2587 signer, 'api.tx.appPromotion.stake',2588 [amountToStake], true,2589 );2590 // TODO extract info from stakeResult2591 return true;2592 }25932594 /**2595 * Unstake tokens for App Promotion2596 * @param signer keyring of signer2597 * @param amountToUnstake amount of tokens to unstake2598 * @param label extra label for log2599 * @returns block number where balances will be unlocked2600 */2601 async unstake(signer: TSigner, label?: string): Promise<number> {2602 if(typeof label === 'undefined') label = `${signer.address}`;2603 const _unstakeResult = await this.helper.executeExtrinsic(2604 signer, 'api.tx.appPromotion.unstake',2605 [], true,2606 );2607 // TODO extract block number fron events2608 return 1;2609 }26102611 /**2612 * Get total staked amount for address2613 * @param address substrate or ethereum address2614 * @returns total staked amount2615 */2616 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2617 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2618 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2619 }26202621 /**2622 * Get total staked per block2623 * @param address substrate or ethereum address2624 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2625 */2626 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2627 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2628 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2629 return {2630 block: block.toBigInt(),2631 amount: amount.toBigInt(),2632 };2633 });2634 }26352636 /**2637 * Get total pending unstake amount for address2638 * @param address substrate or ethereum address2639 * @returns total pending unstake amount2640 */2641 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2642 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2643 }26442645 /**2646 * Get pending unstake amount per block for address2647 * @param address substrate or ethereum address2648 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2649 */2650 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2651 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2652 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2653 return {2654 block: block.toBigInt(),2655 amount: amount.toBigInt(),2656 };2657 });2658 return result;2659 }2660}26612662class SchedulerGroup extends HelperGroup<UniqueHelper> {2663 constructor(helper: UniqueHelper) {2664 super(helper);2665 }26662667 cancelScheduled(signer: TSigner, scheduledId: string) {2668 return this.helper.executeExtrinsic(2669 signer,2670 'api.tx.scheduler.cancelNamed',2671 [scheduledId],2672 true,2673 );2674 }26752676 changePriority(signer: TSigner, scheduledId: string, priority: number) {2677 return this.helper.executeExtrinsic(2678 signer,2679 'api.tx.scheduler.changeNamedPriority',2680 [scheduledId, priority],2681 true,2682 );2683 }26842685 scheduleAt<T extends UniqueHelper>(2686 executionBlockNumber: number,2687 options: ISchedulerOptions = {},2688 ) {2689 return this.schedule<T>('schedule', executionBlockNumber, options);2690 }26912692 scheduleAfter<T extends UniqueHelper>(2693 blocksBeforeExecution: number,2694 options: ISchedulerOptions = {},2695 ) {2696 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2697 }26982699 schedule<T extends UniqueHelper>(2700 scheduleFn: 'schedule' | 'scheduleAfter',2701 blocksNum: number,2702 options: ISchedulerOptions = {},2703 ) {2704 // eslint-disable-next-line @typescript-eslint/naming-convention2705 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2706 return this.helper.clone(ScheduledHelperType, {2707 scheduleFn,2708 blocksNum,2709 options,2710 }) as T;2711 }2712}27132714class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2715 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2716 await this.helper.executeExtrinsic(2717 signer,2718 'api.tx.foreignAssets.registerForeignAsset',2719 [ownerAddress, location, metadata],2720 true,2721 );2722 }27232724 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2725 await this.helper.executeExtrinsic(2726 signer,2727 'api.tx.foreignAssets.updateForeignAsset',2728 [foreignAssetId, location, metadata],2729 true,2730 );2731 }2732}27332734class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2735 palletName: string;27362737 constructor(helper: T, palletName: string) {2738 super(helper);27392740 this.palletName = palletName;2741 }27422743 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2744 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2745 }27462747 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2748 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2749 }27502751 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2752 const destination = {2753 V1: {2754 parents: 0,2755 interior: {2756 X1: {2757 Parachain: destinationParaId,2758 },2759 },2760 },2761 };27622763 const beneficiary = {2764 V1: {2765 parents: 0,2766 interior: {2767 X1: {2768 AccountId32: {2769 network: 'Any',2770 id: targetAccount,2771 },2772 },2773 },2774 },2775 };27762777 const assets = {2778 V1: [2779 {2780 id: {2781 Concrete: {2782 parents: 0,2783 interior: 'Here',2784 },2785 },2786 fun: {2787 Fungible: amount,2788 },2789 },2790 ],2791 };27922793 const feeAssetItem = 0;27942795 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);2796 }2797}27982799class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2800 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {2801 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2802 }28032804 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {2805 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2806 }28072808 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {2809 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2810 }2811}28122813class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2814 async accounts(address: string, currencyId: any) {2815 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2816 return BigInt(free);2817 }2818}28192820class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2821 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2822 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2823 }28242825 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2826 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2827 }28282829 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2830 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2831 }28322833 async account(assetId: string | number, address: string) {2834 const accountAsset = (2835 await this.helper.callRpc('api.query.assets.account', [assetId, address])2836 ).toJSON()! as any;28372838 if (accountAsset !== null) {2839 return BigInt(accountAsset['balance']);2840 } else {2841 return null;2842 }2843 }2844}28452846class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2847 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2848 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2849 }2850}28512852class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2853 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2854 const apiPrefix = 'api.tx.assetManager.';28552856 const registerTx = this.helper.constructApiCall(2857 apiPrefix + 'registerForeignAsset',2858 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2859 );28602861 const setUnitsTx = this.helper.constructApiCall(2862 apiPrefix + 'setAssetUnitsPerSecond',2863 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2864 );28652866 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2867 const encodedProposal = batchCall?.method.toHex() || '';2868 return encodedProposal;2869 }28702871 async assetTypeId(location: any) {2872 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2873 }2874}28752876class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2877 notePreimagePallet: string;28782879 constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {2880 super(helper);2881 this.notePreimagePallet = options.notePreimagePallet;2882 }28832884 async notePreimage(signer: TSigner, encodedProposal: string) {2885 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);2886 }28872888 externalProposeMajority(proposal: any) {2889 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);2890 }28912892 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2893 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2894 }28952896 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2897 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2898 }2899}29002901class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2902 collective: string;29032904 constructor(helper: MoonbeamHelper, collective: string) {2905 super(helper);29062907 this.collective = collective;2908 }29092910 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2911 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2912 }29132914 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2915 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2916 }29172918 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {2919 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2920 }29212922 async proposalCount() {2923 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2924 }2925}29262927export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2928export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;29292930export class UniqueHelper extends ChainHelperBase {2931 balance: BalanceGroup<UniqueHelper>;2932 collection: CollectionGroup;2933 nft: NFTGroup;2934 rft: RFTGroup;2935 ft: FTGroup;2936 staking: StakingGroup;2937 scheduler: SchedulerGroup;2938 foreignAssets: ForeignAssetsGroup;2939 xcm: XcmGroup<UniqueHelper>;2940 xTokens: XTokensGroup<UniqueHelper>;2941 tokens: TokensGroup<UniqueHelper>;29422943 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2944 super(logger, options.helperBase ?? UniqueHelper);29452946 this.balance = new BalanceGroup(this);2947 this.collection = new CollectionGroup(this);2948 this.nft = new NFTGroup(this);2949 this.rft = new RFTGroup(this);2950 this.ft = new FTGroup(this);2951 this.staking = new StakingGroup(this);2952 this.scheduler = new SchedulerGroup(this);2953 this.foreignAssets = new ForeignAssetsGroup(this);2954 this.xcm = new XcmGroup(this, 'polkadotXcm');2955 this.xTokens = new XTokensGroup(this);2956 this.tokens = new TokensGroup(this);2957 }29582959 getSudo<T extends UniqueHelper>() {2960 // eslint-disable-next-line @typescript-eslint/naming-convention2961 const SudoHelperType = SudoHelper(this.helperBase);2962 return this.clone(SudoHelperType) as T;2963 }2964}29652966export class XcmChainHelper extends ChainHelperBase {2967 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2968 const wsProvider = new WsProvider(wsEndpoint);2969 this.api = new ApiPromise({2970 provider: wsProvider,2971 });2972 await this.api.isReadyOrError;2973 this.network = await UniqueHelper.detectNetwork(this.api);2974 }2975}29762977export class RelayHelper extends XcmChainHelper {2978 balance: SubstrateBalanceGroup<RelayHelper>;2979 xcm: XcmGroup<RelayHelper>;29802981 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2982 super(logger, options.helperBase ?? RelayHelper);29832984 this.balance = new SubstrateBalanceGroup(this);2985 this.xcm = new XcmGroup(this, 'xcmPallet');2986 }2987}29882989export class WestmintHelper extends XcmChainHelper {2990 balance: SubstrateBalanceGroup<WestmintHelper>;2991 xcm: XcmGroup<WestmintHelper>;2992 assets: AssetsGroup<WestmintHelper>;2993 xTokens: XTokensGroup<WestmintHelper>;29942995 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2996 super(logger, options.helperBase ?? WestmintHelper);29972998 this.balance = new SubstrateBalanceGroup(this);2999 this.xcm = new XcmGroup(this, 'polkadotXcm');3000 this.assets = new AssetsGroup(this);3001 this.xTokens = new XTokensGroup(this);3002 }3003}30043005export class MoonbeamHelper extends XcmChainHelper {3006 balance: EthereumBalanceGroup<MoonbeamHelper>;3007 assetManager: MoonbeamAssetManagerGroup;3008 assets: AssetsGroup<MoonbeamHelper>;3009 xTokens: XTokensGroup<MoonbeamHelper>;3010 democracy: MoonbeamDemocracyGroup;3011 collective: {3012 council: MoonbeamCollectiveGroup,3013 techCommittee: MoonbeamCollectiveGroup,3014 };30153016 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3017 super(logger, options.helperBase ?? MoonbeamHelper);30183019 this.balance = new EthereumBalanceGroup(this);3020 this.assetManager = new MoonbeamAssetManagerGroup(this);3021 this.assets = new AssetsGroup(this);3022 this.xTokens = new XTokensGroup(this);3023 this.democracy = new MoonbeamDemocracyGroup(this, options);3024 this.collective = {3025 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3026 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3027 };3028 }3029}30303031export class AcalaHelper extends XcmChainHelper {3032 balance: SubstrateBalanceGroup<AcalaHelper>;3033 assetRegistry: AcalaAssetRegistryGroup;3034 xTokens: XTokensGroup<AcalaHelper>;3035 tokens: TokensGroup<AcalaHelper>;30363037 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3038 super(logger, options.helperBase ?? AcalaHelper);30393040 this.balance = new SubstrateBalanceGroup(this);3041 this.assetRegistry = new AcalaAssetRegistryGroup(this);3042 this.xTokens = new XTokensGroup(this);3043 this.tokens = new TokensGroup(this);3044 }30453046 getSudo<T extends AcalaHelper>() {3047 // eslint-disable-next-line @typescript-eslint/naming-convention3048 const SudoHelperType = SudoHelper(this.helperBase);3049 return this.clone(SudoHelperType) as T;3050 }3051}30523053// eslint-disable-next-line @typescript-eslint/naming-convention3054function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3055 return class extends Base {3056 scheduleFn: 'schedule' | 'scheduleAfter';3057 blocksNum: number;3058 options: ISchedulerOptions;30593060 constructor(...args: any[]) {3061 const logger = args[0] as ILogger;3062 const options = args[1] as {3063 scheduleFn: 'schedule' | 'scheduleAfter',3064 blocksNum: number,3065 options: ISchedulerOptions3066 };30673068 super(logger);30693070 this.scheduleFn = options.scheduleFn;3071 this.blocksNum = options.blocksNum;3072 this.options = options.options;3073 }30743075 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3076 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);3077 3078 const mandatorySchedArgs = [3079 this.blocksNum,3080 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3081 this.options.priority ?? null,3082 scheduledTx,3083 ];3084 3085 let schedArgs;3086 let scheduleFn;30873088 if (this.options.scheduledId) {3089 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];30903091 if (this.scheduleFn == 'schedule') {3092 scheduleFn = 'scheduleNamed';3093 } else if (this.scheduleFn == 'scheduleAfter') {3094 scheduleFn = 'scheduleNamedAfter';3095 }3096 } else {3097 schedArgs = mandatorySchedArgs;3098 scheduleFn = this.scheduleFn;3099 }31003101 const extrinsic = 'api.tx.scheduler.' + scheduleFn;31023103 return super.executeExtrinsic(3104 sender,3105 extrinsic,3106 schedArgs,3107 expectSuccess,3108 );3109 }3110 };3111}31123113// eslint-disable-next-line @typescript-eslint/naming-convention3114function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3115 return class extends Base {3116 constructor(...args: any[]) {3117 super(...args);3118 }31193120 executeExtrinsic (3121 sender: IKeyringPair,3122 extrinsic: string,3123 params: any[],3124 expectSuccess?: boolean,3125 ): Promise<ITransactionResult> {3126 const call = this.constructApiCall(extrinsic, params);3127 return super.executeExtrinsic(3128 sender,3129 'api.tx.sudo.sudo',3130 [call],3131 expectSuccess,3132 );3133 }3134 };3135}31363137export class UniqueBaseCollection {3138 helper: UniqueHelper;3139 collectionId: number;31403141 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3142 this.collectionId = collectionId;3143 this.helper = uniqueHelper;3144 }31453146 async getData() {3147 return await this.helper.collection.getData(this.collectionId);3148 }31493150 async getLastTokenId() {3151 return await this.helper.collection.getLastTokenId(this.collectionId);3152 }31533154 async doesTokenExist(tokenId: number) {3155 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3156 }31573158 async getAdmins() {3159 return await this.helper.collection.getAdmins(this.collectionId);3160 }31613162 async getAllowList() {3163 return await this.helper.collection.getAllowList(this.collectionId);3164 }31653166 async getEffectiveLimits() {3167 return await this.helper.collection.getEffectiveLimits(this.collectionId);3168 }31693170 async getProperties(propertyKeys?: string[] | null) {3171 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3172 }31733174 async getPropertiesConsumedSpace() {3175 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3176 }31773178 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3179 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3180 }31813182 async getOptions() {3183 return await this.helper.collection.getCollectionOptions(this.collectionId);3184 }31853186 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3187 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3188 }31893190 async confirmSponsorship(signer: TSigner) {3191 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3192 }31933194 async removeSponsor(signer: TSigner) {3195 return await this.helper.collection.removeSponsor(signer, this.collectionId);3196 }31973198 async setLimits(signer: TSigner, limits: ICollectionLimits) {3199 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3200 }32013202 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3203 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3204 }32053206 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3207 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3208 }32093210 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3211 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3212 }32133214 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3215 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3216 }32173218 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3219 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3220 }32213222 async setProperties(signer: TSigner, properties: IProperty[]) {3223 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3224 }32253226 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3227 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3228 }32293230 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3231 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3232 }32333234 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3235 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3236 }32373238 async disableNesting(signer: TSigner) {3239 return await this.helper.collection.disableNesting(signer, this.collectionId);3240 }32413242 async burn(signer: TSigner) {3243 return await this.helper.collection.burn(signer, this.collectionId);3244 }32453246 scheduleAt<T extends UniqueHelper>(3247 executionBlockNumber: number,3248 options: ISchedulerOptions = {},3249 ) {3250 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3251 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3252 }32533254 scheduleAfter<T extends UniqueHelper>(3255 blocksBeforeExecution: number,3256 options: ISchedulerOptions = {},3257 ) {3258 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3259 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3260 }32613262 getSudo<T extends UniqueHelper>() {3263 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3264 }3265}326632673268export class UniqueNFTCollection extends UniqueBaseCollection {3269 getTokenObject(tokenId: number) {3270 return new UniqueNFToken(tokenId, this);3271 }32723273 async getTokensByAddress(addressObj: ICrossAccountId) {3274 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3275 }32763277 async getToken(tokenId: number, blockHashAt?: string) {3278 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3279 }32803281 async getTokenOwner(tokenId: number, blockHashAt?: string) {3282 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3283 }32843285 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3286 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3287 }32883289 async getTokenChildren(tokenId: number, blockHashAt?: string) {3290 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3291 }32923293 async getPropertyPermissions(propertyKeys: string[] | null = null) {3294 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3295 }32963297 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3298 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3299 }33003301 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3302 const api = this.helper.getApi();3303 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();3304 3305 return (props! as any).consumedSpace;3306 }33073308 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3309 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3310 }33113312 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3313 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3314 }33153316 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3317 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3318 }33193320 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3321 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3322 }33233324 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3325 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3326 }33273328 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3329 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3330 }33313332 async burnToken(signer: TSigner, tokenId: number) {3333 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3334 }33353336 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3337 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3338 }33393340 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3341 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3342 }33433344 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3345 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3346 }33473348 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3349 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3350 }33513352 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3353 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3354 }33553356 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3357 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3358 }33593360 scheduleAt<T extends UniqueHelper>(3361 executionBlockNumber: number,3362 options: ISchedulerOptions = {},3363 ) {3364 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3365 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3366 }33673368 scheduleAfter<T extends UniqueHelper>(3369 blocksBeforeExecution: number,3370 options: ISchedulerOptions = {},3371 ) {3372 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3373 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3374 }33753376 getSudo<T extends UniqueHelper>() {3377 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3378 }3379}338033813382export class UniqueRFTCollection extends UniqueBaseCollection {3383 getTokenObject(tokenId: number) {3384 return new UniqueRFToken(tokenId, this);3385 }33863387 async getToken(tokenId: number, blockHashAt?: string) {3388 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3389 }33903391 async getTokensByAddress(addressObj: ICrossAccountId) {3392 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3393 }33943395 async getTop10TokenOwners(tokenId: number) {3396 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3397 }33983399 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3400 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3401 }34023403 async getTokenTotalPieces(tokenId: number) {3404 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3405 }34063407 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3408 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3409 }34103411 async getPropertyPermissions(propertyKeys: string[] | null = null) {3412 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3413 }34143415 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3416 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3417 }34183419 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3420 const api = this.helper.getApi();3421 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();3422 3423 return (props! as any).consumedSpace;3424 }34253426 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3427 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3428 }34293430 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3431 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3432 }34333434 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3435 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3436 }34373438 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3439 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3440 }34413442 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3443 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3444 }34453446 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3447 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3448 }34493450 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3451 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3452 }34533454 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3455 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3456 }34573458 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3459 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3460 }34613462 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3463 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3464 }34653466 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3467 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3468 }34693470 scheduleAt<T extends UniqueHelper>(3471 executionBlockNumber: number,3472 options: ISchedulerOptions = {},3473 ) {3474 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3475 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3476 }34773478 scheduleAfter<T extends UniqueHelper>(3479 blocksBeforeExecution: number,3480 options: ISchedulerOptions = {},3481 ) {3482 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3483 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3484 }34853486 getSudo<T extends UniqueHelper>() {3487 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3488 }3489}349034913492export class UniqueFTCollection extends UniqueBaseCollection {3493 async getBalance(addressObj: ICrossAccountId) {3494 return await this.helper.ft.getBalance(this.collectionId, addressObj);3495 }34963497 async getTotalPieces() {3498 return await this.helper.ft.getTotalPieces(this.collectionId);3499 }35003501 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3502 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3503 }35043505 async getTop10Owners() {3506 return await this.helper.ft.getTop10Owners(this.collectionId);3507 }35083509 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3510 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3511 }35123513 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3514 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3515 }35163517 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3518 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3519 }35203521 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3522 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3523 }35243525 async burnTokens(signer: TSigner, amount=1n) {3526 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3527 }35283529 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3530 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3531 }35323533 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3534 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3535 }35363537 scheduleAt<T extends UniqueHelper>(3538 executionBlockNumber: number,3539 options: ISchedulerOptions = {},3540 ) {3541 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3542 return new UniqueFTCollection(this.collectionId, scheduledHelper);3543 }35443545 scheduleAfter<T extends UniqueHelper>(3546 blocksBeforeExecution: number,3547 options: ISchedulerOptions = {},3548 ) {3549 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3550 return new UniqueFTCollection(this.collectionId, scheduledHelper);3551 }35523553 getSudo<T extends UniqueHelper>() {3554 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3555 }3556}355735583559export class UniqueBaseToken {3560 collection: UniqueNFTCollection | UniqueRFTCollection;3561 collectionId: number;3562 tokenId: number;35633564 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3565 this.collection = collection;3566 this.collectionId = collection.collectionId;3567 this.tokenId = tokenId;3568 }35693570 async getNextSponsored(addressObj: ICrossAccountId) {3571 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3572 }35733574 async getProperties(propertyKeys?: string[] | null) {3575 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3576 }35773578 async getTokenPropertiesConsumedSpace() {3579 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3580 }35813582 async setProperties(signer: TSigner, properties: IProperty[]) {3583 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3584 }35853586 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3587 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3588 }35893590 async doesExist() {3591 return await this.collection.doesTokenExist(this.tokenId);3592 }35933594 nestingAccount() {3595 return this.collection.helper.util.getTokenAccount(this);3596 }35973598 scheduleAt<T extends UniqueHelper>(3599 executionBlockNumber: number,3600 options: ISchedulerOptions = {},3601 ) {3602 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3603 return new UniqueBaseToken(this.tokenId, scheduledCollection);3604 }36053606 scheduleAfter<T extends UniqueHelper>(3607 blocksBeforeExecution: number,3608 options: ISchedulerOptions = {},3609 ) {3610 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3611 return new UniqueBaseToken(this.tokenId, scheduledCollection);3612 }36133614 getSudo<T extends UniqueHelper>() {3615 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3616 }3617}361836193620export class UniqueNFToken extends UniqueBaseToken {3621 collection: UniqueNFTCollection;36223623 constructor(tokenId: number, collection: UniqueNFTCollection) {3624 super(tokenId, collection);3625 this.collection = collection;3626 }36273628 async getData(blockHashAt?: string) {3629 return await this.collection.getToken(this.tokenId, blockHashAt);3630 }36313632 async getOwner(blockHashAt?: string) {3633 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3634 }36353636 async getTopmostOwner(blockHashAt?: string) {3637 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3638 }36393640 async getChildren(blockHashAt?: string) {3641 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3642 }36433644 async nest(signer: TSigner, toTokenObj: IToken) {3645 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3646 }36473648 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3649 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3650 }36513652 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3653 return await this.collection.transferToken(signer, this.tokenId, addressObj);3654 }36553656 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3657 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3658 }36593660 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3661 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3662 }36633664 async isApproved(toAddressObj: ICrossAccountId) {3665 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3666 }36673668 async burn(signer: TSigner) {3669 return await this.collection.burnToken(signer, this.tokenId);3670 }36713672 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3673 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3674 }36753676 scheduleAt<T extends UniqueHelper>(3677 executionBlockNumber: number,3678 options: ISchedulerOptions = {},3679 ) {3680 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3681 return new UniqueNFToken(this.tokenId, scheduledCollection);3682 }36833684 scheduleAfter<T extends UniqueHelper>(3685 blocksBeforeExecution: number,3686 options: ISchedulerOptions = {},3687 ) {3688 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3689 return new UniqueNFToken(this.tokenId, scheduledCollection);3690 }36913692 getSudo<T extends UniqueHelper>() {3693 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3694 }3695}36963697export class UniqueRFToken extends UniqueBaseToken {3698 collection: UniqueRFTCollection;36993700 constructor(tokenId: number, collection: UniqueRFTCollection) {3701 super(tokenId, collection);3702 this.collection = collection;3703 }37043705 async getData(blockHashAt?: string) {3706 return await this.collection.getToken(this.tokenId, blockHashAt);3707 }37083709 async getTop10Owners() {3710 return await this.collection.getTop10TokenOwners(this.tokenId);3711 }37123713 async getBalance(addressObj: ICrossAccountId) {3714 return await this.collection.getTokenBalance(this.tokenId, addressObj);3715 }37163717 async getTotalPieces() {3718 return await this.collection.getTokenTotalPieces(this.tokenId);3719 }37203721 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3722 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3723 }37243725 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3726 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3727 }37283729 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3730 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3731 }37323733 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3734 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3735 }37363737 async repartition(signer: TSigner, amount: bigint) {3738 return await this.collection.repartitionToken(signer, this.tokenId, amount);3739 }37403741 async burn(signer: TSigner, amount=1n) {3742 return await this.collection.burnToken(signer, this.tokenId, amount);3743 }37443745 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3746 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3747 }37483749 scheduleAt<T extends UniqueHelper>(3750 executionBlockNumber: number,3751 options: ISchedulerOptions = {},3752 ) {3753 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3754 return new UniqueRFToken(this.tokenId, scheduledCollection);3755 }37563757 scheduleAfter<T extends UniqueHelper>(3758 blocksBeforeExecution: number,3759 options: ISchedulerOptions = {},3760 ) {3761 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3762 return new UniqueRFToken(this.tokenId, scheduledCollection);3763 }37643765 getSudo<T extends UniqueHelper>() {3766 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3767 }3768}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15 IApiListeners,16 IBlock,17 IEvent,18 IChainProperties,19 ICollectionCreationOptions,20 ICollectionLimits,21 ICollectionPermissions,22 ICrossAccountId,23 ICrossAccountIdLower,24 ILogger,25 INestingPermissions,26 IProperty,27 IStakingInfo,28 ISchedulerOptions,29 ISubstrateBalance,30 IToken,31 ITokenPropertyPermission,32 ITransactionResult,33 IUniqueHelperLog,34 TApiAllowedListeners,35 TEthereumAccount,36 TSigner,37 TSubstrateAccount,38 TNetworks,39 IForeignAssetMetadata,40 AcalaAssetMetadata,41 MoonbeamAssetInfo,42 DemocracyStandardAccountVote,43 IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50 Substrate?: TSubstrateAccount;51 Ethereum?: TEthereumAccount;5253 constructor(account: ICrossAccountId) {54 if (account.Substrate) this.Substrate = account.Substrate;55 if (account.Ethereum) this.Ethereum = account.Ethereum;56 }5758 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59 switch (domain) {60 case 'Substrate': return new CrossAccountId({Substrate: account.address});61 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62 }63 }6465 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67 }6869 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70 return encodeAddress(decodeAddress(address), ss58Format);71 }7273 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75 }7677 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79 return this;80 }8182 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84 }8586 toEthereum(): CrossAccountId {87 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88 return this;89 }9091 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92 return evmToAddress(address, ss58Format);93 }9495 toSubstrate(ss58Format?: number): CrossAccountId {96 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97 return this;98 }99100 toLowerCase(): CrossAccountId {101 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103 return this;104 }105}106107const nesting = {108 toChecksumAddress(address: string): string {109 if (typeof address === 'undefined') return '';110111 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113 address = address.toLowerCase().replace(/^0x/i,'');114 const addressHash = keccakAsHex(address).replace(/^0x/i,'');115 const checksumAddress = ['0x'];116117 for (let i = 0; i < address.length; i++) {118 // If ith character is 8 to f then make it uppercase119 if (parseInt(addressHash[i], 16) > 7) {120 checksumAddress.push(address[i].toUpperCase());121 } else {122 checksumAddress.push(address[i]);123 }124 }125 return checksumAddress.join('');126 },127 tokenIdToAddress(collectionId: number, tokenId: number) {128 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);129 },130};131132class UniqueUtil {133 static transactionStatus = {134 NOT_READY: 'NotReady',135 FAIL: 'Fail',136 SUCCESS: 'Success',137 };138139 static chainLogType = {140 EXTRINSIC: 'extrinsic',141 RPC: 'rpc',142 };143144 static getTokenAccount(token: IToken): CrossAccountId {145 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146 }147148 static getTokenAddress(token: IToken): string {149 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150 }151152 static getDefaultLogger(): ILogger {153 return {154 log(msg: any, level = 'INFO') {155 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156 },157 level: {158 ERROR: 'ERROR',159 WARNING: 'WARNING',160 INFO: 'INFO',161 },162 };163 }164165 static vec2str(arr: string[] | number[]) {166 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167 }168169 static str2vec(string: string) {170 if (typeof string !== 'string') return string;171 return Array.from(string).map(x => x.charCodeAt(0));172 }173174 static fromSeed(seed: string, ss58Format = 42) {175 const keyring = new Keyring({type: 'sr25519', ss58Format});176 return keyring.addFromUri(seed);177 }178179 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180 if (creationResult.status !== this.transactionStatus.SUCCESS) {181 throw Error('Unable to create collection!');182 }183184 let collectionId = null;185 creationResult.result.events.forEach(({event: {data, method, section}}) => {186 if ((section === 'common') && (method === 'CollectionCreated')) {187 collectionId = parseInt(data[0].toString(), 10);188 }189 });190191 if (collectionId === null) {192 throw Error('No CollectionCreated event was found!');193 }194195 return collectionId;196 }197198 static extractTokensFromCreationResult(creationResult: ITransactionResult): {199 success: boolean,200 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201 } {202 if (creationResult.status !== this.transactionStatus.SUCCESS) {203 throw Error('Unable to create tokens!');204 }205 let success = false;206 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207 creationResult.result.events.forEach(({event: {data, method, section}}) => {208 if (method === 'ExtrinsicSuccess') {209 success = true;210 } else if ((section === 'common') && (method === 'ItemCreated')) {211 tokens.push({212 collectionId: parseInt(data[0].toString(), 10),213 tokenId: parseInt(data[1].toString(), 10),214 owner: data[2].toHuman(),215 amount: data[3].toBigInt(),216 });217 }218 });219 return {success, tokens};220 }221222 static extractTokensFromBurnResult(burnResult: ITransactionResult): {223 success: boolean,224 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225 } {226 if (burnResult.status !== this.transactionStatus.SUCCESS) {227 throw Error('Unable to burn tokens!');228 }229 let success = false;230 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231 burnResult.result.events.forEach(({event: {data, method, section}}) => {232 if (method === 'ExtrinsicSuccess') {233 success = true;234 } else if ((section === 'common') && (method === 'ItemDestroyed')) {235 tokens.push({236 collectionId: parseInt(data[0].toString(), 10),237 tokenId: parseInt(data[1].toString(), 10),238 owner: data[2].toHuman(),239 amount: data[3].toBigInt(),240 });241 }242 });243 return {success, tokens};244 }245246 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247 let eventId = null;248 events.forEach(({event: {data, method, section}}) => {249 if ((section === expectedSection) && (method === expectedMethod)) {250 eventId = parseInt(data[0].toString(), 10);251 }252 });253254 if (eventId === null) {255 throw Error(`No ${expectedMethod} event was found!`);256 }257 return eventId === collectionId;258 }259260 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261 const normalizeAddress = (address: string | ICrossAccountId) => {262 if(typeof address === 'string') return address;263 const obj = {} as any;264 Object.keys(address).forEach(k => {265 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266 });267 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269 return address;270 };271 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272 events.forEach(({event: {data, method, section}}) => {273 if ((section === 'common') && (method === 'Transfer')) {274 const hData = (data as any).toJSON();275 transfer = {276 collectionId: hData[0],277 tokenId: hData[1],278 from: normalizeAddress(hData[2]),279 to: normalizeAddress(hData[3]),280 amount: BigInt(hData[4]),281 };282 }283 });284 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287 isSuccess = isSuccess && amount === transfer.amount;288 return isSuccess;289 }290291 static bigIntToDecimals(number: bigint, decimals = 18) {292 const numberStr = number.toString();293 const dotPos = numberStr.length - decimals;294295 if (dotPos <= 0) {296 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297 } else {298 const intPart = numberStr.substring(0, dotPos);299 const fractPart = numberStr.substring(dotPos);300 return intPart + '.' + fractPart;301 }302 }303}304305class UniqueEventHelper {306 private static extractIndex(index: any): [number, number] | string {307 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308 return index.toJSON();309 }310311 private static extractSub(data: any, subTypes: any): {[key: string]: any} {312 let obj: any = {};313 let index = 0;314315 if (data.entries) {316 for(const [key, value] of data.entries()) {317 obj[key] = this.extractData(value, subTypes[index]);318 index++;319 }320 } else obj = data.toJSON();321322 return obj;323 }324325 private static toHuman(data: any) {326 return data && data.toHuman ? data.toHuman() : `${data}`;327 }328329 private static extractData(data: any, type: any): any {330 if(!type) return this.toHuman(data);331 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334 return this.toHuman(data);335 }336337 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338 const parsedEvents: IEvent[] = [];339340 events.forEach((record) => {341 const {event, phase} = record;342 const types = event.typeDef;343344 const eventData: IEvent = {345 section: event.section.toString(),346 method: event.method.toString(),347 index: this.extractIndex(event.index),348 data: [],349 phase: phase.toJSON(),350 };351352 event.data.forEach((val: any, index: number) => {353 eventData.data.push(this.extractData(val, types[index]));354 });355356 parsedEvents.push(eventData);357 });358359 return parsedEvents;360 }361}362363export class ChainHelperBase {364 helperBase: any;365366 transactionStatus = UniqueUtil.transactionStatus;367 chainLogType = UniqueUtil.chainLogType;368 util: typeof UniqueUtil;369 eventHelper: typeof UniqueEventHelper;370 logger: ILogger;371 api: ApiPromise | null;372 forcedNetwork: TNetworks | null;373 network: TNetworks | null;374 chainLog: IUniqueHelperLog[];375 children: ChainHelperBase[];376 address: AddressGroup;377 chain: ChainGroup;378379 constructor(logger?: ILogger, helperBase?: any) {380 this.helperBase = helperBase;381382 this.util = UniqueUtil;383 this.eventHelper = UniqueEventHelper;384 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();385 this.logger = logger;386 this.api = null;387 this.forcedNetwork = null;388 this.network = null;389 this.chainLog = [];390 this.children = [];391 this.address = new AddressGroup(this);392 this.chain = new ChainGroup(this);393 }394395 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {396 Object.setPrototypeOf(helperCls.prototype, this);397 const newHelper = new helperCls(this.logger, options);398399 newHelper.api = this.api;400 newHelper.network = this.network;401 newHelper.forceNetwork = this.forceNetwork;402403 this.children.push(newHelper);404405 return newHelper;406 }407408 getApi(): ApiPromise {409 if(this.api === null) throw Error('API not initialized');410 return this.api;411 }412413 async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {414 const collectedEvents: IEvent[] = [];415 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {416 const ievents = this.eventHelper.extractEvents(events);417 ievents.forEach((event) => {418 expectedEvents.forEach((e => {419 if (event.section === e.section && e.names.includes(event.method)) {420 collectedEvents.push(event);421 }422 }));423 });424 });425 return {unsubscribe: unsubscribe as any, collectedEvents};426 }427428 clearChainLog(): void {429 this.chainLog = [];430 }431432 forceNetwork(value: TNetworks): void {433 this.forcedNetwork = value;434 }435436 async connect(wsEndpoint: string, listeners?: IApiListeners) {437 if (this.api !== null) throw Error('Already connected');438 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);439 this.api = api;440 this.network = network;441 }442443 async disconnect() {444 for (const child of this.children) {445 child.clearApi();446 }447448 if (this.api === null) return;449 await this.api.disconnect();450 this.clearApi();451 }452453 clearApi() {454 this.api = null;455 this.network = null;456 }457458 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {459 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;460 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];461462 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;463464 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;465 return 'opal';466 }467468 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {469 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});470 await api.isReady;471472 const network = await this.detectNetwork(api);473474 await api.disconnect();475476 return network;477 }478479 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{480 api: ApiPromise;481 network: TNetworks;482 }> {483 if(typeof network === 'undefined' || network === null) network = 'opal';484 const supportedRPC = {485 opal: {486 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,487 },488 quartz: {489 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,490 },491 unique: {492 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,493 },494 rococo: {},495 westend: {},496 moonbeam: {},497 moonriver: {},498 acala: {},499 karura: {},500 westmint: {},501 };502 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);503 const rpc = supportedRPC[network];504505 // TODO: investigate how to replace rpc in runtime506 // api._rpcCore.addUserInterfaces(rpc);507508 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});509510 await api.isReadyOrError;511512 if (typeof listeners === 'undefined') listeners = {};513 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {514 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;515 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);516 }517518 return {api, network};519 }520521 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {522 const {events, status} = data;523 if (status.isReady) {524 return this.transactionStatus.NOT_READY;525 }526 if (status.isBroadcast) {527 return this.transactionStatus.NOT_READY;528 }529 if (status.isInBlock || status.isFinalized) {530 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');531 if (errors.length > 0) {532 return this.transactionStatus.FAIL;533 }534 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {535 return this.transactionStatus.SUCCESS;536 }537 }538539 return this.transactionStatus.FAIL;540 }541542 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {543 const sign = (callback: any) => {544 if(options !== null) return transaction.signAndSend(sender, options, callback);545 return transaction.signAndSend(sender, callback);546 };547 // eslint-disable-next-line no-async-promise-executor548 return new Promise(async (resolve, reject) => {549 try {550 const unsub = await sign((result: any) => {551 const status = this.getTransactionStatus(result);552553 if (status === this.transactionStatus.SUCCESS) {554 this.logger.log(`${label} successful`);555 unsub();556 resolve({result, status});557 } else if (status === this.transactionStatus.FAIL) {558 let moduleError = null;559560 if (result.hasOwnProperty('dispatchError')) {561 const dispatchError = result['dispatchError'];562563 if (dispatchError) {564 if (dispatchError.isModule) {565 const modErr = dispatchError.asModule;566 const errorMeta = dispatchError.registry.findMetaError(modErr);567568 moduleError = `${errorMeta.section}.${errorMeta.name}`;569 } else {570 moduleError = dispatchError.toHuman();571 }572 } else {573 this.logger.log(result, this.logger.level.ERROR);574 }575 }576577 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);578 unsub();579 reject({status, moduleError, result});580 }581 });582 } catch (e) {583 this.logger.log(e, this.logger.level.ERROR);584 reject(e);585 }586 });587 }588589 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {590 const api = this.getApi();591 const signingInfo = await api.derive.tx.signingInfo(signer.address);592593 // We need to sign the tx because594 // unsigned transactions does not have an inclusion fee595 tx.sign(signer, {596 blockHash: api.genesisHash,597 genesisHash: api.genesisHash,598 runtimeVersion: api.runtimeVersion,599 nonce: signingInfo.nonce,600 });601602 if (len === null) {603 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;604 } else {605 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;606 }607 }608609 constructApiCall(apiCall: string, params: any[]) {610 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);611 let call = this.getApi() as any;612 for(const part of apiCall.slice(4).split('.')) {613 call = call[part];614 }615 return call(...params);616 }617618 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {619 if(this.api === null) throw Error('API not initialized');620 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);621622 const startTime = (new Date()).getTime();623 let result: ITransactionResult;624 let events: IEvent[] = [];625 try {626 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;627 events = this.eventHelper.extractEvents(result.result.events);628 }629 catch(e) {630 if(!(e as object).hasOwnProperty('status')) throw e;631 result = e as ITransactionResult;632 }633634 const endTime = (new Date()).getTime();635636 const log = {637 executedAt: endTime,638 executionTime: endTime - startTime,639 type: this.chainLogType.EXTRINSIC,640 status: result.status,641 call: extrinsic,642 signer: this.getSignerAddress(sender),643 params,644 } as IUniqueHelperLog;645646 if(result.status !== this.transactionStatus.SUCCESS) {647 if (result.moduleError) log.moduleError = result.moduleError;648 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;649 }650 if(events.length > 0) log.events = events;651652 this.chainLog.push(log);653654 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {655 if (result.moduleError) throw Error(`${result.moduleError}`);656 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));657 }658 return result;659 }660661 async callRpc(rpc: string, params?: any[]) {662 if(typeof params === 'undefined') params = [];663 if(this.api === null) throw Error('API not initialized');664 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);665666 const startTime = (new Date()).getTime();667 let result;668 let error = null;669 const log = {670 type: this.chainLogType.RPC,671 call: rpc,672 params,673 } as IUniqueHelperLog;674675 try {676 result = await this.constructApiCall(rpc, params);677 }678 catch(e) {679 error = e;680 }681682 const endTime = (new Date()).getTime();683684 log.executedAt = endTime;685 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';686 log.executionTime = endTime - startTime;687688 this.chainLog.push(log);689690 if(error !== null) throw error;691692 return result;693 }694695 getSignerAddress(signer: IKeyringPair | string): string {696 if(typeof signer === 'string') return signer;697 return signer.address;698 }699700 fetchAllPalletNames(): string[] {701 if(this.api === null) throw Error('API not initialized');702 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());703 }704705 fetchMissingPalletNames(requiredPallets: string[]): string[] {706 const palletNames = this.fetchAllPalletNames();707 return requiredPallets.filter(p => !palletNames.includes(p));708 }709}710711712class HelperGroup<T extends ChainHelperBase> {713 helper: T;714715 constructor(uniqueHelper: T) {716 this.helper = uniqueHelper;717 }718}719720721class CollectionGroup extends HelperGroup<UniqueHelper> {722 /**723 * Get number of blocks when sponsored transaction is available.724 *725 * @param collectionId ID of collection726 * @param tokenId ID of token727 * @param addressObj address for which the sponsorship is checked728 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});729 * @returns number of blocks or null if sponsorship hasn't been set730 */731 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {732 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();733 }734735 /**736 * Get the number of created collections.737 *738 * @returns number of created collections739 */740 async getTotalCount(): Promise<number> {741 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();742 }743744 /**745 * Get information about the collection with additional data,746 * including the number of tokens it contains, its administrators,747 * the normalized address of the collection's owner, and decoded name and description.748 *749 * @param collectionId ID of collection750 * @example await getData(2)751 * @returns collection information object752 */753 async getData(collectionId: number): Promise<{754 id: number;755 name: string;756 description: string;757 tokensCount: number;758 admins: CrossAccountId[];759 normalizedOwner: TSubstrateAccount;760 raw: any761 } | null> {762 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);763 const humanCollection = collection.toHuman(), collectionData = {764 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],765 raw: humanCollection,766 } as any, jsonCollection = collection.toJSON();767 if (humanCollection === null) return null;768 collectionData.raw.limits = jsonCollection.limits;769 collectionData.raw.permissions = jsonCollection.permissions;770 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);771 for (const key of ['name', 'description']) {772 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);773 }774775 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))776 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)777 : 0;778 collectionData.admins = await this.getAdmins(collectionId);779780 return collectionData;781 }782783 /**784 * Get the addresses of the collection's administrators, optionally normalized.785 *786 * @param collectionId ID of collection787 * @param normalize whether to normalize the addresses to the default ss58 format788 * @example await getAdmins(1)789 * @returns array of administrators790 */791 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {792 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();793794 return normalize795 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())796 : admins;797 }798799 /**800 * Get the addresses added to the collection allow-list, optionally normalized.801 * @param collectionId ID of collection802 * @param normalize whether to normalize the addresses to the default ss58 format803 * @example await getAllowList(1)804 * @returns array of allow-listed addresses805 */806 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {807 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();808 return normalize809 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())810 : allowListed;811 }812813 /**814 * Get the effective limits of the collection instead of null for default values815 *816 * @param collectionId ID of collection817 * @example await getEffectiveLimits(2)818 * @returns object of collection limits819 */820 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {821 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();822 }823824 /**825 * Burns the collection if the signer has sufficient permissions and collection is empty.826 *827 * @param signer keyring of signer828 * @param collectionId ID of collection829 * @example await helper.collection.burn(aliceKeyring, 3);830 * @returns ```true``` if extrinsic success, otherwise ```false```831 */832 async burn(signer: TSigner, collectionId: number): Promise<boolean> {833 const result = await this.helper.executeExtrinsic(834 signer,835 'api.tx.unique.destroyCollection', [collectionId],836 true,837 );838839 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');840 }841842 /**843 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.844 *845 * @param signer keyring of signer846 * @param collectionId ID of collection847 * @param sponsorAddress Sponsor substrate address848 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")849 * @returns ```true``` if extrinsic success, otherwise ```false```850 */851 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {852 const result = await this.helper.executeExtrinsic(853 signer,854 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],855 true,856 );857858 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');859 }860861 /**862 * Confirms consent to sponsor the collection on behalf of the signer.863 *864 * @param signer keyring of signer865 * @param collectionId ID of collection866 * @example confirmSponsorship(aliceKeyring, 10)867 * @returns ```true``` if extrinsic success, otherwise ```false```868 */869 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {870 const result = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.confirmSponsorship', [collectionId],873 true,874 );875876 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');877 }878879 /**880 * Removes the sponsor of a collection, regardless if it consented or not.881 *882 * @param signer keyring of signer883 * @param collectionId ID of collection884 * @example removeSponsor(aliceKeyring, 10)885 * @returns ```true``` if extrinsic success, otherwise ```false```886 */887 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {888 const result = await this.helper.executeExtrinsic(889 signer,890 'api.tx.unique.removeCollectionSponsor', [collectionId],891 true,892 );893894 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');895 }896897 /**898 * Sets the limits of the collection. At least one limit must be specified for a correct call.899 *900 * @param signer keyring of signer901 * @param collectionId ID of collection902 * @param limits collection limits object903 * @example904 * await setLimits(905 * aliceKeyring,906 * 10,907 * {908 * sponsorTransferTimeout: 0,909 * ownerCanDestroy: false910 * }911 * )912 * @returns ```true``` if extrinsic success, otherwise ```false```913 */914 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {915 const result = await this.helper.executeExtrinsic(916 signer,917 'api.tx.unique.setCollectionLimits', [collectionId, limits],918 true,919 );920921 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');922 }923924 /**925 * Changes the owner of the collection to the new Substrate address.926 *927 * @param signer keyring of signer928 * @param collectionId ID of collection929 * @param ownerAddress substrate address of new owner930 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")931 * @returns ```true``` if extrinsic success, otherwise ```false```932 */933 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {934 const result = await this.helper.executeExtrinsic(935 signer,936 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],937 true,938 );939940 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');941 }942943 /**944 * Adds a collection administrator.945 *946 * @param signer keyring of signer947 * @param collectionId ID of collection948 * @param adminAddressObj Administrator address (substrate or ethereum)949 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})950 * @returns ```true``` if extrinsic success, otherwise ```false```951 */952 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {953 const result = await this.helper.executeExtrinsic(954 signer,955 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],956 true,957 );958959 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');960 }961962 /**963 * Removes a collection administrator.964 *965 * @param signer keyring of signer966 * @param collectionId ID of collection967 * @param adminAddressObj Administrator address (substrate or ethereum)968 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})969 * @returns ```true``` if extrinsic success, otherwise ```false```970 */971 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {972 const result = await this.helper.executeExtrinsic(973 signer,974 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],975 true,976 );977978 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');979 }980981 /**982 * Check if user is in allow list.983 *984 * @param collectionId ID of collection985 * @param user Account to check986 * @example await getAdmins(1)987 * @returns is user in allow list988 */989 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {990 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();991 }992993 /**994 * Adds an address to allow list995 * @param signer keyring of signer996 * @param collectionId ID of collection997 * @param addressObj address to add to the allow list998 * @returns ```true``` if extrinsic success, otherwise ```false```999 */1000 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1001 const result = await this.helper.executeExtrinsic(1002 signer,1003 'api.tx.unique.addToAllowList', [collectionId, addressObj],1004 true,1005 );10061007 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1008 }10091010 /**1011 * Removes an address from allow list1012 *1013 * @param signer keyring of signer1014 * @param collectionId ID of collection1015 * @param addressObj address to remove from the allow list1016 * @returns ```true``` if extrinsic success, otherwise ```false```1017 */1018 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1019 const result = await this.helper.executeExtrinsic(1020 signer,1021 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1022 true,1023 );10241025 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1026 }10271028 /**1029 * Sets onchain permissions for selected collection.1030 *1031 * @param signer keyring of signer1032 * @param collectionId ID of collection1033 * @param permissions collection permissions object1034 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1035 * @returns ```true``` if extrinsic success, otherwise ```false```1036 */1037 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1038 const result = await this.helper.executeExtrinsic(1039 signer,1040 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1041 true,1042 );10431044 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1045 }10461047 /**1048 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1049 *1050 * @param signer keyring of signer1051 * @param collectionId ID of collection1052 * @param permissions nesting permissions object1053 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1054 * @returns ```true``` if extrinsic success, otherwise ```false```1055 */1056 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1057 return await this.setPermissions(signer, collectionId, {nesting: permissions});1058 }10591060 /**1061 * Disables nesting for selected collection.1062 *1063 * @param signer keyring of signer1064 * @param collectionId ID of collection1065 * @example disableNesting(aliceKeyring, 10);1066 * @returns ```true``` if extrinsic success, otherwise ```false```1067 */1068 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1069 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1070 }10711072 /**1073 * Sets onchain properties to the collection.1074 *1075 * @param signer keyring of signer1076 * @param collectionId ID of collection1077 * @param properties array of property objects1078 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1079 * @returns ```true``` if extrinsic success, otherwise ```false```1080 */1081 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1082 const result = await this.helper.executeExtrinsic(1083 signer,1084 'api.tx.unique.setCollectionProperties', [collectionId, properties],1085 true,1086 );10871088 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1089 }10901091 /**1092 * Get collection properties.1093 *1094 * @param collectionId ID of collection1095 * @param propertyKeys optionally filter the returned properties to only these keys1096 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1097 * @returns array of key-value pairs1098 */1099 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1100 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1101 }11021103 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1104 const api = this.helper.getApi();1105 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11061107 return (props! as any).consumedSpace;1108 }11091110 async getCollectionOptions(collectionId: number) {1111 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1112 }11131114 /**1115 * Deletes onchain properties from the collection.1116 *1117 * @param signer keyring of signer1118 * @param collectionId ID of collection1119 * @param propertyKeys array of property keys to delete1120 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1121 * @returns ```true``` if extrinsic success, otherwise ```false```1122 */1123 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1124 const result = await this.helper.executeExtrinsic(1125 signer,1126 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1127 true,1128 );11291130 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1131 }11321133 /**1134 * Changes the owner of the token.1135 *1136 * @param signer keyring of signer1137 * @param collectionId ID of collection1138 * @param tokenId ID of token1139 * @param addressObj address of a new owner1140 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1141 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1142 * @returns true if the token success, otherwise false1143 */1144 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1145 const result = await this.helper.executeExtrinsic(1146 signer,1147 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1148 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1149 );11501151 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1152 }11531154 /**1155 *1156 * Change ownership of a token(s) on behalf of the owner.1157 *1158 * @param signer keyring of signer1159 * @param collectionId ID of collection1160 * @param tokenId ID of token1161 * @param fromAddressObj address on behalf of which the token will be sent1162 * @param toAddressObj new token owner1163 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1164 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1165 * @returns true if the token success, otherwise false1166 */1167 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1168 const result = await this.helper.executeExtrinsic(1169 signer,1170 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1171 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1172 );1173 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1174 }11751176 /**1177 *1178 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1179 *1180 * @param signer keyring of signer1181 * @param collectionId ID of collection1182 * @param tokenId ID of token1183 * @param amount amount of tokens to be burned. For NFT must be set to 1n1184 * @example burnToken(aliceKeyring, 10, 5);1185 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1186 */1187 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1188 const burnResult = await this.helper.executeExtrinsic(1189 signer,1190 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1191 true, // `Unable to burn token for ${label}`,1192 );1193 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1194 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1195 return burnedTokens.success;1196 }11971198 /**1199 * Destroys a concrete instance of NFT on behalf of the owner1200 *1201 * @param signer keyring of signer1202 * @param collectionId ID of collection1203 * @param tokenId ID of token1204 * @param fromAddressObj address on behalf of which the token will be burnt1205 * @param amount amount of tokens to be burned. For NFT must be set to 1n1206 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1207 * @returns ```true``` if extrinsic success, otherwise ```false```1208 */1209 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1210 const burnResult = await this.helper.executeExtrinsic(1211 signer,1212 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1213 true, // `Unable to burn token from for ${label}`,1214 );1215 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1216 return burnedTokens.success && burnedTokens.tokens.length > 0;1217 }12181219 /**1220 * Set, change, or remove approved address to transfer the ownership of the NFT.1221 *1222 * @param signer keyring of signer1223 * @param collectionId ID of collection1224 * @param tokenId ID of token1225 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1226 * @param amount amount of token to be approved. For NFT must be set to 1n1227 * @returns ```true``` if extrinsic success, otherwise ```false```1228 */1229 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1230 const approveResult = await this.helper.executeExtrinsic(1231 signer,1232 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1233 true, // `Unable to approve token for ${label}`,1234 );12351236 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1237 }12381239 /**1240 * Get the amount of token pieces approved to transfer or burn. Normally 0.1241 *1242 * @param collectionId ID of collection1243 * @param tokenId ID of token1244 * @param toAccountObj address which is approved to use token pieces1245 * @param fromAccountObj address which may have allowed the use of its owned tokens1246 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1247 * @returns number of approved to transfer pieces1248 */1249 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1250 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1251 }12521253 /**1254 * Get the last created token ID in a collection1255 *1256 * @param collectionId ID of collection1257 * @example getLastTokenId(10);1258 * @returns id of the last created token1259 */1260 async getLastTokenId(collectionId: number): Promise<number> {1261 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1262 }12631264 /**1265 * Check if token exists1266 *1267 * @param collectionId ID of collection1268 * @param tokenId ID of token1269 * @example doesTokenExist(10, 20);1270 * @returns true if the token exists, otherwise false1271 */1272 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1273 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1274 }1275}12761277class NFTnRFT extends CollectionGroup {1278 /**1279 * Get tokens owned by account1280 *1281 * @param collectionId ID of collection1282 * @param addressObj tokens owner1283 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1284 * @returns array of token ids owned by account1285 */1286 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1287 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1288 }12891290 /**1291 * Get token data1292 *1293 * @param collectionId ID of collection1294 * @param tokenId ID of token1295 * @param propertyKeys optionally filter the token properties to only these keys1296 * @param blockHashAt optionally query the data at some block with this hash1297 * @example getToken(10, 5);1298 * @returns human readable token data1299 */1300 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1301 properties: IProperty[];1302 owner: CrossAccountId;1303 normalizedOwner: CrossAccountId;1304 }| null> {1305 let tokenData;1306 if(typeof blockHashAt === 'undefined') {1307 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1308 }1309 else {1310 if(propertyKeys.length == 0) {1311 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1312 if(!collection) return null;1313 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1314 }1315 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1316 }1317 tokenData = tokenData.toHuman();1318 if (tokenData === null || tokenData.owner === null) return null;1319 const owner = {} as any;1320 for (const key of Object.keys(tokenData.owner)) {1321 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1322 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1323 : tokenData.owner[key];1324 }1325 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1326 return tokenData;1327 }13281329 /**1330 * Set permissions to change token properties1331 *1332 * @param signer keyring of signer1333 * @param collectionId ID of collection1334 * @param permissions permissions to change a property by the collection admin or token owner1335 * @example setTokenPropertyPermissions(1336 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1337 * )1338 * @returns true if extrinsic success otherwise false1339 */1340 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1341 const result = await this.helper.executeExtrinsic(1342 signer,1343 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1344 true,1345 );13461347 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1348 }13491350 /**1351 * Get token property permissions.1352 *1353 * @param collectionId ID of collection1354 * @param propertyKeys optionally filter the returned property permissions to only these keys1355 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1356 * @returns array of key-permission pairs1357 */1358 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1359 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1360 }13611362 /**1363 * Set token properties1364 *1365 * @param signer keyring of signer1366 * @param collectionId ID of collection1367 * @param tokenId ID of token1368 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1369 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1370 * @returns ```true``` if extrinsic success, otherwise ```false```1371 */1372 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1373 const result = await this.helper.executeExtrinsic(1374 signer,1375 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1376 true,1377 );13781379 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1380 }13811382 /**1383 * Get properties, metadata assigned to a token.1384 *1385 * @param collectionId ID of collection1386 * @param tokenId ID of token1387 * @param propertyKeys optionally filter the returned properties to only these keys1388 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1389 * @returns array of key-value pairs1390 */1391 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1392 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1393 }13941395 /**1396 * Delete the provided properties of a token1397 * @param signer keyring of signer1398 * @param collectionId ID of collection1399 * @param tokenId ID of token1400 * @param propertyKeys property keys to be deleted1401 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1402 * @returns ```true``` if extrinsic success, otherwise ```false```1403 */1404 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1405 const result = await this.helper.executeExtrinsic(1406 signer,1407 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1408 true,1409 );14101411 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1412 }14131414 /**1415 * Mint new collection1416 *1417 * @param signer keyring of signer1418 * @param collectionOptions basic collection options and properties1419 * @param mode NFT or RFT type of a collection1420 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1421 * @returns object of the created collection1422 */1423 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1424 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1425 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1426 for (const key of ['name', 'description', 'tokenPrefix']) {1427 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1428 }1429 const creationResult = await this.helper.executeExtrinsic(1430 signer,1431 'api.tx.unique.createCollectionEx', [collectionOptions],1432 true, // errorLabel,1433 );1434 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1435 }14361437 getCollectionObject(_collectionId: number): any {1438 return null;1439 }14401441 getTokenObject(_collectionId: number, _tokenId: number): any {1442 return null;1443 }14441445 /**1446 * Tells whether the given `owner` approves the `operator`.1447 * @param collectionId ID of collection1448 * @param owner owner address1449 * @param operator operator addrees1450 * @returns true if operator is enabled1451 */1452 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1453 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1454 }14551456 /** Sets or unsets the approval of a given operator.1457 * The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1458 * @param operator Operator1459 * @param approved Should operator status be granted or revoked?1460 * @returns ```true``` if extrinsic success, otherwise ```false```1461 */1462 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1463 const result = await this.helper.executeExtrinsic(1464 signer,1465 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1466 true,1467 );1468 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1469 }1470}147114721473class NFTGroup extends NFTnRFT {1474 /**1475 * Get collection object1476 * @param collectionId ID of collection1477 * @example getCollectionObject(2);1478 * @returns instance of UniqueNFTCollection1479 */1480 getCollectionObject(collectionId: number): UniqueNFTCollection {1481 return new UniqueNFTCollection(collectionId, this.helper);1482 }14831484 /**1485 * Get token object1486 * @param collectionId ID of collection1487 * @param tokenId ID of token1488 * @example getTokenObject(10, 5);1489 * @returns instance of UniqueNFTToken1490 */1491 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1492 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1493 }14941495 /**1496 * Get token's owner1497 * @param collectionId ID of collection1498 * @param tokenId ID of token1499 * @param blockHashAt optionally query the data at the block with this hash1500 * @example getTokenOwner(10, 5);1501 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1502 */1503 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1504 let owner;1505 if (typeof blockHashAt === 'undefined') {1506 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1507 } else {1508 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1509 }1510 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1511 }15121513 /**1514 * Is token approved to transfer1515 * @param collectionId ID of collection1516 * @param tokenId ID of token1517 * @param toAccountObj address to be approved1518 * @returns ```true``` if extrinsic success, otherwise ```false```1519 */1520 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1521 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1522 }15231524 /**1525 * Changes the owner of the token.1526 *1527 * @param signer keyring of signer1528 * @param collectionId ID of collection1529 * @param tokenId ID of token1530 * @param addressObj address of a new owner1531 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1532 * @returns ```true``` if extrinsic success, otherwise ```false```1533 */1534 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1535 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1536 }15371538 /**1539 *1540 * Change ownership of a NFT on behalf of the owner.1541 *1542 * @param signer keyring of signer1543 * @param collectionId ID of collection1544 * @param tokenId ID of token1545 * @param fromAddressObj address on behalf of which the token will be sent1546 * @param toAddressObj new token owner1547 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1548 * @returns ```true``` if extrinsic success, otherwise ```false```1549 */1550 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1551 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1552 }15531554 /**1555 * Recursively find the address that owns the token1556 * @param collectionId ID of collection1557 * @param tokenId ID of token1558 * @param blockHashAt1559 * @example getTokenTopmostOwner(10, 5);1560 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1561 */1562 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1563 let owner;1564 if (typeof blockHashAt === 'undefined') {1565 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1566 } else {1567 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1568 }15691570 if (owner === null) return null;15711572 return owner.toHuman();1573 }15741575 /**1576 * Get tokens nested in the provided token1577 * @param collectionId ID of collection1578 * @param tokenId ID of token1579 * @param blockHashAt optionally query the data at the block with this hash1580 * @example getTokenChildren(10, 5);1581 * @returns tokens whose depth of nesting is <= 51582 */1583 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1584 let children;1585 if(typeof blockHashAt === 'undefined') {1586 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1587 } else {1588 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1589 }15901591 return children.toJSON().map((x: any) => {1592 return {collectionId: x.collection, tokenId: x.token};1593 });1594 }15951596 /**1597 * Nest one token into another1598 * @param signer keyring of signer1599 * @param tokenObj token to be nested1600 * @param rootTokenObj token to be parent1601 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1602 * @returns ```true``` if extrinsic success, otherwise ```false```1603 */1604 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1605 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1606 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1607 if(!result) {1608 throw Error('Unable to nest token!');1609 }1610 return result;1611 }16121613 /**1614 * Remove token from nested state1615 * @param signer keyring of signer1616 * @param tokenObj token to unnest1617 * @param rootTokenObj parent of a token1618 * @param toAddressObj address of a new token owner1619 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1620 * @returns ```true``` if extrinsic success, otherwise ```false```1621 */1622 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1623 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1624 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1625 if(!result) {1626 throw Error('Unable to unnest token!');1627 }1628 return result;1629 }16301631 /**1632 * Mint new collection1633 * @param signer keyring of signer1634 * @param collectionOptions Collection options1635 * @example1636 * mintCollection(aliceKeyring, {1637 * name: 'New',1638 * description: 'New collection',1639 * tokenPrefix: 'NEW',1640 * })1641 * @returns object of the created collection1642 */1643 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1644 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1645 }16461647 /**1648 * Mint new token1649 * @param signer keyring of signer1650 * @param data token data1651 * @returns created token object1652 */1653 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1654 const creationResult = await this.helper.executeExtrinsic(1655 signer,1656 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1657 nft: {1658 properties: data.properties,1659 },1660 }],1661 true,1662 );1663 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1664 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1665 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1666 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1667 }16681669 /**1670 * Mint multiple NFT tokens1671 * @param signer keyring of signer1672 * @param collectionId ID of collection1673 * @param tokens array of tokens with owner and properties1674 * @example1675 * mintMultipleTokens(aliceKeyring, 10, [{1676 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1677 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1678 * },{1679 * owner: {Ethereum: "0x9F0583DbB855d..."},1680 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1681 * }]);1682 * @returns ```true``` if extrinsic success, otherwise ```false```1683 */1684 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1685 const creationResult = await this.helper.executeExtrinsic(1686 signer,1687 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1688 true,1689 );1690 const collection = this.getCollectionObject(collectionId);1691 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1692 }16931694 /**1695 * Mint multiple NFT tokens with one owner1696 * @param signer keyring of signer1697 * @param collectionId ID of collection1698 * @param owner tokens owner1699 * @param tokens array of tokens with owner and properties1700 * @example1701 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1702 * properties: [{1703 * key: "gender",1704 * value: "female",1705 * },{1706 * key: "age",1707 * value: "33",1708 * }],1709 * }]);1710 * @returns array of newly created tokens1711 */1712 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1713 const rawTokens = [];1714 for (const token of tokens) {1715 const raw = {NFT: {properties: token.properties}};1716 rawTokens.push(raw);1717 }1718 const creationResult = await this.helper.executeExtrinsic(1719 signer,1720 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1721 true,1722 );1723 const collection = this.getCollectionObject(collectionId);1724 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1725 }17261727 /**1728 * Set, change, or remove approved address to transfer the ownership of the NFT.1729 *1730 * @param signer keyring of signer1731 * @param collectionId ID of collection1732 * @param tokenId ID of token1733 * @param toAddressObj address to approve1734 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1735 * @returns ```true``` if extrinsic success, otherwise ```false```1736 */1737 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1738 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1739 }1740}174117421743class RFTGroup extends NFTnRFT {1744 /**1745 * Get collection object1746 * @param collectionId ID of collection1747 * @example getCollectionObject(2);1748 * @returns instance of UniqueRFTCollection1749 */1750 getCollectionObject(collectionId: number): UniqueRFTCollection {1751 return new UniqueRFTCollection(collectionId, this.helper);1752 }17531754 /**1755 * Get token object1756 * @param collectionId ID of collection1757 * @param tokenId ID of token1758 * @example getTokenObject(10, 5);1759 * @returns instance of UniqueNFTToken1760 */1761 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1762 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1763 }17641765 /**1766 * Get top 10 token owners with the largest number of pieces1767 * @param collectionId ID of collection1768 * @param tokenId ID of token1769 * @example getTokenTop10Owners(10, 5);1770 * @returns array of top 10 owners1771 */1772 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1773 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1774 }17751776 /**1777 * Get number of pieces owned by address1778 * @param collectionId ID of collection1779 * @param tokenId ID of token1780 * @param addressObj address token owner1781 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1782 * @returns number of pieces ownerd by address1783 */1784 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1785 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1786 }17871788 /**1789 * Transfer pieces of token to another address1790 * @param signer keyring of signer1791 * @param collectionId ID of collection1792 * @param tokenId ID of token1793 * @param addressObj address of a new owner1794 * @param amount number of pieces to be transfered1795 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1796 * @returns ```true``` if extrinsic success, otherwise ```false```1797 */1798 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1799 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1800 }18011802 /**1803 * Change ownership of some pieces of RFT on behalf of the owner.1804 * @param signer keyring of signer1805 * @param collectionId ID of collection1806 * @param tokenId ID of token1807 * @param fromAddressObj address on behalf of which the token will be sent1808 * @param toAddressObj new token owner1809 * @param amount number of pieces to be transfered1810 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1811 * @returns ```true``` if extrinsic success, otherwise ```false```1812 */1813 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1814 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1815 }18161817 /**1818 * Mint new collection1819 * @param signer keyring of signer1820 * @param collectionOptions Collection options1821 * @example1822 * mintCollection(aliceKeyring, {1823 * name: 'New',1824 * description: 'New collection',1825 * tokenPrefix: 'NEW',1826 * })1827 * @returns object of the created collection1828 */1829 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1830 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1831 }18321833 /**1834 * Mint new token1835 * @param signer keyring of signer1836 * @param data token data1837 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1838 * @returns created token object1839 */1840 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1841 const creationResult = await this.helper.executeExtrinsic(1842 signer,1843 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1844 refungible: {1845 pieces: data.pieces,1846 properties: data.properties,1847 },1848 }],1849 true,1850 );1851 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1852 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1853 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1854 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1855 }18561857 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1858 throw Error('Not implemented');1859 const creationResult = await this.helper.executeExtrinsic(1860 signer,1861 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1862 true, // `Unable to mint RFT tokens for ${label}`,1863 );1864 const collection = this.getCollectionObject(collectionId);1865 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1866 }18671868 /**1869 * Mint multiple RFT tokens with one owner1870 * @param signer keyring of signer1871 * @param collectionId ID of collection1872 * @param owner tokens owner1873 * @param tokens array of tokens with properties and pieces1874 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1875 * @returns array of newly created RFT tokens1876 */1877 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1878 const rawTokens = [];1879 for (const token of tokens) {1880 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1881 rawTokens.push(raw);1882 }1883 const creationResult = await this.helper.executeExtrinsic(1884 signer,1885 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1886 true,1887 );1888 const collection = this.getCollectionObject(collectionId);1889 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1890 }18911892 /**1893 * Destroys a concrete instance of RFT.1894 * @param signer keyring of signer1895 * @param collectionId ID of collection1896 * @param tokenId ID of token1897 * @param amount number of pieces to be burnt1898 * @example burnToken(aliceKeyring, 10, 5);1899 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1900 */1901 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1902 return await super.burnToken(signer, collectionId, tokenId, amount);1903 }19041905 /**1906 * Destroys a concrete instance of RFT on behalf of the owner.1907 * @param signer keyring of signer1908 * @param collectionId ID of collection1909 * @param tokenId ID of token1910 * @param fromAddressObj address on behalf of which the token will be burnt1911 * @param amount number of pieces to be burnt1912 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1913 * @returns ```true``` if extrinsic success, otherwise ```false```1914 */1915 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1916 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1917 }19181919 /**1920 * Set, change, or remove approved address to transfer the ownership of the RFT.1921 *1922 * @param signer keyring of signer1923 * @param collectionId ID of collection1924 * @param tokenId ID of token1925 * @param toAddressObj address to approve1926 * @param amount number of pieces to be approved1927 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1928 * @returns true if the token success, otherwise false1929 */1930 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1931 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1932 }19331934 /**1935 * Get total number of pieces1936 * @param collectionId ID of collection1937 * @param tokenId ID of token1938 * @example getTokenTotalPieces(10, 5);1939 * @returns number of pieces1940 */1941 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1942 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1943 }19441945 /**1946 * Change number of token pieces. Signer must be the owner of all token pieces.1947 * @param signer keyring of signer1948 * @param collectionId ID of collection1949 * @param tokenId ID of token1950 * @param amount new number of pieces1951 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1952 * @returns true if the repartion was success, otherwise false1953 */1954 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1955 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1956 const repartitionResult = await this.helper.executeExtrinsic(1957 signer,1958 'api.tx.unique.repartition', [collectionId, tokenId, amount],1959 true,1960 );1961 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1962 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1963 }1964}196519661967class FTGroup extends CollectionGroup {1968 /**1969 * Get collection object1970 * @param collectionId ID of collection1971 * @example getCollectionObject(2);1972 * @returns instance of UniqueFTCollection1973 */1974 getCollectionObject(collectionId: number): UniqueFTCollection {1975 return new UniqueFTCollection(collectionId, this.helper);1976 }19771978 /**1979 * Mint new fungible collection1980 * @param signer keyring of signer1981 * @param collectionOptions Collection options1982 * @param decimalPoints number of token decimals1983 * @example1984 * mintCollection(aliceKeyring, {1985 * name: 'New',1986 * description: 'New collection',1987 * tokenPrefix: 'NEW',1988 * }, 18)1989 * @returns newly created fungible collection1990 */1991 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1992 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1993 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1994 collectionOptions.mode = {fungible: decimalPoints};1995 for (const key of ['name', 'description', 'tokenPrefix']) {1996 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1997 }1998 const creationResult = await this.helper.executeExtrinsic(1999 signer,2000 'api.tx.unique.createCollectionEx', [collectionOptions],2001 true,2002 );2003 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2004 }20052006 /**2007 * Mint tokens2008 * @param signer keyring of signer2009 * @param collectionId ID of collection2010 * @param owner address owner of new tokens2011 * @param amount amount of tokens to be meanted2012 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2013 * @returns ```true``` if extrinsic success, otherwise ```false```2014 */2015 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2016 const creationResult = await this.helper.executeExtrinsic(2017 signer,2018 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2019 fungible: {2020 value: amount,2021 },2022 }],2023 true, // `Unable to mint fungible tokens for ${label}`,2024 );2025 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2026 }20272028 /**2029 * Mint multiple Fungible tokens with one owner2030 * @param signer keyring of signer2031 * @param collectionId ID of collection2032 * @param owner tokens owner2033 * @param tokens array of tokens with properties and pieces2034 * @returns ```true``` if extrinsic success, otherwise ```false```2035 */2036 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2037 const rawTokens = [];2038 for (const token of tokens) {2039 const raw = {Fungible: {Value: token.value}};2040 rawTokens.push(raw);2041 }2042 const creationResult = await this.helper.executeExtrinsic(2043 signer,2044 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2045 true,2046 );2047 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2048 }20492050 /**2051 * Get the top 10 owners with the largest balance for the Fungible collection2052 * @param collectionId ID of collection2053 * @example getTop10Owners(10);2054 * @returns array of ```ICrossAccountId```2055 */2056 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2057 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2058 }20592060 /**2061 * Get account balance2062 * @param collectionId ID of collection2063 * @param addressObj address of owner2064 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2065 * @returns amount of fungible tokens owned by address2066 */2067 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2068 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2069 }20702071 /**2072 * Transfer tokens to address2073 * @param signer keyring of signer2074 * @param collectionId ID of collection2075 * @param toAddressObj address recipient2076 * @param amount amount of tokens to be sent2077 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2078 * @returns ```true``` if extrinsic success, otherwise ```false```2079 */2080 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2081 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2082 }20832084 /**2085 * Transfer some tokens on behalf of the owner.2086 * @param signer keyring of signer2087 * @param collectionId ID of collection2088 * @param fromAddressObj address on behalf of which tokens will be sent2089 * @param toAddressObj address where token to be sent2090 * @param amount number of tokens to be sent2091 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2092 * @returns ```true``` if extrinsic success, otherwise ```false```2093 */2094 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2095 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2096 }20972098 /**2099 * Destroy some amount of tokens2100 * @param signer keyring of signer2101 * @param collectionId ID of collection2102 * @param amount amount of tokens to be destroyed2103 * @example burnTokens(aliceKeyring, 10, 1000n);2104 * @returns ```true``` if extrinsic success, otherwise ```false```2105 */2106 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2107 return await super.burnToken(signer, collectionId, 0, amount);2108 }21092110 /**2111 * Burn some tokens on behalf of the owner.2112 * @param signer keyring of signer2113 * @param collectionId ID of collection2114 * @param fromAddressObj address on behalf of which tokens will be burnt2115 * @param amount amount of tokens to be burnt2116 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2117 * @returns ```true``` if extrinsic success, otherwise ```false```2118 */2119 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2120 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2121 }21222123 /**2124 * Get total collection supply2125 * @param collectionId2126 * @returns2127 */2128 async getTotalPieces(collectionId: number): Promise<bigint> {2129 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2130 }21312132 /**2133 * Set, change, or remove approved address to transfer tokens.2134 *2135 * @param signer keyring of signer2136 * @param collectionId ID of collection2137 * @param toAddressObj address to be approved2138 * @param amount amount of tokens to be approved2139 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2140 * @returns ```true``` if extrinsic success, otherwise ```false```2141 */2142 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2143 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2144 }21452146 /**2147 * Get amount of fungible tokens approved to transfer2148 * @param collectionId ID of collection2149 * @param fromAddressObj owner of tokens2150 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2151 * @returns number of tokens approved for the transfer2152 */2153 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2154 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2155 }2156}215721582159class ChainGroup extends HelperGroup<ChainHelperBase> {2160 /**2161 * Get system properties of a chain2162 * @example getChainProperties();2163 * @returns ss58Format, token decimals, and token symbol2164 */2165 getChainProperties(): IChainProperties {2166 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2167 return {2168 ss58Format: properties.ss58Format.toJSON(),2169 tokenDecimals: properties.tokenDecimals.toJSON(),2170 tokenSymbol: properties.tokenSymbol.toJSON(),2171 };2172 }21732174 /**2175 * Get chain header2176 * @example getLatestBlockNumber();2177 * @returns the number of the last block2178 */2179 async getLatestBlockNumber(): Promise<number> {2180 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2181 }21822183 /**2184 * Get block hash by block number2185 * @param blockNumber number of block2186 * @example getBlockHashByNumber(12345);2187 * @returns hash of a block2188 */2189 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2190 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2191 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2192 return blockHash;2193 }21942195 // TODO add docs2196 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2197 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2198 if (!blockHash) return null;2199 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2200 }22012202 /**2203 * Get latest relay block2204 * @returns {number} relay block2205 */2206 async getRelayBlockNumber(): Promise<bigint> {2207 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2208 return BigInt(blockNumber);2209 }22102211 /**2212 * Get account nonce2213 * @param address substrate address2214 * @example getNonce("5GrwvaEF5zXb26Fz...");2215 * @returns number, account's nonce2216 */2217 async getNonce(address: TSubstrateAccount): Promise<number> {2218 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2219 }2220}22212222class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2223 /**2224 * Get substrate address balance2225 * @param address substrate address2226 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2227 * @returns amount of tokens on address2228 */2229 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2230 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2231 }22322233 /**2234 * Transfer tokens to substrate address2235 * @param signer keyring of signer2236 * @param address substrate address of a recipient2237 * @param amount amount of tokens to be transfered2238 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2239 * @returns ```true``` if extrinsic success, otherwise ```false```2240 */2241 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2242 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}`*/);22432244 let transfer = {from: null, to: null, amount: 0n} as any;2245 result.result.events.forEach(({event: {data, method, section}}) => {2246 if ((section === 'balances') && (method === 'Transfer')) {2247 transfer = {2248 from: this.helper.address.normalizeSubstrate(data[0]),2249 to: this.helper.address.normalizeSubstrate(data[1]),2250 amount: BigInt(data[2]),2251 };2252 }2253 });2254 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2255 && this.helper.address.normalizeSubstrate(address) === transfer.to2256 && BigInt(amount) === transfer.amount;2257 return isSuccess;2258 }22592260 /**2261 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2262 * @param address substrate address2263 * @returns2264 */2265 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2266 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2267 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2268 }22692270 async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2271 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2272 return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2273 }2274}22752276class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2277 /**2278 * Get ethereum address balance2279 * @param address ethereum address2280 * @example getEthereum("0x9F0583DbB855d...")2281 * @returns amount of tokens on address2282 */2283 async getEthereum(address: TEthereumAccount): Promise<bigint> {2284 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2285 }22862287 /**2288 * Transfer tokens to address2289 * @param signer keyring of signer2290 * @param address Ethereum address of a recipient2291 * @param amount amount of tokens to be transfered2292 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2293 * @returns ```true``` if extrinsic success, otherwise ```false```2294 */2295 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2296 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22972298 let transfer = {from: null, to: null, amount: 0n} as any;2299 result.result.events.forEach(({event: {data, method, section}}) => {2300 if ((section === 'balances') && (method === 'Transfer')) {2301 transfer = {2302 from: data[0].toString(),2303 to: data[1].toString(),2304 amount: BigInt(data[2]),2305 };2306 }2307 });2308 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2309 && address === transfer.to2310 && BigInt(amount) === transfer.amount;2311 return isSuccess;2312 }2313}23142315class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2316 subBalanceGroup: SubstrateBalanceGroup<T>;2317 ethBalanceGroup: EthereumBalanceGroup<T>;23182319 constructor(helper: T) {2320 super(helper);2321 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2322 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2323 }23242325 getCollectionCreationPrice(): bigint {2326 return 2n * this.getOneTokenNominal();2327 }2328 /**2329 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2330 * @example getOneTokenNominal()2331 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2332 */2333 getOneTokenNominal(): bigint {2334 const chainProperties = this.helper.chain.getChainProperties();2335 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2336 }23372338 /**2339 * Get substrate address balance2340 * @param address substrate address2341 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2342 * @returns amount of tokens on address2343 */2344 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2345 return this.subBalanceGroup.getSubstrate(address);2346 }23472348 /**2349 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2350 * @param address substrate address2351 * @returns2352 */2353 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2354 return this.subBalanceGroup.getSubstrateFull(address);2355 }23562357 /**2358 * Get locked balances2359 * @param address substrate address2360 * @returns locked balances with reason via api.query.balances.locks2361 */2362 getLocked(address: TSubstrateAccount) {2363 return this.subBalanceGroup.getLocked(address);2364 }23652366 /**2367 * Get ethereum address balance2368 * @param address ethereum address2369 * @example getEthereum("0x9F0583DbB855d...")2370 * @returns amount of tokens on address2371 */2372 getEthereum(address: TEthereumAccount): Promise<bigint> {2373 return this.ethBalanceGroup.getEthereum(address);2374 }23752376 /**2377 * Transfer tokens to substrate address2378 * @param signer keyring of signer2379 * @param address substrate address of a recipient2380 * @param amount amount of tokens to be transfered2381 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2382 * @returns ```true``` if extrinsic success, otherwise ```false```2383 */2384 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2385 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2386 }23872388 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2389 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);23902391 let transfer = {from: null, to: null, amount: 0n} as any;2392 result.result.events.forEach(({event: {data, method, section}}) => {2393 if ((section === 'balances') && (method === 'Transfer')) {2394 transfer = {2395 from: this.helper.address.normalizeSubstrate(data[0]),2396 to: this.helper.address.normalizeSubstrate(data[1]),2397 amount: BigInt(data[2]),2398 };2399 }2400 });2401 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2402 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2403 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2404 return isSuccess;2405 }24062407 /**2408 * Transfer tokens with the unlock period2409 * @param signer signers Keyring2410 * @param address Substrate address of recipient2411 * @param schedule Schedule params2412 * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002413 */2414 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2415 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2416 const event = result.result.events2417 .find(e => e.event.section === 'vesting' &&2418 e.event.method === 'VestingScheduleAdded' &&2419 e.event.data[0].toHuman() === signer.address);2420 if (!event) throw Error('Cannot find transfer in events');2421 }24222423 /**2424 * Get schedule for recepient of vested transfer2425 * @param address Substrate address of recipient2426 * @returns2427 */2428 async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2429 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2430 return schedule.map((schedule: any) => {2431 return {2432 start: BigInt(schedule.start),2433 period: BigInt(schedule.period),2434 periodCount: BigInt(schedule.periodCount),2435 perPeriod: BigInt(schedule.perPeriod),2436 };2437 });2438 }24392440 /**2441 * Claim vested tokens2442 * @param signer signers Keyring2443 */2444 async claim(signer: TSigner) {2445 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2446 const event = result.result.events2447 .find(e => e.event.section === 'vesting' &&2448 e.event.method === 'Claimed' &&2449 e.event.data[0].toHuman() === signer.address);2450 if (!event) throw Error('Cannot find claim in events');2451 }2452}24532454class AddressGroup extends HelperGroup<ChainHelperBase> {2455 /**2456 * Normalizes the address to the specified ss58 format, by default ```42```.2457 * @param address substrate address2458 * @param ss58Format format for address conversion, by default ```42```2459 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2460 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2461 */2462 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2463 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2464 }24652466 /**2467 * Get address in the connected chain format2468 * @param address substrate address2469 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2470 * @returns address in chain format2471 */2472 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2473 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2474 }24752476 /**2477 * Get substrate mirror of an ethereum address2478 * @param ethAddress ethereum address2479 * @param toChainFormat false for normalized account2480 * @example ethToSubstrate('0x9F0583DbB855d...')2481 * @returns substrate mirror of a provided ethereum address2482 */2483 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2484 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2485 }24862487 /**2488 * Get ethereum mirror of a substrate address2489 * @param subAddress substrate account2490 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2491 * @returns ethereum mirror of a provided substrate address2492 */2493 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2494 return CrossAccountId.translateSubToEth(subAddress);2495 }24962497 /**2498 * Encode key to substrate address2499 * @param key key for encoding address2500 * @param ss58Format prefix for encoding to the address of the corresponding network2501 * @returns encoded substrate address2502 */2503 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2504 const u8a :Uint8Array = typeof key === 'string'2505 ? hexToU8a(key)2506 : typeof key === 'bigint'2507 ? hexToU8a(key.toString(16))2508 : key;25092510 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2511 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2512 }25132514 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2515 if (!allowedDecodedLengths.includes(u8a.length)) {2516 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2517 }25182519 const u8aPrefix = ss58Format < 642520 ? new Uint8Array([ss58Format])2521 : new Uint8Array([2522 ((ss58Format & 0xfc) >> 2) | 0x40,2523 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2524 ]);25252526 const input = u8aConcat(u8aPrefix, u8a);25272528 return base58Encode(u8aConcat(2529 input,2530 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2531 ));2532 }25332534 /**2535 * Restore substrate address from bigint representation2536 * @param number decimal representation of substrate address2537 * @returns substrate address2538 */2539 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2540 if (this.helper.api === null) {2541 throw 'Not connected';2542 }2543 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2544 if (res === undefined || res === null) {2545 throw 'Restore address error';2546 }2547 return res.toString();2548 }25492550 /**2551 * Convert etherium cross account id to substrate cross account id2552 * @param ethCrossAccount etherium cross account2553 * @returns substrate cross account id2554 */2555 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2556 if (ethCrossAccount.sub === '0') {2557 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2558 }25592560 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2561 return {Substrate: ss58};2562 }25632564 paraSiblingSovereignAccount(paraid: number) {2565 // We are getting a *sibling* parachain sovereign account,2566 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2567 const siblingPrefix = '0x7369626c';25682569 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2570 const suffix = '000000000000000000000000000000000000000000000000';25712572 return siblingPrefix + encodedParaId + suffix;2573 }2574}25752576class StakingGroup extends HelperGroup<UniqueHelper> {2577 /**2578 * Stake tokens for App Promotion2579 * @param signer keyring of signer2580 * @param amountToStake amount of tokens to stake2581 * @param label extra label for log2582 * @returns2583 */2584 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2585 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2586 const _stakeResult = await this.helper.executeExtrinsic(2587 signer, 'api.tx.appPromotion.stake',2588 [amountToStake], true,2589 );2590 // TODO extract info from stakeResult2591 return true;2592 }25932594 /**2595 * Unstake tokens for App Promotion2596 * @param signer keyring of signer2597 * @param amountToUnstake amount of tokens to unstake2598 * @param label extra label for log2599 * @returns block number where balances will be unlocked2600 */2601 async unstake(signer: TSigner, label?: string): Promise<number> {2602 if(typeof label === 'undefined') label = `${signer.address}`;2603 const _unstakeResult = await this.helper.executeExtrinsic(2604 signer, 'api.tx.appPromotion.unstake',2605 [], true,2606 );2607 // TODO extract block number fron events2608 return 1;2609 }26102611 /**2612 * Get total staked amount for address2613 * @param address substrate or ethereum address2614 * @returns total staked amount2615 */2616 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2617 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2618 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2619 }26202621 /**2622 * Get total staked per block2623 * @param address substrate or ethereum address2624 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2625 */2626 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2627 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2628 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2629 return {2630 block: block.toBigInt(),2631 amount: amount.toBigInt(),2632 };2633 });2634 }26352636 /**2637 * Get total pending unstake amount for address2638 * @param address substrate or ethereum address2639 * @returns total pending unstake amount2640 */2641 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2642 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2643 }26442645 /**2646 * Get pending unstake amount per block for address2647 * @param address substrate or ethereum address2648 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2649 */2650 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2651 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2652 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2653 return {2654 block: block.toBigInt(),2655 amount: amount.toBigInt(),2656 };2657 });2658 return result;2659 }2660}26612662class SchedulerGroup extends HelperGroup<UniqueHelper> {2663 constructor(helper: UniqueHelper) {2664 super(helper);2665 }26662667 cancelScheduled(signer: TSigner, scheduledId: string) {2668 return this.helper.executeExtrinsic(2669 signer,2670 'api.tx.scheduler.cancelNamed',2671 [scheduledId],2672 true,2673 );2674 }26752676 changePriority(signer: TSigner, scheduledId: string, priority: number) {2677 return this.helper.executeExtrinsic(2678 signer,2679 'api.tx.scheduler.changeNamedPriority',2680 [scheduledId, priority],2681 true,2682 );2683 }26842685 scheduleAt<T extends UniqueHelper>(2686 executionBlockNumber: number,2687 options: ISchedulerOptions = {},2688 ) {2689 return this.schedule<T>('schedule', executionBlockNumber, options);2690 }26912692 scheduleAfter<T extends UniqueHelper>(2693 blocksBeforeExecution: number,2694 options: ISchedulerOptions = {},2695 ) {2696 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2697 }26982699 schedule<T extends UniqueHelper>(2700 scheduleFn: 'schedule' | 'scheduleAfter',2701 blocksNum: number,2702 options: ISchedulerOptions = {},2703 ) {2704 // eslint-disable-next-line @typescript-eslint/naming-convention2705 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2706 return this.helper.clone(ScheduledHelperType, {2707 scheduleFn,2708 blocksNum,2709 options,2710 }) as T;2711 }2712}27132714class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2715 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2716 await this.helper.executeExtrinsic(2717 signer,2718 'api.tx.foreignAssets.registerForeignAsset',2719 [ownerAddress, location, metadata],2720 true,2721 );2722 }27232724 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2725 await this.helper.executeExtrinsic(2726 signer,2727 'api.tx.foreignAssets.updateForeignAsset',2728 [foreignAssetId, location, metadata],2729 true,2730 );2731 }2732}27332734class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2735 palletName: string;27362737 constructor(helper: T, palletName: string) {2738 super(helper);27392740 this.palletName = palletName;2741 }27422743 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2744 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2745 }27462747 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2748 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2749 }27502751 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2752 const destination = {2753 V1: {2754 parents: 0,2755 interior: {2756 X1: {2757 Parachain: destinationParaId,2758 },2759 },2760 },2761 };27622763 const beneficiary = {2764 V1: {2765 parents: 0,2766 interior: {2767 X1: {2768 AccountId32: {2769 network: 'Any',2770 id: targetAccount,2771 },2772 },2773 },2774 },2775 };27762777 const assets = {2778 V1: [2779 {2780 id: {2781 Concrete: {2782 parents: 0,2783 interior: 'Here',2784 },2785 },2786 fun: {2787 Fungible: amount,2788 },2789 },2790 ],2791 };27922793 const feeAssetItem = 0;27942795 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);2796 }2797}27982799class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2800 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {2801 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2802 }28032804 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {2805 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2806 }28072808 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {2809 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2810 }2811}28122813class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2814 async accounts(address: string, currencyId: any) {2815 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2816 return BigInt(free);2817 }2818}28192820class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2821 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2822 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2823 }28242825 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2826 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2827 }28282829 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2830 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2831 }28322833 async account(assetId: string | number, address: string) {2834 const accountAsset = (2835 await this.helper.callRpc('api.query.assets.account', [assetId, address])2836 ).toJSON()! as any;28372838 if (accountAsset !== null) {2839 return BigInt(accountAsset['balance']);2840 } else {2841 return null;2842 }2843 }2844}28452846class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2847 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2848 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2849 }2850}28512852class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2853 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2854 const apiPrefix = 'api.tx.assetManager.';28552856 const registerTx = this.helper.constructApiCall(2857 apiPrefix + 'registerForeignAsset',2858 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2859 );28602861 const setUnitsTx = this.helper.constructApiCall(2862 apiPrefix + 'setAssetUnitsPerSecond',2863 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2864 );28652866 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2867 const encodedProposal = batchCall?.method.toHex() || '';2868 return encodedProposal;2869 }28702871 async assetTypeId(location: any) {2872 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2873 }2874}28752876class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2877 notePreimagePallet: string;28782879 constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {2880 super(helper);2881 this.notePreimagePallet = options.notePreimagePallet;2882 }28832884 async notePreimage(signer: TSigner, encodedProposal: string) {2885 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);2886 }28872888 externalProposeMajority(proposal: any) {2889 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);2890 }28912892 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2893 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2894 }28952896 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2897 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2898 }2899}29002901class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2902 collective: string;29032904 constructor(helper: MoonbeamHelper, collective: string) {2905 super(helper);29062907 this.collective = collective;2908 }29092910 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2911 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2912 }29132914 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2915 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2916 }29172918 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {2919 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2920 }29212922 async proposalCount() {2923 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2924 }2925}29262927export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2928export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;29292930export class UniqueHelper extends ChainHelperBase {2931 balance: BalanceGroup<UniqueHelper>;2932 collection: CollectionGroup;2933 nft: NFTGroup;2934 rft: RFTGroup;2935 ft: FTGroup;2936 staking: StakingGroup;2937 scheduler: SchedulerGroup;2938 foreignAssets: ForeignAssetsGroup;2939 xcm: XcmGroup<UniqueHelper>;2940 xTokens: XTokensGroup<UniqueHelper>;2941 tokens: TokensGroup<UniqueHelper>;29422943 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2944 super(logger, options.helperBase ?? UniqueHelper);29452946 this.balance = new BalanceGroup(this);2947 this.collection = new CollectionGroup(this);2948 this.nft = new NFTGroup(this);2949 this.rft = new RFTGroup(this);2950 this.ft = new FTGroup(this);2951 this.staking = new StakingGroup(this);2952 this.scheduler = new SchedulerGroup(this);2953 this.foreignAssets = new ForeignAssetsGroup(this);2954 this.xcm = new XcmGroup(this, 'polkadotXcm');2955 this.xTokens = new XTokensGroup(this);2956 this.tokens = new TokensGroup(this);2957 }29582959 getSudo<T extends UniqueHelper>() {2960 // eslint-disable-next-line @typescript-eslint/naming-convention2961 const SudoHelperType = SudoHelper(this.helperBase);2962 return this.clone(SudoHelperType) as T;2963 }2964}29652966export class XcmChainHelper extends ChainHelperBase {2967 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2968 const wsProvider = new WsProvider(wsEndpoint);2969 this.api = new ApiPromise({2970 provider: wsProvider,2971 });2972 await this.api.isReadyOrError;2973 this.network = await UniqueHelper.detectNetwork(this.api);2974 }2975}29762977export class RelayHelper extends XcmChainHelper {2978 balance: SubstrateBalanceGroup<RelayHelper>;2979 xcm: XcmGroup<RelayHelper>;29802981 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2982 super(logger, options.helperBase ?? RelayHelper);29832984 this.balance = new SubstrateBalanceGroup(this);2985 this.xcm = new XcmGroup(this, 'xcmPallet');2986 }2987}29882989export class WestmintHelper extends XcmChainHelper {2990 balance: SubstrateBalanceGroup<WestmintHelper>;2991 xcm: XcmGroup<WestmintHelper>;2992 assets: AssetsGroup<WestmintHelper>;2993 xTokens: XTokensGroup<WestmintHelper>;29942995 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2996 super(logger, options.helperBase ?? WestmintHelper);29972998 this.balance = new SubstrateBalanceGroup(this);2999 this.xcm = new XcmGroup(this, 'polkadotXcm');3000 this.assets = new AssetsGroup(this);3001 this.xTokens = new XTokensGroup(this);3002 }3003}30043005export class MoonbeamHelper extends XcmChainHelper {3006 balance: EthereumBalanceGroup<MoonbeamHelper>;3007 assetManager: MoonbeamAssetManagerGroup;3008 assets: AssetsGroup<MoonbeamHelper>;3009 xTokens: XTokensGroup<MoonbeamHelper>;3010 democracy: MoonbeamDemocracyGroup;3011 collective: {3012 council: MoonbeamCollectiveGroup,3013 techCommittee: MoonbeamCollectiveGroup,3014 };30153016 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3017 super(logger, options.helperBase ?? MoonbeamHelper);30183019 this.balance = new EthereumBalanceGroup(this);3020 this.assetManager = new MoonbeamAssetManagerGroup(this);3021 this.assets = new AssetsGroup(this);3022 this.xTokens = new XTokensGroup(this);3023 this.democracy = new MoonbeamDemocracyGroup(this, options);3024 this.collective = {3025 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3026 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3027 };3028 }3029}30303031export class AcalaHelper extends XcmChainHelper {3032 balance: SubstrateBalanceGroup<AcalaHelper>;3033 assetRegistry: AcalaAssetRegistryGroup;3034 xTokens: XTokensGroup<AcalaHelper>;3035 tokens: TokensGroup<AcalaHelper>;30363037 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3038 super(logger, options.helperBase ?? AcalaHelper);30393040 this.balance = new SubstrateBalanceGroup(this);3041 this.assetRegistry = new AcalaAssetRegistryGroup(this);3042 this.xTokens = new XTokensGroup(this);3043 this.tokens = new TokensGroup(this);3044 }30453046 getSudo<T extends AcalaHelper>() {3047 // eslint-disable-next-line @typescript-eslint/naming-convention3048 const SudoHelperType = SudoHelper(this.helperBase);3049 return this.clone(SudoHelperType) as T;3050 }3051}30523053// eslint-disable-next-line @typescript-eslint/naming-convention3054function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3055 return class extends Base {3056 scheduleFn: 'schedule' | 'scheduleAfter';3057 blocksNum: number;3058 options: ISchedulerOptions;30593060 constructor(...args: any[]) {3061 const logger = args[0] as ILogger;3062 const options = args[1] as {3063 scheduleFn: 'schedule' | 'scheduleAfter',3064 blocksNum: number,3065 options: ISchedulerOptions3066 };30673068 super(logger);30693070 this.scheduleFn = options.scheduleFn;3071 this.blocksNum = options.blocksNum;3072 this.options = options.options;3073 }30743075 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3076 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);30773078 const mandatorySchedArgs = [3079 this.blocksNum,3080 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3081 this.options.priority ?? null,3082 scheduledTx,3083 ];30843085 let schedArgs;3086 let scheduleFn;30873088 if (this.options.scheduledId) {3089 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];30903091 if (this.scheduleFn == 'schedule') {3092 scheduleFn = 'scheduleNamed';3093 } else if (this.scheduleFn == 'scheduleAfter') {3094 scheduleFn = 'scheduleNamedAfter';3095 }3096 } else {3097 schedArgs = mandatorySchedArgs;3098 scheduleFn = this.scheduleFn;3099 }31003101 const extrinsic = 'api.tx.scheduler.' + scheduleFn;31023103 return super.executeExtrinsic(3104 sender,3105 extrinsic,3106 schedArgs,3107 expectSuccess,3108 );3109 }3110 };3111}31123113// eslint-disable-next-line @typescript-eslint/naming-convention3114function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3115 return class extends Base {3116 constructor(...args: any[]) {3117 super(...args);3118 }31193120 executeExtrinsic (3121 sender: IKeyringPair,3122 extrinsic: string,3123 params: any[],3124 expectSuccess?: boolean,3125 ): Promise<ITransactionResult> {3126 const call = this.constructApiCall(extrinsic, params);3127 return super.executeExtrinsic(3128 sender,3129 'api.tx.sudo.sudo',3130 [call],3131 expectSuccess,3132 );3133 }3134 };3135}31363137export class UniqueBaseCollection {3138 helper: UniqueHelper;3139 collectionId: number;31403141 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3142 this.collectionId = collectionId;3143 this.helper = uniqueHelper;3144 }31453146 async getData() {3147 return await this.helper.collection.getData(this.collectionId);3148 }31493150 async getLastTokenId() {3151 return await this.helper.collection.getLastTokenId(this.collectionId);3152 }31533154 async doesTokenExist(tokenId: number) {3155 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3156 }31573158 async getAdmins() {3159 return await this.helper.collection.getAdmins(this.collectionId);3160 }31613162 async getAllowList() {3163 return await this.helper.collection.getAllowList(this.collectionId);3164 }31653166 async getEffectiveLimits() {3167 return await this.helper.collection.getEffectiveLimits(this.collectionId);3168 }31693170 async getProperties(propertyKeys?: string[] | null) {3171 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3172 }31733174 async getPropertiesConsumedSpace() {3175 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3176 }31773178 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3179 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3180 }31813182 async getOptions() {3183 return await this.helper.collection.getCollectionOptions(this.collectionId);3184 }31853186 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3187 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3188 }31893190 async confirmSponsorship(signer: TSigner) {3191 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3192 }31933194 async removeSponsor(signer: TSigner) {3195 return await this.helper.collection.removeSponsor(signer, this.collectionId);3196 }31973198 async setLimits(signer: TSigner, limits: ICollectionLimits) {3199 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3200 }32013202 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3203 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3204 }32053206 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3207 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3208 }32093210 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3211 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3212 }32133214 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3215 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3216 }32173218 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3219 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3220 }32213222 async setProperties(signer: TSigner, properties: IProperty[]) {3223 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3224 }32253226 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3227 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3228 }32293230 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3231 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3232 }32333234 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3235 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3236 }32373238 async disableNesting(signer: TSigner) {3239 return await this.helper.collection.disableNesting(signer, this.collectionId);3240 }32413242 async burn(signer: TSigner) {3243 return await this.helper.collection.burn(signer, this.collectionId);3244 }32453246 scheduleAt<T extends UniqueHelper>(3247 executionBlockNumber: number,3248 options: ISchedulerOptions = {},3249 ) {3250 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3251 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3252 }32533254 scheduleAfter<T extends UniqueHelper>(3255 blocksBeforeExecution: number,3256 options: ISchedulerOptions = {},3257 ) {3258 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3259 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3260 }32613262 getSudo<T extends UniqueHelper>() {3263 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3264 }3265}326632673268export class UniqueNFTCollection extends UniqueBaseCollection {3269 getTokenObject(tokenId: number) {3270 return new UniqueNFToken(tokenId, this);3271 }32723273 async getTokensByAddress(addressObj: ICrossAccountId) {3274 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3275 }32763277 async getToken(tokenId: number, blockHashAt?: string) {3278 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3279 }32803281 async getTokenOwner(tokenId: number, blockHashAt?: string) {3282 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3283 }32843285 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3286 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3287 }32883289 async getTokenChildren(tokenId: number, blockHashAt?: string) {3290 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3291 }32923293 async getPropertyPermissions(propertyKeys: string[] | null = null) {3294 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3295 }32963297 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3298 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3299 }33003301 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3302 const api = this.helper.getApi();3303 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();33043305 return (props! as any).consumedSpace;3306 }33073308 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3309 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3310 }33113312 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3313 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3314 }33153316 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3317 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3318 }33193320 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3321 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3322 }33233324 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3325 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3326 }33273328 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3329 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3330 }33313332 async burnToken(signer: TSigner, tokenId: number) {3333 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3334 }33353336 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3337 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3338 }33393340 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3341 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3342 }33433344 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3345 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3346 }33473348 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3349 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3350 }33513352 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3353 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3354 }33553356 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3357 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3358 }33593360 scheduleAt<T extends UniqueHelper>(3361 executionBlockNumber: number,3362 options: ISchedulerOptions = {},3363 ) {3364 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3365 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3366 }33673368 scheduleAfter<T extends UniqueHelper>(3369 blocksBeforeExecution: number,3370 options: ISchedulerOptions = {},3371 ) {3372 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3373 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3374 }33753376 getSudo<T extends UniqueHelper>() {3377 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3378 }3379}338033813382export class UniqueRFTCollection extends UniqueBaseCollection {3383 getTokenObject(tokenId: number) {3384 return new UniqueRFToken(tokenId, this);3385 }33863387 async getToken(tokenId: number, blockHashAt?: string) {3388 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3389 }33903391 async getTokensByAddress(addressObj: ICrossAccountId) {3392 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3393 }33943395 async getTop10TokenOwners(tokenId: number) {3396 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3397 }33983399 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3400 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3401 }34023403 async getTokenTotalPieces(tokenId: number) {3404 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3405 }34063407 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3408 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3409 }34103411 async getPropertyPermissions(propertyKeys: string[] | null = null) {3412 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3413 }34143415 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3416 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3417 }34183419 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3420 const api = this.helper.getApi();3421 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();34223423 return (props! as any).consumedSpace;3424 }34253426 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3427 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3428 }34293430 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3431 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3432 }34333434 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3435 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3436 }34373438 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3439 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3440 }34413442 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3443 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3444 }34453446 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3447 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3448 }34493450 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3451 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3452 }34533454 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3455 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3456 }34573458 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3459 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3460 }34613462 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3463 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3464 }34653466 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3467 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3468 }34693470 scheduleAt<T extends UniqueHelper>(3471 executionBlockNumber: number,3472 options: ISchedulerOptions = {},3473 ) {3474 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3475 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3476 }34773478 scheduleAfter<T extends UniqueHelper>(3479 blocksBeforeExecution: number,3480 options: ISchedulerOptions = {},3481 ) {3482 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3483 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3484 }34853486 getSudo<T extends UniqueHelper>() {3487 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3488 }3489}349034913492export class UniqueFTCollection extends UniqueBaseCollection {3493 async getBalance(addressObj: ICrossAccountId) {3494 return await this.helper.ft.getBalance(this.collectionId, addressObj);3495 }34963497 async getTotalPieces() {3498 return await this.helper.ft.getTotalPieces(this.collectionId);3499 }35003501 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3502 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3503 }35043505 async getTop10Owners() {3506 return await this.helper.ft.getTop10Owners(this.collectionId);3507 }35083509 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3510 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3511 }35123513 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3514 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3515 }35163517 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3518 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3519 }35203521 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3522 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3523 }35243525 async burnTokens(signer: TSigner, amount=1n) {3526 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3527 }35283529 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3530 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3531 }35323533 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3534 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3535 }35363537 scheduleAt<T extends UniqueHelper>(3538 executionBlockNumber: number,3539 options: ISchedulerOptions = {},3540 ) {3541 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3542 return new UniqueFTCollection(this.collectionId, scheduledHelper);3543 }35443545 scheduleAfter<T extends UniqueHelper>(3546 blocksBeforeExecution: number,3547 options: ISchedulerOptions = {},3548 ) {3549 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3550 return new UniqueFTCollection(this.collectionId, scheduledHelper);3551 }35523553 getSudo<T extends UniqueHelper>() {3554 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3555 }3556}355735583559export class UniqueBaseToken {3560 collection: UniqueNFTCollection | UniqueRFTCollection;3561 collectionId: number;3562 tokenId: number;35633564 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3565 this.collection = collection;3566 this.collectionId = collection.collectionId;3567 this.tokenId = tokenId;3568 }35693570 async getNextSponsored(addressObj: ICrossAccountId) {3571 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3572 }35733574 async getProperties(propertyKeys?: string[] | null) {3575 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3576 }35773578 async getTokenPropertiesConsumedSpace() {3579 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3580 }35813582 async setProperties(signer: TSigner, properties: IProperty[]) {3583 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3584 }35853586 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3587 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3588 }35893590 async doesExist() {3591 return await this.collection.doesTokenExist(this.tokenId);3592 }35933594 nestingAccount() {3595 return this.collection.helper.util.getTokenAccount(this);3596 }35973598 scheduleAt<T extends UniqueHelper>(3599 executionBlockNumber: number,3600 options: ISchedulerOptions = {},3601 ) {3602 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3603 return new UniqueBaseToken(this.tokenId, scheduledCollection);3604 }36053606 scheduleAfter<T extends UniqueHelper>(3607 blocksBeforeExecution: number,3608 options: ISchedulerOptions = {},3609 ) {3610 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3611 return new UniqueBaseToken(this.tokenId, scheduledCollection);3612 }36133614 getSudo<T extends UniqueHelper>() {3615 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3616 }3617}361836193620export class UniqueNFToken extends UniqueBaseToken {3621 collection: UniqueNFTCollection;36223623 constructor(tokenId: number, collection: UniqueNFTCollection) {3624 super(tokenId, collection);3625 this.collection = collection;3626 }36273628 async getData(blockHashAt?: string) {3629 return await this.collection.getToken(this.tokenId, blockHashAt);3630 }36313632 async getOwner(blockHashAt?: string) {3633 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3634 }36353636 async getTopmostOwner(blockHashAt?: string) {3637 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3638 }36393640 async getChildren(blockHashAt?: string) {3641 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3642 }36433644 async nest(signer: TSigner, toTokenObj: IToken) {3645 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3646 }36473648 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3649 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3650 }36513652 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3653 return await this.collection.transferToken(signer, this.tokenId, addressObj);3654 }36553656 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3657 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3658 }36593660 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3661 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3662 }36633664 async isApproved(toAddressObj: ICrossAccountId) {3665 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3666 }36673668 async burn(signer: TSigner) {3669 return await this.collection.burnToken(signer, this.tokenId);3670 }36713672 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3673 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3674 }36753676 scheduleAt<T extends UniqueHelper>(3677 executionBlockNumber: number,3678 options: ISchedulerOptions = {},3679 ) {3680 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3681 return new UniqueNFToken(this.tokenId, scheduledCollection);3682 }36833684 scheduleAfter<T extends UniqueHelper>(3685 blocksBeforeExecution: number,3686 options: ISchedulerOptions = {},3687 ) {3688 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3689 return new UniqueNFToken(this.tokenId, scheduledCollection);3690 }36913692 getSudo<T extends UniqueHelper>() {3693 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3694 }3695}36963697export class UniqueRFToken extends UniqueBaseToken {3698 collection: UniqueRFTCollection;36993700 constructor(tokenId: number, collection: UniqueRFTCollection) {3701 super(tokenId, collection);3702 this.collection = collection;3703 }37043705 async getData(blockHashAt?: string) {3706 return await this.collection.getToken(this.tokenId, blockHashAt);3707 }37083709 async getTop10Owners() {3710 return await this.collection.getTop10TokenOwners(this.tokenId);3711 }37123713 async getBalance(addressObj: ICrossAccountId) {3714 return await this.collection.getTokenBalance(this.tokenId, addressObj);3715 }37163717 async getTotalPieces() {3718 return await this.collection.getTokenTotalPieces(this.tokenId);3719 }37203721 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3722 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3723 }37243725 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3726 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3727 }37283729 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3730 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3731 }37323733 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3734 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3735 }37363737 async repartition(signer: TSigner, amount: bigint) {3738 return await this.collection.repartitionToken(signer, this.tokenId, amount);3739 }37403741 async burn(signer: TSigner, amount=1n) {3742 return await this.collection.burnToken(signer, this.tokenId, amount);3743 }37443745 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3746 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3747 }37483749 scheduleAt<T extends UniqueHelper>(3750 executionBlockNumber: number,3751 options: ISchedulerOptions = {},3752 ) {3753 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3754 return new UniqueRFToken(this.tokenId, scheduledCollection);3755 }37563757 scheduleAfter<T extends UniqueHelper>(3758 blocksBeforeExecution: number,3759 options: ISchedulerOptions = {},3760 ) {3761 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3762 return new UniqueRFToken(this.tokenId, scheduledCollection);3763 }37643765 getSudo<T extends UniqueHelper>() {3766 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3767 }3768}tests/src/vesting.test.tsdiffbeforeafterboth--- a/tests/src/vesting.test.ts
+++ b/tests/src/vesting.test.ts
@@ -73,7 +73,7 @@
expect(balanceRecepient.feeFrozen).to.eq(250n * nominal);
expect(balanceRecepient.miscFrozen).to.eq(250n * nominal);
expect(balanceRecepient.reserved).to.eq(0n);
-
+
// Wait first schedule ends and first part od second schedule:
await helper.wait.forRelayBlockNumber(SCHEDULE_2_START + SCHEDULE_2_PERIOD);
await helper.balance.claim(recepient);
@@ -84,7 +84,7 @@
expect(balanceRecepient.feeFrozen).to.eq(100n * nominal);
expect(balanceRecepient.miscFrozen).to.eq(100n * nominal);
expect(balanceRecepient.reserved).to.eq(0n);
-
+
// Schedules list contain 1 vesting:
schedule = await helper.balance.getVestingSchedules(recepient.address);
expect(schedule).to.has.length(1);
@@ -100,7 +100,7 @@
expect(balanceRecepient.feeFrozen).to.eq(0n);
expect(balanceRecepient.miscFrozen).to.eq(0n);
expect(balanceRecepient.reserved).to.eq(0n);
-
+
// check sender balance does not changed:
balanceSender = await helper.balance.getSubstrateFull(sender.address);
expect(balanceSender.free / nominal).to.eq(699n);
tests/src/xcm/xcmOpal.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmOpal.test.ts
+++ b/tests/src/xcm/xcmOpal.test.ts
@@ -37,12 +37,12 @@
const TRANSFER_AMOUNT = 1_000_000_000_000_000_000n;
// 10,000.00 (ten thousands) USDT
-const ASSET_AMOUNT = 1_000_000_000_000_000_000_000n;
+const ASSET_AMOUNT = 1_000_000_000_000_000_000_000n;
describeXCM('[XCM] Integration test: Exchanging USDT with Westmint', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
-
+
let balanceStmnBefore: bigint;
let balanceStmnAfter: bigint;
@@ -66,7 +66,7 @@
await usingWestmintPlaygrounds(westmintUrl, async (helper) => {
// 350.00 (three hundred fifty) DOT
- const fundingAmount = 3_500_000_000_000n;
+ const fundingAmount = 3_500_000_000_000n;
await helper.assets.create(alice, ASSET_ID, alice.address, ASSET_METADATA_MINIMAL_BALANCE);
await helper.assets.setMetadata(alice, ASSET_ID, ASSET_METADATA_NAME, ASSET_METADATA_DESCRIPTION, ASSET_METADATA_DECIMALS);
@@ -151,7 +151,7 @@
await helper.xcm.limitedReserveTransferAssets(alice, destination, beneficiary, assets, feeAssetItem, 'Unlimited');
});
-
+
});
itSub('Should connect and send USDT from Westmint to Opal', async ({helper}) => {
@@ -190,7 +190,7 @@
},
{
GeneralIndex: ASSET_ID,
- },
+ },
]},
},
},
@@ -266,7 +266,7 @@
},
//10_000_000_000_000_000n,
TRANSFER_AMOUNT,
- ],
+ ],
[
{
NativeAssetId: 'Parent',
@@ -278,16 +278,16 @@
const feeItem = 1;
await helper.xTokens.transferMulticurrencies(alice, currencies, feeItem, destination, 'Unlimited');
-
+
// the commission has been paid in parachain native token
balanceOpalFinal = await helper.balance.getSubstrate(alice.address);
expect(balanceOpalAfter > balanceOpalFinal).to.be.true;
await usingWestmintPlaygrounds(westmintUrl, async (helper) => {
await helper.wait.newBlocks(3);
-
+
// The USDT token never paid fees. Its amount not changed from begin value.
- // Also check that xcm transfer has been succeeded
+ // Also check that xcm transfer has been succeeded
expect((await helper.assets.account(ASSET_ID, alice.address))! == ASSET_AMOUNT).to.be.true;
});
});
@@ -341,13 +341,13 @@
await helper.xcm.limitedReserveTransferAssets(bob, destination, beneficiary, assets, feeAssetItem, 'Unlimited');
});
-
+
await helper.wait.newBlocks(3);
- balanceBobAfter = await helper.balance.getSubstrate(bob.address);
+ balanceBobAfter = await helper.balance.getSubstrate(bob.address);
balanceBobRelayTokenAfter = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});
- const wndFee = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore;
+ const wndFee = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore;
console.log(
'Relay (Westend) to Opal transaction fees: %s OPL',
helper.util.bigIntToDecimals(balanceBobAfter - balanceBobBefore),
tests/src/xcm/xcmQuartz.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmQuartz.test.ts
+++ b/tests/src/xcm/xcmQuartz.test.ts
@@ -38,7 +38,7 @@
const TRANSFER_AMOUNT = 2000000000000000000000000n;
-const FUNDING_AMOUNT = 3_500_000_0000_000_000n;
+const FUNDING_AMOUNT = 3_500_000_0000_000_000n;
const TRANSFER_AMOUNT_RELAY = 50_000_000_000_000_000n;
@@ -52,7 +52,7 @@
describeXCM('[XCM] Integration test: Exchanging USDT with Statemine', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
-
+
let balanceStmnBefore: bigint;
let balanceStmnAfter: bigint;
@@ -81,7 +81,7 @@
});
await usingStateminePlaygrounds(statemineUrl, async (helper) => {
- const sovereignFundingAmount = 3_500_000_000n;
+ const sovereignFundingAmount = 3_500_000_000n;
await helper.assets.create(
alice,
@@ -185,7 +185,7 @@
await helper.xcm.limitedReserveTransferAssets(alice, destination, beneficiary, assets, feeAssetItem, 'Unlimited');
});
-
+
});
itSub('Should connect and send USDT from Statemine to Quartz', async ({helper}) => {
@@ -224,7 +224,7 @@
},
{
GeneralIndex: USDT_ASSET_ID,
- },
+ },
]},
},
},
@@ -267,7 +267,7 @@
console.log(
'[Statemine -> Quartz] transaction fees on Quartz: %s QTZ',
helper.util.bigIntToDecimals(balanceQuartzAfter - balanceQuartzBefore),
- );
+ );
// commission has not paid in USDT token
expect(free).to.be.equal(TRANSFER_AMOUNT);
// ... and parachain native token
@@ -299,7 +299,7 @@
ForeignAssetId: 0,
},
TRANSFER_AMOUNT,
- ],
+ ],
[
{
NativeAssetId: 'Parent',
@@ -311,7 +311,7 @@
const feeItem = 1;
await helper.xTokens.transferMulticurrencies(alice, currencies, feeItem, destination, 'Unlimited');
-
+
// the commission has been paid in parachain native token
balanceQuartzFinal = await helper.balance.getSubstrate(alice.address);
console.log('[Quartz -> Statemine] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(balanceQuartzFinal - balanceQuartzAfter));
@@ -319,9 +319,9 @@
await usingStateminePlaygrounds(statemineUrl, async (helper) => {
await helper.wait.newBlocks(3);
-
+
// The USDT token never paid fees. Its amount not changed from begin value.
- // Also check that xcm transfer has been succeeded
+ // Also check that xcm transfer has been succeeded
expect((await helper.assets.account(USDT_ASSET_ID, alice.address))! == USDT_ASSET_AMOUNT).to.be.true;
});
});
@@ -372,10 +372,10 @@
await helper.xcm.limitedReserveTransferAssets(bob, destination, beneficiary, assets, feeAssetItem, 'Unlimited');
});
-
+
await helper.wait.newBlocks(3);
- balanceBobAfter = await helper.balance.getSubstrate(bob.address);
+ balanceBobAfter = await helper.balance.getSubstrate(bob.address);
balanceBobRelayTokenAfter = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});
const wndFeeOnQuartz = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore;
tests/src/xcm/xcmUnique.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmUnique.test.ts
+++ b/tests/src/xcm/xcmUnique.test.ts
@@ -38,7 +38,7 @@
const TRANSFER_AMOUNT = 2000000000000000000000000n;
-const FUNDING_AMOUNT = 3_500_000_0000_000_000n;
+const FUNDING_AMOUNT = 3_500_000_0000_000_000n;
const TRANSFER_AMOUNT_RELAY = 50_000_000_000_000_000n;
@@ -52,7 +52,7 @@
describeXCM('[XCM] Integration test: Exchanging USDT with Statemint', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
-
+
let balanceStmnBefore: bigint;
let balanceStmnAfter: bigint;
@@ -81,7 +81,7 @@
});
await usingStatemintPlaygrounds(statemintUrl, async (helper) => {
- const sovereignFundingAmount = 3_500_000_000n;
+ const sovereignFundingAmount = 3_500_000_000n;
await helper.assets.create(
alice,
@@ -185,7 +185,7 @@
await helper.xcm.limitedReserveTransferAssets(alice, destination, beneficiary, assets, feeAssetItem, 'Unlimited');
});
-
+
});
itSub('Should connect and send USDT from Statemint to Unique', async ({helper}) => {
@@ -224,7 +224,7 @@
},
{
GeneralIndex: USDT_ASSET_ID,
- },
+ },
]},
},
},
@@ -267,7 +267,7 @@
console.log(
'[Statemint -> Unique] transaction fees on Unique: %s UNQ',
helper.util.bigIntToDecimals(balanceUniqueAfter - balanceUniqueBefore),
- );
+ );
// commission has not paid in USDT token
expect(free).to.be.equal(TRANSFER_AMOUNT);
// ... and parachain native token
@@ -299,7 +299,7 @@
ForeignAssetId: 0,
},
TRANSFER_AMOUNT,
- ],
+ ],
[
{
NativeAssetId: 'Parent',
@@ -311,7 +311,7 @@
const feeItem = 1;
await helper.xTokens.transferMulticurrencies(alice, currencies, feeItem, destination, 'Unlimited');
-
+
// the commission has been paid in parachain native token
balanceUniqueFinal = await helper.balance.getSubstrate(alice.address);
console.log('[Unique -> Statemint] transaction fees on Unique: %s UNQ', helper.util.bigIntToDecimals(balanceUniqueFinal - balanceUniqueAfter));
@@ -319,9 +319,9 @@
await usingStatemintPlaygrounds(statemintUrl, async (helper) => {
await helper.wait.newBlocks(3);
-
+
// The USDT token never paid fees. Its amount not changed from begin value.
- // Also check that xcm transfer has been succeeded
+ // Also check that xcm transfer has been succeeded
expect((await helper.assets.account(USDT_ASSET_ID, alice.address))! == USDT_ASSET_AMOUNT).to.be.true;
});
});
@@ -372,10 +372,10 @@
await helper.xcm.limitedReserveTransferAssets(bob, destination, beneficiary, assets, feeAssetItem, 'Unlimited');
});
-
+
await helper.wait.newBlocks(3);
- balanceBobAfter = await helper.balance.getSubstrate(bob.address);
+ balanceBobAfter = await helper.balance.getSubstrate(bob.address);
balanceBobRelayTokenAfter = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});
const wndFeeOnUnique = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore;
@@ -909,7 +909,7 @@
const unqRandomAccountAsset = await helper.assets.account(assetId, randomAccountMoonbeam.address);
expect(unqRandomAccountAsset).to.be.null;
-
+
balanceForeignUnqTokenFinal = 0n;
const unqOutcomeTransfer = balanceForeignUnqTokenMiddle - balanceForeignUnqTokenFinal;
tests/yarn.lockdiffbeforeafterboth--- a/tests/yarn.lock
+++ b/tests/yarn.lock
@@ -1065,7 +1065,7 @@
dependencies:
"@types/node" "*"
-"@typescript-eslint/eslint-plugin@^5.40.1":
+"@typescript-eslint/eslint-plugin@^5.47.0":
version "5.47.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.47.0.tgz#dadb79df3b0499699b155839fd6792f16897d910"
integrity sha512-AHZtlXAMGkDmyLuLZsRpH3p4G/1iARIwc/T0vIem2YB+xW6pZaXYXzCBnZSF/5fdM97R9QqZWZ+h3iW10XgevQ==
@@ -1080,7 +1080,7 @@
semver "^7.3.7"
tsutils "^3.21.0"
-"@typescript-eslint/parser@^5.40.1":
+"@typescript-eslint/parser@^5.47.0":
version "5.47.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-5.47.0.tgz#62e83de93499bf4b500528f74bf2e0554e3a6c8d"
integrity sha512-udPU4ckK+R1JWCGdQC4Qa27NtBg7w020ffHqGyAK8pAgOVuNw7YaKXGChk+udh+iiGIJf6/E/0xhVXyPAbsczw==