difftreelog
Merge remote-tracking branch 'origin/develop' into feature/multi-assets-redone
in: master
21 files changed
.docker/Dockerfile-chain-devdiffbeforeafterboth--- a/.docker/Dockerfile-chain-dev
+++ b/.docker/Dockerfile-chain-dev
@@ -1,17 +1,19 @@
FROM ubuntu:20.04
+ARG RUST_TOOLCHAIN=
+ARG FEATURE=
+
ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Etc/UTC
-
-RUN apt-get update && apt-get install -y git curl libssl-dev llvm pkg-config libclang-dev clang git make cmake
-
+ENV FEATURE=$FEATURE
ENV CARGO_HOME="/cargo-home"
ENV PATH="/cargo-home/bin:$PATH"
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
+RUN echo "$FEATURE\n" && echo "$RUST_TOOLCHAIN\n"
-ARG RUST_TOOLCHAIN=
-ARG FEATURE=
+RUN apt-get update && apt-get install -y git curl libssl-dev llvm pkg-config libclang-dev clang git make cmake
+
+RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
RUN rustup toolchain uninstall $(rustup toolchain list) && \
rustup toolchain install $RUST_TOOLCHAIN && \
@@ -24,5 +26,6 @@
WORKDIR /dev_chain
RUN cargo build --release
+RUN echo "$FEATURE"
CMD cargo run --release --features=$FEATURE -- --dev -linfo --unsafe-ws-external --rpc-cors=all --unsafe-rpc-external
.docker/docker-compose.tmp-dev.j2diffbeforeafterboth--- a/.docker/docker-compose.tmp-dev.j2
+++ b/.docker/docker-compose.tmp-dev.j2
@@ -18,4 +18,4 @@
options:
max-size: "1m"
max-file: "3"
- command: cargo run --release --features=$FEATURE -- --dev -linfo --unsafe-ws-external --rpc-cors=all --unsafe-rpc-external
+ command: cargo run --release --features={{ FEATURE }} -- --dev -linfo --unsafe-ws-external --rpc-cors=all --unsafe-rpc-external
.github/workflows/ci-master.ymldiffbeforeafterboth--- a/.github/workflows/ci-master.yml
+++ b/.github/workflows/ci-master.yml
@@ -18,16 +18,13 @@
uses: ./.github/workflows/node-only-update_v2.yml
forkless:
- if: ${{ contains( github.event.pull_request.labels.*.name, 'forkless') }}
uses: ./.github/workflows/forkless.yml
canary:
- if: ${{ contains( github.event.pull_request.labels.*.name, 'canary') }}
uses: ./.github/workflows/canary.yml
secrets: inherit # pass all secrets
xcm:
- if: ${{ contains( github.event.pull_request.labels.*.name, 'xcm') }}
uses: ./.github/workflows/xcm.yml
secrets: inherit # pass all secrets
.github/workflows/dev-build-tests_v2.ymldiffbeforeafterboth--- a/.github/workflows/dev-build-tests_v2.yml
+++ b/.github/workflows/dev-build-tests_v2.yml
@@ -95,3 +95,10 @@
- name: Stop running containers
if: always() # run this step always
run: docker-compose -f ".docker/docker-compose-dev.yaml" -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
\ No newline at end of file
.github/workflows/market-test.ymldiffbeforeafterboth--- a/.github/workflows/market-test.yml
+++ /dev/null
@@ -1,227 +0,0 @@
-name: market api tests
-
-# Controls when the action will run.
-on:
- # Triggers the workflow on push or pull request events but only for the master branch
- pull_request:
- branches:
- - master
- types:
- - opened
- - reopened
- - synchronize #commit(s) pushed to the pull request
- - ready_for_review
-
- # Allows you to run this workflow manually from the Actions tab
- workflow_dispatch:
-
-
-concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
- cancel-in-progress: true
-
-# A workflow run is made up of one or more jobs that can run sequentially or in parallel
-jobs:
-
- market_test:
- # The type of runner that the job will run on
- runs-on: [self-hosted-ci,large]
- timeout-minutes: 1380
-
- strategy:
- matrix:
- include:
- - network: "opal"
- features: "opal-runtime"
- - network: "quartz"
- features: "quartz-runtime"
- - network: "unique"
- features: "unique-runtime"
-
- name: draft job
-
- 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.
-
-
- steps:
-# - name: Skip if pull request is in Draft
- # `if: github.event.pull_request.draft == true` should be kept here, at
- # the step level, rather than at the job level. The latter is not
- # recommended because when the PR is moved from "Draft" to "Ready to
- # review" the workflow will immediately be passing (since it was skipped),
- # even though it hasn't actually ran, since it takes a few seconds for
- # the workflow to start. This is also disclosed in:
- # https://github.community/t/dont-run-actions-on-draft-pull-requests/16817/17
- # That scenario would open an opportunity for the check to be bypassed:
- # 1. Get your PR approved
- # 2. Move it to Draft
- # 3. Push whatever commits you want
- # 4. Move it to "Ready for review"; now the workflow is passing (it was
- # skipped) and "Check reviews" is also passing (it won't be updated
- # until the workflow is finished)
-# if: github.event.pull_request.draft == true
-# run: exit 1
-
- - name: Clean Workspace
- uses: AutoModality/action-clean@v1.1.0
-
- # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- - name: Checkout master repo
- uses: actions/checkout@master
- with:
- ref: ${{ github.head_ref }} #Checking out head commit
-
- - name: Checkout Market e2e tests
- uses: actions/checkout@v3
- with:
- repository: 'UniqueNetwork/market-e2e-tests'
- ssh-key: '${{ secrets.GH_PAT }}'
- path: 'qa-tests'
- ref: 'QA-65_maxandreev'
-
- - name: Read .env file
- uses: xom9ikk/dotenv@v1.0.2
-
- - name: Copy qa-tests/.env.example to qa-tests/.env
- working-directory: qa-tests
- run: cp .env.docker .env
-
- - name: Show content of qa-test/.env
- working-directory: qa-tests
- run: cat .env
-
- - name: Read qa -test .env file
- uses: xom9ikk/dotenv@v1.0.2
- with:
- path: qa-tests/
-
- - name: Generate ENV related extend file for docker-compose
- uses: cuchi/jinja2-action@v1.2.0
- with:
- template: qa-tests/.docker/docker-compose.tmp-market.j2
- output_file: qa-tests/.docker/docker-compose.${{ matrix.network }}.yml
- variables: |
- REPO_URL=${{ github.server_url }}/${{ github.repository }}.git
- RUST_TOOLCHAIN=${{ env.RUST_TOOLCHAIN }}
- POLKADOT_BUILD_BRANCH=${{ env.POLKADOT_BUILD_BRANCH }}
- FEATURE=${{ matrix.features }}
- BRANCH=${{ github.head_ref }}
-
-
- - name: Show build configuration
- working-directory: qa-tests
- run: cat .docker/docker-compose.${{ matrix.network }}.yml
-
- - name: Start node-parachain
- working-directory: qa-tests
- run: docker-compose -f ".docker/docker-compose.market.yml" -f ".docker/docker-compose.${{ matrix.network }}.yml" up -d --build --remove-orphans --force-recreate node-parachain
-
- - name: Start nonce-app
- working-directory: qa-tests
- run: docker-compose -f ".docker/docker-compose.market.yml" up -d --build --remove-orphans --force-recreate nonce-app
-
- - uses: actions/setup-node@v3
- with:
- node-version: 16
-
- - name: Setup TypeScript
- working-directory: qa-tests
- run: |
- npm install
- npm install -g ts-node
-
- - name: Copy qa-tests/.env.example to qa-tests/.env
- working-directory: qa-tests
- run: |
- rm -rf .env
- cp .env.example .env
-
-
- - name: Show content of qa-test/.env
- working-directory: qa-tests
- run: cat .env
-
-
- - name: Read qa -test .env file
- uses: xom9ikk/dotenv@v1.0.2
- with:
- path: qa-tests/
-
- - name: Generate accounts
- working-directory: qa-tests
- run: ts-node ./src/scripts/create-market-accounts.ts
-
- - name: Deploy contracts
- run: |
- cd qa-tests
- ts-node ./src/scripts/deploy-contract.ts
-
- - name: Import test data
- working-directory: qa-tests
- run: ts-node ./src/scripts/create-test-collections.ts
-
- - name: Show content of qa-test .env
- working-directory: qa-tests
- run: cat .env
-
- - name: Copy qa-tests/.env.example to qa-tests/.env
- working-directory: qa-tests
- run: |
- rm -rf .env.docker
- cp .env .env.docker
- sed -i '/UNIQUE_WS_ENDPOINT/c UNIQUE_WS_ENDPOINT=ws://node-parachain:9944' .env.docker
-
- - name: Read qa -test .env file
- uses: xom9ikk/dotenv@v1.0.2
- with:
- path: qa-tests/
-
- - name: local-market:start
- run: docker-compose -f "qa-tests/.docker/docker-compose.market.yml" -f "qa-tests/.docker/docker-compose.${{ matrix.network }}.yml" up -d --build
-
- - name: Wait for market readyness
- working-directory: qa-tests
- run: src/scripts/wait-market-ready.sh
- shell: bash
-
- - name: Install dependecies
- working-directory: qa-tests
- run: |
- npm ci
- npm install -D @playwright/test
- npx playwright install-deps
- npx playwright install
-
- - name:
- working-directory: qa-tests
- run: |
- npx playwright test --workers=8 --quiet .*.api.test.ts --reporter=github --config playwright.config.ts
-
- - name: Show env variables
- if: success() || failure()
- run: printenv
-
- - name: look up for report
- if: success() || failure()
- run: |
- ls -la
- ls -la qa-tests/
-
-
- - name: Stop running containers
- if: always() # run this step always
- run: docker-compose -f "qa-tests/.docker/docker-compose.market.yml" -f "qa-tests/.docker/docker-compose.${{ matrix.network }}.yml" down --volumes
-
- - name: Remove builder cache
- if: always() # run this step always
- run: |
- docker builder prune -f
- docker system prune -f
-
- - name: Clean Workspace
- if: always()
- uses: AutoModality/action-clean@v1.1.0
-
-
-
-
.github/workflows/market-test_v2.ymldiffbeforeafterboth--- a/.github/workflows/market-test_v2.yml
+++ b/.github/workflows/market-test_v2.yml
@@ -45,7 +45,7 @@
repository: 'UniqueNetwork/market-e2e-tests'
ssh-key: ${{ secrets.GH_PAT }}
path: 'qa-tests'
- ref: 'ci_test_v2'
+ ref: 'master'
- name: Read .env file
uses: xom9ikk/dotenv@v1.0.2
.github/workflows/node-only-update_v2.ymldiffbeforeafterboth--- a/.github/workflows/node-only-update_v2.yml
+++ b/.github/workflows/node-only-update_v2.yml
@@ -10,7 +10,7 @@
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
- execution-marix:
+ nodes-execution-matrix:
name: execution matrix
@@ -42,8 +42,8 @@
- forkless-update-nodata:
- needs: execution-marix
+ nodes-only-update:
+ needs: nodes-execution-matrix
# The type of runner that the job will run on
runs-on: [self-hosted-ci,large]
@@ -57,7 +57,7 @@
strategy:
matrix:
- include: ${{fromJson(needs.prepare-execution-marix.outputs.matrix)}}
+ include: ${{fromJson(needs.nodes-execution-matrix.outputs.matrix)}}
steps:
@@ -156,12 +156,18 @@
exit 0
shell: bash
+ - name: Checkout at '${{ matrix.mainnet_branch }}' branch
+ uses: actions/checkout@master
+ with:
+ ref: ${{ matrix.mainnet_branch }} #Checking out head commit
+ path: ${{ matrix.mainnet_branch }}
+
+
- name: Run tests before Node Parachain upgrade
- working-directory: tests
+ working-directory: ${{ matrix.mainnet_branch }}/tests
run: |
yarn install
yarn add mochawesome
- node scripts/readyness.js
echo "Ready to start tests"
yarn polkadot-types
NOW=$(date +%s) && yarn test --reporter mochawesome --reporter-options reportFilename=test-${NOW}
@@ -174,7 +180,7 @@
if: success() || failure() # run this step even if previous step failed
with:
name: Tests before node upgrade ${{ matrix.network }} # Name of the check run which will be created
- path: tests/mochawesome-report/test-*.json # Path to test results
+ path: ${{ matrix.mainnet_branch }}/tests/mochawesome-report/test-*.json # Path to test results
reporter: mochawesome-json
fail-on-error: 'false'
@@ -263,8 +269,9 @@
- name: Remove builder cache
if: always() # run this step always
run: |
- docker builder prune -f
+ docker builder prune -f -a
docker system prune -f
+ docker image prune -f -a
- name: Clean Workspace
if: always()
pallets/app-promotion/Cargo.tomldiffbeforeafterboth--- a/pallets/app-promotion/Cargo.toml
+++ b/pallets/app-promotion/Cargo.toml
@@ -68,4 +68,6 @@
pallet-evm-contract-helpers ={ default-features = false, path = "../evm-contract-helpers" }
pallet-evm-migration ={ default-features = false, path = "../evm-migration" }
+# [dev-dependencies]
+
################################################################################
pallets/app-promotion/src/lib.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//! # App Promotion pallet18//!19//! The pallet implements the mechanics of staking and sponsoring collections/contracts.20//!21//! - [`Config`]22//! - [`Pallet`]23//! - [`Error`]24//! - [`Event`]25//!26//! ## Overview27//! The App Promotion pallet allows fund holders to stake at a certain daily rate of return.28//! The mechanics implemented in the pallet allow it to act as a sponsor for collections / contracts,29//! the list of which is set by the pallet administrator.30//! 31//!32//! ## Interface33//! The pallet provides interfaces for funds, collection/contract operations (see [types] module).3435//!36//! ### Dispatchable Functions37//! - [`set_admin_address`][`Pallet::set_admin_address`] - sets an address as the the admin.38//! - [`stake`][`Pallet::stake`] - stakes the amount of native tokens.39//! - [`unstake`][`Pallet::unstake`] - unstakes all stakes.40//! - [`sponsor_collection`][`Pallet::sponsor_collection`] - sets the pallet to be the sponsor for the collection.41//! - [`stop_sponsoring_collection`][`Pallet::stop_sponsoring_collection`] - removes the pallet as the sponsor for the collection.42//! - [`sponsor_contract`][`Pallet::sponsor_contract`] - sets the pallet to be the sponsor for the contract.43//! - [`stop_sponsoring_contract`][`Pallet::stop_sponsoring_contract`] - removes the pallet as the sponsor for the contract.44//! - [`payout_stakers`][`Pallet::payout_stakers`] - recalculates interest for the specified number of stakers.45//!4647// #![recursion_limit = "1024"]48#![cfg_attr(not(feature = "std"), no_std)]4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;5253pub mod types;54pub mod weights;5556use sp_std::{57 vec::{Vec},58 vec,59 iter::Sum,60 borrow::ToOwned,61 cell::RefCell,62};63use sp_core::H160;64use codec::EncodeLike;65use pallet_balances::BalanceLock;66pub use types::*;6768use up_data_structs::CollectionId;6970use frame_support::{71 dispatch::{DispatchResult},72 traits::{73 Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,74 },75 ensure,76};7778use weights::WeightInfo;7980pub use pallet::*;81use pallet_evm::account::CrossAccountId;82use sp_runtime::{83 Perbill,84 traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},85 ArithmeticError,86};8788pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";8990const PENDING_LIMIT_PER_BLOCK: u32 = 3;9192type BalanceOf<T> =93 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;9495#[frame_support::pallet]96pub mod pallet {97 use super::*;98 use frame_support::{99 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,100 traits::ReservableCurrency,101 };102 use frame_system::pallet_prelude::*;103104 #[pallet::config]105 pub trait Config: frame_system::Config + pallet_evm::account::Config {106 /// Type to interact with the native token107 type Currency: ExtendedLockableCurrency<Self::AccountId>108 + ReservableCurrency<Self::AccountId>;109110 /// Type for interacting with collections111 type CollectionHandler: CollectionHandler<112 AccountId = Self::AccountId,113 CollectionId = CollectionId,114 >;115116 /// Type for interacting with conrtacts117 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;118119 /// `AccountId` for treasury120 type TreasuryAccountId: Get<Self::AccountId>;121122 /// The app's pallet id, used for deriving its sovereign account address.123 #[pallet::constant]124 type PalletId: Get<PalletId>;125126 /// In relay blocks.127 #[pallet::constant]128 type RecalculationInterval: Get<Self::BlockNumber>;129130 /// In parachain blocks.131 #[pallet::constant]132 type PendingInterval: Get<Self::BlockNumber>;133134 /// Rate of return for interval in blocks defined in `RecalculationInterval`.135 #[pallet::constant]136 type IntervalIncome: Get<Perbill>;137138 /// Decimals for the `Currency`.139 #[pallet::constant]140 type Nominal: Get<BalanceOf<Self>>;141142 /// Weight information for extrinsics in this pallet.143 type WeightInfo: WeightInfo;144145 // The relay block number provider146 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;147148 /// Events compatible with [`frame_system::Config::Event`].149 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;150 }151152 #[pallet::pallet]153 #[pallet::generate_store(pub(super) trait Store)]154 pub struct Pallet<T>(_);155156 #[pallet::event]157 #[pallet::generate_deposit(fn deposit_event)]158 pub enum Event<T: Config> {159 /// Staking recalculation was performed160 ///161 /// # Arguments162 /// * AccountId: account of the staker.163 /// * Balance : recalculation base164 /// * Balance : total income165 StakingRecalculation(166 /// An recalculated staker167 T::AccountId,168 /// Base on which interest is calculated169 BalanceOf<T>,170 /// Amount of accrued interest171 BalanceOf<T>,172 ),173174 /// Staking was performed175 ///176 /// # Arguments177 /// * AccountId: account of the staker178 /// * Balance : staking amount179 Stake(T::AccountId, BalanceOf<T>),180181 /// Unstaking was performed182 ///183 /// # Arguments184 /// * AccountId: account of the staker185 /// * Balance : unstaking amount186 Unstake(T::AccountId, BalanceOf<T>),187188 /// The admin was set189 ///190 /// # Arguments191 /// * AccountId: account address of the admin192 SetAdmin(T::AccountId),193 }194195 #[pallet::error]196 pub enum Error<T> {197 /// Error due to action requiring admin to be set.198 AdminNotSet,199 /// No permission to perform an action.200 NoPermission,201 /// Insufficient funds to perform an action.202 NotSufficientFunds,203 /// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.204 PendingForBlockOverflow,205 /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.206 SponsorNotSet,207 /// Errors caused by incorrect actions with a locked balance.208 IncorrectLockedBalanceOperation,209 }210211 /// Stores the total staked amount.212 #[pallet::storage]213 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;214215 /// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.216 #[pallet::storage]217 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;218219 /// Stores the amount of tokens staked by account in the blocknumber.220 ///221 /// * **Key1** - Staker account.222 /// * **Key2** - Relay block number when the stake was made.223 /// * **(Balance, BlockNumber)** - Balance of the stake.224 /// The number of the relay block in which we must perform the interest recalculation225 #[pallet::storage]226 pub type Staked<T: Config> = StorageNMap<227 Key = (228 Key<Blake2_128Concat, T::AccountId>,229 Key<Twox64Concat, T::BlockNumber>,230 ),231 Value = (BalanceOf<T>, T::BlockNumber),232 QueryKind = ValueQuery,233 >;234235 /// Stores amount of stakes for an `Account`.236 ///237 /// * **Key** - Staker account.238 /// * **Value** - Amount of stakes.239 #[pallet::storage]240 pub type StakesPerAccount<T: Config> =241 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;242243 /// Stores amount of stakes for an `Account`.244 ///245 /// * **Key** - Staker account.246 /// * **Value** - Amount of stakes.247 #[pallet::storage]248 pub type PendingUnstake<T: Config> = StorageMap<249 _,250 Twox64Concat,251 T::BlockNumber,252 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,253 ValueQuery,254 >;255256 /// Stores a key for record for which the next revenue recalculation would be performed.257 /// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.258 #[pallet::storage]259 #[pallet::getter(fn get_next_calculated_record)]260 pub type NextCalculatedRecord<T: Config> =261 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;262263 #[pallet::hooks]264 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {265 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize266 /// implies the execution of a strictly limited number of relatively lightweight operations.267 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.268 fn on_initialize(current_block_number: T::BlockNumber) -> Weight269 where270 <T as frame_system::Config>::BlockNumber: From<u32>,271 {272 let block_pending = PendingUnstake::<T>::take(current_block_number);273 let counter = block_pending.len() as u32;274275 if !block_pending.is_empty() {276 block_pending.into_iter().for_each(|(staker, amount)| {277 <T::Currency as ReservableCurrency<T::AccountId>>::unreserve(&staker, amount);278 });279 }280281 T::WeightInfo::on_initialize(counter)282 }283 }284285 #[pallet::call]286 impl<T: Config> Pallet<T>287 where288 T::BlockNumber: From<u32> + Into<u32>,289 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,290 {291 /// Sets an address as the the admin.292 ///293 /// # Permissions294 ///295 /// * Sudo296 ///297 /// # Arguments298 ///299 /// * `admin`: account of the new admin.300 #[pallet::weight(T::WeightInfo::set_admin_address())]301 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {302 ensure_root(origin)?;303304 <Admin<T>>::set(Some(admin.as_sub().to_owned()));305306 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));307308 Ok(())309 }310311 /// Stakes the amount of native tokens.312 /// Sets `amount` to the locked state.313 /// The maximum number of stakes for a staker is 10.314 ///315 /// # Arguments316 ///317 /// * `amount`: in native tokens.318 #[pallet::weight(T::WeightInfo::stake())]319 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {320 let staker_id = ensure_signed(staker)?;321322 ensure!(323 StakesPerAccount::<T>::get(&staker_id) < 10,324 Error::<T>::NoPermission325 );326327 ensure!(328 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),329 ArithmeticError::Underflow330 );331332 let balance =333 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);334335 // checks that we can lock `amount` on the `staker` account.336 <<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(337 &staker_id,338 amount,339 WithdrawReasons::all(),340 balance341 .checked_sub(&amount)342 .ok_or(ArithmeticError::Underflow)?,343 )?;344345 Self::add_lock_balance(&staker_id, amount)?;346347 let block_number = T::RelayBlockNumberProvider::current_block_number();348349 // Calculation of the number of recalculation periods,350 // after how much the first interest calculation should be performed for the stake351 let recalculate_after_interval: T::BlockNumber =352 if block_number % T::RecalculationInterval::get() == 0u32.into() {353 1u32.into()354 } else {355 2u32.into()356 };357358 // Сalculation of the number of the relay block359 // in which it is necessary to accrue remuneration for the stake.360 let recalc_block = (block_number / T::RecalculationInterval::get()361 + recalculate_after_interval)362 * T::RecalculationInterval::get();363364 <Staked<T>>::insert((&staker_id, block_number), {365 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));366 balance_and_recalc_block.0 = balance_and_recalc_block367 .0368 .checked_add(&amount)369 .ok_or(ArithmeticError::Overflow)?;370 balance_and_recalc_block.1 = recalc_block;371 balance_and_recalc_block372 });373374 <TotalStaked<T>>::set(375 <TotalStaked<T>>::get()376 .checked_add(&amount)377 .ok_or(ArithmeticError::Overflow)?,378 );379380 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);381382 Self::deposit_event(Event::Stake(staker_id, amount));383384 Ok(())385 }386387 /// Unstakes all stakes.388 /// Moves the sum of all stakes to the `reserved` state.389 /// After the end of `PendingInterval` this sum becomes completely390 /// free for further use.391 #[pallet::weight(T::WeightInfo::unstake())]392 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {393 let staker_id = ensure_signed(staker)?;394395 // calculate block number where the sum would be free396 let block = <frame_system::Pallet<T>>::block_number() + T::PendingInterval::get();397398 let mut pendings = <PendingUnstake<T>>::get(block);399400 // checks that we can do unreserve stakes in the block401 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);402403 let mut total_stakes = 0u64;404405 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))406 .map(|(_, (amount, _))| {407 total_stakes += 1;408 amount409 })410 .sum();411412 if total_staked.is_zero() {413 return Ok(None.into()); // TO-DO414 }415416 pendings417 .try_push((staker_id.clone(), total_staked))418 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;419420 <PendingUnstake<T>>::insert(block, pendings);421422 Self::unlock_balance(&staker_id, total_staked)?;423424 <T::Currency as ReservableCurrency<T::AccountId>>::reserve(&staker_id, total_staked)?;425426 TotalStaked::<T>::set(427 TotalStaked::<T>::get()428 .checked_sub(&total_staked)429 .ok_or(ArithmeticError::Underflow)?,430 );431432 StakesPerAccount::<T>::remove(&staker_id);433434 Self::deposit_event(Event::Unstake(staker_id, total_staked));435436 Ok(None.into())437 }438439 /// Sets the pallet to be the sponsor for the collection.440 ///441 /// # Permissions442 ///443 /// * Pallet admin444 ///445 /// # Arguments446 ///447 /// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`448 #[pallet::weight(T::WeightInfo::sponsor_collection())]449 pub fn sponsor_collection(450 admin: OriginFor<T>,451 collection_id: CollectionId,452 ) -> DispatchResult {453 let admin_id = ensure_signed(admin)?;454 ensure!(455 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,456 Error::<T>::NoPermission457 );458459 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)460 }461462 /// Removes the pallet as the sponsor for the collection.463 /// Returns [`NoPermission`][`Error::NoPermission`]464 /// if the pallet wasn't the sponsor.465 ///466 /// # Permissions467 ///468 /// * Pallet admin469 ///470 /// # Arguments471 ///472 /// * `collection_id`: ID of the collection that is sponsored by `pallet_id`473 #[pallet::weight(T::WeightInfo::stop_sponsoring_collection())]474 pub fn stop_sponsoring_collection(475 admin: OriginFor<T>,476 collection_id: CollectionId,477 ) -> DispatchResult {478 let admin_id = ensure_signed(admin)?;479480 ensure!(481 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,482 Error::<T>::NoPermission483 );484485 ensure!(486 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?487 == Self::account_id(),488 <Error<T>>::NoPermission489 );490 T::CollectionHandler::remove_collection_sponsor(collection_id)491 }492493 /// Sets the pallet to be the sponsor for the contract.494 ///495 /// # Permissions496 ///497 /// * Pallet admin498 ///499 /// # Arguments500 ///501 /// * `contract_id`: the contract address that will be sponsored by `pallet_id`502 #[pallet::weight(T::WeightInfo::sponsor_contract())]503 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {504 let admin_id = ensure_signed(admin)?;505506 ensure!(507 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,508 Error::<T>::NoPermission509 );510511 T::ContractHandler::set_sponsor(512 T::CrossAccountId::from_sub(Self::account_id()),513 contract_id,514 )515 }516517 /// Removes the pallet as the sponsor for the contract.518 /// Returns [`NoPermission`][`Error::NoPermission`]519 /// if the pallet wasn't the sponsor.520 ///521 /// # Permissions522 ///523 /// * Pallet admin524 ///525 /// # Arguments526 ///527 /// * `contract_id`: the contract address that is sponsored by `pallet_id`528 #[pallet::weight(T::WeightInfo::stop_sponsoring_contract())]529 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {530 let admin_id = ensure_signed(admin)?;531532 ensure!(533 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,534 Error::<T>::NoPermission535 );536537 ensure!(538 T::ContractHandler::sponsor(contract_id)?539 .ok_or(<Error<T>>::SponsorNotSet)?540 .as_sub() == &Self::account_id(),541 <Error<T>>::NoPermission542 );543 T::ContractHandler::remove_contract_sponsor(contract_id)544 }545546 /// Recalculates interest for the specified number of stakers.547 /// If all stakers are not recalculated, the next call of the extrinsic548 /// will continue the recalculation, from those stakers for whom this549 /// was not perform in last call.550 ///551 /// # Permissions552 ///553 /// * Pallet admin554 ///555 /// # Arguments556 ///557 /// * `stakers_number`: the number of stakers for which recalculation will be performed558 #[pallet::weight(T::WeightInfo::payout_stakers(stakers_number.unwrap_or(20) as u32))]559 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {560 let admin_id = ensure_signed(admin)?;561562 ensure!(563 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,564 Error::<T>::NoPermission565 );566567 // calculate the number of the current recalculation block,568 // this is necessary in order to understand which stakers we should calculate interest569 let current_recalc_block =570 Self::get_current_recalc_block(T::RelayBlockNumberProvider::current_block_number());571572 // calculate the number of the next recalculation block,573 // this value is set for the stakers to whom the recalculation will be performed574 let next_recalc_block = current_recalc_block + T::RecalculationInterval::get();575576 let mut storage_iterator = Self::get_next_calculated_key()577 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));578579 NextCalculatedRecord::<T>::set(None);580581 {582 let mut stakers_number = stakers_number.unwrap_or(20);583 let last_id = RefCell::new(None);584 let income_acc = RefCell::new(BalanceOf::<T>::default());585 let amount_acc = RefCell::new(BalanceOf::<T>::default());586587 // this closure is used to perform some of the actions if we break the loop because we reached the number of stakers for recalculation,588 // but there were unrecalculated records in the storage.589 let flush_stake = || -> DispatchResult {590 if let Some(last_id) = &*last_id.borrow() {591 if !income_acc.borrow().is_zero() {592 <T::Currency as Currency<T::AccountId>>::transfer(593 &T::TreasuryAccountId::get(),594 last_id,595 *income_acc.borrow(),596 ExistenceRequirement::KeepAlive,597 )598 .and_then(|_| {599 Self::add_lock_balance(last_id, *income_acc.borrow())?;600 <TotalStaked<T>>::try_mutate(|staked| {601 staked602 .checked_add(&*income_acc.borrow())603 .ok_or(ArithmeticError::Overflow.into())604 })605 })?;606607 Self::deposit_event(Event::StakingRecalculation(608 last_id.clone(),609 *amount_acc.borrow(),610 *income_acc.borrow(),611 ));612 }613614 *income_acc.borrow_mut() = BalanceOf::<T>::default();615 *amount_acc.borrow_mut() = BalanceOf::<T>::default();616 }617 Ok(())618 };619620 while let Some((621 (current_id, staked_block),622 (amount, next_recalc_block_for_stake),623 )) = storage_iterator.next()624 {625 if stakers_number == 0 {626 NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));627 break;628 }629 if last_id.borrow().as_ref() != Some(¤t_id) {630 flush_stake()?;631 *last_id.borrow_mut() = Some(current_id.clone());632 stakers_number -= 1;633 };634 if current_recalc_block >= next_recalc_block_for_stake {635 *amount_acc.borrow_mut() += amount;636 Self::recalculate_and_insert_stake(637 ¤t_id,638 staked_block,639 next_recalc_block,640 amount,641 ((current_recalc_block - next_recalc_block_for_stake)642 / T::RecalculationInterval::get())643 .into() + 1,644 &mut *income_acc.borrow_mut(),645 );646 }647 }648 flush_stake()?;649 }650651 Ok(())652 }653 }654}655656impl<T: Config> Pallet<T> {657 /// The account address of the app promotion pot.658 ///659 /// This actually does computation. If you need to keep using it, then make sure you cache the660 /// value and only call this once.661 pub fn account_id() -> T::AccountId {662 T::PalletId::get().into_account_truncating()663 }664665 /// Unlocks the balance that was locked by the pallet.666 ///667 /// - `staker`: staker account.668 /// - `amount`: amount of unlocked funds.669 fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {670 let locked_balance = Self::get_locked_balance(staker)671 .map(|l| l.amount)672 .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;673674 // It is understood that we cannot unlock more funds than were locked by staking.675 // Therefore, if implemented correctly, this error should not occur.676 Self::set_lock_unchecked(677 staker,678 locked_balance679 .checked_sub(&amount)680 .ok_or(ArithmeticError::Underflow)?,681 );682 Ok(())683 }684685 /// Adds the balance to locked by the pallet.686 ///687 /// - `staker`: staker account.688 /// - `amount`: amount of added locked funds.689 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {690 Self::get_locked_balance(staker)691 .map_or(<BalanceOf<T>>::default(), |l| l.amount)692 .checked_add(&amount)693 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))694 .ok_or(ArithmeticError::Overflow.into())695 }696697 /// Sets the new state of a balance locked by the pallet.698 ///699 /// - `staker`: staker account.700 /// - `amount`: amount of locked funds.701 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {702 if amount.is_zero() {703 <T::Currency as LockableCurrency<T::AccountId>>::remove_lock(LOCK_IDENTIFIER, &staker);704 } else {705 <T::Currency as LockableCurrency<T::AccountId>>::set_lock(706 LOCK_IDENTIFIER,707 staker,708 amount,709 WithdrawReasons::all(),710 )711 }712 }713714 /// Returns the balance locked by the pallet for the staker.715 ///716 /// - `staker`: staker account.717 pub fn get_locked_balance(718 staker: impl EncodeLike<T::AccountId>,719 ) -> Option<BalanceLock<BalanceOf<T>>> {720 <T::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)721 .into_iter()722 .find(|l| l.id == LOCK_IDENTIFIER)723 }724725 /// Returns the total staked balance for the staker.726 ///727 /// - `staker`: staker account.728 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {729 let staked = Staked::<T>::iter_prefix((staker,))730 .into_iter()731 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {732 acc + amount733 });734 if staked != <BalanceOf<T>>::default() {735 Some(staked)736 } else {737 None738 }739 }740741 /// Returns all relay block numbers when stake was made,742 /// the amount of the stake.743 ///744 /// - `staker`: staker account.745 pub fn total_staked_by_id_per_block(746 staker: impl EncodeLike<T::AccountId>,747 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {748 let mut staked = Staked::<T>::iter_prefix((staker,))749 .into_iter()750 .map(|(block, (amount, _))| (block, amount))751 .collect::<Vec<_>>();752 staked.sort_by_key(|(block, _)| *block);753 if !staked.is_empty() {754 Some(staked)755 } else {756 None757 }758 }759760 /// Returns the total staked balance for the staker.761 /// If `staker` is `None`, returns the total amount staked.762 /// - `staker`: staker account.763 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {764 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {765 Self::total_staked_by_id(s.as_sub())766 })767 }768769 // pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {770 // Self::get_locked_balance(staker.as_sub())771 // .map(|l| l.amount)772 // .unwrap_or_default()773 // }774775 /// Returns all relay block numbers when stake was made,776 /// the amount of the stake.777 ///778 /// - `staker`: staker account.779 pub fn cross_id_total_staked_per_block(780 staker: T::CrossAccountId,781 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {782 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()783 }784785 fn recalculate_and_insert_stake(786 staker: &T::AccountId,787 staked_block: T::BlockNumber,788 next_recalc_block: T::BlockNumber,789 base: BalanceOf<T>,790 iters: u32,791 income_acc: &mut BalanceOf<T>,792 ) {793 let income = Self::calculate_income(base, iters);794795 base.checked_add(&income).map(|res| {796 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));797 *income_acc += income;798 });799 }800801 fn calculate_income<I>(base: I, iters: u32) -> I802 where803 I: EncodeLike<BalanceOf<T>> + Balance,804 {805 let mut income = base;806807 (0..iters).for_each(|_| income += T::IntervalIncome::get() * income);808809 income - base810 }811812 fn get_current_recalc_block(current_relay_block: T::BlockNumber) -> T::BlockNumber {813 (current_relay_block / T::RecalculationInterval::get()) * T::RecalculationInterval::get()814 }815816 fn get_next_calculated_key() -> Option<Vec<u8>> {817 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))818 }819}820821impl<T: Config> Pallet<T>822where823 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,824{825 /// Returns the amount reserved by the pending.826 /// If `staker` is `None`, returns the total pending.827 ///828 /// -`staker`: staker account.829 ///830 /// Since user funds are not transferred anywhere by staking, overflow protection is provided831 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,832 /// the staker must have more funds on his account than the maximum set for `Balance` type.833 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {834 staker.map_or(835 PendingUnstake::<T>::iter_values()836 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))837 .sum(),838 |s| {839 PendingUnstake::<T>::iter_values()840 .flatten()841 .filter_map(|(id, amount)| {842 if id == *s.as_sub() {843 Some(amount)844 } else {845 None846 }847 })848 .sum()849 },850 )851 }852853 /// Returns all parachain block numbers when unreserve is expected,854 /// the amount of the unreserved funds.855 ///856 /// - `staker`: staker account.857 pub fn cross_id_pending_unstake_per_block(858 staker: T::CrossAccountId,859 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {860 let mut unsorted_res = vec![];861 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {862 pendings.into_iter().for_each(|(id, amount)| {863 if id == *staker.as_sub() {864 unsorted_res.push((block, amount));865 };866 })867 });868869 unsorted_res.sort_by_key(|(block, _)| *block);870 unsorted_res871 }872}runtime/common/mod.rsdiffbeforeafterboth--- a/runtime/common/mod.rs
+++ b/runtime/common/mod.rs
@@ -82,7 +82,7 @@
pub type SignedExtra = (
frame_system::CheckSpecVersion<Runtime>,
- // system::CheckTxVersion<Runtime>,
+ frame_system::CheckTxVersion<Runtime>,
frame_system::CheckGenesis<Runtime>,
frame_system::CheckEra<Runtime>,
frame_system::CheckNonce<Runtime>,
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -50,7 +50,7 @@
spec_name: create_runtime_str!(RUNTIME_NAME),
impl_name: create_runtime_str!(RUNTIME_NAME),
authoring_version: 1,
- spec_version: 927020,
+ spec_version: 927030,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
transaction_version: 2,
runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -50,7 +50,7 @@
spec_name: create_runtime_str!(RUNTIME_NAME),
impl_name: create_runtime_str!(RUNTIME_NAME),
authoring_version: 1,
- spec_version: 927020,
+ spec_version: 927030,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
transaction_version: 2,
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -50,7 +50,7 @@
spec_name: create_runtime_str!(RUNTIME_NAME),
impl_name: create_runtime_str!(RUNTIME_NAME),
authoring_version: 1,
- spec_version: 927020,
+ spec_version: 927030,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
transaction_version: 2,
tests/src/adminTransferAndBurn.test.tsdiffbeforeafterboth--- a/tests/src/adminTransferAndBurn.test.ts
+++ b/tests/src/adminTransferAndBurn.test.ts
@@ -24,19 +24,14 @@
let donor: IKeyringPair;
-before(async () => {
- await usingPlaygrounds(async (_, privateKey) => {
- donor = privateKey('//Alice');
- });
-});
-
describe('Integration Test: ownerCanTransfer allows admins to use only transferFrom/burnFrom:', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
let charlie: IKeyringPair;
before(async () => {
- await usingPlaygrounds(async (helper) => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ donor = privateKey('//Alice');
[alice, bob, charlie] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
});
});
tests/src/allowLists.test.tsdiffbeforeafterboth--- a/tests/src/allowLists.test.ts
+++ b/tests/src/allowLists.test.ts
@@ -24,12 +24,6 @@
let donor: IKeyringPair;
-before(async () => {
- await usingPlaygrounds(async (_, privateKey) => {
- donor = privateKey('//Alice');
- });
-});
-
let alice: IKeyringPair;
let bob: IKeyringPair;
let charlie: IKeyringPair;
@@ -37,7 +31,8 @@
describe('Integration Test ext. Allow list tests', () => {
before(async () => {
- await usingPlaygrounds(async (helper) => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ donor = privateKey('//Alice');
[alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
});
});
tests/src/app-promotion.test.tsdiffbeforeafterboth--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -20,17 +20,12 @@
getModuleNames,
Pallets,
} from './util/helpers';
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {usingPlaygrounds} from './util/playgrounds';
-
+import {itSub, usingPlaygrounds} from './util/playgrounds';
import {encodeAddress} from '@polkadot/util-crypto';
import {stringToU8a} from '@polkadot/util';
-import {SponsoringMode, contractHelpers, createEthAccountWithBalance, deployFlipper, itWeb3, transferBalanceToEth} from './eth/util/helpers';
+import {SponsoringMode} from './eth/util/helpers';
import {DevUniqueHelper} from './util/playgrounds/unique.dev';
-chai.use(chaiAsPromised);
-const expect = chai.expect;
+import {itEth, expect} from './eth/util/playgrounds';
let alice: IKeyringPair;
let palletAdmin: IKeyringPair;
@@ -38,723 +33,652 @@
const palletAddress = calculatePalleteAddress('appstake');
let accounts: IKeyringPair[] = [];
const LOCKING_PERIOD = 20n; // 20 blocks of relay
-const UNLOCKING_PERIOD = 10n; // 20 blocks of parachain
+const UNLOCKING_PERIOD = 10n; // 10 blocks of parachain
const rewardAvailableInBlock = (stakedInBlock: bigint) => (stakedInBlock - stakedInBlock % LOCKING_PERIOD) + (LOCKING_PERIOD * 2n);
-const beforeEach = async (context: Mocha.Context) => {
- await usingPlaygrounds(async (helper, privateKey) => {
- if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) context.skip();
- alice = privateKey('//Alice');
- palletAdmin = privateKey('//Charlie'); // TODO use custom address
- await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
- nominal = helper.balance.getOneTokenNominal();
- await helper.balance.transferToSubstrate(alice, palletAdmin.address, 1000n * nominal);
- await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);
- accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests
- });
-};
-
-describe('app-promotions.stake extrinsic', () => {
+describe('App promotion', () => {
before(async function () {
- await beforeEach(this);
+ await usingPlaygrounds(async (helper, privateKey) => {
+ if (!getModuleNames(helper.api!).includes(Pallets.AppPromotion)) this.skip();
+ alice = privateKey('//Alice');
+ palletAdmin = privateKey('//Charlie'); // TODO use custom address
+ await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})));
+ nominal = helper.balance.getOneTokenNominal();
+ await helper.balance.transferToSubstrate(alice, palletAdmin.address, 1000n * nominal);
+ await helper.balance.transferToSubstrate(alice, palletAddress, 1000n * nominal);
+ accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests
+ });
});
- it('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async () => {
- await usingPlaygrounds(async (helper) => {
+ describe('stake extrinsic', () => {
+ itSub('should "lock" staking balance, add it to "staked" map, and increase "totalStaked" amount', async ({helper}) => {
const [staker, recepient] = [accounts.pop()!, accounts.pop()!];
const totalStakedBefore = await helper.staking.getTotalStaked();
-
+
// Minimum stake amount is 100:
- await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.eventually.rejected;
+ await expect(helper.staking.stake(staker, 100n * nominal - 1n)).to.be.rejected;
await helper.staking.stake(staker, 100n * nominal);
-
+
// Staker balance is: miscFrozen: 100, feeFrozen: 100, reserved: 0n...
// ...so he can not transfer 900
expect (await helper.balance.getSubstrateFull(staker.address)).to.contain({miscFrozen: 100n * nominal, feeFrozen: 100n * nominal, reserved: 0n});
- await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejected;
+ await expect(helper.balance.transferToSubstrate(staker, recepient.address, 900n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(100n * nominal);
expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
// it is potentially flaky test. Promotion can credited some tokens. Maybe we need to use closeTo?
expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore + 100n * nominal); // total tokens amount staked in app-promotion increased
-
+
await helper.staking.stake(staker, 200n * nominal);
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(300n * nominal);
- expect((await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map((x) => x[1])).to.be.deep.equal([100n * nominal, 200n * nominal]);
+ const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ expect(totalStakedPerBlock[0].amount).to.equal(100n * nominal);
+ expect(totalStakedPerBlock[1].amount).to.equal(200n * nominal);
});
- });
-
- it('should allow to create maximum 10 stakes for account', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('should allow to create maximum 10 stakes for account', async ({helper}) => {
const [staker] = await helper.arrange.createAccounts([2000n], alice);
for (let i = 0; i < 10; i++) {
await helper.staking.stake(staker, 100n * nominal);
}
-
+
// can have 10 stakes
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);
expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);
-
- await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejected;
-
+
+ await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejectedWith('appPromotion.NoPermission');
+
// After unstake can stake again
await helper.staking.unstake(staker);
await helper.staking.stake(staker, 100n * nominal);
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);
});
- });
+
+ itSub('should reject transaction if stake amount is more than total free balance minus frozen', async ({helper}) => {
+ const staker = accounts.pop()!;
- it('should reject transaction if stake amount is more than total free balance minus frozen', async () => {
- await usingPlaygrounds(async helper => {
- const staker = accounts.pop()!;
-
// Can't stake full balance because Alice needs to pay some fee
- await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.eventually.rejected;
+ await expect(helper.staking.stake(staker, 1000n * nominal)).to.be.rejected;
await helper.staking.stake(staker, 500n * nominal);
-
+
// Can't stake 500 tkn because Alice has Less than 500 transferable;
- await expect(helper.staking.stake(staker, 500n * nominal)).to.be.eventually.rejected;
+ await expect(helper.staking.stake(staker, 500n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(500n * nominal);
});
- });
-
- it('for different accounts in one block is possible', async () => {
- await usingPlaygrounds(async helper => {
+
+ itSub('for different accounts in one block is possible', async ({helper}) => {
const crowd = [accounts.pop()!, accounts.pop()!, accounts.pop()!, accounts.pop()!];
-
+
const crowdStartsToStake = crowd.map(user => helper.staking.stake(user, 100n * nominal));
- await expect(Promise.all(crowdStartsToStake)).to.be.eventually.fulfilled;
-
+ await expect(Promise.all(crowdStartsToStake)).to.be.fulfilled;
+
const crowdStakes = await Promise.all(crowd.map(address => helper.staking.getTotalStaked({Substrate: address.address})));
expect(crowdStakes).to.deep.equal([100n * nominal, 100n * nominal, 100n * nominal, 100n * nominal]);
});
});
-});
-
-describe('unstake balance extrinsic', () => {
- before(async function () {
- await beforeEach(this);
- });
-
- it('should change balance state from "frozen" to "reserved", add it to "pendingUnstake" map, and subtract it from totalStaked', async () => {
- await usingPlaygrounds(async helper => {
+
+ describe('unstake extrinsic', () => {
+ itSub('should change balance state from "frozen" to "reserved", add it to "pendingUnstake" map, and subtract it from totalStaked', async ({helper}) => {
const [staker, recepient] = [accounts.pop()!, accounts.pop()!];
const totalStakedBefore = await helper.staking.getTotalStaked();
await helper.staking.stake(staker, 900n * nominal);
await helper.staking.unstake(staker);
-
+
// Right after unstake balance is reserved
// Staker can not transfer
expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 900n * nominal, miscFrozen: 0n, feeFrozen: 0n});
- await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejected;
+ await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.InsufficientBalance');
expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(900n * nominal);
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);
});
- });
-
- it('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async ({helper}) => {
const staker = accounts.pop()!;
await helper.staking.stake(staker, 100n * nominal);
await helper.staking.unstake(staker);
- const unstakedInBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address}))[0][0];
-
+ const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+
// Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n
- await helper.wait.forParachainBlockNumber(unstakedInBlock);
+ await helper.wait.forParachainBlockNumber(pendingUnstake.block);
expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});
expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
-
+
// staker can transfer:
await helper.balance.transferToSubstrate(staker, alice.address, 998n * nominal);
expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);
});
- });
-
- it('should successfully unstake multiple stakes', async () => {
- await usingPlaygrounds(async helper => {
+
+ itSub('should successfully unstake multiple stakes', async ({helper}) => {
const staker = accounts.pop()!;
await helper.staking.stake(staker, 100n * nominal);
await helper.staking.stake(staker, 200n * nominal);
await helper.staking.stake(staker, 300n * nominal);
-
+
// staked: [100, 200, 300]; unstaked: 0
- let pendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
- let unstakedPerBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).map(stake => stake[1]);
- let stakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(stake => stake[1]);
- expect(pendingUnstake).to.be.deep.equal(0n);
- expect(unstakedPerBlock).to.be.deep.equal([]);
- expect(stakedPerBlock).to.be.deep.equal([100n * nominal, 200n * nominal, 300n * nominal]);
-
+ let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
+ let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+ let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ expect(totalPendingUnstake).to.be.deep.equal(0n);
+ expect(pendingUnstake).to.be.deep.equal([]);
+ expect(stakes[0].amount).to.equal(100n * nominal);
+ expect(stakes[1].amount).to.equal(200n * nominal);
+ expect(stakes[2].amount).to.equal(300n * nominal);
+
// Can unstake multiple stakes
await helper.staking.unstake(staker);
- const unstakingBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address}))[0][0];
- pendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
- unstakedPerBlock = (await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address})).map(stake => stake[1]);
- stakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(stake => stake[1]);
- expect(pendingUnstake).to.be.equal(600n * nominal);
- expect(stakedPerBlock).to.be.deep.equal([]);
- expect(unstakedPerBlock).to.be.deep.equal([600n * nominal]);
-
+ pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+ totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
+ stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ expect(totalPendingUnstake).to.be.equal(600n * nominal);
+ expect(stakes).to.be.deep.equal([]);
+ expect(pendingUnstake[0].amount).to.equal(600n * nominal);
+
expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 600n * nominal, feeFrozen: 0n, miscFrozen: 0n});
- await helper.wait.forParachainBlockNumber(unstakingBlock);
+ await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);
expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});
expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
});
- });
-
- it('should not have any effects if no active stakes', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('should not have any effects if no active stakes', async ({helper}) => {
const staker = accounts.pop()!;
-
+
// unstake has no effect if no stakes at all
await helper.staking.unstake(staker);
expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);
expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper
-
+
// TODO stake() unstake() waitUnstaked() unstake();
-
+
// can't unstake if there are only pendingUnstakes
await helper.staking.stake(staker, 100n * nominal);
await helper.staking.unstake(staker);
await helper.staking.unstake(staker);
-
+
expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
});
- });
-
- it('should keep different unlocking block for each unlocking stake', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('should keep different unlocking block for each unlocking stake', async ({helper}) => {
const staker = accounts.pop()!;
await helper.staking.stake(staker, 100n * nominal);
await helper.staking.unstake(staker);
await helper.staking.stake(staker, 120n * nominal);
await helper.staking.unstake(staker);
-
+
const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
expect(unstakingPerBlock).has.length(2);
- expect(unstakingPerBlock[0][1]).to.equal(100n * nominal);
- expect(unstakingPerBlock[1][1]).to.equal(120n * nominal);
+ expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);
+ expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);
});
- });
-
- it('should be possible for different accounts in one block', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('should be possible for different accounts in one block', async ({helper}) => {
const stakers = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
-
+
await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
await Promise.all(stakers.map(staker => helper.staking.unstake(staker)));
-
+
await Promise.all(stakers.map(async (staker) => {
expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
}));
});
});
-});
-
-describe('Admin adress', () => {
- before(async function () {
- await beforeEach(this);
- });
-
- it('can be set by sudo only', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ describe('admin adress', () => {
+ itSub('can be set by sudo only', async ({helper}) => {
const nonAdmin = accounts.pop()!;
// nonAdmin can not set admin not from himself nor as a sudo
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.eventually.rejected;
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.eventually.rejected;
-
+ await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address}))).to.be.rejected;
+ await expect(helper.signTransaction(nonAdmin, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: nonAdmin.address})))).to.be.rejected;
+
// Alice can
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.eventually.fulfilled;
+ await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.fulfilled;
});
- });
-
- it('can be any valid CrossAccountId', async () => {
- // We are not going to set an eth address as a sponsor,
- // but we do want to check, it doesn't break anything;
- await usingPlaygrounds(async (helper) => {
+
+ 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 account = accounts.pop()!;
const ethAccount = helper.address.substrateToEth(account.address);
// Alice sets Ethereum address as a sudo. Then Substrate address back...
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.eventually.fulfilled;
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address})))).to.be.eventually.fulfilled;
-
+ await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Ethereum: ethAccount})))).to.be.fulfilled;
+ await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.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, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
+ await expect(helper.signTransaction(account, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
});
- });
-
- it('can be reassigned', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('can be reassigned', async ({helper}) => {
const [oldAdmin, newAdmin, collectionOwner] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
-
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.eventually.fulfilled;
- await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.eventually.fulfilled;
- await expect(helper.signTransaction(oldAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
-
- await expect(helper.signTransaction(newAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;
+
+ await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(oldAdmin))))).to.be.fulfilled;
+ await expect(helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress(normalizeAccountId(newAdmin))))).to.be.fulfilled;
+ await expect(helper.signTransaction(oldAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
+
+ await expect(helper.signTransaction(newAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
});
});
-});
-
-describe('App-promotion collection sponsoring', () => {
- before(async function () {
- await beforeEach(this);
- await usingPlaygrounds(async (helper) => {
- const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));
- await helper.signTransaction(alice, tx);
+
+ describe('collection sponsoring', () => {
+ before(async function () {
+ await usingPlaygrounds(async (helper) => {
+ const tx = helper.api!.tx.sudo.sudo(helper.api!.tx.appPromotion.setAdminAddress({Substrate: palletAdmin.address}));
+ await helper.signTransaction(alice, tx);
+ });
});
- });
-
- it('should actually sponsor transactions', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('should actually sponsor transactions', async ({helper}) => {
const [collectionOwner, tokenSender, receiver] = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'Name', description: 'Description', tokenPrefix: 'Prefix', limits: {sponsorTransferTimeout: 0}});
const token = await collection.mintToken(collectionOwner, {Substrate: tokenSender.address});
await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));
const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);
-
+
await token.transfer(tokenSender, {Substrate: receiver.address});
expect (await token.getOwner()).to.be.deep.equal({Substrate: receiver.address});
const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);
-
+
// senders balance the same, transaction has sponsored
expect (await helper.balance.getSubstrate(tokenSender.address)).to.be.equal(1000n * nominal);
expect (palletBalanceBefore > palletBalanceAfter).to.be.true;
});
- });
-
- it('can not be set by non admin', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('can not be set by non admin', async ({helper}) => {
const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
-
+
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
-
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
+
+ await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
expect((await collection.getData())?.raw.sponsorship).to.equal('Disabled');
});
- });
-
- it('should set pallet address as confirmed admin', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('should set pallet address as confirmed admin', async ({helper}) => {
const [collectionOwner, oldSponsor] = [accounts.pop()!, accounts.pop()!];
-
+
// Can set sponsoring for collection without sponsor
const collectionWithoutSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'No-sponsor', description: 'New Collection', tokenPrefix: 'Promotion'});
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.eventually.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithoutSponsor.collectionId))).to.be.fulfilled;
expect((await collectionWithoutSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
-
+
// Can set sponsoring for collection with unconfirmed sponsor
const collectionWithUnconfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Unconfirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: oldSponsor.address});
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.eventually.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithUnconfirmedSponsor.collectionId))).to.be.fulfilled;
expect((await collectionWithUnconfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
-
+
// Can set sponsoring for collection with confirmed sponsor
const collectionWithConfirmedSponsor = await helper.nft.mintCollection(collectionOwner, {name: 'Confirmed', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: oldSponsor.address});
await collectionWithConfirmedSponsor.confirmSponsorship(oldSponsor);
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.eventually.fulfilled;
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithConfirmedSponsor.collectionId))).to.be.fulfilled;
expect((await collectionWithConfirmedSponsor.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
});
- });
-
- it('can be overwritten by collection owner', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('can be overwritten by collection owner', async ({helper}) => {
const [collectionOwner, newSponsor] = [accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
const collectionId = collection.collectionId;
-
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionId))).to.be.eventually.fulfilled;
-
+
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionId))).to.be.fulfilled;
+
// Collection limits still can be changed by the owner
expect(await collection.setLimits(collectionOwner, {sponsorTransferTimeout: 0})).to.be.true;
expect((await collection.getData())?.raw.limits.sponsorTransferTimeout).to.be.equal(0);
expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
-
+
// Collection sponsor can be changed too
expect((await collection.setSponsor(collectionOwner, newSponsor.address))).to.be.true;
expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Unconfirmed: newSponsor.address});
});
- });
-
- it('should not overwrite collection limits set by the owner earlier', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('should not overwrite collection limits set by the owner earlier', async ({helper}) => {
const limits = {ownerCanDestroy: true, ownerCanTransfer: true, sponsorTransferTimeout: 0};
const collectionWithLimits = await helper.nft.mintCollection(alice, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits});
-
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.eventually.fulfilled;
+
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collectionWithLimits.collectionId))).to.be.fulfilled;
expect((await collectionWithLimits.getData())?.raw.limits).to.be.deep.contain(limits);
});
- });
-
- it('should reject transaction if collection doesn\'t exist', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('should reject transaction if collection doesn\'t exist', async ({helper}) => {
const collectionOwner = accounts.pop()!;
-
+
// collection has never existed
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(999999999))).to.be.eventually.rejected;
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(999999999))).to.be.rejected;
// collection has been burned
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
await collection.burn(collectionOwner);
-
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.rejected;
+
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.rejected;
});
});
-});
-
-describe('app-promotion stopSponsoringCollection', () => {
- before(async function () {
- await beforeEach(this);
- });
-
- it('can not be called by non-admin', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ describe('stopSponsoringCollection', () => {
+ itSub('can not be called by non-admin', async ({helper}) => {
const [collectionOwner, nonAdmin] = [accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
-
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.eventually.fulfilled;
-
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;
+
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId))).to.be.fulfilled;
+
+ await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: palletAddress});
});
- });
-
- it('should set sponsoring as disabled', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('should set sponsoring as disabled', async ({helper}) => {
const [collectionOwner, recepient] = [accounts.pop()!, accounts.pop()!];
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', limits: {sponsorTransferTimeout: 0}});
const token = await collection.mintToken(collectionOwner, {Substrate: collectionOwner.address});
-
+
await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorCollection(collection.collectionId));
await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId));
-
+
expect((await collection.getData())?.raw.sponsorship).to.be.equal('Disabled');
-
+
// Transactions are not sponsored anymore:
const ownerBalanceBefore = await helper.balance.getSubstrate(collectionOwner.address);
await token.transfer(collectionOwner, {Substrate: recepient.address});
const ownerBalanceAfter = await helper.balance.getSubstrate(collectionOwner.address);
expect(ownerBalanceAfter < ownerBalanceBefore).to.be.equal(true);
});
- });
-
- it('should not affect collection which is not sponsored by pallete', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('should not affect collection which is not sponsored by pallete', async ({helper}) => {
const collectionOwner = accounts.pop()!;
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion', pendingSponsor: collectionOwner.address});
await collection.confirmSponsorship(collectionOwner);
-
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;
-
+
+ await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
+
expect((await collection.getData())?.raw.sponsorship).to.be.deep.equal({Confirmed: collectionOwner.address});
});
- });
-
- it('should reject transaction if collection does not exist', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('should reject transaction if collection does not exist', async ({helper}) => {
const collectionOwner = accounts.pop()!;
const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
-
+
await collection.burn(collectionOwner);
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.eventually.rejected;
- await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(999999999))).to.be.eventually.rejected;
+ await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');
+ await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');
});
});
-});
-
-describe('app-promotion contract sponsoring', () => {
- before(async function () {
- await beforeEach(this);
- });
-
- itWeb3('should set palletes address as a sponsor', async ({api, web3, privateKeyWrapper}) => {
- await usingPlaygrounds(async (helper) => {
- const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
- const flipper = await deployFlipper(web3, contractOwner);
- const contractMethods = contractHelpers(web3, contractOwner);
-
- await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));
+
+ describe('contract sponsoring', () => {
+ itEth('should set palletes address as a sponsor', async ({helper}) => {
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);
- expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true;
- expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
- expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;
+ expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
confirmed: {
substrate: palletAddress,
},
});
});
- });
-
- itWeb3('should overwrite sponsoring mode and existed sponsor', async ({api, web3, privateKeyWrapper}) => {
- await usingPlaygrounds(async (helper) => {
- const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
- const flipper = await deployFlipper(web3, contractOwner);
- const contractMethods = contractHelpers(web3, contractOwner);
-
- await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
-
+
+ itEth('should overwrite sponsoring mode and existed sponsor', async ({helper}) => {
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+
+ await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
+
// Contract is self sponsored
- expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.be.deep.equal({
+ expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.be.deep.equal({
confirmed: {
ethereum: flipper.options.address.toLowerCase(),
},
});
-
+
// set promotion sponsoring
- await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));
-
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
+
// new sponsor is pallet address
- expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true;
- expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
- expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;
+ expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({
confirmed: {
substrate: palletAddress,
},
});
});
- });
-
- itWeb3('can be overwritten by contract owner', async ({api, web3, privateKeyWrapper}) => {
- await usingPlaygrounds(async (helper) => {
- const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
- const flipper = await deployFlipper(web3, contractOwner);
- const contractMethods = contractHelpers(web3, contractOwner);
-
+
+ itEth('can be overwritten by contract owner', async ({helper}) => {
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+
// contract sponsored by pallet
- await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));
-
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
+
// owner sets self sponsoring
- await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
-
- expect(await contractMethods.methods.hasSponsor(flipper.options.address).call()).to.be.true;
- expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
- expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
+
+ expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;
+ expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
confirmed: {
ethereum: flipper.options.address.toLowerCase(),
},
});
});
- });
-
- itWeb3('can not be set by non admin', async ({api, web3, privateKeyWrapper}) => {
- await usingPlaygrounds(async (helper) => {
+
+ itEth('can not be set by non admin', async ({helper}) => {
const nonAdmin = accounts.pop()!;
- const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
- const flipper = await deployFlipper(web3, contractOwner);
- const contractMethods = contractHelpers(web3, contractOwner);
-
- await expect(contractMethods.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
-
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+
+ await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
+
// nonAdmin calls sponsorContract
- await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address))).to.be.rejected;
-
+ await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');
+
// contract still self-sponsored
- expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
confirmed: {
ethereum: flipper.options.address.toLowerCase(),
},
});
});
-
- itWeb3('should be rejected for non-contract address', async ({api, web3, privateKeyWrapper}) => {
- await usingPlaygrounds(async (helper) => {
-
- });
- });
- });
-
- itWeb3('should actually sponsor transactions', async ({api, web3, privateKeyWrapper}) => {
- await usingPlaygrounds(async (helper) => {
- const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
- const flipper = await deployFlipper(web3, contractOwner);
- const contractHelper = contractHelpers(web3, contractOwner);
+
+ itEth('should actually sponsor transactions', async ({helper}) => {
+ // Contract caller
+ const caller = await helper.eth.createAccountWithBalance(alice, 1000n);
+ const palletBalanceBefore = await helper.balance.getSubstrate(palletAddress);
+
+ // Deploy flipper
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner); // await deployFlipper(web3, contractOwner);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+
+ // Owner sets to sponsor every tx
await contractHelper.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: contractOwner});
await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});
- await transferBalanceToEth(api, alice, flipper.options.address, 1000n);
-
- await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));
+ await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address, 1000n); // transferBalanceToEth(api, alice, flipper.options.address, 1000n);
+
+ // Set promotion to the Flipper
+ await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.sponsorContract(flipper.options.address));
+
+ // Caller calls Flipper
await flipper.methods.flip().send({from: caller});
expect(await flipper.methods.getValue().call()).to.be.true;
-
+
+ // The contracts and caller balances have not changed
const callerBalance = await helper.balance.getEthereum(caller);
const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);
-
expect(callerBalance).to.be.equal(1000n * nominal);
- expect(1000n * nominal > contractBalanceAfter).to.be.true;
+ expect(1000n * nominal === contractBalanceAfter).to.be.true;
+
+ // The pallet balance has decreased
+ const palletBalanceAfter = await helper.balance.getSubstrate(palletAddress);
+ expect(palletBalanceAfter < palletBalanceBefore).to.be.true;
});
- });
-});
-
-describe('app-promotion stopSponsoringContract', () => {
- before(async function () {
- await beforeEach(this);
});
-
- itWeb3('should remove pallet address from contract sponsors', async ({api, web3, privateKeyWrapper}) => {
- await usingPlaygrounds(async (helper) => {
- const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
- const flipper = await deployFlipper(web3, contractOwner);
- await transferBalanceToEth(api, alice, flipper.options.address);
- const contractHelper = contractHelpers(web3, contractOwner);
+
+ describe('stopSponsoringContract', () => {
+ itEth('should remove pallet address from contract sponsors', async ({helper}) => {
+ const caller = await helper.eth.createAccountWithBalance(alice, 1000n);
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner);
+ await helper.eth.transferBalanceFromSubstrate(alice, flipper.options.address);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+
await contractHelper.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: contractOwner});
- await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));
- await helper.signTransaction(palletAdmin, api.tx.appPromotion.stopSponsoringContract(flipper.options.address));
-
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address], true);
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true);
+
expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.false;
- expect((await api.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
- expect((await api.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+ expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);
+ expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
disabled: null,
});
-
+
await flipper.methods.flip().send({from: caller});
expect(await flipper.methods.getValue().call()).to.be.true;
-
+
const callerBalance = await helper.balance.getEthereum(caller);
const contractBalanceAfter = await helper.balance.getEthereum(flipper.options.address);
-
+
// caller payed for call
expect(1000n * nominal > callerBalance).to.be.true;
expect(contractBalanceAfter).to.be.equal(1000n * nominal);
});
- });
-
- itWeb3('can not be called by non-admin', async ({api, web3, privateKeyWrapper}) => {
- await usingPlaygrounds(async (helper) => {
+
+ itEth('can not be called by non-admin', async ({helper}) => {
const nonAdmin = accounts.pop()!;
- const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
- const flipper = await deployFlipper(web3, contractOwner);
-
- await helper.signTransaction(palletAdmin, api.tx.appPromotion.sponsorContract(flipper.options.address));
- await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner);
+
+ await helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.sponsorContract', [flipper.options.address]);
+ const stopSponsoringResult = await helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address]);
+ expect(stopSponsoringResult.status).to.equal('Fail');
+ expect(stopSponsoringResult.moduleError).to.equal('appPromotion.NoPermission');
});
- });
-
- itWeb3('should not affect a contract which is not sponsored by pallete', async ({api, web3, privateKeyWrapper}) => {
- await usingPlaygrounds(async (helper) => {
+
+ itEth('should not affect a contract which is not sponsored by pallete', async ({helper}) => {
const nonAdmin = accounts.pop()!;
- const contractOwner = (await createEthAccountWithBalance(api, web3, privateKeyWrapper)).toLowerCase();
- const flipper = await deployFlipper(web3, contractOwner);
- const contractHelper = contractHelpers(web3, contractOwner);
- await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.not.rejected;
-
- await expect(helper.signTransaction(nonAdmin, api.tx.appPromotion.stopSponsoringContract(flipper.options.address))).to.be.rejected;
+ const contractOwner = (await helper.eth.createAccountWithBalance(alice, 1000n)).toLowerCase();
+ const flipper = await helper.eth.deployFlipper(contractOwner);
+ const contractHelper = helper.ethNativeContract.contractHelpers(contractOwner);
+ await expect(contractHelper.methods.selfSponsoredEnable(flipper.options.address).send()).to.be.fulfilled;
+
+ await expect(helper.executeExtrinsic(nonAdmin, 'api.tx.appPromotion.stopSponsoringContract', [flipper.options.address], true)).to.be.rejectedWith('appPromotion.NoPermission');
});
});
-});
-
-describe('app-promotion rewards', () => {
- before(async function () {
- await beforeEach(this);
- });
-
- it('can not be called by non admin', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ describe('rewards', () => {
+ itSub('can not be called by non admin', async ({helper}) => {
const nonAdmin = accounts.pop()!;
- await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.payoutStakers(100))).to.be.rejected;
+ await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');
});
- });
-
- it('should credit 0.05% for staking period', async () => {
- await usingPlaygrounds(async helper => {
+
+ itSub('should increase total staked', async ({helper}) => {
const staker = accounts.pop()!;
-
+ const totalStakedBefore = await helper.staking.getTotalStaked();
+ await helper.staking.stake(staker, 100n * nominal);
+
+ // Wait for rewards and pay
+ const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));
+ const totalPayout = (await helper.admin.payoutStakers(palletAdmin, 100)).reduce((prev, payout) => prev + payout.payout, 0n);
+
+ const totalStakedAfter = await helper.staking.getTotalStaked();
+ expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);
+ // staker can unstake
+ await helper.staking.unstake(staker);
+ expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedAfter - calculateIncome(100n * nominal, 10n));
+ });
+
+ itSub('should credit 0.05% for staking period', async ({helper}) => {
+ const staker = accounts.pop()!;
+
await waitPromotionPeriodDoesntEnd(helper);
-
+
await helper.staking.stake(staker, 100n * nominal);
await helper.staking.stake(staker, 200n * nominal);
-
+
// wait rewards are available:
- const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[1][0];
- await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock));
-
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
-
- const totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
- expect(totalStakedPerBlock).to.be.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n)]);
+ const [_, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));
+
+ const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)?.payout;
+ expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal, 10n));
+
+ const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ expect(totalStakedPerBlock[0].amount).to.equal(calculateIncome(100n * nominal, 10n));
+ expect(totalStakedPerBlock[1].amount).to.equal(calculateIncome(200n * nominal, 10n));
});
- });
-
- it('shoud be paid for more than one period if payments was missed', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub('shoud be paid for more than one period if payments was missed', async ({helper}) => {
const staker = accounts.pop()!;
-
+
await helper.staking.stake(staker, 100n * nominal);
// wait for two rewards are available:
- const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[0][0];
- await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock) + LOCKING_PERIOD);
-
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
- const stakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);
+
+ await helper.admin.payoutStakers(palletAdmin, 100);
+ [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
const frozenBalanceShouldBe = calculateIncome(100n * nominal, 10n, 2);
- expect(stakedPerBlock[0][1]).to.be.equal(frozenBalanceShouldBe);
-
+ expect(stake.amount).to.be.equal(frozenBalanceShouldBe);
+
const stakerFullBalance = await helper.balance.getSubstrateFull(staker.address);
-
+
expect(stakerFullBalance).to.contain({reserved: 0n, feeFrozen: frozenBalanceShouldBe, miscFrozen: frozenBalanceShouldBe});
});
- });
-
- it('should not be credited for unstaked (reserved) balance', async () => {
- await usingPlaygrounds(async helper => {
+
+ itSub('should not be credited for unstaked (reserved) balance', async ({helper}) => {
// staker unstakes before rewards has been payed
const staker = accounts.pop()!;
await helper.staking.stake(staker, 100n * nominal);
- const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[0][0];
- await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock) + LOCKING_PERIOD);
+ const [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);
await helper.staking.unstake(staker);
-
+
// so he did not receive any rewards
const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
+ await helper.admin.payoutStakers(palletAdmin, 100);
const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);
-
+
expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);
});
- });
-
- it('should bring compound interest', async () => {
- await usingPlaygrounds(async helper => {
+
+ itSub('should bring compound interest', async ({helper}) => {
const staker = accounts.pop()!;
-
+
await helper.staking.stake(staker, 100n * nominal);
-
- const stakedInBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address}))[0][0];
- await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock));
-
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
- let totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
- expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n)]);
-
- await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock) + LOCKING_PERIOD);
- await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
- totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
- expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n, 2)]);
+
+ let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));
+
+ await helper.admin.payoutStakers(palletAdmin, 100);
+ [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ expect(stake.amount).to.equal(calculateIncome(100n * nominal, 10n));
+
+ await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);
+ await helper.admin.payoutStakers(palletAdmin, 100);
+ [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+ expect(stake.amount).to.equal(calculateIncome(100n * nominal, 10n, 2));
});
- });
-
- it.skip('can be paid 1000 rewards in a time', async () => {
- // all other stakes should be unstaked
- await usingPlaygrounds(async (helper) => {
+
+ itSub.skip('can be paid 1000 rewards in a time', async ({helper}) => {
+ // all other stakes should be unstaked
const oneHundredStakers = await helper.arrange.createCrowd(100, 1050n, alice);
-
+
// stakers stakes 10 times each
for (let i = 0; i < 10; i++) {
await Promise.all(oneHundredStakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
}
await helper.wait.newBlocks(40);
- const result = await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
+ await helper.admin.payoutStakers(palletAdmin, 100);
});
- });
-
- it.skip('can handle 40.000 rewards', async () => {
- await usingPlaygrounds(async (helper) => {
+
+ itSub.skip('can handle 40.000 rewards', async ({helper}) => {
const [donor] = await helper.arrange.createAccounts([7_000_000n], alice);
const crowdStakes = async () => {
// each account in the crowd stakes 2 times
@@ -763,11 +687,11 @@
await Promise.all(crowd.map(account => helper.staking.stake(account, 100n * nominal)));
//
};
-
+
for (let i = 0; i < 40; i++) {
await crowdStakes();
}
-
+
// TODO pay rewards for some period
});
});
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -198,8 +198,24 @@
}
`);
}
-}
-
+
+ async deployFlipper(signer: string): Promise<Contract> {
+ return await this.helper.ethContract.deployByCode(signer, 'Flipper', `
+ // SPDX-License-Identifier: UNLICENSED
+ pragma solidity ^0.8.6;
+
+ contract Flipper {
+ bool value = false;
+ function flip() public {
+ value = !value;
+ }
+ function getValue() public view returns (bool) {
+ return value;
+ }
+ }
+ `);
+ }
+}
class EthAddressGroup extends EthGroupBase {
extractCollectionId(address: string): number {
tests/src/tx-version-presence.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/tx-version-presence.test.ts
@@ -0,0 +1,32 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import { Metadata } from '@polkadot/types';
+import {itSub, usingPlaygrounds, expect} from './util/playgrounds';
+
+let metadata: Metadata;
+
+describe('TxVersion is present', () => {
+ before(async () => {
+ await usingPlaygrounds(async helper => {
+ metadata = await helper.api!.rpc.state.getMetadata();
+ });
+ });
+
+ itSub('Signed extension CheckTxVersion is present', async () => {
+ expect(metadata.asLatest.extrinsic.signedExtensions.map(se => se.identifier.toString())).to.include('CheckTxVersion');
+ });
+});
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -147,6 +147,11 @@
feeFrozen: bigint
}
+export interface IStakingInfo {
+ block: bigint,
+ amount: bigint,
+}
+
export type TSubstrateAccount = string;
export type TEthereumAccount = string;
export type TApiAllowedListeners = 'connected' | 'disconnected' | 'error' | 'ready' | 'decorated';
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -60,11 +60,13 @@
*/
arrange: ArrangeGroup;
wait: WaitGroup;
+ admin: AdminGroup;
constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
super(logger);
this.arrange = new ArrangeGroup(this);
this.wait = new WaitGroup(this);
+ this.admin = new AdminGroup(this);
}
async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
@@ -120,6 +122,7 @@
*/
createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {
let nonce = await this.helper.chain.getNonce(donor.address);
+ const wait = new WaitGroup(this.helper);
const ss58Format = this.helper.chain.getChainProperties().ss58Format;
const tokenNominal = this.helper.balance.getOneTokenNominal();
const transactions = [];
@@ -154,7 +157,7 @@
for (let index = 0; index < 5; index++) {
accountsCreated = await checkBalances();
if(accountsCreated) break;
-
+ await wait.newBlocks(1);
}
if (!accountsCreated) throw Error('Accounts generation failed');
@@ -281,3 +284,22 @@
});
}
}
+
+class AdminGroup {
+ helper: UniqueHelper;
+
+ constructor(helper: UniqueHelper) {
+ this.helper = helper;
+ }
+
+ async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {
+ const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);
+ return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {
+ return {
+ staker: e.event.data[0].toString(),
+ stake: e.event.data[1].toBigInt(),
+ payout: e.event.data[2].toBigInt(),
+ };
+ });
+ }
+}
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -9,7 +9,7 @@
import {ApiInterfaceEvents} from '@polkadot/api/types';
import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';
import {IKeyringPair} from '@polkadot/types/types';
-import {IApiListeners, IBlock, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';
+import {IApiListeners, IBlock, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';
export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {
const address = {} as ICrossAccountId;
@@ -2029,21 +2029,54 @@
return 1;
}
+ /**
+ * Get total staked amount for address
+ * @param address substrate or ethereum address
+ * @returns total staked amount
+ */
async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {
if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();
return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();
}
- async getTotalStakedPerBlock(address: ICrossAccountId): Promise<bigint[][]> {
- return (await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);
+ /**
+ * Get total staked per block
+ * @param address substrate or ethereum address
+ * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block
+ */
+ async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {
+ const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);
+ return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {
+ return {
+ block: block.toBigInt(),
+ amount: amount.toBigInt(),
+ };
+ });
}
+ /**
+ * Get total pending unstake amount for address
+ * @param address substrate or ethereum address
+ * @returns total pending unstake amount
+ */
async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {
return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();
}
- async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<bigint[][]> {
- return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address])).map(([block, amount]: any[]) => [block.toBigInt(), amount.toBigInt()]);
+ /**
+ * Get pending unstake amount per block for address
+ * @param address substrate or ethereum address
+ * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block
+ */
+ async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {
+ const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);
+ const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {
+ return {
+ block: block.toBigInt(),
+ amount: amount.toBigInt(),
+ };
+ });
+ return result;
}
}