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.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// std18use std::sync::Arc;19use std::sync::Mutex;20use std::collections::BTreeMap;21use std::time::Duration;22use std::pin::Pin;23use fc_rpc_core::types::FeeHistoryCache;24use futures::{25 Stream, StreamExt,26 stream::select,27 task::{Context, Poll},28};29use tokio::time::Interval;3031use unique_rpc::overrides_handle;3233use serde::{Serialize, Deserialize};3435// Cumulus Imports36use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};37use cumulus_client_consensus_common::{38 ParachainConsensus, ParachainBlockImport as TParachainBlockImport,39};40use cumulus_client_service::{41 prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,42};43use cumulus_client_cli::CollatorOptions;44use cumulus_client_network::BlockAnnounceValidator;45use cumulus_primitives_core::ParaId;46use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;47use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};48use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node;4950// Substrate Imports51use sp_api::BlockT;52use sc_executor::NativeElseWasmExecutor;53use sc_executor::NativeExecutionDispatch;54use sc_network::{NetworkService, NetworkBlock};55use sc_service::{BasePath, Configuration, PartialComponents, TaskManager};56use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};57use sp_keystore::SyncCryptoStorePtr;58use sp_runtime::traits::BlakeTwo256;59use substrate_prometheus_endpoint::Registry;60use sc_client_api::BlockchainEvents;61use sc_consensus::ImportQueue;6263use polkadot_service::CollatorPair;6465// Frontier Imports66use fc_rpc_core::types::FilterPool;67use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6869use up_common::types::opaque::{70 AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block, BlockNumber,71};7273// RMRK74use up_data_structs::{75 RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,76 RmrkPartType, RmrkTheme,77};7879/// Unique native executor instance.80#[cfg(feature = "unique-runtime")]81pub struct UniqueRuntimeExecutor;8283#[cfg(feature = "quartz-runtime")]84/// Quartz native executor instance.85pub struct QuartzRuntimeExecutor;8687/// Opal native executor instance.88pub struct OpalRuntimeExecutor;8990#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]91pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;9293#[cfg(all(94 not(feature = "unique-runtime"),95 feature = "quartz-runtime",96 feature = "runtime-benchmarks"97))]98pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;99100#[cfg(all(101 not(feature = "unique-runtime"),102 not(feature = "quartz-runtime"),103 feature = "runtime-benchmarks"104))]105pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;106107#[cfg(feature = "unique-runtime")]108impl NativeExecutionDispatch for UniqueRuntimeExecutor {109 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;110111 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {112 unique_runtime::api::dispatch(method, data)113 }114115 fn native_version() -> sc_executor::NativeVersion {116 unique_runtime::native_version()117 }118}119120#[cfg(feature = "quartz-runtime")]121impl NativeExecutionDispatch for QuartzRuntimeExecutor {122 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;123124 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {125 quartz_runtime::api::dispatch(method, data)126 }127128 fn native_version() -> sc_executor::NativeVersion {129 quartz_runtime::native_version()130 }131}132133impl NativeExecutionDispatch for OpalRuntimeExecutor {134 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;135136 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {137 opal_runtime::api::dispatch(method, data)138 }139140 fn native_version() -> sc_executor::NativeVersion {141 opal_runtime::native_version()142 }143}144145pub struct AutosealInterval {146 interval: Interval,147}148149impl AutosealInterval {150 pub fn new(config: &Configuration, interval: Duration) -> Self {151 let _tokio_runtime = config.tokio_handle.enter();152 let interval = tokio::time::interval(interval);153154 Self { interval }155 }156}157158impl Stream for AutosealInterval {159 type Item = tokio::time::Instant;160161 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {162 self.interval.poll_tick(cx).map(Some)163 }164}165166pub fn open_frontier_backend<Block: BlockT, C: sp_blockchain::HeaderBackend<Block>>(167 client: Arc<C>,168 config: &Configuration,169) -> Result<Arc<fc_db::Backend<Block>>, String> {170 let config_dir = config171 .base_path172 .as_ref()173 .map(|base_path| base_path.config_dir(config.chain_spec.id()))174 .unwrap_or_else(|| {175 BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())176 });177 let database_dir = config_dir.join("frontier").join("db");178179 Ok(Arc::new(fc_db::Backend::<Block>::new(180 client,181 &fc_db::DatabaseSettings {182 source: fc_db::DatabaseSource::RocksDb {183 path: database_dir,184 cache_size: 0,185 },186 },187 )?))188}189190type FullClient<RuntimeApi, ExecutorDispatch> =191 sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;192type FullBackend = sc_service::TFullBackend<Block>;193type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;194type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =195 TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;196197/// Starts a `ServiceBuilder` for a full service.198///199/// Use this macro if you don't actually need the full service, but just the builder in order to200/// be able to perform chain operations.201#[allow(clippy::type_complexity)]202pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(203 config: &Configuration,204 build_import_queue: BIQ,205) -> Result<206 PartialComponents<207 FullClient<RuntimeApi, ExecutorDispatch>,208 FullBackend,209 FullSelectChain,210 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,211 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,212 (213 Option<Telemetry>,214 Option<FilterPool>,215 Arc<fc_db::Backend<Block>>,216 Option<TelemetryWorkerHandle>,217 FeeHistoryCache,218 ),219 >,220 sc_service::Error,221>222where223 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,224 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>225 + Send226 + Sync227 + 'static,228 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,229 ExecutorDispatch: NativeExecutionDispatch + 'static,230 BIQ: FnOnce(231 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,232 Arc<FullBackend>,233 &Configuration,234 Option<TelemetryHandle>,235 &TaskManager,236 ) -> Result<237 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,238 sc_service::Error,239 >,240{241 let _telemetry = config242 .telemetry_endpoints243 .clone()244 .filter(|x| !x.is_empty())245 .map(|endpoints| -> Result<_, sc_telemetry::Error> {246 let worker = TelemetryWorker::new(16)?;247 let telemetry = worker.handle().new_telemetry(endpoints);248 Ok((worker, telemetry))249 })250 .transpose()?;251252 let telemetry = config253 .telemetry_endpoints254 .clone()255 .filter(|x| !x.is_empty())256 .map(|endpoints| -> Result<_, sc_telemetry::Error> {257 let worker = TelemetryWorker::new(16)?;258 let telemetry = worker.handle().new_telemetry(endpoints);259 Ok((worker, telemetry))260 })261 .transpose()?;262263 let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(264 config.wasm_method,265 config.default_heap_pages,266 config.max_runtime_instances,267 config.runtime_cache_size,268 );269270 let (client, backend, keystore_container, task_manager) =271 sc_service::new_full_parts::<Block, RuntimeApi, _>(272 config,273 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),274 executor,275 )?;276 let client = Arc::new(client);277278 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());279280 let telemetry = telemetry.map(|(worker, telemetry)| {281 task_manager282 .spawn_handle()283 .spawn("telemetry", None, worker.run());284 telemetry285 });286287 let select_chain = sc_consensus::LongestChain::new(backend.clone());288289 let transaction_pool = sc_transaction_pool::BasicPool::new_full(290 config.transaction_pool.clone(),291 config.role.is_authority().into(),292 config.prometheus_registry(),293 task_manager.spawn_essential_handle(),294 client.clone(),295 );296297 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));298299 let frontier_backend = open_frontier_backend(client.clone(), config)?;300301 let import_queue = build_import_queue(302 client.clone(),303 backend.clone(),304 config,305 telemetry.as_ref().map(|telemetry| telemetry.handle()),306 &task_manager,307 )?;308 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));309310 let params = PartialComponents {311 backend,312 client,313 import_queue,314 keystore_container,315 task_manager,316 transaction_pool,317 select_chain,318 other: (319 telemetry,320 filter_pool,321 frontier_backend,322 telemetry_worker_handle,323 fee_history_cache,324 ),325 };326327 Ok(params)328}329330async fn build_relay_chain_interface(331 polkadot_config: Configuration,332 parachain_config: &Configuration,333 telemetry_worker_handle: Option<TelemetryWorkerHandle>,334 task_manager: &mut TaskManager,335 collator_options: CollatorOptions,336 hwbench: Option<sc_sysinfo::HwBench>,337) -> RelayChainResult<(338 Arc<(dyn RelayChainInterface + 'static)>,339 Option<CollatorPair>,340)> {341 if collator_options.relay_chain_rpc_urls.is_empty() {342 build_inprocess_relay_chain(343 polkadot_config,344 parachain_config,345 telemetry_worker_handle,346 task_manager,347 hwbench,348 )349 } else {350 build_minimal_relay_chain_node(351 polkadot_config,352 task_manager,353 collator_options.relay_chain_rpc_urls,354 )355 .await356 }357}358359/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.360///361/// This is the actual implementation that is abstract over the executor and the runtime api.362#[sc_tracing::logging::prefix_logs_with("Parachain")]363async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(364 parachain_config: Configuration,365 polkadot_config: Configuration,366 collator_options: CollatorOptions,367 id: ParaId,368 build_import_queue: BIQ,369 build_consensus: BIC,370 hwbench: Option<sc_sysinfo::HwBench>,371) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>372where373 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,374 Runtime: RuntimeInstance + Send + Sync + 'static,375 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,376 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,377 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>378 + Send379 + Sync380 + 'static,381 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>382 + fp_rpc::EthereumRuntimeRPCApi<Block>383 + fp_rpc::ConvertTransactionRuntimeApi<Block>384 + sp_session::SessionKeys<Block>385 + sp_block_builder::BlockBuilder<Block>386 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>387 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>388 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>389 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>390 + rmrk_rpc::RmrkApi<391 Block,392 AccountId,393 RmrkCollectionInfo<AccountId>,394 RmrkInstanceInfo<AccountId>,395 RmrkResourceInfo,396 RmrkPropertyInfo,397 RmrkBaseInfo<AccountId>,398 RmrkPartType,399 RmrkTheme,400 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>401 + sp_api::Metadata<Block>402 + sp_offchain::OffchainWorkerApi<Block>403 + cumulus_primitives_core::CollectCollationInfo<Block>,404 ExecutorDispatch: NativeExecutionDispatch + 'static,405 BIQ: FnOnce(406 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,407 Arc<FullBackend>,408 &Configuration,409 Option<TelemetryHandle>,410 &TaskManager,411 ) -> Result<412 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,413 sc_service::Error,414 >,415 BIC: FnOnce(416 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,417 Arc<FullBackend>,418 Option<&Registry>,419 Option<TelemetryHandle>,420 &TaskManager,421 Arc<dyn RelayChainInterface>,422 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,423 Arc<NetworkService<Block, Hash>>,424 SyncCryptoStorePtr,425 bool,426 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,427{428 let parachain_config = prepare_node_config(parachain_config);429430 let params =431 new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(¶chain_config, build_import_queue)?;432 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =433 params.other;434435 let client = params.client.clone();436 let backend = params.backend.clone();437 let mut task_manager = params.task_manager;438439 let (relay_chain_interface, collator_key) = build_relay_chain_interface(440 polkadot_config,441 ¶chain_config,442 telemetry_worker_handle,443 &mut task_manager,444 collator_options.clone(),445 hwbench.clone(),446 )447 .await448 .map_err(|e| match e {449 RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,450 s => s.to_string().into(),451 })?;452453 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);454455 let force_authoring = parachain_config.force_authoring;456 let validator = parachain_config.role.is_authority();457 let prometheus_registry = parachain_config.prometheus_registry().cloned();458 let transaction_pool = params.transaction_pool.clone();459 let import_queue_service = params.import_queue.service();460461 let (network, system_rpc_tx, tx_handler_controller, start_network) =462 sc_service::build_network(sc_service::BuildNetworkParams {463 config: ¶chain_config,464 client: client.clone(),465 transaction_pool: transaction_pool.clone(),466 spawn_handle: task_manager.spawn_handle(),467 import_queue: params.import_queue,468 block_announce_validator_builder: Some(Box::new(|_| {469 Box::new(block_announce_validator)470 })),471 warp_sync: None,472 })?;473474 let rpc_client = client.clone();475 let rpc_pool = transaction_pool.clone();476 let select_chain = params.select_chain.clone();477 let rpc_network = network.clone();478479 let rpc_frontier_backend = frontier_backend.clone();480481 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(482 task_manager.spawn_handle(),483 overrides_handle::<_, _, Runtime>(client.clone()),484 50,485 50,486 prometheus_registry.clone(),487 ));488489 task_manager.spawn_essential_handle().spawn(490 "frontier-mapping-sync-worker",491 None,492 MappingSyncWorker::new(493 client.import_notification_stream(),494 Duration::new(6, 0),495 client.clone(),496 backend.clone(),497 frontier_backend.clone(),498 3,499 0,500 SyncStrategy::Normal,501 )502 .for_each(|()| futures::future::ready(())),503 );504505 let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {506 let full_deps = unique_rpc::FullDeps {507 backend: rpc_frontier_backend.clone(),508 deny_unsafe,509 client: rpc_client.clone(),510 pool: rpc_pool.clone(),511 graph: rpc_pool.pool().clone(),512 // TODO: Unhardcode513 enable_dev_signer: false,514 filter_pool: filter_pool.clone(),515 network: rpc_network.clone(),516 select_chain: select_chain.clone(),517 is_authority: validator,518 // TODO: Unhardcode519 max_past_logs: 10000,520 block_data_cache: block_data_cache.clone(),521 fee_history_cache: fee_history_cache.clone(),522 // TODO: Unhardcode523 fee_history_limit: 2048,524 };525526 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(527 full_deps,528 subscription_task_executor,529 )530 .map_err(Into::into)531 });532533 sc_service::spawn_tasks(sc_service::SpawnTasksParams {534 rpc_builder,535 client: client.clone(),536 transaction_pool: transaction_pool.clone(),537 task_manager: &mut task_manager,538 config: parachain_config,539 keystore: params.keystore_container.sync_keystore(),540 backend: backend.clone(),541 network: network.clone(),542 system_rpc_tx,543 telemetry: telemetry.as_mut(),544 tx_handler_controller,545 })?;546547 if let Some(hwbench) = hwbench {548 sc_sysinfo::print_hwbench(&hwbench);549550 if let Some(ref mut telemetry) = telemetry {551 let telemetry_handle = telemetry.handle();552 task_manager.spawn_handle().spawn(553 "telemetry_hwbench",554 None,555 sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),556 );557 }558 }559560 let announce_block = {561 let network = network.clone();562 Arc::new(Box::new(move |hash, data| {563 network.announce_block(hash, data)564 }))565 };566567 let relay_chain_slot_duration = Duration::from_secs(6);568569 if validator {570 let parachain_consensus = build_consensus(571 client.clone(),572 backend.clone(),573 prometheus_registry.as_ref(),574 telemetry.as_ref().map(|t| t.handle()),575 &task_manager,576 relay_chain_interface.clone(),577 transaction_pool,578 network,579 params.keystore_container.sync_keystore(),580 force_authoring,581 )?;582583 let spawner = task_manager.spawn_handle();584585 let params = StartCollatorParams {586 para_id: id,587 block_status: client.clone(),588 announce_block,589 client: client.clone(),590 task_manager: &mut task_manager,591 spawner,592 parachain_consensus,593 import_queue: import_queue_service,594 collator_key: collator_key.expect("Command line arguments do not allow this. qed"),595 relay_chain_interface,596 relay_chain_slot_duration,597 };598599 start_collator(params).await?;600 } else {601 let params = StartFullNodeParams {602 client: client.clone(),603 announce_block,604 task_manager: &mut task_manager,605 para_id: id,606 import_queue: import_queue_service,607 relay_chain_interface,608 relay_chain_slot_duration,609 };610611 start_full_node(params)?;612 }613614 start_network.start_network();615616 Ok((task_manager, client))617}618619/// Build the import queue for the the parachain runtime.620pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(621 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,622 backend: Arc<FullBackend>,623 config: &Configuration,624 telemetry: Option<TelemetryHandle>,625 task_manager: &TaskManager,626) -> Result<627 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,628 sc_service::Error,629>630where631 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>632 + Send633 + Sync634 + 'static,635 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>636 + sp_block_builder::BlockBuilder<Block>637 + sp_consensus_aura::AuraApi<Block, AuraId>638 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,639 ExecutorDispatch: NativeExecutionDispatch + 'static,640{641 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;642643 let block_import = ParachainBlockImport::new(client.clone(), backend.clone());644645 cumulus_client_consensus_aura::import_queue::<646 sp_consensus_aura::sr25519::AuthorityPair,647 _,648 _,649 _,650 _,651 _,652 >(cumulus_client_consensus_aura::ImportQueueParams {653 block_import,654 client: client.clone(),655 create_inherent_data_providers: move |_, _| async move {656 let time = sp_timestamp::InherentDataProvider::from_system_time();657658 let slot =659 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(660 *time,661 slot_duration,662 );663664 Ok((slot, time))665 },666 registry: config.prometheus_registry(),667 spawner: &task_manager.spawn_essential_handle(),668 telemetry,669 })670 .map_err(Into::into)671}672673/// Start a normal parachain node.674pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(675 parachain_config: Configuration,676 polkadot_config: Configuration,677 collator_options: CollatorOptions,678 id: ParaId,679 hwbench: Option<sc_sysinfo::HwBench>,680) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>681where682 Runtime: RuntimeInstance + Send + Sync + 'static,683 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,684 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,685 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>686 + Send687 + Sync688 + 'static,689 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>690 + fp_rpc::EthereumRuntimeRPCApi<Block>691 + fp_rpc::ConvertTransactionRuntimeApi<Block>692 + sp_session::SessionKeys<Block>693 + sp_block_builder::BlockBuilder<Block>694 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>695 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>696 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>697 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>698 + rmrk_rpc::RmrkApi<699 Block,700 AccountId,701 RmrkCollectionInfo<AccountId>,702 RmrkInstanceInfo<AccountId>,703 RmrkResourceInfo,704 RmrkPropertyInfo,705 RmrkBaseInfo<AccountId>,706 RmrkPartType,707 RmrkTheme,708 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>709 + sp_api::Metadata<Block>710 + sp_offchain::OffchainWorkerApi<Block>711 + cumulus_primitives_core::CollectCollationInfo<Block>712 + sp_consensus_aura::AuraApi<Block, AuraId>,713 ExecutorDispatch: NativeExecutionDispatch + 'static,714{715 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(716 parachain_config,717 polkadot_config,718 collator_options,719 id,720 parachain_build_import_queue,721 |client,722 backend,723 prometheus_registry,724 telemetry,725 task_manager,726 relay_chain_interface,727 transaction_pool,728 sync_oracle,729 keystore,730 force_authoring| {731 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;732733 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(734 task_manager.spawn_handle(),735 client.clone(),736 transaction_pool,737 prometheus_registry,738 telemetry.clone(),739 );740741 let block_import = ParachainBlockImport::new(client.clone(), backend.clone());742743 Ok(AuraConsensus::build::<744 sp_consensus_aura::sr25519::AuthorityPair,745 _,746 _,747 _,748 _,749 _,750 _,751 >(BuildAuraConsensusParams {752 proposer_factory,753 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {754 let relay_chain_interface = relay_chain_interface.clone();755 async move {756 let parachain_inherent =757 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(758 relay_parent,759 &relay_chain_interface,760 &validation_data,761 id,762 ).await;763764 let time = sp_timestamp::InherentDataProvider::from_system_time();765766 let slot =767 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(768 *time,769 slot_duration,770 );771772 let parachain_inherent = parachain_inherent.ok_or_else(|| {773 Box::<dyn std::error::Error + Send + Sync>::from(774 "Failed to create parachain inherent",775 )776 })?;777 Ok((slot, time, parachain_inherent))778 }779 },780 block_import,781 para_client: client,782 backoff_authoring_blocks: Option::<()>::None,783 sync_oracle,784 keystore,785 force_authoring,786 slot_duration,787 // We got around 500ms for proposing788 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),789 telemetry,790 max_block_proposal_slot_portion: None,791 }))792 },793 hwbench,794 )795 .await796}797798fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(799 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,800 _: Arc<FullBackend>,801 config: &Configuration,802 _: Option<TelemetryHandle>,803 task_manager: &TaskManager,804) -> Result<805 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,806 sc_service::Error,807>808where809 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>810 + Send811 + Sync812 + 'static,813 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>814 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,815 ExecutorDispatch: NativeExecutionDispatch + 'static,816{817 Ok(sc_consensus_manual_seal::import_queue(818 Box::new(client.clone()),819 &task_manager.spawn_essential_handle(),820 config.prometheus_registry(),821 ))822}823824/// Builds a new development service. This service uses instant seal, and mocks825/// the parachain inherent826pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(827 config: Configuration,828 autoseal_interval: Duration,829) -> sc_service::error::Result<TaskManager>830where831 Runtime: RuntimeInstance + Send + Sync + 'static,832 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,833 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,834 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>835 + Send836 + Sync837 + 'static,838 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>839 + fp_rpc::EthereumRuntimeRPCApi<Block>840 + fp_rpc::ConvertTransactionRuntimeApi<Block>841 + sp_session::SessionKeys<Block>842 + sp_block_builder::BlockBuilder<Block>843 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>844 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>845 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>846 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>847 + rmrk_rpc::RmrkApi<848 Block,849 AccountId,850 RmrkCollectionInfo<AccountId>,851 RmrkInstanceInfo<AccountId>,852 RmrkResourceInfo,853 RmrkPropertyInfo,854 RmrkBaseInfo<AccountId>,855 RmrkPartType,856 RmrkTheme,857 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>858 + sp_api::Metadata<Block>859 + sp_offchain::OffchainWorkerApi<Block>860 + cumulus_primitives_core::CollectCollationInfo<Block>861 + sp_consensus_aura::AuraApi<Block, AuraId>,862 ExecutorDispatch: NativeExecutionDispatch + 'static,863{864 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};865 use fc_consensus::FrontierBlockImport;866 use sc_client_api::HeaderBackend;867868 let sc_service::PartialComponents {869 client,870 backend,871 mut task_manager,872 import_queue,873 keystore_container,874 select_chain: maybe_select_chain,875 transaction_pool,876 other:877 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),878 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(879 &config,880 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,881 )?;882 let prometheus_registry = config.prometheus_registry().cloned();883884 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(885 task_manager.spawn_handle(),886 overrides_handle::<_, _, Runtime>(client.clone()),887 50,888 50,889 prometheus_registry.clone(),890 ));891892 let (network, system_rpc_tx, tx_handler_controller, network_starter) =893 sc_service::build_network(sc_service::BuildNetworkParams {894 config: &config,895 client: client.clone(),896 transaction_pool: transaction_pool.clone(),897 spawn_handle: task_manager.spawn_handle(),898 import_queue,899 block_announce_validator_builder: None,900 warp_sync: None,901 })?;902903 if config.offchain_worker.enabled {904 sc_service::build_offchain_workers(905 &config,906 task_manager.spawn_handle(),907 client.clone(),908 network.clone(),909 );910 }911912 let collator = config.role.is_authority();913914 let select_chain = maybe_select_chain.clone();915916 if collator {917 let block_import =918 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());919920 let env = sc_basic_authorship::ProposerFactory::new(921 task_manager.spawn_handle(),922 client.clone(),923 transaction_pool.clone(),924 prometheus_registry.as_ref(),925 telemetry.as_ref().map(|x| x.handle()),926 );927928 let transactions_commands_stream: Box<929 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,930 > = Box::new(931 transaction_pool932 .pool()933 .validated_pool()934 .import_notification_stream()935 .map(|_| EngineCommand::SealNewBlock {936 create_empty: true,937 finalize: false,938 parent_hash: None,939 sender: None,940 }),941 );942943 let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));944 let idle_commands_stream: Box<945 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,946 > = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {947 create_empty: true,948 finalize: false,949 parent_hash: None,950 sender: None,951 }));952953 let commands_stream = select(transactions_commands_stream, idle_commands_stream);954955 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;956 let client_set_aside_for_cidp = client.clone();957958 task_manager.spawn_essential_handle().spawn_blocking(959 "authorship_task",960 Some("block-authoring"),961 run_manual_seal(ManualSealParams {962 block_import,963 env,964 client: client.clone(),965 pool: transaction_pool.clone(),966 commands_stream,967 select_chain: select_chain.clone(),968 consensus_data_provider: None,969 create_inherent_data_providers: move |block: Hash, ()| {970 let current_para_block = client_set_aside_for_cidp971 .number(block)972 .expect("Header lookup should succeed")973 .expect("Header passed in as parent should be present in backend.");974975 let client_for_xcm = client_set_aside_for_cidp.clone();976 async move {977 let time = sp_timestamp::InherentDataProvider::from_system_time();978979 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {980 current_para_block,981 relay_offset: 1000,982 relay_blocks_per_para_block: 2,983 para_blocks_per_relay_epoch: 0,984 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(985 &*client_for_xcm,986 block,987 Default::default(),988 Default::default(),989 ),990 relay_randomness_config: (),991 raw_downward_messages: vec![],992 raw_horizontal_messages: vec![],993 };994995 let slot =996 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(997 *time,998 slot_duration,999 );10001001 Ok((time, slot, mocked_parachain))1002 }1003 },1004 }),1005 );1006 }10071008 task_manager.spawn_essential_handle().spawn(1009 "frontier-mapping-sync-worker",1010 Some("block-authoring"),1011 MappingSyncWorker::new(1012 client.import_notification_stream(),1013 Duration::new(6, 0),1014 client.clone(),1015 backend.clone(),1016 frontier_backend.clone(),1017 3,1018 0,1019 SyncStrategy::Normal,1020 )1021 .for_each(|()| futures::future::ready(())),1022 );10231024 let rpc_client = client.clone();1025 let rpc_pool = transaction_pool.clone();1026 let rpc_network = network.clone();1027 let rpc_frontier_backend = frontier_backend.clone();1028 let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {1029 let full_deps = unique_rpc::FullDeps {1030 backend: rpc_frontier_backend.clone(),1031 deny_unsafe,1032 client: rpc_client.clone(),1033 pool: rpc_pool.clone(),1034 graph: rpc_pool.pool().clone(),1035 // TODO: Unhardcode1036 enable_dev_signer: false,1037 filter_pool: filter_pool.clone(),1038 network: rpc_network.clone(),1039 select_chain: select_chain.clone(),1040 is_authority: collator,1041 // TODO: Unhardcode1042 max_past_logs: 10000,1043 block_data_cache: block_data_cache.clone(),1044 fee_history_cache: fee_history_cache.clone(),1045 // TODO: Unhardcode1046 fee_history_limit: 2048,1047 };10481049 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1050 full_deps,1051 subscription_executor,1052 )1053 .map_err(Into::into)1054 });10551056 sc_service::spawn_tasks(sc_service::SpawnTasksParams {1057 network,1058 client,1059 keystore: keystore_container.sync_keystore(),1060 task_manager: &mut task_manager,1061 transaction_pool,1062 rpc_builder,1063 backend,1064 system_rpc_tx,1065 config,1066 telemetry: None,1067 tx_handler_controller,1068 })?;10691070 network_starter.start_network();1071 Ok(task_manager)1072}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// std18use std::sync::Arc;19use std::sync::Mutex;20use std::collections::BTreeMap;21use std::time::Duration;22use std::pin::Pin;23use fc_rpc_core::types::FeeHistoryCache;24use futures::{25 Stream, StreamExt,26 stream::select,27 task::{Context, Poll},28};29use tokio::time::Interval;3031use unique_rpc::overrides_handle;3233use serde::{Serialize, Deserialize};3435// Cumulus Imports36use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};37use cumulus_client_consensus_common::{38 ParachainConsensus, ParachainBlockImport as TParachainBlockImport,39};40use cumulus_client_service::{41 prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,42};43use cumulus_client_cli::CollatorOptions;44use cumulus_client_network::BlockAnnounceValidator;45use cumulus_primitives_core::ParaId;46use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;47use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};48use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node;4950// Substrate Imports51use sp_api::BlockT;52use sc_executor::NativeElseWasmExecutor;53use sc_executor::NativeExecutionDispatch;54use sc_network::{NetworkService, NetworkBlock};55use sc_service::{BasePath, Configuration, PartialComponents, TaskManager};56use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};57use sp_keystore::SyncCryptoStorePtr;58use sp_runtime::traits::BlakeTwo256;59use substrate_prometheus_endpoint::Registry;60use sc_client_api::BlockchainEvents;61use sc_consensus::ImportQueue;6263use polkadot_service::CollatorPair;6465// Frontier Imports66use fc_rpc_core::types::FilterPool;67use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6869use up_common::types::opaque::{70 AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block, BlockNumber,71};7273// RMRK74use up_data_structs::{75 RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,76 RmrkPartType, RmrkTheme,77};7879/// Unique native executor instance.80#[cfg(feature = "unique-runtime")]81pub struct UniqueRuntimeExecutor;8283#[cfg(feature = "quartz-runtime")]84/// Quartz native executor instance.85pub struct QuartzRuntimeExecutor;8687/// Opal native executor instance.88pub struct OpalRuntimeExecutor;8990#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]91pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;9293#[cfg(all(94 not(feature = "unique-runtime"),95 feature = "quartz-runtime",96 feature = "runtime-benchmarks"97))]98pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;99100#[cfg(all(101 not(feature = "unique-runtime"),102 not(feature = "quartz-runtime"),103 feature = "runtime-benchmarks"104))]105pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;106107#[cfg(feature = "unique-runtime")]108impl NativeExecutionDispatch for UniqueRuntimeExecutor {109 /// Only enable the benchmarking host functions when we actually want to benchmark.110 #[cfg(feature = "runtime-benchmarks")]111 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;112 /// Otherwise we only use the default Substrate host functions.113 #[cfg(not(feature = "runtime-benchmarks"))]114 type ExtendHostFunctions = ();115116 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {117 unique_runtime::api::dispatch(method, data)118 }119120 fn native_version() -> sc_executor::NativeVersion {121 unique_runtime::native_version()122 }123}124125#[cfg(feature = "quartz-runtime")]126impl NativeExecutionDispatch for QuartzRuntimeExecutor {127 /// Only enable the benchmarking host functions when we actually want to benchmark.128 #[cfg(feature = "runtime-benchmarks")]129 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;130 /// Otherwise we only use the default Substrate host functions.131 #[cfg(not(feature = "runtime-benchmarks"))]132 type ExtendHostFunctions = ();133134 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {135 quartz_runtime::api::dispatch(method, data)136 }137138 fn native_version() -> sc_executor::NativeVersion {139 quartz_runtime::native_version()140 }141}142143impl NativeExecutionDispatch for OpalRuntimeExecutor {144 /// Only enable the benchmarking host functions when we actually want to benchmark.145 #[cfg(feature = "runtime-benchmarks")]146 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;147 /// Otherwise we only use the default Substrate host functions.148 #[cfg(not(feature = "runtime-benchmarks"))]149 type ExtendHostFunctions = ();150151 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {152 opal_runtime::api::dispatch(method, data)153 }154155 fn native_version() -> sc_executor::NativeVersion {156 opal_runtime::native_version()157 }158}159160pub struct AutosealInterval {161 interval: Interval,162}163164impl AutosealInterval {165 pub fn new(config: &Configuration, interval: Duration) -> Self {166 let _tokio_runtime = config.tokio_handle.enter();167 let interval = tokio::time::interval(interval);168169 Self { interval }170 }171}172173impl Stream for AutosealInterval {174 type Item = tokio::time::Instant;175176 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {177 self.interval.poll_tick(cx).map(Some)178 }179}180181pub fn open_frontier_backend<Block: BlockT, C: sp_blockchain::HeaderBackend<Block>>(182 client: Arc<C>,183 config: &Configuration,184) -> Result<Arc<fc_db::Backend<Block>>, String> {185 let config_dir = config186 .base_path187 .as_ref()188 .map(|base_path| base_path.config_dir(config.chain_spec.id()))189 .unwrap_or_else(|| {190 BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())191 });192 let database_dir = config_dir.join("frontier").join("db");193194 Ok(Arc::new(fc_db::Backend::<Block>::new(195 client,196 &fc_db::DatabaseSettings {197 source: fc_db::DatabaseSource::RocksDb {198 path: database_dir,199 cache_size: 0,200 },201 },202 )?))203}204205type FullClient<RuntimeApi, ExecutorDispatch> =206 sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;207type FullBackend = sc_service::TFullBackend<Block>;208type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;209type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =210 TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;211212/// Starts a `ServiceBuilder` for a full service.213///214/// Use this macro if you don't actually need the full service, but just the builder in order to215/// be able to perform chain operations.216#[allow(clippy::type_complexity)]217pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(218 config: &Configuration,219 build_import_queue: BIQ,220) -> Result<221 PartialComponents<222 FullClient<RuntimeApi, ExecutorDispatch>,223 FullBackend,224 FullSelectChain,225 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,226 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,227 (228 Option<Telemetry>,229 Option<FilterPool>,230 Arc<fc_db::Backend<Block>>,231 Option<TelemetryWorkerHandle>,232 FeeHistoryCache,233 ),234 >,235 sc_service::Error,236>237where238 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,239 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>240 + Send241 + Sync242 + 'static,243 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,244 ExecutorDispatch: NativeExecutionDispatch + 'static,245 BIQ: FnOnce(246 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,247 Arc<FullBackend>,248 &Configuration,249 Option<TelemetryHandle>,250 &TaskManager,251 ) -> Result<252 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,253 sc_service::Error,254 >,255{256 let _telemetry = config257 .telemetry_endpoints258 .clone()259 .filter(|x| !x.is_empty())260 .map(|endpoints| -> Result<_, sc_telemetry::Error> {261 let worker = TelemetryWorker::new(16)?;262 let telemetry = worker.handle().new_telemetry(endpoints);263 Ok((worker, telemetry))264 })265 .transpose()?;266267 let telemetry = config268 .telemetry_endpoints269 .clone()270 .filter(|x| !x.is_empty())271 .map(|endpoints| -> Result<_, sc_telemetry::Error> {272 let worker = TelemetryWorker::new(16)?;273 let telemetry = worker.handle().new_telemetry(endpoints);274 Ok((worker, telemetry))275 })276 .transpose()?;277278 let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(279 config.wasm_method,280 config.default_heap_pages,281 config.max_runtime_instances,282 config.runtime_cache_size,283 );284285 let (client, backend, keystore_container, task_manager) =286 sc_service::new_full_parts::<Block, RuntimeApi, _>(287 config,288 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),289 executor,290 )?;291 let client = Arc::new(client);292293 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());294295 let telemetry = telemetry.map(|(worker, telemetry)| {296 task_manager297 .spawn_handle()298 .spawn("telemetry", None, worker.run());299 telemetry300 });301302 let select_chain = sc_consensus::LongestChain::new(backend.clone());303304 let transaction_pool = sc_transaction_pool::BasicPool::new_full(305 config.transaction_pool.clone(),306 config.role.is_authority().into(),307 config.prometheus_registry(),308 task_manager.spawn_essential_handle(),309 client.clone(),310 );311312 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));313314 let frontier_backend = open_frontier_backend(client.clone(), config)?;315316 let import_queue = build_import_queue(317 client.clone(),318 backend.clone(),319 config,320 telemetry.as_ref().map(|telemetry| telemetry.handle()),321 &task_manager,322 )?;323 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));324325 let params = PartialComponents {326 backend,327 client,328 import_queue,329 keystore_container,330 task_manager,331 transaction_pool,332 select_chain,333 other: (334 telemetry,335 filter_pool,336 frontier_backend,337 telemetry_worker_handle,338 fee_history_cache,339 ),340 };341342 Ok(params)343}344345async fn build_relay_chain_interface(346 polkadot_config: Configuration,347 parachain_config: &Configuration,348 telemetry_worker_handle: Option<TelemetryWorkerHandle>,349 task_manager: &mut TaskManager,350 collator_options: CollatorOptions,351 hwbench: Option<sc_sysinfo::HwBench>,352) -> RelayChainResult<(353 Arc<(dyn RelayChainInterface + 'static)>,354 Option<CollatorPair>,355)> {356 if collator_options.relay_chain_rpc_urls.is_empty() {357 build_inprocess_relay_chain(358 polkadot_config,359 parachain_config,360 telemetry_worker_handle,361 task_manager,362 hwbench,363 )364 } else {365 build_minimal_relay_chain_node(366 polkadot_config,367 task_manager,368 collator_options.relay_chain_rpc_urls,369 )370 .await371 }372}373374/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.375///376/// This is the actual implementation that is abstract over the executor and the runtime api.377#[sc_tracing::logging::prefix_logs_with("Parachain")]378async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(379 parachain_config: Configuration,380 polkadot_config: Configuration,381 collator_options: CollatorOptions,382 id: ParaId,383 build_import_queue: BIQ,384 build_consensus: BIC,385 hwbench: Option<sc_sysinfo::HwBench>,386) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>387where388 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,389 Runtime: RuntimeInstance + Send + Sync + 'static,390 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,391 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,392 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>393 + Send394 + Sync395 + 'static,396 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>397 + fp_rpc::EthereumRuntimeRPCApi<Block>398 + fp_rpc::ConvertTransactionRuntimeApi<Block>399 + sp_session::SessionKeys<Block>400 + sp_block_builder::BlockBuilder<Block>401 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>402 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>403 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>404 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>405 + rmrk_rpc::RmrkApi<406 Block,407 AccountId,408 RmrkCollectionInfo<AccountId>,409 RmrkInstanceInfo<AccountId>,410 RmrkResourceInfo,411 RmrkPropertyInfo,412 RmrkBaseInfo<AccountId>,413 RmrkPartType,414 RmrkTheme,415 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>416 + sp_api::Metadata<Block>417 + sp_offchain::OffchainWorkerApi<Block>418 + cumulus_primitives_core::CollectCollationInfo<Block>,419 ExecutorDispatch: NativeExecutionDispatch + 'static,420 BIQ: FnOnce(421 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,422 Arc<FullBackend>,423 &Configuration,424 Option<TelemetryHandle>,425 &TaskManager,426 ) -> Result<427 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,428 sc_service::Error,429 >,430 BIC: FnOnce(431 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,432 Arc<FullBackend>,433 Option<&Registry>,434 Option<TelemetryHandle>,435 &TaskManager,436 Arc<dyn RelayChainInterface>,437 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,438 Arc<NetworkService<Block, Hash>>,439 SyncCryptoStorePtr,440 bool,441 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,442{443 let parachain_config = prepare_node_config(parachain_config);444445 let params =446 new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(¶chain_config, build_import_queue)?;447 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =448 params.other;449450 let client = params.client.clone();451 let backend = params.backend.clone();452 let mut task_manager = params.task_manager;453454 let (relay_chain_interface, collator_key) = build_relay_chain_interface(455 polkadot_config,456 ¶chain_config,457 telemetry_worker_handle,458 &mut task_manager,459 collator_options.clone(),460 hwbench.clone(),461 )462 .await463 .map_err(|e| match e {464 RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,465 s => s.to_string().into(),466 })?;467468 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);469470 let force_authoring = parachain_config.force_authoring;471 let validator = parachain_config.role.is_authority();472 let prometheus_registry = parachain_config.prometheus_registry().cloned();473 let transaction_pool = params.transaction_pool.clone();474 let import_queue_service = params.import_queue.service();475476 let (network, system_rpc_tx, tx_handler_controller, start_network) =477 sc_service::build_network(sc_service::BuildNetworkParams {478 config: ¶chain_config,479 client: client.clone(),480 transaction_pool: transaction_pool.clone(),481 spawn_handle: task_manager.spawn_handle(),482 import_queue: params.import_queue,483 block_announce_validator_builder: Some(Box::new(|_| {484 Box::new(block_announce_validator)485 })),486 warp_sync: None,487 })?;488489 let rpc_client = client.clone();490 let rpc_pool = transaction_pool.clone();491 let select_chain = params.select_chain.clone();492 let rpc_network = network.clone();493494 let rpc_frontier_backend = frontier_backend.clone();495496 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(497 task_manager.spawn_handle(),498 overrides_handle::<_, _, Runtime>(client.clone()),499 50,500 50,501 prometheus_registry.clone(),502 ));503504 task_manager.spawn_essential_handle().spawn(505 "frontier-mapping-sync-worker",506 None,507 MappingSyncWorker::new(508 client.import_notification_stream(),509 Duration::new(6, 0),510 client.clone(),511 backend.clone(),512 frontier_backend.clone(),513 3,514 0,515 SyncStrategy::Normal,516 )517 .for_each(|()| futures::future::ready(())),518 );519520 let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {521 let full_deps = unique_rpc::FullDeps {522 backend: rpc_frontier_backend.clone(),523 deny_unsafe,524 client: rpc_client.clone(),525 pool: rpc_pool.clone(),526 graph: rpc_pool.pool().clone(),527 // TODO: Unhardcode528 enable_dev_signer: false,529 filter_pool: filter_pool.clone(),530 network: rpc_network.clone(),531 select_chain: select_chain.clone(),532 is_authority: validator,533 // TODO: Unhardcode534 max_past_logs: 10000,535 block_data_cache: block_data_cache.clone(),536 fee_history_cache: fee_history_cache.clone(),537 // TODO: Unhardcode538 fee_history_limit: 2048,539 };540541 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(542 full_deps,543 subscription_task_executor,544 )545 .map_err(Into::into)546 });547548 sc_service::spawn_tasks(sc_service::SpawnTasksParams {549 rpc_builder,550 client: client.clone(),551 transaction_pool: transaction_pool.clone(),552 task_manager: &mut task_manager,553 config: parachain_config,554 keystore: params.keystore_container.sync_keystore(),555 backend: backend.clone(),556 network: network.clone(),557 system_rpc_tx,558 telemetry: telemetry.as_mut(),559 tx_handler_controller,560 })?;561562 if let Some(hwbench) = hwbench {563 sc_sysinfo::print_hwbench(&hwbench);564565 if let Some(ref mut telemetry) = telemetry {566 let telemetry_handle = telemetry.handle();567 task_manager.spawn_handle().spawn(568 "telemetry_hwbench",569 None,570 sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),571 );572 }573 }574575 let announce_block = {576 let network = network.clone();577 Arc::new(Box::new(move |hash, data| {578 network.announce_block(hash, data)579 }))580 };581582 let relay_chain_slot_duration = Duration::from_secs(6);583584 if validator {585 let parachain_consensus = build_consensus(586 client.clone(),587 backend.clone(),588 prometheus_registry.as_ref(),589 telemetry.as_ref().map(|t| t.handle()),590 &task_manager,591 relay_chain_interface.clone(),592 transaction_pool,593 network,594 params.keystore_container.sync_keystore(),595 force_authoring,596 )?;597598 let spawner = task_manager.spawn_handle();599600 let params = StartCollatorParams {601 para_id: id,602 block_status: client.clone(),603 announce_block,604 client: client.clone(),605 task_manager: &mut task_manager,606 spawner,607 parachain_consensus,608 import_queue: import_queue_service,609 collator_key: collator_key.expect("Command line arguments do not allow this. qed"),610 relay_chain_interface,611 relay_chain_slot_duration,612 };613614 start_collator(params).await?;615 } else {616 let params = StartFullNodeParams {617 client: client.clone(),618 announce_block,619 task_manager: &mut task_manager,620 para_id: id,621 import_queue: import_queue_service,622 relay_chain_interface,623 relay_chain_slot_duration,624 };625626 start_full_node(params)?;627 }628629 start_network.start_network();630631 Ok((task_manager, client))632}633634/// Build the import queue for the the parachain runtime.635pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(636 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,637 backend: Arc<FullBackend>,638 config: &Configuration,639 telemetry: Option<TelemetryHandle>,640 task_manager: &TaskManager,641) -> Result<642 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,643 sc_service::Error,644>645where646 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>647 + Send648 + Sync649 + 'static,650 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>651 + sp_block_builder::BlockBuilder<Block>652 + sp_consensus_aura::AuraApi<Block, AuraId>653 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,654 ExecutorDispatch: NativeExecutionDispatch + 'static,655{656 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;657658 let block_import = ParachainBlockImport::new(client.clone(), backend.clone());659660 cumulus_client_consensus_aura::import_queue::<661 sp_consensus_aura::sr25519::AuthorityPair,662 _,663 _,664 _,665 _,666 _,667 >(cumulus_client_consensus_aura::ImportQueueParams {668 block_import,669 client: client.clone(),670 create_inherent_data_providers: move |_, _| async move {671 let time = sp_timestamp::InherentDataProvider::from_system_time();672673 let slot =674 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(675 *time,676 slot_duration,677 );678679 Ok((slot, time))680 },681 registry: config.prometheus_registry(),682 spawner: &task_manager.spawn_essential_handle(),683 telemetry,684 })685 .map_err(Into::into)686}687688/// Start a normal parachain node.689pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(690 parachain_config: Configuration,691 polkadot_config: Configuration,692 collator_options: CollatorOptions,693 id: ParaId,694 hwbench: Option<sc_sysinfo::HwBench>,695) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>696where697 Runtime: RuntimeInstance + Send + Sync + 'static,698 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,699 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,700 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>701 + Send702 + Sync703 + 'static,704 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>705 + fp_rpc::EthereumRuntimeRPCApi<Block>706 + fp_rpc::ConvertTransactionRuntimeApi<Block>707 + sp_session::SessionKeys<Block>708 + sp_block_builder::BlockBuilder<Block>709 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>710 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>711 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>712 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>713 + rmrk_rpc::RmrkApi<714 Block,715 AccountId,716 RmrkCollectionInfo<AccountId>,717 RmrkInstanceInfo<AccountId>,718 RmrkResourceInfo,719 RmrkPropertyInfo,720 RmrkBaseInfo<AccountId>,721 RmrkPartType,722 RmrkTheme,723 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>724 + sp_api::Metadata<Block>725 + sp_offchain::OffchainWorkerApi<Block>726 + cumulus_primitives_core::CollectCollationInfo<Block>727 + sp_consensus_aura::AuraApi<Block, AuraId>,728 ExecutorDispatch: NativeExecutionDispatch + 'static,729{730 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(731 parachain_config,732 polkadot_config,733 collator_options,734 id,735 parachain_build_import_queue,736 |client,737 backend,738 prometheus_registry,739 telemetry,740 task_manager,741 relay_chain_interface,742 transaction_pool,743 sync_oracle,744 keystore,745 force_authoring| {746 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;747748 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(749 task_manager.spawn_handle(),750 client.clone(),751 transaction_pool,752 prometheus_registry,753 telemetry.clone(),754 );755756 let block_import = ParachainBlockImport::new(client.clone(), backend.clone());757758 Ok(AuraConsensus::build::<759 sp_consensus_aura::sr25519::AuthorityPair,760 _,761 _,762 _,763 _,764 _,765 _,766 >(BuildAuraConsensusParams {767 proposer_factory,768 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {769 let relay_chain_interface = relay_chain_interface.clone();770 async move {771 let parachain_inherent =772 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(773 relay_parent,774 &relay_chain_interface,775 &validation_data,776 id,777 ).await;778779 let time = sp_timestamp::InherentDataProvider::from_system_time();780781 let slot =782 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(783 *time,784 slot_duration,785 );786787 let parachain_inherent = parachain_inherent.ok_or_else(|| {788 Box::<dyn std::error::Error + Send + Sync>::from(789 "Failed to create parachain inherent",790 )791 })?;792 Ok((slot, time, parachain_inherent))793 }794 },795 block_import,796 para_client: client,797 backoff_authoring_blocks: Option::<()>::None,798 sync_oracle,799 keystore,800 force_authoring,801 slot_duration,802 // We got around 500ms for proposing803 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),804 telemetry,805 max_block_proposal_slot_portion: None,806 }))807 },808 hwbench,809 )810 .await811}812813fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(814 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,815 _: Arc<FullBackend>,816 config: &Configuration,817 _: Option<TelemetryHandle>,818 task_manager: &TaskManager,819) -> Result<820 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,821 sc_service::Error,822>823where824 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>825 + Send826 + Sync827 + 'static,828 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>829 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,830 ExecutorDispatch: NativeExecutionDispatch + 'static,831{832 Ok(sc_consensus_manual_seal::import_queue(833 Box::new(client.clone()),834 &task_manager.spawn_essential_handle(),835 config.prometheus_registry(),836 ))837}838839/// Builds a new development service. This service uses instant seal, and mocks840/// the parachain inherent841pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(842 config: Configuration,843 autoseal_interval: Duration,844) -> sc_service::error::Result<TaskManager>845where846 Runtime: RuntimeInstance + Send + Sync + 'static,847 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,848 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,849 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>850 + Send851 + Sync852 + 'static,853 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>854 + fp_rpc::EthereumRuntimeRPCApi<Block>855 + fp_rpc::ConvertTransactionRuntimeApi<Block>856 + sp_session::SessionKeys<Block>857 + sp_block_builder::BlockBuilder<Block>858 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>859 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>860 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>861 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>862 + rmrk_rpc::RmrkApi<863 Block,864 AccountId,865 RmrkCollectionInfo<AccountId>,866 RmrkInstanceInfo<AccountId>,867 RmrkResourceInfo,868 RmrkPropertyInfo,869 RmrkBaseInfo<AccountId>,870 RmrkPartType,871 RmrkTheme,872 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>873 + sp_api::Metadata<Block>874 + sp_offchain::OffchainWorkerApi<Block>875 + cumulus_primitives_core::CollectCollationInfo<Block>876 + sp_consensus_aura::AuraApi<Block, AuraId>,877 ExecutorDispatch: NativeExecutionDispatch + 'static,878{879 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};880 use fc_consensus::FrontierBlockImport;881 use sc_client_api::HeaderBackend;882883 let sc_service::PartialComponents {884 client,885 backend,886 mut task_manager,887 import_queue,888 keystore_container,889 select_chain: maybe_select_chain,890 transaction_pool,891 other:892 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),893 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(894 &config,895 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,896 )?;897 let prometheus_registry = config.prometheus_registry().cloned();898899 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(900 task_manager.spawn_handle(),901 overrides_handle::<_, _, Runtime>(client.clone()),902 50,903 50,904 prometheus_registry.clone(),905 ));906907 let (network, system_rpc_tx, tx_handler_controller, network_starter) =908 sc_service::build_network(sc_service::BuildNetworkParams {909 config: &config,910 client: client.clone(),911 transaction_pool: transaction_pool.clone(),912 spawn_handle: task_manager.spawn_handle(),913 import_queue,914 block_announce_validator_builder: None,915 warp_sync: None,916 })?;917918 if config.offchain_worker.enabled {919 sc_service::build_offchain_workers(920 &config,921 task_manager.spawn_handle(),922 client.clone(),923 network.clone(),924 );925 }926927 let collator = config.role.is_authority();928929 let select_chain = maybe_select_chain.clone();930931 if collator {932 let block_import =933 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());934935 let env = sc_basic_authorship::ProposerFactory::new(936 task_manager.spawn_handle(),937 client.clone(),938 transaction_pool.clone(),939 prometheus_registry.as_ref(),940 telemetry.as_ref().map(|x| x.handle()),941 );942943 let transactions_commands_stream: Box<944 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,945 > = Box::new(946 transaction_pool947 .pool()948 .validated_pool()949 .import_notification_stream()950 .map(|_| EngineCommand::SealNewBlock {951 create_empty: true,952 finalize: false,953 parent_hash: None,954 sender: None,955 }),956 );957958 let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));959 let idle_commands_stream: Box<960 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,961 > = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {962 create_empty: true,963 finalize: false,964 parent_hash: None,965 sender: None,966 }));967968 let commands_stream = select(transactions_commands_stream, idle_commands_stream);969970 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;971 let client_set_aside_for_cidp = client.clone();972973 task_manager.spawn_essential_handle().spawn_blocking(974 "authorship_task",975 Some("block-authoring"),976 run_manual_seal(ManualSealParams {977 block_import,978 env,979 client: client.clone(),980 pool: transaction_pool.clone(),981 commands_stream,982 select_chain: select_chain.clone(),983 consensus_data_provider: None,984 create_inherent_data_providers: move |block: Hash, ()| {985 let current_para_block = client_set_aside_for_cidp986 .number(block)987 .expect("Header lookup should succeed")988 .expect("Header passed in as parent should be present in backend.");989990 let client_for_xcm = client_set_aside_for_cidp.clone();991 async move {992 let time = sp_timestamp::InherentDataProvider::from_system_time();993994 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {995 current_para_block,996 relay_offset: 1000,997 relay_blocks_per_para_block: 2,998 para_blocks_per_relay_epoch: 0,999 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(1000 &*client_for_xcm,1001 block,1002 Default::default(),1003 Default::default(),1004 ),1005 relay_randomness_config: (),1006 raw_downward_messages: vec![],1007 raw_horizontal_messages: vec![],1008 };10091010 let slot =1011 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(1012 *time,1013 slot_duration,1014 );10151016 Ok((time, slot, mocked_parachain))1017 }1018 },1019 }),1020 );1021 }10221023 task_manager.spawn_essential_handle().spawn(1024 "frontier-mapping-sync-worker",1025 Some("block-authoring"),1026 MappingSyncWorker::new(1027 client.import_notification_stream(),1028 Duration::new(6, 0),1029 client.clone(),1030 backend.clone(),1031 frontier_backend.clone(),1032 3,1033 0,1034 SyncStrategy::Normal,1035 )1036 .for_each(|()| futures::future::ready(())),1037 );10381039 let rpc_client = client.clone();1040 let rpc_pool = transaction_pool.clone();1041 let rpc_network = network.clone();1042 let rpc_frontier_backend = frontier_backend.clone();1043 let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {1044 let full_deps = unique_rpc::FullDeps {1045 backend: rpc_frontier_backend.clone(),1046 deny_unsafe,1047 client: rpc_client.clone(),1048 pool: rpc_pool.clone(),1049 graph: rpc_pool.pool().clone(),1050 // TODO: Unhardcode1051 enable_dev_signer: false,1052 filter_pool: filter_pool.clone(),1053 network: rpc_network.clone(),1054 select_chain: select_chain.clone(),1055 is_authority: collator,1056 // TODO: Unhardcode1057 max_past_logs: 10000,1058 block_data_cache: block_data_cache.clone(),1059 fee_history_cache: fee_history_cache.clone(),1060 // TODO: Unhardcode1061 fee_history_limit: 2048,1062 };10631064 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1065 full_deps,1066 subscription_executor,1067 )1068 .map_err(Into::into)1069 });10701071 sc_service::spawn_tasks(sc_service::SpawnTasksParams {1072 network,1073 client,1074 keystore: keystore_container.sync_keystore(),1075 task_manager: &mut task_manager,1076 transaction_pool,1077 rpc_builder,1078 backend,1079 system_rpc_tx,1080 config,1081 telemetry: None,1082 tx_handler_controller,1083 })?;10841085 network_starter.start_network();1086 Ok(task_manager)1087}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.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -1103,7 +1103,7 @@
async getPropertiesConsumedSpace(collectionId: number): Promise<number> {
const api = this.helper.getApi();
const props = (await api.query.common.collectionProperties(collectionId)).toJSON();
-
+
return (props! as any).consumedSpace;
}
@@ -2423,7 +2423,7 @@
/**
* Get schedule for recepient of vested transfer
* @param address Substrate address of recipient
- * @returns
+ * @returns
*/
async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {
const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();
@@ -2506,16 +2506,16 @@
: typeof key === 'bigint'
? hexToU8a(key.toString(16))
: key;
-
+
if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {
throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);
}
-
+
const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];
if (!allowedDecodedLengths.includes(u8a.length)) {
throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);
}
-
+
const u8aPrefix = ss58Format < 64
? new Uint8Array([ss58Format])
: new Uint8Array([
@@ -2524,7 +2524,7 @@
]);
const input = u8aConcat(u8aPrefix, u8a);
-
+
return base58Encode(u8aConcat(
input,
blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),
@@ -2556,7 +2556,7 @@
if (ethCrossAccount.sub === '0') {
return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};
}
-
+
const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));
return {Substrate: ss58};
}
@@ -3074,14 +3074,14 @@
executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {
const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);
-
+
const mandatorySchedArgs = [
this.blocksNum,
this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,
this.options.priority ?? null,
scheduledTx,
];
-
+
let schedArgs;
let scheduleFn;
@@ -3301,7 +3301,7 @@
async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {
const api = this.helper.getApi();
const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();
-
+
return (props! as any).consumedSpace;
}
@@ -3419,7 +3419,7 @@
async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {
const api = this.helper.getApi();
const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();
-
+
return (props! as any).consumedSpace;
}
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==