difftreelog
merge develop
in: master
70 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4940,7 +4940,7 @@
[[package]]
name = "nft"
-version = "3.0.0"
+version = "0.9.12"
dependencies = [
"cumulus-client-cli",
"cumulus-client-collator",
@@ -5076,7 +5076,7 @@
[[package]]
name = "nft-runtime"
-version = "3.0.0"
+version = "0.9.12"
dependencies = [
"cumulus-pallet-aura-ext",
"cumulus-pallet-dmp-queue",
@@ -5109,12 +5109,12 @@
"pallet-fungible",
"pallet-inflation",
"pallet-nft",
- "pallet-nft-charge-transaction",
"pallet-nft-transaction-payment",
"pallet-nonfungible",
"pallet-randomness-collective-flip",
"pallet-refungible",
"pallet-sudo",
+ "pallet-template-transaction-payment",
"pallet-timestamp",
"pallet-transaction-payment",
"pallet-transaction-payment-rpc-runtime-api",
@@ -6074,25 +6074,6 @@
"sp-runtime",
"sp-std",
"up-sponsorship",
-]
-
-[[package]]
-name = "pallet-nft-charge-transaction"
-version = "3.0.0"
-dependencies = [
- "frame-benchmarking",
- "frame-support",
- "frame-system",
- "pallet-balances",
- "pallet-nft-transaction-payment",
- "pallet-transaction-payment",
- "parity-scale-codec",
- "scale-info",
- "serde",
- "sp-core",
- "sp-io",
- "sp-runtime",
- "sp-std",
]
[[package]]
@@ -6370,6 +6351,26 @@
]
[[package]]
+name = "pallet-template-transaction-payment"
+version = "3.0.0"
+source = "git+https://github.com/UniqueNetwork/pallet-sponsoring#ab8b91e9350a31133f3a3e4f52a84c6de4108e95"
+dependencies = [
+ "frame-benchmarking",
+ "frame-support",
+ "frame-system",
+ "pallet-balances",
+ "pallet-transaction-payment",
+ "parity-scale-codec",
+ "scale-info",
+ "serde",
+ "sp-core",
+ "sp-io",
+ "sp-runtime",
+ "sp-std",
+ "up-sponsorship",
+]
+
+[[package]]
name = "pallet-timestamp"
version = "4.0.0-dev"
source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.12#d76f39995315ec36980908e4b99709bd14927044"
@@ -11847,6 +11848,7 @@
[[package]]
name = "up-sponsorship"
version = "0.1.0"
+source = "git+https://github.com/UniqueNetwork/pallet-sponsoring#ab8b91e9350a31133f3a3e4f52a84c6de4108e95"
dependencies = [
"impl-trait-for-tuples 0.2.1",
]
README.mddiffbeforeafterboth--- a/README.md
+++ b/README.md
@@ -41,7 +41,7 @@
- Re-Fungible Token Mode
- Off-Chain Schema to store token image URLs
- Alternative economic model
- - White Lists and Public Mint Permission
+ - Allow Lists and Public Mint Permission
- Use example: [SubstraPunks Game](https://github.com/usetech-llc/substrapunks), fully hosted on IPFS and NFT Testnet
Blockchain.
doc/builders_walk_through.mddiffbeforeafterboth--- a/doc/builders_walk_through.md
+++ b/doc/builders_walk_through.md
@@ -173,11 +173,11 @@
6. Now select your "ZERO BALANCE" address in the drop-down list and repeat searching and adding the collection for this address.
7. Transfer token back to your main address. Observe that despite the zero balance, the transfer is successful.
-### White Lists and Public Mint Permission
+### Allow Lists and Public Mint Permission
-We did not complete these features in time by Hackusama deadline, but because they are important for security of the network, we completed them after the deadline anyway. They can be seen in branch [feature/white_list](https://github.com/usetech-llc/nft_parachain/tree/feature/white_list). Here are the permalinks to essential functions:
+We did not complete these features in time by Hackusama deadline, but because they are important for security of the network, we completed them after the deadline anyway. They can be seen in branch [feature/allow_list](https://github.com/usetech-llc/nft_parachain/tree/feature/allow_list). Here are the permalinks to essential functions:
-[white_lists](https://github.com/usetech-llc/nft_parachain/blob/b7c59f0085ed2bc1922e937adf68ef4174a8ba36/pallets/nft/src/lib.rs#L659)
+[allow_lists](https://github.com/usetech-llc/nft_parachain/blob/b7c59f0085ed2bc1922e937adf68ef4174a8ba36/pallets/nft/src/lib.rs#L659)
[mint_permission](https://github.com/usetech-llc/nft_parachain/blob/b7c59f0085ed2bc1922e937adf68ef4174a8ba36/pallets/nft/src/lib.rs#L373)
doc/economic_model.mddiffbeforeafterboth--- a/doc/economic_model.md
+++ b/doc/economic_model.md
@@ -40,7 +40,7 @@
Set the collection sponsor address. The sponsorship needs to be confirmed by sending a ConfirmSponsorship transaction
from that address. Also, the protection measures need to be in place so that sponsor account cannot be depleted by
-malicious users. White listing is one of the measured. It can be enabled with SetPublicAccessMode method.
+malicious users. Allow listing is one of the measured. It can be enabled with SetPublicAccessMode method.
##### List of transactions
@@ -67,7 +67,7 @@
Further, the logic is similar to limiting by token as above. If only one of the limits (by token or by address)
indicates that fee should be paid by the user, the fee is paid by the user.
- A pallet method (SetCollectionRateLimits) will be added to set these parameters and enable rate limiting.
-- One idea to consider is deposits that must be made by an address in order to become white listed (instead of admin
+- One idea to consider is deposits that must be made by an address in order to become allow listed (instead of admin
review).
#### Permissions
@@ -173,12 +173,12 @@
#### Description
-Toggle between normal and white list access for the methods with access for “Anyone”. If White List mode is enabled,
-AddToWhiteList and RemoveFromWhiteList methods can be called to add to and remove addresses from the white list.
+Toggle between normal and allow list access for the methods with access for “Anyone”. If Allow List mode is enabled,
+AddToAllowList and RemoveFromAllowList methods can be called to add to and remove addresses from the allow list.
-White list mode is the property of collection. If it is turned on, all public operations such as token transfers, for
-example, which normally have “Anyone” permission, become white listed, i.e. are only available to collection owner,
-admins, and addresses from the white list. White lists can be helpful for rate limiting of transfers when collection
+Allow list mode is the property of collection. If it is turned on, all public operations such as token transfers, for
+example, which normally have “Anyone” permission, become allow listed, i.e. are only available to collection owner,
+admins, and addresses from the allow list. Allow lists can be helpful for rate limiting of transfers when collection
sponsoring is enabled.
#### Permissions
@@ -190,13 +190,13 @@
- CollectionID: ID of the Collection to set access mode for
- Mode
- 0 = Normal
- - 1 = White list
+ - 1 = Allow list
-### AddToWhiteList
+### AddToAllowList
#### Description
-Add an address to white list.
+Add an address to allow list.
#### Permissions
@@ -208,11 +208,11 @@
- CollectionID: ID of the Collection
- Address
-### RemoveFromWhiteList
+### RemoveFromAllowList
#### Description
-Remove an address from white list.
+Remove an address from allow list.
#### Permissions
doc/hackusama_walk_through.mddiffbeforeafterboth--- a/doc/hackusama_walk_through.md
+++ b/doc/hackusama_walk_through.md
@@ -187,14 +187,14 @@
address.
7. Transfer token back to your main address. Observe that despite the zero balance, the transfer is successful.
-### White Lists and Public Mint Permission
+### Allow Lists and Public Mint Permission
We did not complete these features in time by Hackusama deadline, but because they are important for security of the
network, we completed them after the deadline anyway. They can be seen in branch
-[feature/white_list](https://github.com/usetech-llc/nft_parachain/tree/feature/white_list). Here are the permalinks to
+[feature/allow_list](https://github.com/usetech-llc/nft_parachain/tree/feature/allow_list). Here are the permalinks to
essential functions:
-[white_lists](https://github.com/usetech-llc/nft_parachain/blob/b7c59f0085ed2bc1922e937adf68ef4174a8ba36/pallets/nft/src/lib.rs#L659)
+[allow_lists](https://github.com/usetech-llc/nft_parachain/blob/b7c59f0085ed2bc1922e937adf68ef4174a8ba36/pallets/nft/src/lib.rs#L659)
[mint_permission](https://github.com/usetech-llc/nft_parachain/blob/b7c59f0085ed2bc1922e937adf68ef4174a8ba36/pallets/nft/src/lib.rs#L373)
doc/milestone_1.mddiffbeforeafterboth--- a/doc/milestone_1.md
+++ b/doc/milestone_1.md
@@ -1,38 +1,38 @@
## Milestone 1
-**User Paid Fees and Sponsored. Finish/Debug white listing and spam/DOS protection**
+**User Paid Fees and Sponsored. Finish/Debug allow listing and spam/DOS protection**
Implementation of two models
If collection sponsor is set and confirmed for collection instance that means Sponsored Economic Model has chosen. Otherwise default economic model User Paid Fees is set.
-For Sponsored Economic Model exists timeouts for token transactions. For every NFT type timeouts defined separately. Timeouts and white list limits together prevented spam and malicious actions.
+For Sponsored Economic Model exists timeouts for token transactions. For every NFT type timeouts defined separately. Timeouts and allow list limits together prevented spam and malicious actions.
Set sponsor
`nft`.`set_collection_sponsor`
Confirm sponsor
`nft`.`confirm_sponsorship`
-A white list mode presented by collection property `access` and can be enabled with `set_public_access_mode`. Rules provide spam/DOS protection
-While collection in the white list mode rules below are active:
-Owner can add address to white list
-Admin can add address to white list
-Non-privileged user cannot add address to white list
-Owner can remove address from white list
-Admin can remove address from white list
-Non-privileged user cannot remove address from white list
-If Public Access mode is set to WhiteList, tokens can’t be transferred from a non-whitelisted address with transfer or transferFrom
-If Public Access mode is set to WhiteList, tokens can’t be transferred to a non-whitelisted address with transfer or transferFrom
-If Public Access mode is set to WhiteList, tokens can’t be destroyed by a non-whitelisted address (even if it owned them before enabling WhiteList mode)
-If Public Access mode is set to WhiteList, token transfers can’t be Approved by a non-whitelisted address (see Approve method).
-If Public Access mode is set to WhiteList, tokens can be transferred to a whitelisted address with transfer or transferFrom
-If Public Access mode is set to WhiteList, tokens can be transferred from a whitelisted address with transfer or transferFrom
-If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens can be created by owner.
-If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens can be created by admin.
-If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens cannot be created by non-privileged and white listed address.
-If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens cannot be created by non-privileged and non-white listed address.
-If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by owner.
-If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by admin.
-If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens cannot be created by non-privileged and non-white listed address.
-If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by non-privileged and white listed address.
+A allow list mode presented by collection property `access` and can be enabled with `set_public_access_mode`. Rules provide spam/DOS protection
+While collection in the allow list mode rules below are active:
+Owner can add address to allow list
+Admin can add address to allow list
+Non-privileged user cannot add address to allow list
+Owner can remove address from allow list
+Admin can remove address from allow list
+Non-privileged user cannot remove address from allow list
+If Public Access mode is set to AllowList, tokens can’t be transferred from a non-allowlisted address with transfer or transferFrom
+If Public Access mode is set to AllowList, tokens can’t be transferred to a non-allowlisted address with transfer or transferFrom
+If Public Access mode is set to AllowList, tokens can’t be destroyed by a non-allowlisted address (even if it owned them before enabling AllowList mode)
+If Public Access mode is set to AllowList, token transfers can’t be Approved by a non-allowlisted address (see Approve method).
+If Public Access mode is set to AllowList, tokens can be transferred to a allowlisted address with transfer or transferFrom
+If Public Access mode is set to AllowList, tokens can be transferred from a allowlisted address with transfer or transferFrom
+If Public Access mode is set to AllowList, and Mint Permission is set to false, tokens can be created by owner.
+If Public Access mode is set to AllowList, and Mint Permission is set to false, tokens can be created by admin.
+If Public Access mode is set to AllowList, and Mint Permission is set to false, tokens cannot be created by non-privileged and allow listed address.
+If Public Access mode is set to AllowList, and Mint Permission is set to false, tokens cannot be created by non-privileged and non-allow listed address.
+If Public Access mode is set to AllowList, and Mint Permission is set to true, tokens can be created by owner.
+If Public Access mode is set to AllowList, and Mint Permission is set to true, tokens can be created by admin.
+If Public Access mode is set to AllowList, and Mint Permission is set to true, tokens cannot be created by non-privileged and non-allow listed address.
+If Public Access mode is set to AllowList, and Mint Permission is set to true, tokens can be created by non-privileged and allow listed address.
**Add missing custom types (CollectionMode, FungibleItemType, ReFungibleItemType)**
docker-compose-tests-parachain.ymldiffbeforeafterboth--- a/docker-compose-tests-parachain.yml
+++ b/docker-compose-tests-parachain.yml
@@ -2,12 +2,6 @@
services:
blockchain_nodes:
- image: blockchain_nodes
- container_name: blockchain_nodes
- ports:
- - 9944:9944
- - 9844:9844
- - 9933:9933
build:
context: ./
dockerfile: Dockerfile-parachain
@@ -17,18 +11,11 @@
- POLKA_VERSION=${POLKA_VERSION:?err}
- NFT_BRANCH=${NFT_BRANCH:?err}
volumes:
-# - ./chain-data:/chain-data
- ./launch-config.json:/polkadot-launch/launch-config.json
env_file:
- ./.env
- networks:
- - node_test_network
- #command: bash -c "yarn --cwd polkadot-launch start"
- #command: bash -c 'while true; do sleep 60; df -h; done'
integration_tests:
- container_name: integration_tests
- image: integration_tests
build:
context: tests/
dockerfile: Dockerfile-tests
@@ -37,25 +24,5 @@
volumes:
- ./tests/src/config_docker.ts:/nft_parachain/src/config.ts
- /home/ubuntu/mochawesome-report:/nft_parachain/mochawesome-report
-# command: bash -c 'while true; do sleep 20; df -h; done'
- networks:
- - node_test_network
depends_on:
- blockchain_nodes
-
-# unit_tests:
-# container_name: unit_test
-# image: nft_unit_test
-# build:
-# context: ./
-# dockerfile: Dockerfile-unit
-# container_name: unit_test
-# networks:
-# - node_test_network
- # command: bash -c 'while true; do sleep 20; df -h; done'
-# command: bash -c 'cargo test'
-
-networks:
- node_test_network:
- name: node_test_network
- driver: bridge
node/cli/Cargo.tomldiffbeforeafterboth--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -233,7 +233,7 @@
[dependencies.nft-runtime]
path = '../../runtime'
-version = '3.0.0'
+version = '0.9.12'
[dependencies.nft-data-structs]
path = "../../primitives/nft"
@@ -251,7 +251,7 @@
license = 'All Rights Reserved'
name = 'nft'
repository = 'https://github.com/usetech-llc/nft_private/'
-version = '3.0.0'
+version = '0.9.12'
[[bin]]
name = 'nft'
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -260,7 +260,7 @@
NoPermission,
/// Collection is not in mint mode.
PublicMintingNotAllowed,
- /// Address is not in white list.
+ /// Address is not in allow list.
AddressNotInAllowlist,
/// Collection name can not be longer than 63 char.
pallets/contract-helpers/Cargo.tomldiffbeforeafterboth--- a/pallets/contract-helpers/Cargo.toml
+++ b/pallets/contract-helpers/Cargo.toml
@@ -9,11 +9,6 @@
package = 'parity-scale-codec'
version = '2.3.0'
-[dependencies.up-sponsorship]
-default-features = false
-path = '../../primitives/sponsorship'
-version = '0.1.0'
-
[dependencies]
scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
@@ -21,6 +16,7 @@
pallet-contracts = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring" }
[features]
default = ["std"]
pallets/evm-contract-helpers/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-contract-helpers/Cargo.toml
+++ b/pallets/evm-contract-helpers/Cargo.toml
@@ -15,7 +15,7 @@
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
-up-sponsorship = { default-features = false, path = '../../primitives/sponsorship' }
+up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring" }
log = "0.4.14"
[dependencies.codec]
pallets/evm-transaction-payment/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-transaction-payment/Cargo.toml
+++ b/pallets/evm-transaction-payment/Cargo.toml
@@ -16,7 +16,7 @@
pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
-up-sponsorship = { default-features = false, path = '../../primitives/sponsorship' }
+up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring" }
[dependencies.codec]
default-features = false
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -132,7 +132,7 @@
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
collection.check_allowlist(owner)?;
}
@@ -170,7 +170,7 @@
<CommonError<T>>::TransferNotAllowed,
);
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
collection.check_allowlist(from)?;
collection.check_allowlist(to)?;
}
@@ -302,7 +302,7 @@
spender: &T::CrossAccountId,
amount: u128,
) -> DispatchResult {
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
collection.check_allowlist(&owner)?;
collection.check_allowlist(&spender)?;
}
@@ -330,7 +330,7 @@
if spender.conv_eq(from) {
return Self::transfer(collection, from, to, amount);
}
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
// `from`, `to` checked in [`transfer`]
collection.check_allowlist(spender)?;
}
@@ -361,7 +361,7 @@
if spender.conv_eq(from) {
return Self::burn(collection, from, amount);
}
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
// `from` checked in [`burn`]
collection.check_allowlist(spender)?;
}
pallets/nft-charge-transaction/Cargo.tomldiffbeforeafterboth--- a/pallets/nft-charge-transaction/Cargo.toml
+++ /dev/null
@@ -1,50 +0,0 @@
-[package]
-authors = ['Substrate DevHub <https://github.com/substrate-developer-hub>']
-description = 'Unqiue pallet nft specific transaction payment'
-edition = '2018'
-homepage = 'https://substrate.io'
-license = 'Unlicense'
-name = 'pallet-nft-charge-transaction'
-repository = 'https://github.com/usetech-llc/nft_private/'
-version = '3.0.0'
-
-[package.metadata.docs.rs]
-targets = ['x86_64-unknown-linux-gnu']
-
-# alias "parity-scale-code" to "codec"
-[dependencies.codec]
-default-features = false
-features = ['derive']
-package = 'parity-scale-codec'
-version = '2.3.0'
-
-[dependencies]
-scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
-serde = { version = "1.0.130", default-features = false }
-frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-pallet-balances = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-pallet-transaction-payment = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-sp-io = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-
-pallet-nft-transaction-payment = { default-features = false, path = "../nft-transaction-payment" }
-
-[features]
-default = ['std']
-std = [
- 'codec/std',
- 'serde/std',
- 'frame-support/std',
- 'frame-system/std',
- 'pallet-balances/std',
- 'pallet-transaction-payment/std',
- 'pallet-nft-transaction-payment/std',
- 'sp-std/std',
- 'sp-runtime/std',
- 'frame-benchmarking/std',
-]
-runtime-benchmarks = ["frame-benchmarking"]
pallets/nft-charge-transaction/src/lib.rsdiffbeforeafterboth--- a/pallets/nft-charge-transaction/src/lib.rs
+++ /dev/null
@@ -1,196 +0,0 @@
-//
-// This file is subject to the terms and conditions defined in
-// file 'LICENSE', which is part of this source code package.
-//
-
-#![cfg_attr(not(feature = "std"), no_std)]
-
-#[cfg(feature = "std")]
-pub use std::*;
-
-use scale_info::TypeInfo;
-#[cfg(feature = "std")]
-pub use serde::*;
-
-use codec::{Decode, Encode};
-use frame_support::traits::Get;
-use frame_support::{
- decl_module, decl_storage,
- weights::{DispatchInfo, PostDispatchInfo, DispatchClass},
-};
-use sp_runtime::{
- traits::{
- DispatchInfoOf, Dispatchable, PostDispatchInfoOf, Saturating, SaturatedConversion,
- SignedExtension, Zero,
- },
- transaction_validity::{
- TransactionPriority, TransactionValidity, TransactionValidityError, ValidTransaction,
- },
- FixedPointOperand, DispatchResult,
-};
-use pallet_transaction_payment::OnChargeTransaction;
-use sp_std::prelude::*;
-
-pub trait Config: frame_system::Config + pallet_nft_transaction_payment::Config + TypeInfo {}
-
-decl_storage! {
- trait Store for Module<T: Config> as NftTransactionPayment
- {}
-}
-
-decl_module! {
-
- pub struct Module<T: Config> for enum Call
- where
- origin: T::Origin,
- {}
-}
-
-type BalanceOf<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::Balance;
-
-/// Require the transactor pay for themselves and maybe include a tip to gain additional priority
-/// in the queue.
-#[derive(Encode, Decode, Clone, Eq, PartialEq, scale_info::TypeInfo)]
-pub struct ChargeTransactionPayment<T: Config>(#[codec(compact)] BalanceOf<T>);
-
-impl<T: Config + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {
- #[cfg(feature = "std")]
- fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
- write!(f, "ChargeTransactionPayment<{:?}>", self.0)
- }
- #[cfg(not(feature = "std"))]
- fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
- Ok(())
- }
-}
-
-impl<T: Config> ChargeTransactionPayment<T>
-where
- T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
- BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,
-{
- fn traditional_fee(
- len: usize,
- info: &DispatchInfoOf<T::Call>,
- tip: BalanceOf<T>,
- ) -> BalanceOf<T>
- where
- T::Call: Dispatchable<Info = DispatchInfo>,
- {
- <pallet_transaction_payment::Pallet<T>>::compute_fee(len as u32, info, tip)
- }
-
- fn get_priority(
- len: usize,
- info: &DispatchInfoOf<T::Call>,
- final_fee: BalanceOf<T>,
- ) -> TransactionPriority {
- let weight_saturation = T::BlockWeights::get().max_block / info.weight.max(1);
- let max_block_length = *T::BlockLength::get().max.get(DispatchClass::Normal);
- let len_saturation = max_block_length as u64 / (len as u64).max(1);
- let coefficient: BalanceOf<T> = weight_saturation
- .min(len_saturation)
- .saturated_into::<BalanceOf<T>>();
- final_fee
- .saturating_mul(coefficient)
- .saturated_into::<TransactionPriority>()
- }
-
- #[allow(clippy::type_complexity)]
- fn withdraw_fee(
- &self,
- who: &T::AccountId,
- call: &T::Call,
- info: &DispatchInfoOf<T::Call>,
- len: usize,
- ) -> Result<
- (
- BalanceOf<T>,
- <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,
- ),
- TransactionValidityError,
- >{
- let tip = self.0;
-
- let fee = Self::traditional_fee(len, info, tip);
-
- // Only mess with balances if fee is not zero.
- if fee.is_zero() {
- return <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(who, call, info, fee, tip)
- .map(|i| (fee, i));
- }
-
- // Determine who is paying transaction fee based on ecnomic model
- // Parse call to extract collection ID and access collection sponsor
- let sponsor = <pallet_nft_transaction_payment::Module<T>>::withdraw_type(who, call);
-
- let who_pays_fee = sponsor.unwrap_or_else(|| who.clone());
-
- <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(&who_pays_fee, call, info, fee, tip)
- .map(|i| (fee, i))
- }
-}
-
-impl<T: Config + Send + Sync> SignedExtension for ChargeTransactionPayment<T>
-where
- BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,
- T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
-{
- const IDENTIFIER: &'static str = "ChargeTransactionPayment";
- type AccountId = T::AccountId;
- type Call = T::Call;
- type AdditionalSigned = ();
- type Pre = (
- // tip
- BalanceOf<T>,
- // who pays fee
- Self::AccountId,
- // imbalance resulting from withdrawing the fee
- <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,
- );
- fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {
- Ok(())
- }
-
- fn validate(
- &self,
- who: &Self::AccountId,
- call: &Self::Call,
- info: &DispatchInfoOf<Self::Call>,
- len: usize,
- ) -> TransactionValidity {
- let (fee, _) = self.withdraw_fee(who, call, info, len)?;
- Ok(ValidTransaction {
- priority: Self::get_priority(len, info, fee),
- ..Default::default()
- })
- }
-
- fn pre_dispatch(
- self,
- who: &Self::AccountId,
- call: &Self::Call,
- info: &DispatchInfoOf<Self::Call>,
- len: usize,
- ) -> Result<Self::Pre, TransactionValidityError> {
- let (_fee, imbalance) = self.withdraw_fee(who, call, info, len)?;
- Ok((self.0, who.clone(), imbalance))
- }
-
- fn post_dispatch(
- pre: Self::Pre,
- info: &DispatchInfoOf<Self::Call>,
- post_info: &PostDispatchInfoOf<Self::Call>,
- len: usize,
- _result: &DispatchResult,
- ) -> Result<(), TransactionValidityError> {
- let (tip, who, imbalance) = pre;
- let actual_fee = pallet_transaction_payment::Pallet::<T>::compute_actual_fee(
- len as u32, info, post_info, tip,
- );
- <T as pallet_transaction_payment::Config>::OnChargeTransaction::correct_and_deposit_fee(
- &who, info, post_info, actual_fee, tip, imbalance,
- )?;
- Ok(())
- }
-}
pallets/nft-transaction-payment/Cargo.tomldiffbeforeafterboth--- a/pallets/nft-transaction-payment/Cargo.toml
+++ b/pallets/nft-transaction-payment/Cargo.toml
@@ -30,7 +30,7 @@
sp-io = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-up-sponsorship = { default-features = false, path = "../../primitives/sponsorship", version = "0.1.0" }
+up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring" }
[features]
default = ['std']
pallets/nft/Cargo.tomldiffbeforeafterboth--- a/pallets/nft/Cargo.toml
+++ b/pallets/nft/Cargo.toml
@@ -126,12 +126,6 @@
path = '../../primitives/nft'
version = '0.9.0'
-[dependencies.up-sponsorship]
-default-features = false
-path = '../../primitives/sponsorship'
-version = '0.1.0'
-
-
[dependencies]
scale-info = { version = "1.0.0", default-features = false, features = [
"derive",
@@ -140,6 +134,8 @@
rlp = { default-features = false, version = "0.5.0" }
sp-api = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.12" }
+up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring" }
+
evm-coder = { default-features = false, path = "../../crates/evm-coder" }
pallet-evm-coder-substrate = { default-features = false, path = "../../pallets/evm-coder-substrate" }
primitive-types = { version = "0.10.1", default-features = false, features = [
pallets/nft/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nft/src/benchmarking.rs
+++ b/pallets/nft/src/benchmarking.rs
@@ -55,23 +55,23 @@
let collection = create_nft_collection::<T>(caller.clone())?;
}: _(RawOrigin::Signed(caller.clone()), collection)
- add_to_white_list {
+ add_to_allow_list {
let caller: T::AccountId = account("caller", 0, SEED);
- let whitelist_account: T::AccountId = account("admin", 0, SEED);
+ let allowlist_account: T::AccountId = account("admin", 0, SEED);
let collection = create_nft_collection::<T>(caller.clone())?;
- }: _(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(whitelist_account))
+ }: _(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(allowlist_account))
- remove_from_white_list {
+ remove_from_allow_list {
let caller: T::AccountId = account("caller", 0, SEED);
- let whitelist_account: T::AccountId = account("admin", 0, SEED);
+ let allowlist_account: T::AccountId = account("admin", 0, SEED);
let collection = create_nft_collection::<T>(caller.clone())?;
- <Pallet<T>>::add_to_white_list(RawOrigin::Signed(caller.clone()).into(), collection, T::CrossAccountId::from_sub(whitelist_account.clone()))?;
- }: _(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(whitelist_account))
+ <Pallet<T>>::add_to_allow_list(RawOrigin::Signed(caller.clone()).into(), collection, T::CrossAccountId::from_sub(allowlist_account.clone()))?;
+ }: _(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(allowlist_account))
set_public_access_mode {
let caller: T::AccountId = account("caller", 0, SEED);
let collection = create_nft_collection::<T>(caller.clone())?;
- }: _(RawOrigin::Signed(caller.clone()), collection, AccessMode::WhiteList)
+ }: _(RawOrigin::Signed(caller.clone()), collection, AccessMode::AllowList)
set_mint_permission {
let caller: T::AccountId = account("caller", 0, SEED);
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -256,7 +256,7 @@
Ok(())
}
- /// Add an address to white list.
+ /// Add an address to allow list.
///
/// # Permissions
///
@@ -268,9 +268,9 @@
/// * collection_id.
///
/// * address.
- #[weight = <SelfWeightOf<T>>::add_to_white_list()]
+ #[weight = <SelfWeightOf<T>>::add_to_allow_list()]
#[transactional]
- pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{
+ pub fn add_to_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let collection = <CollectionHandle<T>>::try_get(collection_id)?;
@@ -285,7 +285,7 @@
Ok(())
}
- /// Remove an address from white list.
+ /// Remove an address from allow list.
///
/// # Permissions
///
@@ -297,9 +297,9 @@
/// * collection_id.
///
/// * address.
- #[weight = <SelfWeightOf<T>>::remove_from_white_list()]
+ #[weight = <SelfWeightOf<T>>::remove_from_allow_list()]
#[transactional]
- pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{
+ pub fn remove_from_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let collection = <CollectionHandle<T>>::try_get(collection_id)?;
@@ -314,7 +314,7 @@
Ok(())
}
- /// Toggle between normal and white list access for the methods with access for `Anyone`.
+ /// Toggle between normal and allow list access for the methods with access for `Anyone`.
///
/// # Permissions
///
@@ -339,8 +339,8 @@
}
/// Allows Anyone to create tokens if:
- /// * White List is enabled, and
- /// * Address is added to white list, and
+ /// * Allow List is enabled, and
+ /// * Address is added to allow list, and
/// * This method was called with True parameter
///
/// # Permissions
@@ -502,8 +502,8 @@
/// * Collection Owner.
/// * Collection Admin.
/// * Anyone if
- /// * White List is enabled, and
- /// * Address is added to white list, and
+ /// * Allow List is enabled, and
+ /// * Address is added to allow list, and
/// * MintPermission is enabled (see SetMintPermission method)
///
/// # Arguments
@@ -528,8 +528,8 @@
/// * Collection Owner.
/// * Collection Admin.
/// * Anyone if
- /// * White List is enabled, and
- /// * Address is added to white list, and
+ /// * Allow List is enabled, and
+ /// * Address is added to allow list, and
/// * MintPermission is enabled (see SetMintPermission method)
///
/// # Arguments
pallets/nft/src/tests.rsdiffbeforeafterboth--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -460,7 +460,7 @@
}
#[test]
-fn nft_approve_and_transfer_from_white_list() {
+fn nft_approve_and_transfer_from_allow_list() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -485,19 +485,19 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
1,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(1)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(2)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(3)
@@ -549,19 +549,19 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
1,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(1)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(2)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(3)
@@ -609,19 +609,19 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
1,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(1)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(2)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(3)
@@ -765,9 +765,9 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(1)
@@ -952,19 +952,19 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
1,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(1)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(2)
));
- assert_ok!(TemplateModule::add_to_white_list(origin1, 1, account(3)));
+ assert_ok!(TemplateModule::add_to_allow_list(origin1, 1, account(3)));
assert_ok!(TemplateModule::transfer_from(
origin2,
@@ -987,22 +987,22 @@
// #region
#[test]
-fn owner_can_add_address_to_white_list() {
+fn owner_can_add_address_to_allow_list() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
let origin1 = Origin::signed(1);
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1,
collection_id,
account(2)
));
- assert!(TemplateModule::white_list(collection_id, 2));
+ assert!(TemplateModule::allow_list(collection_id, 2));
});
}
#[test]
-fn admin_can_add_address_to_white_list() {
+fn admin_can_add_address_to_allow_list() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
let origin1 = Origin::signed(1);
@@ -1013,42 +1013,42 @@
collection_id,
account(2)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin2,
collection_id,
account(3)
));
- assert!(TemplateModule::white_list(collection_id, 3));
+ assert!(TemplateModule::allow_list(collection_id, 3));
});
}
#[test]
-fn nonprivileged_user_cannot_add_address_to_white_list() {
+fn nonprivileged_user_cannot_add_address_to_allow_list() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
let origin2 = Origin::signed(2);
assert_noop!(
- TemplateModule::add_to_white_list(origin2, collection_id, account(3)),
+ TemplateModule::add_to_allow_list(origin2, collection_id, account(3)),
Error::<Test>::NoPermission
);
});
}
#[test]
-fn nobody_can_add_address_to_white_list_of_nonexisting_collection() {
+fn nobody_can_add_address_to_allow_list_of_nonexisting_collection() {
new_test_ext().execute_with(|| {
let origin1 = Origin::signed(1);
assert_noop!(
- TemplateModule::add_to_white_list(origin1, 1, account(2)),
+ TemplateModule::add_to_allow_list(origin1, 1, account(2)),
Error::<Test>::CollectionNotFound
);
});
}
#[test]
-fn nobody_can_add_address_to_white_list_of_deleted_collection() {
+fn nobody_can_add_address_to_allow_list_of_deleted_collection() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1058,55 +1058,55 @@
collection_id
));
assert_noop!(
- TemplateModule::add_to_white_list(origin1, collection_id, account(2)),
+ TemplateModule::add_to_allow_list(origin1, collection_id, account(2)),
Error::<Test>::CollectionNotFound
);
});
}
-// If address is already added to white list, nothing happens
+// If address is already added to allow list, nothing happens
#[test]
-fn address_is_already_added_to_white_list() {
+fn address_is_already_added_to_allow_list() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
let origin1 = Origin::signed(1);
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
collection_id,
account(2)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1,
collection_id,
account(2)
));
- assert!(TemplateModule::white_list(collection_id, 2));
+ assert!(TemplateModule::allow_list(collection_id, 2));
});
}
#[test]
-fn owner_can_remove_address_from_white_list() {
+fn owner_can_remove_address_from_allow_list() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
let origin1 = Origin::signed(1);
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
collection_id,
account(2)
));
- assert_ok!(TemplateModule::remove_from_white_list(
+ assert_ok!(TemplateModule::remove_from_allow_list(
origin1,
collection_id,
account(2)
));
- assert!(!TemplateModule::white_list(collection_id, 2));
+ assert!(!TemplateModule::allow_list(collection_id, 2));
});
}
#[test]
-fn admin_can_remove_address_from_white_list() {
+fn admin_can_remove_address_from_allow_list() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
let origin1 = Origin::signed(1);
@@ -1118,102 +1118,102 @@
account(2)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1,
collection_id,
account(3)
));
- assert_ok!(TemplateModule::remove_from_white_list(
+ assert_ok!(TemplateModule::remove_from_allow_list(
origin2,
collection_id,
account(3)
));
- assert!(!TemplateModule::white_list(collection_id, 3));
+ assert!(!TemplateModule::allow_list(collection_id, 3));
});
}
#[test]
-fn nonprivileged_user_cannot_remove_address_from_white_list() {
+fn nonprivileged_user_cannot_remove_address_from_allow_list() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1,
collection_id,
account(2)
));
assert_noop!(
- TemplateModule::remove_from_white_list(origin2, collection_id, account(2)),
+ TemplateModule::remove_from_allow_list(origin2, collection_id, account(2)),
Error::<Test>::NoPermission
);
- assert!(TemplateModule::white_list(collection_id, 2));
+ assert!(TemplateModule::allow_list(collection_id, 2));
});
}
#[test]
-fn nobody_can_remove_address_from_white_list_of_nonexisting_collection() {
+fn nobody_can_remove_address_from_allow_list_of_nonexisting_collection() {
new_test_ext().execute_with(|| {
let origin1 = Origin::signed(1);
assert_noop!(
- TemplateModule::remove_from_white_list(origin1, 1, account(2)),
+ TemplateModule::remove_from_allow_list(origin1, 1, account(2)),
Error::<Test>::CollectionNotFound
);
});
}
#[test]
-fn nobody_can_remove_address_from_white_list_of_deleted_collection() {
+fn nobody_can_remove_address_from_allow_list_of_deleted_collection() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
collection_id,
account(2)
));
assert_ok!(TemplateModule::destroy_collection(origin1, collection_id));
assert_noop!(
- TemplateModule::remove_from_white_list(origin2, collection_id, account(2)),
+ TemplateModule::remove_from_allow_list(origin2, collection_id, account(2)),
Error::<Test>::CollectionNotFound
);
- assert!(!TemplateModule::white_list(collection_id, 2));
+ assert!(!TemplateModule::allow_list(collection_id, 2));
});
}
-// If address is already removed from white list, nothing happens
+// If address is already removed from allow list, nothing happens
#[test]
-fn address_is_already_removed_from_white_list() {
+fn address_is_already_removed_from_allow_list() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
let origin1 = Origin::signed(1);
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
collection_id,
account(2)
));
- assert_ok!(TemplateModule::remove_from_white_list(
+ assert_ok!(TemplateModule::remove_from_allow_list(
origin1.clone(),
collection_id,
account(2)
));
- assert_ok!(TemplateModule::remove_from_white_list(
+ assert_ok!(TemplateModule::remove_from_allow_list(
origin1,
collection_id,
account(2)
));
- assert!(!TemplateModule::white_list(collection_id, 2));
+ assert!(!TemplateModule::allow_list(collection_id, 2));
});
}
-// If Public Access mode is set to WhiteList, tokens can’t be transferred from a non-whitelisted address with transfer or transferFrom (2 tests)
+// If Public Access mode is set to AllowList, tokens can’t be transferred from a non-allowlisted address with transfer or transferFrom (2 tests)
#[test]
-fn white_list_test_1() {
+fn allow_list_test_1() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1225,9 +1225,9 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
collection_id,
account(2)
@@ -1235,13 +1235,13 @@
assert_noop!(
TemplateModule::transfer(origin1, account(3), 1, 1, 1),
- Error::<Test>::AddresNotInWhiteList
+ Error::<Test>::AddresNotInAllowList
);
});
}
#[test]
-fn white_list_test_2() {
+fn allow_list_test_2() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
let origin1 = Origin::signed(1);
@@ -1252,14 +1252,14 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(1)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(2)
@@ -1275,7 +1275,7 @@
));
assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 1);
- assert_ok!(TemplateModule::remove_from_white_list(
+ assert_ok!(TemplateModule::remove_from_allow_list(
origin1.clone(),
1,
account(1)
@@ -1283,14 +1283,14 @@
assert_noop!(
TemplateModule::transfer_from(origin1, account(1), account(3), 1, 1, 1),
- Error::<Test>::AddresNotInWhiteList
+ Error::<Test>::AddresNotInAllowList
);
});
}
-// If Public Access mode is set to WhiteList, tokens can’t be transferred to a non-whitelisted address with transfer or transferFrom (2 tests)
+// If Public Access mode is set to AllowList, tokens can’t be transferred to a non-allowlisted address with transfer or transferFrom (2 tests)
#[test]
-fn white_list_test_3() {
+fn allow_list_test_3() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1302,9 +1302,9 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
1,
account(1)
@@ -1312,13 +1312,13 @@
assert_noop!(
TemplateModule::transfer(origin1, account(3), 1, 1, 1),
- Error::<Test>::AddresNotInWhiteList
+ Error::<Test>::AddresNotInAllowList
);
});
}
#[test]
-fn white_list_test_4() {
+fn allow_list_test_4() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1330,14 +1330,14 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
collection_id,
account(1)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
collection_id,
account(2)
@@ -1353,7 +1353,7 @@
));
assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 1);
- assert_ok!(TemplateModule::remove_from_white_list(
+ assert_ok!(TemplateModule::remove_from_allow_list(
origin1.clone(),
collection_id,
account(2)
@@ -1361,14 +1361,14 @@
assert_noop!(
TemplateModule::transfer_from(origin1, account(1), account(3), 1, 1, 1),
- Error::<Test>::AddresNotInWhiteList
+ Error::<Test>::AddresNotInAllowList
);
});
}
-// If Public Access mode is set to WhiteList, tokens can’t be destroyed by a non-whitelisted address (even if it owned them before enabling WhiteList mode)
+// If Public Access mode is set to AllowList, tokens can’t be destroyed by a non-allowlisted address (even if it owned them before enabling AllowList mode)
#[test]
-fn white_list_test_5() {
+fn allow_list_test_5() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1380,18 +1380,18 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
assert_noop!(
TemplateModule::burn_item(origin1.clone(), 1, 1, 5),
- Error::<Test>::AddresNotInWhiteList
+ Error::<Test>::AddresNotInAllowList
);
});
}
-// If Public Access mode is set to WhiteList, token transfers can’t be Approved by a non-whitelisted address (see Approve method).
+// If Public Access mode is set to AllowList, token transfers can’t be Approved by a non-allowlisted address (see Approve method).
#[test]
-fn white_list_test_6() {
+fn allow_list_test_6() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1403,21 +1403,21 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
// do approve
assert_noop!(
TemplateModule::approve(origin1, account(1), 1, 1, 5),
- Error::<Test>::AddresNotInWhiteList
+ Error::<Test>::AddresNotInAllowList
);
});
}
-// If Public Access mode is set to WhiteList, tokens can be transferred from a whitelisted address with transfer or transferFrom (2 tests) and
-// tokens can be transferred from a whitelisted address with transfer or transferFrom (2 tests)
+// If Public Access mode is set to AllowList, tokens can be transferred from a allowlisted address with transfer or transferFrom (2 tests) and
+// tokens can be transferred from a allowlisted address with transfer or transferFrom (2 tests)
#[test]
-fn white_list_test_7() {
+fn allow_list_test_7() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1429,14 +1429,14 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
collection_id,
account(1)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
collection_id,
account(2)
@@ -1447,7 +1447,7 @@
}
#[test]
-fn white_list_test_8() {
+fn allow_list_test_8() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1459,14 +1459,14 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
collection_id,
account(1)
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
collection_id,
account(2)
@@ -1493,9 +1493,9 @@
});
}
-// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens can be created by owner.
+// If Public Access mode is set to AllowList, and Mint Permission is set to false, tokens can be created by owner.
#[test]
-fn white_list_test_9() {
+fn allow_list_test_9() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
let origin1 = Origin::signed(1);
@@ -1503,7 +1503,7 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
assert_ok!(TemplateModule::set_mint_permission(
origin1,
@@ -1516,9 +1516,9 @@
});
}
-// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens can be created by admin.
+// If Public Access mode is set to AllowList, and Mint Permission is set to false, tokens can be created by admin.
#[test]
-fn white_list_test_10() {
+fn allow_list_test_10() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1528,7 +1528,7 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
assert_ok!(TemplateModule::set_mint_permission(
origin1.clone(),
@@ -1551,9 +1551,9 @@
});
}
-// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens cannot be created by non-privileged and white listed address.
+// If Public Access mode is set to AllowList, and Mint Permission is set to false, tokens cannot be created by non-privileged and allow listed address.
#[test]
-fn white_list_test_11() {
+fn allow_list_test_11() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1563,14 +1563,14 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
assert_ok!(TemplateModule::set_mint_permission(
origin1.clone(),
collection_id,
false
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1,
collection_id,
account(2)
@@ -1583,9 +1583,9 @@
});
}
-// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens cannot be created by non-privileged and non-white listed address.
+// If Public Access mode is set to AllowList, and Mint Permission is set to false, tokens cannot be created by non-privileged and non-allow listed address.
#[test]
-fn white_list_test_12() {
+fn allow_list_test_12() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1595,7 +1595,7 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
assert_ok!(TemplateModule::set_mint_permission(
origin1,
@@ -1610,9 +1610,9 @@
});
}
-// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by owner.
+// If Public Access mode is set to AllowList, and Mint Permission is set to true, tokens can be created by owner.
#[test]
-fn white_list_test_13() {
+fn allow_list_test_13() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1621,7 +1621,7 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
assert_ok!(TemplateModule::set_mint_permission(
origin1,
@@ -1634,9 +1634,9 @@
});
}
-// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by admin.
+// If Public Access mode is set to AllowList, and Mint Permission is set to true, tokens can be created by admin.
#[test]
-fn white_list_test_14() {
+fn allow_list_test_14() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1646,7 +1646,7 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
assert_ok!(TemplateModule::set_mint_permission(
origin1.clone(),
@@ -1669,9 +1669,9 @@
});
}
-// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens cannot be created by non-privileged and non-white listed address.
+// If Public Access mode is set to AllowList, and Mint Permission is set to true, tokens cannot be created by non-privileged and non-allow listed address.
#[test]
-fn white_list_test_15() {
+fn allow_list_test_15() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1681,7 +1681,7 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
assert_ok!(TemplateModule::set_mint_permission(
origin1,
@@ -1691,14 +1691,14 @@
assert_noop!(
TemplateModule::create_item(origin2, 1, account(2), default_nft_data().into()),
- Error::<Test>::AddresNotInWhiteList
+ Error::<Test>::AddresNotInAllowList
);
});
}
-// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by non-privileged and white listed address.
+// If Public Access mode is set to AllowList, and Mint Permission is set to true, tokens can be created by non-privileged and allow listed address.
#[test]
-fn white_list_test_16() {
+fn allow_list_test_16() {
new_test_ext().execute_with(|| {
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
@@ -1708,14 +1708,14 @@
assert_ok!(TemplateModule::set_public_access_mode(
origin1.clone(),
collection_id,
- AccessMode::WhiteList
+ AccessMode::AllowList
));
assert_ok!(TemplateModule::set_mint_permission(
origin1.clone(),
collection_id,
true
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1,
collection_id,
account(2)
@@ -2056,7 +2056,7 @@
collection_id,
true
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin1.clone(),
collection_id,
account(1)
@@ -2124,7 +2124,7 @@
collection_id,
true
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin2.clone(),
collection_id,
account(1)
@@ -2177,7 +2177,7 @@
collection_id,
true
));
- assert_ok!(TemplateModule::add_to_white_list(
+ assert_ok!(TemplateModule::add_to_allow_list(
origin2.clone(),
collection_id,
account(1)
pallets/nft/src/weights.rsdiffbeforeafterboth--- a/pallets/nft/src/weights.rs
+++ b/pallets/nft/src/weights.rs
@@ -33,8 +33,8 @@
pub trait WeightInfo {
fn create_collection() -> Weight;
fn destroy_collection() -> Weight;
- fn add_to_white_list() -> Weight;
- fn remove_from_white_list() -> Weight;
+ fn add_to_allow_list() -> Weight;
+ fn remove_from_allow_list() -> Weight;
fn set_public_access_mode() -> Weight;
fn set_mint_permission() -> Weight;
fn change_collection_owner() -> Weight;
@@ -75,14 +75,14 @@
}
// Storage: Common CollectionById (r:1 w:0)
// Storage: Common Allowlist (r:0 w:1)
- fn add_to_white_list() -> Weight {
+ fn add_to_allow_list() -> Weight {
(6_629_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Common CollectionById (r:1 w:0)
// Storage: Common Allowlist (r:0 w:1)
- fn remove_from_white_list() -> Weight {
+ fn remove_from_allow_list() -> Weight {
(6_596_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
@@ -205,14 +205,14 @@
}
// Storage: Common CollectionById (r:1 w:0)
// Storage: Common Allowlist (r:0 w:1)
- fn add_to_white_list() -> Weight {
+ fn add_to_allow_list() -> Weight {
(6_629_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Common CollectionById (r:1 w:0)
// Storage: Common Allowlist (r:0 w:1)
- fn remove_from_white_list() -> Weight {
+ fn remove_from_allow_list() -> Weight {
(6_596_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -177,7 +177,7 @@
<CommonError<T>>::NoPermission
);
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
collection.check_allowlist(sender)?;
}
@@ -235,7 +235,7 @@
<CommonError<T>>::NoPermission
);
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
collection.check_allowlist(from)?;
collection.check_allowlist(to)?;
}
@@ -442,7 +442,7 @@
token: TokenId,
spender: Option<&T::CrossAccountId>,
) -> DispatchResult {
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
collection.check_allowlist(&sender)?;
if let Some(spender) = spender {
collection.check_allowlist(&spender)?;
@@ -477,7 +477,7 @@
if spender.conv_eq(from) {
return Self::transfer(collection, from, to, token);
}
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
// `from`, `to` checked in [`transfer`]
collection.check_allowlist(spender)?;
}
@@ -505,7 +505,7 @@
if spender.conv_eq(from) {
return Self::burn(collection, from, token);
}
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
// `from` checked in [`burn`]
collection.check_allowlist(spender)?;
}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -272,7 +272,7 @@
<CommonError<T>>::TransferNotAllowed
);
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
collection.check_allowlist(from)?;
collection.check_allowlist(to)?;
}
@@ -482,7 +482,7 @@
token: TokenId,
amount: u128,
) -> DispatchResult {
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
collection.check_allowlist(&sender)?;
collection.check_allowlist(&spender)?;
}
@@ -513,7 +513,7 @@
if spender.conv_eq(from) {
return Self::transfer(collection, from, to, token, amount);
}
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
// `from`, `to` checked in [`transfer`]
collection.check_allowlist(spender)?;
}
@@ -546,7 +546,7 @@
if spender.conv_eq(from) {
return Self::burn(collection, from, token, amount);
}
- if collection.access == AccessMode::WhiteList {
+ if collection.access == AccessMode::AllowList {
// `from` checked in [`burn`]
collection.check_allowlist(spender)?;
}
pallets/scheduler/Cargo.tomldiffbeforeafterboth--- a/pallets/scheduler/Cargo.toml
+++ b/pallets/scheduler/Cargo.toml
@@ -20,7 +20,7 @@
sp-io = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-up-sponsorship = { default-features = false, path = "../../primitives/sponsorship", version = "0.1.0" }
+up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring" }
log = { version = "0.4.14", default-features = false }
[dev-dependencies]
primitives/nft/src/lib.rsdiffbeforeafterboth--- a/primitives/nft/src/lib.rs
+++ b/primitives/nft/src/lib.rs
@@ -142,7 +142,7 @@
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub enum AccessMode {
Normal,
- WhiteList,
+ AllowList,
}
impl Default for AccessMode {
fn default() -> Self {
primitives/sponsorship/Cargo.tomldiffbeforeafterboth--- a/primitives/sponsorship/Cargo.toml
+++ /dev/null
@@ -1,11 +0,0 @@
-[package]
-name = "up-sponsorship"
-version = "0.1.0"
-edition = "2018"
-
-[dependencies]
-impl-trait-for-tuples = "0.2.1"
-
-[features]
-default = ["std"]
-std = []
\ No newline at end of file
primitives/sponsorship/src/lib.rsdiffbeforeafterboth--- a/primitives/sponsorship/src/lib.rs
+++ /dev/null
@@ -1,42 +0,0 @@
-#![no_std]
-
-pub trait SponsorshipHandler<AccountId, Call> {
- fn get_sponsor(who: &AccountId, call: &Call) -> Option<AccountId>;
-}
-
-impl<A, C> SponsorshipHandler<A, C> for () {
- fn get_sponsor(_who: &A, _call: &C) -> Option<A> {
- None
- }
-}
-
-macro_rules! impl_tuples {
- ($($ident:ident)+) => {
- impl<AccountId, Call, $($ident),+> SponsorshipHandler<AccountId, Call> for ($($ident,)+)
- where
- $(
- $ident: SponsorshipHandler<AccountId, Call>
- ),+
- {
- fn get_sponsor(who: &AccountId, call: &Call) -> Option<AccountId> {
- $(
- if let Some(account) = $ident::get_sponsor(who, call) {
- return Some(account);
- }
- )+
- None
- }
- }
- }
-}
-
-impl_tuples! {A}
-impl_tuples! {A B}
-impl_tuples! {A B C}
-impl_tuples! {A B C D}
-impl_tuples! {A B C D E}
-impl_tuples! {A B C D E F}
-impl_tuples! {A B C D E F G}
-impl_tuples! {A B C D E F G H}
-impl_tuples! {A B C D E F G H I}
-impl_tuples! {A B C D E F G H I J}
runtime/Cargo.tomldiffbeforeafterboth--- a/runtime/Cargo.toml
+++ b/runtime/Cargo.toml
@@ -10,7 +10,7 @@
license = 'All Rights Reserved'
name = 'nft-runtime'
repository = 'https://github.com/usetech-llc/nft_private/'
-version = '3.0.0'
+version = '0.9.12'
[package.metadata.docs.rs]
targets = ['x86_64-unknown-linux-gnu']
@@ -381,7 +381,7 @@
pallet-unq-scheduler = { path = '../pallets/scheduler', default-features = false, version = '3.0.0' }
# pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
pallet-nft-transaction-payment = { path = '../pallets/nft-transaction-payment', default-features = false, version = '3.0.0' }
-pallet-nft-charge-transaction = { path = '../pallets/nft-charge-transaction', default-features = false, version = '3.0.0' }
+pallet-nft-charge-transaction = {git = "https://github.com/UniqueNetwork/pallet-sponsoring", package = "pallet-template-transaction-payment", default-features = false, version = '3.0.0' }
pallet-evm-migration = { path = '../pallets/evm-migration', default-features = false }
pallet-evm-contract-helpers = { path = '../pallets/evm-contract-helpers', default-features = false }
pallet-evm-transaction-payment = { path = '../pallets/evm-transaction-payment', default-features = false }
runtime/src/chain_extension.rsdiffbeforeafterboth--- a/runtime/src/chain_extension.rs
+++ b/runtime/src/chain_extension.rs
@@ -75,10 +75,10 @@
}
#[derive(Debug, PartialEq, Encode, Decode, MaxEncodedLen)]
-pub struct NFTExtToggleWhiteList<AccountId> {
+pub struct NFTExtToggleAllowList<AccountId> {
pub collection_id: u32,
pub address: AccountId,
- pub whitelisted: bool,
+ pub allowlisted: bool,
}
/// The chain Extension of NFT pallet
@@ -211,18 +211,18 @@
Ok(RetVal::Converging(0))
}
6 => {
- // Toggle whitelist
+ // Toggle allowlist
let mut env = env.buf_in_buf_out();
- let input: NFTExtToggleWhiteList<AccountIdOf<C>> = env.read_as()?;
- env.charge_weight(NftWeightInfoOf::<C>::add_to_white_list())?;
+ let input: NFTExtToggleAllowList<AccountIdOf<C>> = env.read_as()?;
+ env.charge_weight(NftWeightInfoOf::<C>::add_to_allow_list())?;
let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
- pallet_nft::Module::<C>::toggle_white_list_internal(
+ pallet_nft::Module::<C>::toggle_allow_list_internal(
&C::CrossAccountId::from_sub(env.ext().address().clone()),
&collection,
&C::CrossAccountId::from_sub(input.address),
- input.whitelisted,
+ input.allowlisted,
)?;
collection.submit_logs()?;
runtime/src/lib.rsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19// #[cfg(any(feature = "std", test))]20// pub use sp_runtime::BuildStorage;2122use sp_runtime::{23 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24 traits::{25 AccountIdLookup, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify,26 AccountIdConversion,27 },28 transaction_validity::{TransactionSource, TransactionValidity},29 ApplyExtrinsicResult, MultiSignature,30};3132use sp_std::prelude::*;3334#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{38 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,39};40// A few exports that help ease life for downstream crates.41pub use pallet_balances::Call as BalancesCall;42pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};43pub use frame_support::{44 construct_runtime, match_type,45 dispatch::DispatchResult,46 PalletId, parameter_types, StorageValue, ConsensusEngineId,47 traits::{48 Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,49 LockIdentifier, OnUnbalanced, Randomness, FindAuthor,50 },51 weights::{52 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},53 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,54 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,55 },56};57use nft_data_structs::*;58// use pallet_contracts::weights::WeightInfo;59// #[cfg(any(feature = "std", test))]60use frame_system::{61 self as system, EnsureRoot, EnsureSigned,62 limits::{BlockWeights, BlockLength},63};64use sp_arithmetic::{65 traits::{BaseArithmetic, Unsigned},66};67use smallvec::smallvec;68use codec::{Encode, Decode};69use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};70use fp_rpc::TransactionStatus;71use sp_core::crypto::Public;72use sp_runtime::{73 traits::{Dispatchable, PostDispatchInfoOf},74 transaction_validity::TransactionValidityError,75};7677// pub use pallet_timestamp::Call as TimestampCall;78pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;7980// Polkadot imports81use pallet_xcm::XcmPassthrough;82use polkadot_parachain::primitives::Sibling;83use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};84use xcm_builder::{85 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,86 EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,87 ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,88 SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,89 SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,90};91use xcm_executor::{Config, XcmExecutor};9293// mod chain_extension;94// use crate::chain_extension::{NFTExtension, Imbalance};9596/// An index to a block.97pub type BlockNumber = u32;9899/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.100pub type Signature = MultiSignature;101102/// Some way of identifying an account on the chain. We intentionally make it equivalent103/// to the public key of our transaction signing scheme.104pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;105106pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;107108/// The type for looking up accounts. We don't expect more than 4 billion of them, but you109/// never know...110pub type AccountIndex = u32;111112/// Balance of an account.113pub type Balance = u128;114115/// Index of a transaction in the chain.116pub type Index = u32;117118/// A hash of some data used by the chain.119pub type Hash = sp_core::H256;120121/// Digest item type.122pub type DigestItem = generic::DigestItem<Hash>;123124/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know125/// the specifics of the runtime. They can then be made to be agnostic over specific formats126/// of data like extrinsics, allowing for them to continue syncing the network through upgrades127/// to even the core data structures.128pub mod opaque {129 use super::*;130131 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;132133 /// Opaque block type.134 pub type Block = generic::Block<Header, UncheckedExtrinsic>;135136 pub type SessionHandlers = ();137138 impl_opaque_keys! {139 pub struct SessionKeys {140 pub aura: Aura,141 }142 }143}144145/// This runtime version.146pub const VERSION: RuntimeVersion = RuntimeVersion {147 spec_name: create_runtime_str!("opal"),148 impl_name: create_runtime_str!("opal"),149 authoring_version: 1,150 spec_version: 912200,151 impl_version: 1,152 apis: RUNTIME_API_VERSIONS,153 transaction_version: 1,154};155156pub const MILLISECS_PER_BLOCK: u64 = 12000;157158pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;159160// These time units are defined in number of blocks.161pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);162pub const HOURS: BlockNumber = MINUTES * 60;163pub const DAYS: BlockNumber = HOURS * 24;164165parameter_types! {166 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;167}168169#[derive(codec::Encode, codec::Decode)]170pub enum XCMPMessage<XAccountId, XBalance> {171 /// Transfer tokens to the given account from the Parachain account.172 TransferToken(XAccountId, XBalance),173}174175/// The version information used to identify this runtime when compiled natively.176#[cfg(feature = "std")]177pub fn native_version() -> NativeVersion {178 NativeVersion {179 runtime_version: VERSION,180 can_author_with: Default::default(),181 }182}183184type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;185186pub struct DealWithFees;187impl OnUnbalanced<NegativeImbalance> for DealWithFees {188 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {189 if let Some(fees) = fees_then_tips.next() {190 // for fees, 100% to treasury191 let mut split = fees.ration(100, 0);192 if let Some(tips) = fees_then_tips.next() {193 // for tips, if any, 100% to treasury194 tips.ration_merge_into(100, 0, &mut split);195 }196 Treasury::on_unbalanced(split.0);197 // Author::on_unbalanced(split.1);198 }199 }200}201202/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.203/// This is used to limit the maximal weight of a single extrinsic.204const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);205/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used206/// by Operational extrinsics.207const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);208/// We allow for 2 seconds of compute with a 6 second average block time.209const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;210211parameter_types! {212 pub const BlockHashCount: BlockNumber = 2400;213 pub RuntimeBlockLength: BlockLength =214 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);215 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);216 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;217 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()218 .base_block(BlockExecutionWeight::get())219 .for_class(DispatchClass::all(), |weights| {220 weights.base_extrinsic = ExtrinsicBaseWeight::get();221 })222 .for_class(DispatchClass::Normal, |weights| {223 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);224 })225 .for_class(DispatchClass::Operational, |weights| {226 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);227 // Operational transactions have some extra reserved space, so that they228 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.229 weights.reserved = Some(230 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT231 );232 })233 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)234 .build_or_panic();235 pub const Version: RuntimeVersion = VERSION;236 pub const SS58Prefix: u8 = 42;237}238239parameter_types! {240 pub const ChainId: u64 = 8888;241}242243pub struct FixedFee;244impl FeeCalculator for FixedFee {245 fn min_gas_price() -> U256 {246 // Targeting 0.15 UNQ per transfer247 (1 * MICROUNIQUE).into()248 }249}250251// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case252// (contract, which only writes a lot of data),253// approximating on top of our real store write weight254parameter_types! {255 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;256 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;257 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();258}259260/// Limiting EVM execution to 50% of block for substrate users and management tasks261/// EVM transaction consumes more weight than substrate's, so we can't rely on them being262/// scheduled fairly263const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);264parameter_types! {265 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());266}267268pub enum FixedGasWeightMapping {}269impl GasWeightMapping for FixedGasWeightMapping {270 fn gas_to_weight(gas: u64) -> Weight {271 gas.saturating_mul(WeightPerGas::get())272 }273 fn weight_to_gas(weight: Weight) -> u64 {274 weight / WeightPerGas::get()275 }276}277278impl pallet_evm::Config for Runtime {279 type BlockGasLimit = BlockGasLimit;280 type FeeCalculator = FixedFee;281 type GasWeightMapping = FixedGasWeightMapping;282 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;283 type CallOrigin = EnsureAddressTruncated;284 type WithdrawOrigin = EnsureAddressTruncated;285 type AddressMapping = HashedAddressMapping<Self::Hashing>;286 type Precompiles = ();287 type Currency = Balances;288 type Event = Event;289 type OnMethodCall = (290 pallet_evm_migration::OnMethodCall<Self>,291 pallet_nft::NftErcSupport<Self>,292 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,293 );294 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;295 type ChainId = ChainId;296 type Runner = pallet_evm::runner::stack::Runner<Self>;297 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;298 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;299 type FindAuthor = EthereumFindAuthor<Aura>;300}301302impl pallet_evm_migration::Config for Runtime {303 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;304}305306pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);307impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {308 fn find_author<'a, I>(digests: I) -> Option<H160>309 where310 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,311 {312 if let Some(author_index) = F::find_author(digests) {313 let authority_id = Aura::authorities()[author_index as usize].clone();314 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));315 }316 None317 }318}319320impl pallet_ethereum::Config for Runtime {321 type Event = Event;322 type StateRoot = pallet_ethereum::IntermediateStateRoot;323}324325impl pallet_randomness_collective_flip::Config for Runtime {}326327impl system::Config for Runtime {328 /// The data to be stored in an account.329 type AccountData = pallet_balances::AccountData<Balance>;330 /// The identifier used to distinguish between accounts.331 type AccountId = AccountId;332 /// The basic call filter to use in dispatchable.333 type BaseCallFilter = Everything;334 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).335 type BlockHashCount = BlockHashCount;336 /// The maximum length of a block (in bytes).337 type BlockLength = RuntimeBlockLength;338 /// The index type for blocks.339 type BlockNumber = BlockNumber;340 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.341 type BlockWeights = RuntimeBlockWeights;342 /// The aggregated dispatch type that is available for extrinsics.343 type Call = Call;344 /// The weight of database operations that the runtime can invoke.345 type DbWeight = RocksDbWeight;346 /// The ubiquitous event type.347 type Event = Event;348 /// The type for hashing blocks and tries.349 type Hash = Hash;350 /// The hashing algorithm used.351 type Hashing = BlakeTwo256;352 /// The header type.353 type Header = generic::Header<BlockNumber, BlakeTwo256>;354 /// The index type for storing how many extrinsics an account has signed.355 type Index = Index;356 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.357 type Lookup = AccountIdLookup<AccountId, ()>;358 /// What to do if an account is fully reaped from the system.359 type OnKilledAccount = ();360 /// What to do if a new account is created.361 type OnNewAccount = ();362 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;363 /// The ubiquitous origin type.364 type Origin = Origin;365 /// This type is being generated by `construct_runtime!`.366 type PalletInfo = PalletInfo;367 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.368 type SS58Prefix = SS58Prefix;369 /// Weight information for the extrinsics of this pallet.370 type SystemWeightInfo = system::weights::SubstrateWeight<Self>;371 /// Version of the runtime.372 type Version = Version;373}374375parameter_types! {376 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;377}378379impl pallet_timestamp::Config for Runtime {380 /// A timestamp: milliseconds since the unix epoch.381 type Moment = u64;382 type OnTimestampSet = ();383 type MinimumPeriod = MinimumPeriod;384 type WeightInfo = ();385}386387parameter_types! {388 // pub const ExistentialDeposit: u128 = 500;389 pub const ExistentialDeposit: u128 = 0;390 pub const MaxLocks: u32 = 50;391}392393impl pallet_balances::Config for Runtime {394 type MaxLocks = MaxLocks;395 type MaxReserves = ();396 type ReserveIdentifier = [u8; 8];397 /// The type for recording an account's balance.398 type Balance = Balance;399 /// The ubiquitous event type.400 type Event = Event;401 type DustRemoval = Treasury;402 type ExistentialDeposit = ExistentialDeposit;403 type AccountStore = System;404 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;405}406407pub const MICROUNIQUE: Balance = 1_000_000_000;408pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;409pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;410pub const UNIQUE: Balance = 100 * CENTIUNIQUE;411412pub const fn deposit(items: u32, bytes: u32) -> Balance {413 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE414}415416/*417parameter_types! {418 pub TombstoneDeposit: Balance = deposit(419 1,420 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,421 );422 pub DepositPerContract: Balance = TombstoneDeposit::get();423 pub const DepositPerStorageByte: Balance = deposit(0, 1);424 pub const DepositPerStorageItem: Balance = deposit(1, 0);425 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);426 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;427 pub const SignedClaimHandicap: u32 = 2;428 pub const MaxDepth: u32 = 32;429 pub const MaxValueSize: u32 = 16 * 1024;430 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb431 // The lazy deletion runs inside on_initialize.432 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *433 RuntimeBlockWeights::get().max_block;434 // The weight needed for decoding the queue should be less or equal than a fifth435 // of the overall weight dedicated to the lazy deletion.436 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (437 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -438 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)439 )) / 5) as u32;440 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();441}442443impl pallet_contracts::Config for Runtime {444 type Time = Timestamp;445 type Randomness = RandomnessCollectiveFlip;446 type Currency = Balances;447 type Event = Event;448 type RentPayment = ();449 type SignedClaimHandicap = SignedClaimHandicap;450 type TombstoneDeposit = TombstoneDeposit;451 type DepositPerContract = DepositPerContract;452 type DepositPerStorageByte = DepositPerStorageByte;453 type DepositPerStorageItem = DepositPerStorageItem;454 type RentFraction = RentFraction;455 type SurchargeReward = SurchargeReward;456 type WeightPrice = pallet_transaction_payment::Pallet<Self>;457 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;458 type ChainExtension = NFTExtension;459 type DeletionQueueDepth = DeletionQueueDepth;460 type DeletionWeightLimit = DeletionWeightLimit;461 type Schedule = Schedule;462 type CallStack = [pallet_contracts::Frame<Self>; 31];463}464*/465466parameter_types! {467 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer468 /// This value increases the priority of `Operational` transactions by adding469 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.470 pub const OperationalFeeMultiplier: u8 = 5;471}472473/// Linear implementor of `WeightToFeePolynomial`474pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);475476impl<T> WeightToFeePolynomial for LinearFee<T>477where478 T: BaseArithmetic + From<u32> + Copy + Unsigned,479{480 type Balance = T;481482 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {483 smallvec!(WeightToFeeCoefficient {484 coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer485 coeff_frac: Perbill::zero(),486 negative: false,487 degree: 1,488 })489 }490}491492impl pallet_transaction_payment::Config for Runtime {493 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;494 type TransactionByteFee = TransactionByteFee;495 type OperationalFeeMultiplier = OperationalFeeMultiplier;496 type WeightToFee = LinearFee<Balance>;497 type FeeMultiplierUpdate = ();498}499500parameter_types! {501 pub const ProposalBond: Permill = Permill::from_percent(5);502 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;503 pub const SpendPeriod: BlockNumber = 5 * MINUTES;504 pub const Burn: Permill = Permill::from_percent(0);505 pub const TipCountdown: BlockNumber = 1 * DAYS;506 pub const TipFindersFee: Percent = Percent::from_percent(20);507 pub const TipReportDepositBase: Balance = 1 * UNIQUE;508 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;509 pub const BountyDepositBase: Balance = 1 * UNIQUE;510 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;511 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");512 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;513 pub const MaximumReasonLength: u32 = 16384;514 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);515 pub const BountyValueMinimum: Balance = 5 * UNIQUE;516 pub const MaxApprovals: u32 = 100;517}518519impl pallet_treasury::Config for Runtime {520 type PalletId = TreasuryModuleId;521 type Currency = Balances;522 type ApproveOrigin = EnsureRoot<AccountId>;523 type RejectOrigin = EnsureRoot<AccountId>;524 type Event = Event;525 type OnSlash = ();526 type ProposalBond = ProposalBond;527 type ProposalBondMinimum = ProposalBondMinimum;528 type SpendPeriod = SpendPeriod;529 type Burn = Burn;530 type BurnDestination = ();531 type SpendFunds = ();532 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;533 type MaxApprovals = MaxApprovals;534}535536impl pallet_sudo::Config for Runtime {537 type Event = Event;538 type Call = Call;539}540541parameter_types! {542 pub const MinVestedTransfer: Balance = 10 * UNIQUE;543}544545impl pallet_vesting::Config for Runtime {546 type Event = Event;547 type Currency = Balances;548 type BlockNumberToBalance = ConvertInto;549 type MinVestedTransfer = MinVestedTransfer;550 type WeightInfo = ();551 const MAX_VESTING_SCHEDULES: u32 = 28;552}553554parameter_types! {555 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;556 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;557}558559impl cumulus_pallet_parachain_system::Config for Runtime {560 type Event = Event;561 type OnValidationData = ();562 type SelfParaId = parachain_info::Pallet<Self>;563 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<564 // MaxDownwardMessageWeight,565 // XcmExecutor<XcmConfig>,566 // Call,567 // >;568 type OutboundXcmpMessageSource = XcmpQueue;569 type DmpMessageHandler = DmpQueue;570 type ReservedDmpWeight = ReservedDmpWeight;571 type ReservedXcmpWeight = ReservedXcmpWeight;572 type XcmpMessageHandler = XcmpQueue;573}574575impl parachain_info::Config for Runtime {}576577impl cumulus_pallet_aura_ext::Config for Runtime {}578579parameter_types! {580 pub const RelayLocation: MultiLocation = MultiLocation::parent();581 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;582 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();583 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();584}585586/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used587/// when determining ownership of accounts for asset transacting and when attempting to use XCM588/// `Transact` in order to determine the dispatch Origin.589pub type LocationToAccountId = (590 // The parent (Relay-chain) origin converts to the default `AccountId`.591 ParentIsDefault<AccountId>,592 // Sibling parachain origins convert to AccountId via the `ParaId::into`.593 SiblingParachainConvertsVia<Sibling, AccountId>,594 // Straight up local `AccountId32` origins just alias directly to `AccountId`.595 AccountId32Aliases<RelayNetwork, AccountId>,596);597598/// Means for transacting assets on this chain.599pub type LocalAssetTransactor = CurrencyAdapter<600 // Use this currency:601 Balances,602 // Use this currency when it is a fungible asset matching the given location or name:603 IsConcrete<RelayLocation>,604 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:605 LocationToAccountId,606 // Our chain's account ID type (we can't get away without mentioning it explicitly):607 AccountId,608 // We don't track any teleports.609 (),610>;611612/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,613/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can614/// biases the kind of local `Origin` it will become.615pub type XcmOriginToTransactDispatchOrigin = (616 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location617 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for618 // foreign chains who want to have a local sovereign account on this chain which they control.619 SovereignSignedViaLocation<LocationToAccountId, Origin>,620 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when621 // recognised.622 RelayChainAsNative<RelayOrigin, Origin>,623 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when624 // recognised.625 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,626 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a627 // transaction from the Root origin.628 ParentAsSuperuser<Origin>,629 // Native signed account converter; this just converts an `AccountId32` origin into a normal630 // `Origin::Signed` origin of the same 32-byte value.631 SignedAccountId32AsNative<RelayNetwork, Origin>,632 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.633 XcmPassthrough<Origin>,634);635636parameter_types! {637 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.638 pub UnitWeightCost: Weight = 1_000_000;639 // 1200 UNIQUEs buy 1 second of weight.640 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);641 pub const MaxInstructions: u32 = 100;642 pub const MaxAuthorities: u32 = 100_000;643}644645match_type! {646 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {647 MultiLocation { parents: 1, interior: Here } |648 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }649 };650}651652pub type Barrier = (653 TakeWeightCredit,654 AllowTopLevelPaidExecutionFrom<Everything>,655 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,656 // ^^^ Parent & its unit plurality gets free execution657);658659pub struct XcmConfig;660impl Config for XcmConfig {661 type Call = Call;662 type XcmSender = XcmRouter;663 // How to withdraw and deposit an asset.664 type AssetTransactor = LocalAssetTransactor;665 type OriginConverter = XcmOriginToTransactDispatchOrigin;666 type IsReserve = NativeAsset;667 type IsTeleporter = (); // Teleportation is disabled668 type LocationInverter = LocationInverter<Ancestry>;669 type Barrier = Barrier;670 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;671 type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;672 type ResponseHandler = (); // Don't handle responses for now.673 type SubscriptionService = PolkadotXcm;674675 type AssetTrap = PolkadotXcm;676 type AssetClaims = PolkadotXcm;677}678679// parameter_types! {680// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;681// }682683/// No local origins on this chain are allowed to dispatch XCM sends/executions.684pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);685686/// The means for routing XCM messages which are not for local execution into the right message687/// queues.688pub type XcmRouter = (689 // Two routers - use UMP to communicate with the relay chain:690 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,691 // ..and XCMP to communicate with the sibling chains.692 XcmpQueue,693);694695impl pallet_evm_coder_substrate::Config for Runtime {696 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;697 type GasWeightMapping = FixedGasWeightMapping;698}699700impl pallet_xcm::Config for Runtime {701 type Event = Event;702 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;703 type XcmRouter = XcmRouter;704 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;705 type XcmExecuteFilter = Everything;706 type XcmExecutor = XcmExecutor<XcmConfig>;707 type XcmTeleportFilter = Everything;708 type XcmReserveTransferFilter = Everything;709 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;710 type LocationInverter = LocationInverter<Ancestry>;711 type Origin = Origin;712 type Call = Call;713 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;714 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;715}716717impl cumulus_pallet_xcm::Config for Runtime {718 type Event = Event;719 type XcmExecutor = XcmExecutor<XcmConfig>;720}721722impl cumulus_pallet_xcmp_queue::Config for Runtime {723 type Event = Event;724 type XcmExecutor = XcmExecutor<XcmConfig>;725 type ChannelInfo = ParachainSystem;726 type VersionWrapper = ();727}728729impl cumulus_pallet_dmp_queue::Config for Runtime {730 type Event = Event;731 type XcmExecutor = XcmExecutor<XcmConfig>;732 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;733}734735impl pallet_aura::Config for Runtime {736 type AuthorityId = AuraId;737 type DisabledValidators = ();738 type MaxAuthorities = MaxAuthorities;739}740741parameter_types! {742 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();743 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;744}745746impl pallet_common::Config for Runtime {747 type Event = Event;748 type EvmBackwardsAddressMapping = pallet_common::account::MapBackwardsAddressTruncated;749 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;750 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;751752 type Currency = Balances;753 type CollectionCreationPrice = CollectionCreationPrice;754 type TreasuryAccountId = TreasuryAccountId;755}756757impl pallet_fungible::Config for Runtime {758 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;759}760impl pallet_refungible::Config for Runtime {761 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;762}763impl pallet_nonfungible::Config for Runtime {764 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;765}766767/// Used for the pallet nft in `./nft.rs`768impl pallet_nft::Config for Runtime {769 type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;770}771772parameter_types! {773 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied774}775776/// Used for the pallet inflation777impl pallet_inflation::Config for Runtime {778 type Currency = Balances;779 type TreasuryAccountId = TreasuryAccountId;780 type InflationBlockInterval = InflationBlockInterval;781}782783parameter_types! {784 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *785 RuntimeBlockWeights::get().max_block;786 pub const MaxScheduledPerBlock: u32 = 50;787}788789pub struct Sponsoring;790impl SponsoringResolve<AccountId, Call> for Sponsoring {791 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>792 where793 Call: Dispatchable<Info = DispatchInfo>,794 AccountId: AsRef<[u8]>,795 {796 pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)797 }798}799800type SponsorshipHandler = (801 pallet_nft::NftSponsorshipHandler<Runtime>,802 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,803);804805impl pallet_unq_scheduler::Config for Runtime {806 type Event = Event;807 type Origin = Origin;808 type PalletsOrigin = OriginCaller;809 type Call = Call;810 type MaximumWeight = MaximumSchedulerWeight;811 type ScheduleOrigin = EnsureSigned<AccountId>;812 type MaxScheduledPerBlock = MaxScheduledPerBlock;813 type SponsorshipHandler = SponsorshipHandler;814 type WeightInfo = ();815}816817impl pallet_nft_transaction_payment::Config for Runtime {818 type SponsorshipHandler = SponsorshipHandler;819}820821impl pallet_evm_transaction_payment::Config for Runtime {822 type SponsorshipHandler = (823 pallet_nft::NftEthSponsorshipHandler<Self>,824 pallet_evm_contract_helpers::HelpersContractSponsoring<Self>,825 );826 type Currency = Balances;827}828829impl pallet_nft_charge_transaction::Config for Runtime {}830831// impl pallet_contract_helpers::Config for Runtime {832// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;833// }834835parameter_types! {836 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049837 pub const HelpersContractAddress: H160 = H160([838 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,839 ]);840}841842impl pallet_evm_contract_helpers::Config for Runtime {843 type ContractAddress = HelpersContractAddress;844 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;845}846847construct_runtime!(848 pub enum Runtime where849 Block = Block,850 NodeBlock = opaque::Block,851 UncheckedExtrinsic = UncheckedExtrinsic852 {853 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,854 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,855856 Aura: pallet_aura::{Pallet, Config<T>} = 22,857 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,858859 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,860 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,861 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,862 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,863 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,864 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,865 System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,866 Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,867 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,868869 // XCM helpers.870 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,871 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,872 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,873 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,874875 // Unique Pallets876 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,877 Nft: pallet_nft::{Pallet, Call, Storage} = 61,878 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,879 NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,880 Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,881 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,882 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,883 Fungible: pallet_fungible::{Pallet, Storage} = 67,884 Refungible: pallet_refungible::{Pallet, Storage} = 68,885 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,886887 // Frontier888 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,889 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,890891 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,892 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,893 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,894 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,895 }896);897898pub struct TransactionConverter;899900impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {901 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {902 UncheckedExtrinsic::new_unsigned(903 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),904 )905 }906}907908impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {909 fn convert_transaction(910 &self,911 transaction: pallet_ethereum::Transaction,912 ) -> opaque::UncheckedExtrinsic {913 let extrinsic = UncheckedExtrinsic::new_unsigned(914 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),915 );916 let encoded = extrinsic.encode();917 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])918 .expect("Encoded extrinsic is always valid")919 }920}921922/// The address format for describing accounts.923pub type Address = sp_runtime::MultiAddress<AccountId, ()>;924/// Block header type as expected by this runtime.925pub type Header = generic::Header<BlockNumber, BlakeTwo256>;926/// Block type as expected by this runtime.927pub type Block = generic::Block<Header, UncheckedExtrinsic>;928/// A Block signed with a Justification929pub type SignedBlock = generic::SignedBlock<Block>;930/// BlockId type as expected by this runtime.931pub type BlockId = generic::BlockId<Block>;932/// The SignedExtension to the basic transaction logic.933pub type SignedExtra = (934 system::CheckSpecVersion<Runtime>,935 // system::CheckTxVersion<Runtime>,936 system::CheckGenesis<Runtime>,937 system::CheckEra<Runtime>,938 system::CheckNonce<Runtime>,939 system::CheckWeight<Runtime>,940 pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,941 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,942);943/// Unchecked extrinsic type as expected by this runtime.944pub type UncheckedExtrinsic =945 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;946/// Extrinsic type that has already been checked.947pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;948/// Executive: handles dispatch to the various modules.949pub type Executive = frame_executive::Executive<950 Runtime,951 Block,952 frame_system::ChainContext<Runtime>,953 Runtime,954 AllPallets,955>;956957impl_opaque_keys! {958 pub struct SessionKeys {959 pub aura: Aura,960 }961}962963impl fp_self_contained::SelfContainedCall for Call {964 type SignedInfo = H160;965966 fn is_self_contained(&self) -> bool {967 match self {968 Call::Ethereum(call) => call.is_self_contained(),969 _ => false,970 }971 }972973 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {974 match self {975 Call::Ethereum(call) => call.check_self_contained(),976 _ => None,977 }978 }979980 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {981 match self {982 Call::Ethereum(call) => call.validate_self_contained(info),983 _ => None,984 }985 }986987 fn pre_dispatch_self_contained(988 &self,989 info: &Self::SignedInfo,990 ) -> Option<Result<(), TransactionValidityError>> {991 match self {992 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),993 _ => None,994 }995 }996997 fn apply_self_contained(998 self,999 info: Self::SignedInfo,1000 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1001 match self {1002 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1003 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1004 )),1005 _ => None,1006 }1007 }1008}10091010macro_rules! dispatch_nft_runtime {1011 ($collection:ident.$method:ident($($name:ident),*)) => {{1012 use pallet_nft::dispatch::Dispatched;10131014 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::new($collection).unwrap());1015 let dispatch = collection.as_dyn();10161017 dispatch.$method($($name),*)1018 }};1019}1020impl_runtime_apis! {1021 impl up_rpc::NftApi<Block, CrossAccountId, AccountId>1022 for Runtime1023 {1024 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId> {1025 dispatch_nft_runtime!(collection.account_tokens(account))1026 }1027 fn token_exists(collection: CollectionId, token: TokenId) -> bool {1028 dispatch_nft_runtime!(collection.token_exists(token))1029 }10301031 fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId {1032 dispatch_nft_runtime!(collection.token_owner(token))1033 }1034 fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1035 dispatch_nft_runtime!(collection.const_metadata(token))1036 }1037 fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1038 dispatch_nft_runtime!(collection.variable_metadata(token))1039 }10401041 fn collection_tokens(collection: CollectionId) -> u32 {1042 dispatch_nft_runtime!(collection.collection_tokens())1043 }1044 fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32 {1045 dispatch_nft_runtime!(collection.account_balance(account))1046 }1047 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128 {1048 dispatch_nft_runtime!(collection.balance(account, token))1049 }1050 fn allowance(1051 collection: CollectionId,1052 sender: CrossAccountId,1053 spender: CrossAccountId,1054 token: TokenId,1055 ) -> u128 {1056 dispatch_nft_runtime!(collection.allowance(sender, spender, token))1057 }10581059 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1060 <pallet_nft::NftErcSupport<Runtime>>::get_code(&account)1061 .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1062 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1063 }1064 fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {1065 <pallet_nft::Pallet<Runtime>>::adminlist(collection)1066 }1067 fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {1068 <pallet_nft::Pallet<Runtime>>::allowlist(collection)1069 }1070 fn last_token_id(collection: CollectionId) -> TokenId {1071 dispatch_nft_runtime!(collection.last_token_id())1072 }1073 }10741075 impl sp_api::Core<Block> for Runtime {1076 fn version() -> RuntimeVersion {1077 VERSION1078 }10791080 fn execute_block(block: Block) {1081 Executive::execute_block(block)1082 }10831084 fn initialize_block(header: &<Block as BlockT>::Header) {1085 Executive::initialize_block(header)1086 }1087 }10881089 impl sp_api::Metadata<Block> for Runtime {1090 fn metadata() -> OpaqueMetadata {1091 OpaqueMetadata::new(Runtime::metadata().into())1092 }1093 }10941095 impl sp_block_builder::BlockBuilder<Block> for Runtime {1096 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1097 Executive::apply_extrinsic(extrinsic)1098 }10991100 fn finalize_block() -> <Block as BlockT>::Header {1101 Executive::finalize_block()1102 }11031104 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1105 data.create_extrinsics()1106 }11071108 fn check_inherents(1109 block: Block,1110 data: sp_inherents::InherentData,1111 ) -> sp_inherents::CheckInherentsResult {1112 data.check_extrinsics(&block)1113 }11141115 // fn random_seed() -> <Block as BlockT>::Hash {1116 // RandomnessCollectiveFlip::random_seed().01117 // }1118 }11191120 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1121 fn validate_transaction(1122 source: TransactionSource,1123 tx: <Block as BlockT>::Extrinsic,1124 hash: <Block as BlockT>::Hash,1125 ) -> TransactionValidity {1126 Executive::validate_transaction(source, tx, hash)1127 }1128 }11291130 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1131 fn offchain_worker(header: &<Block as BlockT>::Header) {1132 Executive::offchain_worker(header)1133 }1134 }11351136 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1137 fn chain_id() -> u64 {1138 <Runtime as pallet_evm::Config>::ChainId::get()1139 }11401141 fn account_basic(address: H160) -> EVMAccount {1142 EVM::account_basic(&address)1143 }11441145 fn gas_price() -> U256 {1146 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1147 }11481149 fn account_code_at(address: H160) -> Vec<u8> {1150 EVM::account_codes(address)1151 }11521153 fn author() -> H160 {1154 <pallet_evm::Pallet<Runtime>>::find_author()1155 }11561157 fn storage_at(address: H160, index: U256) -> H256 {1158 let mut tmp = [0u8; 32];1159 index.to_big_endian(&mut tmp);1160 EVM::account_storages(address, H256::from_slice(&tmp[..]))1161 }11621163 fn call(1164 from: H160,1165 to: H160,1166 data: Vec<u8>,1167 value: U256,1168 gas_limit: U256,1169 gas_price: Option<U256>,1170 nonce: Option<U256>,1171 estimate: bool,1172 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1173 let config = if estimate {1174 let mut config = <Runtime as pallet_evm::Config>::config().clone();1175 config.estimate = true;1176 Some(config)1177 } else {1178 None1179 };11801181 <Runtime as pallet_evm::Config>::Runner::call(1182 from,1183 to,1184 data,1185 value,1186 gas_limit.low_u64(),1187 gas_price,1188 nonce,1189 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1190 ).map_err(|err| err.into())1191 }11921193 fn create(1194 from: H160,1195 data: Vec<u8>,1196 value: U256,1197 gas_limit: U256,1198 gas_price: Option<U256>,1199 nonce: Option<U256>,1200 estimate: bool,1201 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1202 let config = if estimate {1203 let mut config = <Runtime as pallet_evm::Config>::config().clone();1204 config.estimate = true;1205 Some(config)1206 } else {1207 None1208 };12091210 <Runtime as pallet_evm::Config>::Runner::create(1211 from,1212 data,1213 value,1214 gas_limit.low_u64(),1215 gas_price,1216 nonce,1217 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1218 ).map_err(|err| err.into())1219 }12201221 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1222 Ethereum::current_transaction_statuses()1223 }12241225 fn current_block() -> Option<pallet_ethereum::Block> {1226 Ethereum::current_block()1227 }12281229 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1230 Ethereum::current_receipts()1231 }12321233 fn current_all() -> (1234 Option<pallet_ethereum::Block>,1235 Option<Vec<pallet_ethereum::Receipt>>,1236 Option<Vec<TransactionStatus>>1237 ) {1238 (1239 Ethereum::current_block(),1240 Ethereum::current_receipts(),1241 Ethereum::current_transaction_statuses()1242 )1243 }12441245 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1246 xts.into_iter().filter_map(|xt| match xt.0.function {1247 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1248 _ => None1249 }).collect()1250 }1251 }12521253 impl sp_session::SessionKeys<Block> for Runtime {1254 fn decode_session_keys(1255 encoded: Vec<u8>,1256 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1257 SessionKeys::decode_into_raw_public_keys(&encoded)1258 }12591260 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1261 SessionKeys::generate(seed)1262 }1263 }12641265 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1266 fn slot_duration() -> sp_consensus_aura::SlotDuration {1267 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1268 }12691270 fn authorities() -> Vec<AuraId> {1271 Aura::authorities().to_vec()1272 }1273 }12741275 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1276 fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1277 ParachainSystem::collect_collation_info()1278 }1279 }12801281 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1282 fn account_nonce(account: AccountId) -> Index {1283 System::account_nonce(account)1284 }1285 }12861287 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1288 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1289 TransactionPayment::query_info(uxt, len)1290 }1291 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1292 TransactionPayment::query_fee_details(uxt, len)1293 }1294 }12951296 /*1297 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1298 for Runtime1299 {1300 fn call(1301 origin: AccountId,1302 dest: AccountId,1303 value: Balance,1304 gas_limit: u64,1305 input_data: Vec<u8>,1306 ) -> pallet_contracts_primitives::ContractExecResult {1307 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1308 }13091310 fn instantiate(1311 origin: AccountId,1312 endowment: Balance,1313 gas_limit: u64,1314 code: pallet_contracts_primitives::Code<Hash>,1315 data: Vec<u8>,1316 salt: Vec<u8>,1317 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1318 {1319 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1320 }13211322 fn get_storage(1323 address: AccountId,1324 key: [u8; 32],1325 ) -> pallet_contracts_primitives::GetStorageResult {1326 Contracts::get_storage(address, key)1327 }13281329 fn rent_projection(1330 address: AccountId,1331 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1332 Contracts::rent_projection(address)1333 }1334 }1335 */13361337 #[cfg(feature = "runtime-benchmarks")]1338 impl frame_benchmarking::Benchmark<Block> for Runtime {1339 fn benchmark_metadata(extra: bool) -> (1340 Vec<frame_benchmarking::BenchmarkList>,1341 Vec<frame_support::traits::StorageInfo>,1342 ) {1343 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1344 use frame_support::traits::StorageInfoTrait;13451346 let mut list = Vec::<BenchmarkList>::new();13471348 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1349 list_benchmark!(list, extra, pallet_nft, Nft);1350 list_benchmark!(list, extra, pallet_inflation, Inflation);1351 list_benchmark!(list, extra, pallet_fungible, Fungible);1352 list_benchmark!(list, extra, pallet_refungible, Refungible);1353 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);1354 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);13551356 let storage_info = AllPalletsWithSystem::storage_info();13571358 return (list, storage_info)1359 }13601361 fn dispatch_benchmark(1362 config: frame_benchmarking::BenchmarkConfig1363 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1364 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};13651366 let whitelist: Vec<TrackedStorageKey> = vec![1367 // Block Number1368 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1369 // Total Issuance1370 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1371 // Execution Phase1372 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1373 // Event Count1374 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1375 // System Events1376 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1377 ];13781379 let mut batches = Vec::<BenchmarkBatch>::new();1380 let params = (&config, &whitelist);13811382 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1383 add_benchmark!(params, batches, pallet_nft, Nft);1384 add_benchmark!(params, batches, pallet_inflation, Inflation);1385 add_benchmark!(params, batches, pallet_fungible, Fungible);1386 add_benchmark!(params, batches, pallet_refungible, Refungible);1387 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);1388 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);13891390 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1391 Ok(batches)1392 }1393 }1394}13951396struct CheckInherents;13971398impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1399 fn check_inherents(1400 block: &Block,1401 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1402 ) -> sp_inherents::CheckInherentsResult {1403 let relay_chain_slot = relay_state_proof1404 .read_slot()1405 .expect("Could not read the relay chain slot from the proof");14061407 let inherent_data =1408 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1409 relay_chain_slot,1410 sp_std::time::Duration::from_secs(6),1411 )1412 .create_inherent_data()1413 .expect("Could not create the timestamp inherent data");14141415 inherent_data.check_extrinsics(block)1416 }1417}14181419cumulus_pallet_parachain_system::register_validate_block!(1420 Runtime = Runtime,1421 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1422 CheckInherents = CheckInherents,1423);1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19// #[cfg(any(feature = "std", test))]20// pub use sp_runtime::BuildStorage;2122use sp_runtime::{23 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24 traits::{25 AccountIdLookup, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify,26 AccountIdConversion,27 },28 transaction_validity::{TransactionSource, TransactionValidity},29 ApplyExtrinsicResult, MultiSignature,30};3132use sp_std::prelude::*;3334#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{38 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,39};40// A few exports that help ease life for downstream crates.41pub use pallet_balances::Call as BalancesCall;42pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};43pub use frame_support::{44 construct_runtime, match_type,45 dispatch::DispatchResult,46 PalletId, parameter_types, StorageValue, ConsensusEngineId,47 traits::{48 Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,49 LockIdentifier, OnUnbalanced, Randomness, FindAuthor,50 },51 weights::{52 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},53 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,54 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,55 },56};57use nft_data_structs::*;58// use pallet_contracts::weights::WeightInfo;59// #[cfg(any(feature = "std", test))]60use frame_system::{61 self as system, EnsureRoot, EnsureSigned,62 limits::{BlockWeights, BlockLength},63};64use sp_arithmetic::{65 traits::{BaseArithmetic, Unsigned},66};67use smallvec::smallvec;68use codec::{Encode, Decode};69use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};70use fp_rpc::TransactionStatus;71use sp_core::crypto::Public;72use sp_runtime::{73 traits::{Dispatchable, PostDispatchInfoOf},74 transaction_validity::TransactionValidityError,75};7677// pub use pallet_timestamp::Call as TimestampCall;78pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;7980// Polkadot imports81use pallet_xcm::XcmPassthrough;82use polkadot_parachain::primitives::Sibling;83use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};84use xcm_builder::{85 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,86 EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,87 ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,88 SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,89 SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,90};91use xcm_executor::{Config, XcmExecutor};9293// mod chain_extension;94// use crate::chain_extension::{NFTExtension, Imbalance};9596/// An index to a block.97pub type BlockNumber = u32;9899/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.100pub type Signature = MultiSignature;101102/// Some way of identifying an account on the chain. We intentionally make it equivalent103/// to the public key of our transaction signing scheme.104pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;105106pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;107108/// The type for looking up accounts. We don't expect more than 4 billion of them, but you109/// never know...110pub type AccountIndex = u32;111112/// Balance of an account.113pub type Balance = u128;114115/// Index of a transaction in the chain.116pub type Index = u32;117118/// A hash of some data used by the chain.119pub type Hash = sp_core::H256;120121/// Digest item type.122pub type DigestItem = generic::DigestItem<Hash>;123124/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know125/// the specifics of the runtime. They can then be made to be agnostic over specific formats126/// of data like extrinsics, allowing for them to continue syncing the network through upgrades127/// to even the core data structures.128pub mod opaque {129 use super::*;130131 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;132133 /// Opaque block type.134 pub type Block = generic::Block<Header, UncheckedExtrinsic>;135136 pub type SessionHandlers = ();137138 impl_opaque_keys! {139 pub struct SessionKeys {140 pub aura: Aura,141 }142 }143}144145/// This runtime version.146pub const VERSION: RuntimeVersion = RuntimeVersion {147 spec_name: create_runtime_str!("opal"),148 impl_name: create_runtime_str!("opal"),149 authoring_version: 1,150 spec_version: 912202,151 impl_version: 1,152 apis: RUNTIME_API_VERSIONS,153 transaction_version: 1,154};155156pub const MILLISECS_PER_BLOCK: u64 = 12000;157158pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;159160// These time units are defined in number of blocks.161pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);162pub const HOURS: BlockNumber = MINUTES * 60;163pub const DAYS: BlockNumber = HOURS * 24;164165parameter_types! {166 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;167}168169#[derive(codec::Encode, codec::Decode)]170pub enum XCMPMessage<XAccountId, XBalance> {171 /// Transfer tokens to the given account from the Parachain account.172 TransferToken(XAccountId, XBalance),173}174175/// The version information used to identify this runtime when compiled natively.176#[cfg(feature = "std")]177pub fn native_version() -> NativeVersion {178 NativeVersion {179 runtime_version: VERSION,180 can_author_with: Default::default(),181 }182}183184type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;185186pub struct DealWithFees;187impl OnUnbalanced<NegativeImbalance> for DealWithFees {188 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {189 if let Some(fees) = fees_then_tips.next() {190 // for fees, 100% to treasury191 let mut split = fees.ration(100, 0);192 if let Some(tips) = fees_then_tips.next() {193 // for tips, if any, 100% to treasury194 tips.ration_merge_into(100, 0, &mut split);195 }196 Treasury::on_unbalanced(split.0);197 // Author::on_unbalanced(split.1);198 }199 }200}201202/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.203/// This is used to limit the maximal weight of a single extrinsic.204const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);205/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used206/// by Operational extrinsics.207const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);208/// We allow for 2 seconds of compute with a 6 second average block time.209const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;210211parameter_types! {212 pub const BlockHashCount: BlockNumber = 2400;213 pub RuntimeBlockLength: BlockLength =214 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);215 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);216 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;217 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()218 .base_block(BlockExecutionWeight::get())219 .for_class(DispatchClass::all(), |weights| {220 weights.base_extrinsic = ExtrinsicBaseWeight::get();221 })222 .for_class(DispatchClass::Normal, |weights| {223 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);224 })225 .for_class(DispatchClass::Operational, |weights| {226 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);227 // Operational transactions have some extra reserved space, so that they228 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.229 weights.reserved = Some(230 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT231 );232 })233 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)234 .build_or_panic();235 pub const Version: RuntimeVersion = VERSION;236 pub const SS58Prefix: u8 = 42;237}238239parameter_types! {240 pub const ChainId: u64 = 8888;241}242243pub struct FixedFee;244impl FeeCalculator for FixedFee {245 fn min_gas_price() -> U256 {246 // Targeting 0.15 UNQ per transfer247 (1 * MICROUNIQUE).into()248 }249}250251// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case252// (contract, which only writes a lot of data),253// approximating on top of our real store write weight254parameter_types! {255 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;256 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;257 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();258}259260/// Limiting EVM execution to 50% of block for substrate users and management tasks261/// EVM transaction consumes more weight than substrate's, so we can't rely on them being262/// scheduled fairly263const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);264parameter_types! {265 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());266}267268pub enum FixedGasWeightMapping {}269impl GasWeightMapping for FixedGasWeightMapping {270 fn gas_to_weight(gas: u64) -> Weight {271 gas.saturating_mul(WeightPerGas::get())272 }273 fn weight_to_gas(weight: Weight) -> u64 {274 weight / WeightPerGas::get()275 }276}277278impl pallet_evm::Config for Runtime {279 type BlockGasLimit = BlockGasLimit;280 type FeeCalculator = FixedFee;281 type GasWeightMapping = FixedGasWeightMapping;282 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;283 type CallOrigin = EnsureAddressTruncated;284 type WithdrawOrigin = EnsureAddressTruncated;285 type AddressMapping = HashedAddressMapping<Self::Hashing>;286 type Precompiles = ();287 type Currency = Balances;288 type Event = Event;289 type OnMethodCall = (290 pallet_evm_migration::OnMethodCall<Self>,291 pallet_nft::NftErcSupport<Self>,292 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,293 );294 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;295 type ChainId = ChainId;296 type Runner = pallet_evm::runner::stack::Runner<Self>;297 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;298 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;299 type FindAuthor = EthereumFindAuthor<Aura>;300}301302impl pallet_evm_migration::Config for Runtime {303 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;304}305306pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);307impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {308 fn find_author<'a, I>(digests: I) -> Option<H160>309 where310 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,311 {312 if let Some(author_index) = F::find_author(digests) {313 let authority_id = Aura::authorities()[author_index as usize].clone();314 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));315 }316 None317 }318}319320impl pallet_ethereum::Config for Runtime {321 type Event = Event;322 type StateRoot = pallet_ethereum::IntermediateStateRoot;323}324325impl pallet_randomness_collective_flip::Config for Runtime {}326327impl system::Config for Runtime {328 /// The data to be stored in an account.329 type AccountData = pallet_balances::AccountData<Balance>;330 /// The identifier used to distinguish between accounts.331 type AccountId = AccountId;332 /// The basic call filter to use in dispatchable.333 type BaseCallFilter = Everything;334 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).335 type BlockHashCount = BlockHashCount;336 /// The maximum length of a block (in bytes).337 type BlockLength = RuntimeBlockLength;338 /// The index type for blocks.339 type BlockNumber = BlockNumber;340 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.341 type BlockWeights = RuntimeBlockWeights;342 /// The aggregated dispatch type that is available for extrinsics.343 type Call = Call;344 /// The weight of database operations that the runtime can invoke.345 type DbWeight = RocksDbWeight;346 /// The ubiquitous event type.347 type Event = Event;348 /// The type for hashing blocks and tries.349 type Hash = Hash;350 /// The hashing algorithm used.351 type Hashing = BlakeTwo256;352 /// The header type.353 type Header = generic::Header<BlockNumber, BlakeTwo256>;354 /// The index type for storing how many extrinsics an account has signed.355 type Index = Index;356 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.357 type Lookup = AccountIdLookup<AccountId, ()>;358 /// What to do if an account is fully reaped from the system.359 type OnKilledAccount = ();360 /// What to do if a new account is created.361 type OnNewAccount = ();362 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;363 /// The ubiquitous origin type.364 type Origin = Origin;365 /// This type is being generated by `construct_runtime!`.366 type PalletInfo = PalletInfo;367 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.368 type SS58Prefix = SS58Prefix;369 /// Weight information for the extrinsics of this pallet.370 type SystemWeightInfo = system::weights::SubstrateWeight<Self>;371 /// Version of the runtime.372 type Version = Version;373}374375parameter_types! {376 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;377}378379impl pallet_timestamp::Config for Runtime {380 /// A timestamp: milliseconds since the unix epoch.381 type Moment = u64;382 type OnTimestampSet = ();383 type MinimumPeriod = MinimumPeriod;384 type WeightInfo = ();385}386387parameter_types! {388 // pub const ExistentialDeposit: u128 = 500;389 pub const ExistentialDeposit: u128 = 0;390 pub const MaxLocks: u32 = 50;391}392393impl pallet_balances::Config for Runtime {394 type MaxLocks = MaxLocks;395 type MaxReserves = ();396 type ReserveIdentifier = [u8; 8];397 /// The type for recording an account's balance.398 type Balance = Balance;399 /// The ubiquitous event type.400 type Event = Event;401 type DustRemoval = Treasury;402 type ExistentialDeposit = ExistentialDeposit;403 type AccountStore = System;404 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;405}406407pub const MICROUNIQUE: Balance = 1_000_000_000;408pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;409pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;410pub const UNIQUE: Balance = 100 * CENTIUNIQUE;411412pub const fn deposit(items: u32, bytes: u32) -> Balance {413 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE414}415416/*417parameter_types! {418 pub TombstoneDeposit: Balance = deposit(419 1,420 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,421 );422 pub DepositPerContract: Balance = TombstoneDeposit::get();423 pub const DepositPerStorageByte: Balance = deposit(0, 1);424 pub const DepositPerStorageItem: Balance = deposit(1, 0);425 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);426 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;427 pub const SignedClaimHandicap: u32 = 2;428 pub const MaxDepth: u32 = 32;429 pub const MaxValueSize: u32 = 16 * 1024;430 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb431 // The lazy deletion runs inside on_initialize.432 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *433 RuntimeBlockWeights::get().max_block;434 // The weight needed for decoding the queue should be less or equal than a fifth435 // of the overall weight dedicated to the lazy deletion.436 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (437 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -438 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)439 )) / 5) as u32;440 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();441}442443impl pallet_contracts::Config for Runtime {444 type Time = Timestamp;445 type Randomness = RandomnessCollectiveFlip;446 type Currency = Balances;447 type Event = Event;448 type RentPayment = ();449 type SignedClaimHandicap = SignedClaimHandicap;450 type TombstoneDeposit = TombstoneDeposit;451 type DepositPerContract = DepositPerContract;452 type DepositPerStorageByte = DepositPerStorageByte;453 type DepositPerStorageItem = DepositPerStorageItem;454 type RentFraction = RentFraction;455 type SurchargeReward = SurchargeReward;456 type WeightPrice = pallet_transaction_payment::Pallet<Self>;457 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;458 type ChainExtension = NFTExtension;459 type DeletionQueueDepth = DeletionQueueDepth;460 type DeletionWeightLimit = DeletionWeightLimit;461 type Schedule = Schedule;462 type CallStack = [pallet_contracts::Frame<Self>; 31];463}464*/465466parameter_types! {467 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer468 /// This value increases the priority of `Operational` transactions by adding469 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.470 pub const OperationalFeeMultiplier: u8 = 5;471}472473/// Linear implementor of `WeightToFeePolynomial`474pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);475476impl<T> WeightToFeePolynomial for LinearFee<T>477where478 T: BaseArithmetic + From<u32> + Copy + Unsigned,479{480 type Balance = T;481482 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {483 smallvec!(WeightToFeeCoefficient {484 coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer485 coeff_frac: Perbill::zero(),486 negative: false,487 degree: 1,488 })489 }490}491492impl pallet_transaction_payment::Config for Runtime {493 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;494 type TransactionByteFee = TransactionByteFee;495 type OperationalFeeMultiplier = OperationalFeeMultiplier;496 type WeightToFee = LinearFee<Balance>;497 type FeeMultiplierUpdate = ();498}499500parameter_types! {501 pub const ProposalBond: Permill = Permill::from_percent(5);502 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;503 pub const SpendPeriod: BlockNumber = 5 * MINUTES;504 pub const Burn: Permill = Permill::from_percent(0);505 pub const TipCountdown: BlockNumber = 1 * DAYS;506 pub const TipFindersFee: Percent = Percent::from_percent(20);507 pub const TipReportDepositBase: Balance = 1 * UNIQUE;508 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;509 pub const BountyDepositBase: Balance = 1 * UNIQUE;510 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;511 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");512 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;513 pub const MaximumReasonLength: u32 = 16384;514 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);515 pub const BountyValueMinimum: Balance = 5 * UNIQUE;516 pub const MaxApprovals: u32 = 100;517}518519impl pallet_treasury::Config for Runtime {520 type PalletId = TreasuryModuleId;521 type Currency = Balances;522 type ApproveOrigin = EnsureRoot<AccountId>;523 type RejectOrigin = EnsureRoot<AccountId>;524 type Event = Event;525 type OnSlash = ();526 type ProposalBond = ProposalBond;527 type ProposalBondMinimum = ProposalBondMinimum;528 type SpendPeriod = SpendPeriod;529 type Burn = Burn;530 type BurnDestination = ();531 type SpendFunds = ();532 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;533 type MaxApprovals = MaxApprovals;534}535536impl pallet_sudo::Config for Runtime {537 type Event = Event;538 type Call = Call;539}540541parameter_types! {542 pub const MinVestedTransfer: Balance = 10 * UNIQUE;543}544545impl pallet_vesting::Config for Runtime {546 type Event = Event;547 type Currency = Balances;548 type BlockNumberToBalance = ConvertInto;549 type MinVestedTransfer = MinVestedTransfer;550 type WeightInfo = ();551 const MAX_VESTING_SCHEDULES: u32 = 28;552}553554parameter_types! {555 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;556 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;557}558559impl cumulus_pallet_parachain_system::Config for Runtime {560 type Event = Event;561 type OnValidationData = ();562 type SelfParaId = parachain_info::Pallet<Self>;563 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<564 // MaxDownwardMessageWeight,565 // XcmExecutor<XcmConfig>,566 // Call,567 // >;568 type OutboundXcmpMessageSource = XcmpQueue;569 type DmpMessageHandler = DmpQueue;570 type ReservedDmpWeight = ReservedDmpWeight;571 type ReservedXcmpWeight = ReservedXcmpWeight;572 type XcmpMessageHandler = XcmpQueue;573}574575impl parachain_info::Config for Runtime {}576577impl cumulus_pallet_aura_ext::Config for Runtime {}578579parameter_types! {580 pub const RelayLocation: MultiLocation = MultiLocation::parent();581 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;582 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();583 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();584}585586/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used587/// when determining ownership of accounts for asset transacting and when attempting to use XCM588/// `Transact` in order to determine the dispatch Origin.589pub type LocationToAccountId = (590 // The parent (Relay-chain) origin converts to the default `AccountId`.591 ParentIsDefault<AccountId>,592 // Sibling parachain origins convert to AccountId via the `ParaId::into`.593 SiblingParachainConvertsVia<Sibling, AccountId>,594 // Straight up local `AccountId32` origins just alias directly to `AccountId`.595 AccountId32Aliases<RelayNetwork, AccountId>,596);597598/// Means for transacting assets on this chain.599pub type LocalAssetTransactor = CurrencyAdapter<600 // Use this currency:601 Balances,602 // Use this currency when it is a fungible asset matching the given location or name:603 IsConcrete<RelayLocation>,604 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:605 LocationToAccountId,606 // Our chain's account ID type (we can't get away without mentioning it explicitly):607 AccountId,608 // We don't track any teleports.609 (),610>;611612/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,613/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can614/// biases the kind of local `Origin` it will become.615pub type XcmOriginToTransactDispatchOrigin = (616 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location617 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for618 // foreign chains who want to have a local sovereign account on this chain which they control.619 SovereignSignedViaLocation<LocationToAccountId, Origin>,620 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when621 // recognised.622 RelayChainAsNative<RelayOrigin, Origin>,623 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when624 // recognised.625 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,626 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a627 // transaction from the Root origin.628 ParentAsSuperuser<Origin>,629 // Native signed account converter; this just converts an `AccountId32` origin into a normal630 // `Origin::Signed` origin of the same 32-byte value.631 SignedAccountId32AsNative<RelayNetwork, Origin>,632 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.633 XcmPassthrough<Origin>,634);635636parameter_types! {637 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.638 pub UnitWeightCost: Weight = 1_000_000;639 // 1200 UNIQUEs buy 1 second of weight.640 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);641 pub const MaxInstructions: u32 = 100;642 pub const MaxAuthorities: u32 = 100_000;643}644645match_type! {646 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {647 MultiLocation { parents: 1, interior: Here } |648 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }649 };650}651652pub type Barrier = (653 TakeWeightCredit,654 AllowTopLevelPaidExecutionFrom<Everything>,655 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,656 // ^^^ Parent & its unit plurality gets free execution657);658659pub struct XcmConfig;660impl Config for XcmConfig {661 type Call = Call;662 type XcmSender = XcmRouter;663 // How to withdraw and deposit an asset.664 type AssetTransactor = LocalAssetTransactor;665 type OriginConverter = XcmOriginToTransactDispatchOrigin;666 type IsReserve = NativeAsset;667 type IsTeleporter = (); // Teleportation is disabled668 type LocationInverter = LocationInverter<Ancestry>;669 type Barrier = Barrier;670 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;671 type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;672 type ResponseHandler = (); // Don't handle responses for now.673 type SubscriptionService = PolkadotXcm;674675 type AssetTrap = PolkadotXcm;676 type AssetClaims = PolkadotXcm;677}678679// parameter_types! {680// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;681// }682683/// No local origins on this chain are allowed to dispatch XCM sends/executions.684pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);685686/// The means for routing XCM messages which are not for local execution into the right message687/// queues.688pub type XcmRouter = (689 // Two routers - use UMP to communicate with the relay chain:690 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,691 // ..and XCMP to communicate with the sibling chains.692 XcmpQueue,693);694695impl pallet_evm_coder_substrate::Config for Runtime {696 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;697 type GasWeightMapping = FixedGasWeightMapping;698}699700impl pallet_xcm::Config for Runtime {701 type Event = Event;702 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;703 type XcmRouter = XcmRouter;704 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;705 type XcmExecuteFilter = Everything;706 type XcmExecutor = XcmExecutor<XcmConfig>;707 type XcmTeleportFilter = Everything;708 type XcmReserveTransferFilter = Everything;709 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;710 type LocationInverter = LocationInverter<Ancestry>;711 type Origin = Origin;712 type Call = Call;713 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;714 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;715}716717impl cumulus_pallet_xcm::Config for Runtime {718 type Event = Event;719 type XcmExecutor = XcmExecutor<XcmConfig>;720}721722impl cumulus_pallet_xcmp_queue::Config for Runtime {723 type Event = Event;724 type XcmExecutor = XcmExecutor<XcmConfig>;725 type ChannelInfo = ParachainSystem;726 type VersionWrapper = ();727}728729impl cumulus_pallet_dmp_queue::Config for Runtime {730 type Event = Event;731 type XcmExecutor = XcmExecutor<XcmConfig>;732 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;733}734735impl pallet_aura::Config for Runtime {736 type AuthorityId = AuraId;737 type DisabledValidators = ();738 type MaxAuthorities = MaxAuthorities;739}740741parameter_types! {742 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();743 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;744}745746impl pallet_common::Config for Runtime {747 type Event = Event;748 type EvmBackwardsAddressMapping = pallet_common::account::MapBackwardsAddressTruncated;749 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;750 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;751752 type Currency = Balances;753 type CollectionCreationPrice = CollectionCreationPrice;754 type TreasuryAccountId = TreasuryAccountId;755}756757impl pallet_fungible::Config for Runtime {758 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;759}760impl pallet_refungible::Config for Runtime {761 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;762}763impl pallet_nonfungible::Config for Runtime {764 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;765}766767/// Used for the pallet nft in `./nft.rs`768impl pallet_nft::Config for Runtime {769 type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;770}771772parameter_types! {773 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied774}775776/// Used for the pallet inflation777impl pallet_inflation::Config for Runtime {778 type Currency = Balances;779 type TreasuryAccountId = TreasuryAccountId;780 type InflationBlockInterval = InflationBlockInterval;781}782783parameter_types! {784 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *785 RuntimeBlockWeights::get().max_block;786 pub const MaxScheduledPerBlock: u32 = 50;787}788789pub struct Sponsoring;790impl SponsoringResolve<AccountId, Call> for Sponsoring {791 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>792 where793 Call: Dispatchable<Info = DispatchInfo>,794 AccountId: AsRef<[u8]>,795 {796 pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)797 }798}799800type SponsorshipHandler = (801 pallet_nft::NftSponsorshipHandler<Runtime>,802 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,803);804805impl pallet_unq_scheduler::Config for Runtime {806 type Event = Event;807 type Origin = Origin;808 type PalletsOrigin = OriginCaller;809 type Call = Call;810 type MaximumWeight = MaximumSchedulerWeight;811 type ScheduleOrigin = EnsureSigned<AccountId>;812 type MaxScheduledPerBlock = MaxScheduledPerBlock;813 type SponsorshipHandler = SponsorshipHandler;814 type WeightInfo = ();815}816817impl pallet_nft_transaction_payment::Config for Runtime {818 type SponsorshipHandler = SponsorshipHandler;819}820821impl pallet_evm_transaction_payment::Config for Runtime {822 type SponsorshipHandler = (823 pallet_nft::NftEthSponsorshipHandler<Self>,824 pallet_evm_contract_helpers::HelpersContractSponsoring<Self>,825 );826 type Currency = Balances;827}828829impl pallet_nft_charge_transaction::Config for Runtime {830 type SponsorshipHandler = pallet_nft::NftSponsorshipHandler<Runtime>;831}832833// impl pallet_contract_helpers::Config for Runtime {834// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;835// }836837parameter_types! {838 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049839 pub const HelpersContractAddress: H160 = H160([840 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,841 ]);842}843844impl pallet_evm_contract_helpers::Config for Runtime {845 type ContractAddress = HelpersContractAddress;846 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;847}848849construct_runtime!(850 pub enum Runtime where851 Block = Block,852 NodeBlock = opaque::Block,853 UncheckedExtrinsic = UncheckedExtrinsic854 {855 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,856 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,857858 Aura: pallet_aura::{Pallet, Config<T>} = 22,859 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,860861 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,862 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,863 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,864 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,865 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,866 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,867 System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,868 Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,869 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,870871 // XCM helpers.872 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,873 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,874 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,875 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,876877 // Unique Pallets878 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,879 Nft: pallet_nft::{Pallet, Call, Storage} = 61,880 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,881 NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,882 Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,883 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,884 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,885 Fungible: pallet_fungible::{Pallet, Storage} = 67,886 Refungible: pallet_refungible::{Pallet, Storage} = 68,887 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,888889 // Frontier890 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,891 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,892893 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,894 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,895 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,896 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,897 }898);899900pub struct TransactionConverter;901902impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {903 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {904 UncheckedExtrinsic::new_unsigned(905 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),906 )907 }908}909910impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {911 fn convert_transaction(912 &self,913 transaction: pallet_ethereum::Transaction,914 ) -> opaque::UncheckedExtrinsic {915 let extrinsic = UncheckedExtrinsic::new_unsigned(916 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),917 );918 let encoded = extrinsic.encode();919 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])920 .expect("Encoded extrinsic is always valid")921 }922}923924/// The address format for describing accounts.925pub type Address = sp_runtime::MultiAddress<AccountId, ()>;926/// Block header type as expected by this runtime.927pub type Header = generic::Header<BlockNumber, BlakeTwo256>;928/// Block type as expected by this runtime.929pub type Block = generic::Block<Header, UncheckedExtrinsic>;930/// A Block signed with a Justification931pub type SignedBlock = generic::SignedBlock<Block>;932/// BlockId type as expected by this runtime.933pub type BlockId = generic::BlockId<Block>;934/// The SignedExtension to the basic transaction logic.935pub type SignedExtra = (936 system::CheckSpecVersion<Runtime>,937 // system::CheckTxVersion<Runtime>,938 system::CheckGenesis<Runtime>,939 system::CheckEra<Runtime>,940 system::CheckNonce<Runtime>,941 system::CheckWeight<Runtime>,942 pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,943 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,944);945/// Unchecked extrinsic type as expected by this runtime.946pub type UncheckedExtrinsic =947 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;948/// Extrinsic type that has already been checked.949pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;950/// Executive: handles dispatch to the various modules.951pub type Executive = frame_executive::Executive<952 Runtime,953 Block,954 frame_system::ChainContext<Runtime>,955 Runtime,956 AllPallets,957>;958959impl_opaque_keys! {960 pub struct SessionKeys {961 pub aura: Aura,962 }963}964965impl fp_self_contained::SelfContainedCall for Call {966 type SignedInfo = H160;967968 fn is_self_contained(&self) -> bool {969 match self {970 Call::Ethereum(call) => call.is_self_contained(),971 _ => false,972 }973 }974975 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {976 match self {977 Call::Ethereum(call) => call.check_self_contained(),978 _ => None,979 }980 }981982 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {983 match self {984 Call::Ethereum(call) => call.validate_self_contained(info),985 _ => None,986 }987 }988989 fn pre_dispatch_self_contained(990 &self,991 info: &Self::SignedInfo,992 ) -> Option<Result<(), TransactionValidityError>> {993 match self {994 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),995 _ => None,996 }997 }998999 fn apply_self_contained(1000 self,1001 info: Self::SignedInfo,1002 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1003 match self {1004 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1005 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1006 )),1007 _ => None,1008 }1009 }1010}10111012macro_rules! dispatch_nft_runtime {1013 ($collection:ident.$method:ident($($name:ident),*)) => {{1014 use pallet_nft::dispatch::Dispatched;10151016 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::new($collection).unwrap());1017 let dispatch = collection.as_dyn();10181019 dispatch.$method($($name),*)1020 }};1021}1022impl_runtime_apis! {1023 impl up_rpc::NftApi<Block, CrossAccountId, AccountId>1024 for Runtime1025 {1026 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId> {1027 dispatch_nft_runtime!(collection.account_tokens(account))1028 }1029 fn token_exists(collection: CollectionId, token: TokenId) -> bool {1030 dispatch_nft_runtime!(collection.token_exists(token))1031 }10321033 fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId {1034 dispatch_nft_runtime!(collection.token_owner(token))1035 }1036 fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1037 dispatch_nft_runtime!(collection.const_metadata(token))1038 }1039 fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1040 dispatch_nft_runtime!(collection.variable_metadata(token))1041 }10421043 fn collection_tokens(collection: CollectionId) -> u32 {1044 dispatch_nft_runtime!(collection.collection_tokens())1045 }1046 fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32 {1047 dispatch_nft_runtime!(collection.account_balance(account))1048 }1049 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128 {1050 dispatch_nft_runtime!(collection.balance(account, token))1051 }1052 fn allowance(1053 collection: CollectionId,1054 sender: CrossAccountId,1055 spender: CrossAccountId,1056 token: TokenId,1057 ) -> u128 {1058 dispatch_nft_runtime!(collection.allowance(sender, spender, token))1059 }10601061 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1062 <pallet_nft::NftErcSupport<Runtime>>::get_code(&account)1063 .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1064 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1065 }1066 fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {1067 <pallet_nft::Pallet<Runtime>>::adminlist(collection)1068 }1069 fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {1070 <pallet_nft::Pallet<Runtime>>::allowlist(collection)1071 }1072 fn last_token_id(collection: CollectionId) -> TokenId {1073 dispatch_nft_runtime!(collection.last_token_id())1074 }1075 }10761077 impl sp_api::Core<Block> for Runtime {1078 fn version() -> RuntimeVersion {1079 VERSION1080 }10811082 fn execute_block(block: Block) {1083 Executive::execute_block(block)1084 }10851086 fn initialize_block(header: &<Block as BlockT>::Header) {1087 Executive::initialize_block(header)1088 }1089 }10901091 impl sp_api::Metadata<Block> for Runtime {1092 fn metadata() -> OpaqueMetadata {1093 OpaqueMetadata::new(Runtime::metadata().into())1094 }1095 }10961097 impl sp_block_builder::BlockBuilder<Block> for Runtime {1098 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1099 Executive::apply_extrinsic(extrinsic)1100 }11011102 fn finalize_block() -> <Block as BlockT>::Header {1103 Executive::finalize_block()1104 }11051106 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1107 data.create_extrinsics()1108 }11091110 fn check_inherents(1111 block: Block,1112 data: sp_inherents::InherentData,1113 ) -> sp_inherents::CheckInherentsResult {1114 data.check_extrinsics(&block)1115 }11161117 // fn random_seed() -> <Block as BlockT>::Hash {1118 // RandomnessCollectiveFlip::random_seed().01119 // }1120 }11211122 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1123 fn validate_transaction(1124 source: TransactionSource,1125 tx: <Block as BlockT>::Extrinsic,1126 hash: <Block as BlockT>::Hash,1127 ) -> TransactionValidity {1128 Executive::validate_transaction(source, tx, hash)1129 }1130 }11311132 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1133 fn offchain_worker(header: &<Block as BlockT>::Header) {1134 Executive::offchain_worker(header)1135 }1136 }11371138 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1139 fn chain_id() -> u64 {1140 <Runtime as pallet_evm::Config>::ChainId::get()1141 }11421143 fn account_basic(address: H160) -> EVMAccount {1144 EVM::account_basic(&address)1145 }11461147 fn gas_price() -> U256 {1148 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1149 }11501151 fn account_code_at(address: H160) -> Vec<u8> {1152 EVM::account_codes(address)1153 }11541155 fn author() -> H160 {1156 <pallet_evm::Pallet<Runtime>>::find_author()1157 }11581159 fn storage_at(address: H160, index: U256) -> H256 {1160 let mut tmp = [0u8; 32];1161 index.to_big_endian(&mut tmp);1162 EVM::account_storages(address, H256::from_slice(&tmp[..]))1163 }11641165 fn call(1166 from: H160,1167 to: H160,1168 data: Vec<u8>,1169 value: U256,1170 gas_limit: U256,1171 gas_price: Option<U256>,1172 nonce: Option<U256>,1173 estimate: bool,1174 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1175 let config = if estimate {1176 let mut config = <Runtime as pallet_evm::Config>::config().clone();1177 config.estimate = true;1178 Some(config)1179 } else {1180 None1181 };11821183 <Runtime as pallet_evm::Config>::Runner::call(1184 from,1185 to,1186 data,1187 value,1188 gas_limit.low_u64(),1189 gas_price,1190 nonce,1191 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1192 ).map_err(|err| err.into())1193 }11941195 fn create(1196 from: H160,1197 data: Vec<u8>,1198 value: U256,1199 gas_limit: U256,1200 gas_price: Option<U256>,1201 nonce: Option<U256>,1202 estimate: bool,1203 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1204 let config = if estimate {1205 let mut config = <Runtime as pallet_evm::Config>::config().clone();1206 config.estimate = true;1207 Some(config)1208 } else {1209 None1210 };12111212 <Runtime as pallet_evm::Config>::Runner::create(1213 from,1214 data,1215 value,1216 gas_limit.low_u64(),1217 gas_price,1218 nonce,1219 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1220 ).map_err(|err| err.into())1221 }12221223 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1224 Ethereum::current_transaction_statuses()1225 }12261227 fn current_block() -> Option<pallet_ethereum::Block> {1228 Ethereum::current_block()1229 }12301231 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1232 Ethereum::current_receipts()1233 }12341235 fn current_all() -> (1236 Option<pallet_ethereum::Block>,1237 Option<Vec<pallet_ethereum::Receipt>>,1238 Option<Vec<TransactionStatus>>1239 ) {1240 (1241 Ethereum::current_block(),1242 Ethereum::current_receipts(),1243 Ethereum::current_transaction_statuses()1244 )1245 }12461247 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1248 xts.into_iter().filter_map(|xt| match xt.0.function {1249 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1250 _ => None1251 }).collect()1252 }1253 }12541255 impl sp_session::SessionKeys<Block> for Runtime {1256 fn decode_session_keys(1257 encoded: Vec<u8>,1258 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1259 SessionKeys::decode_into_raw_public_keys(&encoded)1260 }12611262 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1263 SessionKeys::generate(seed)1264 }1265 }12661267 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1268 fn slot_duration() -> sp_consensus_aura::SlotDuration {1269 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1270 }12711272 fn authorities() -> Vec<AuraId> {1273 Aura::authorities().to_vec()1274 }1275 }12761277 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1278 fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1279 ParachainSystem::collect_collation_info()1280 }1281 }12821283 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1284 fn account_nonce(account: AccountId) -> Index {1285 System::account_nonce(account)1286 }1287 }12881289 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1290 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1291 TransactionPayment::query_info(uxt, len)1292 }1293 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1294 TransactionPayment::query_fee_details(uxt, len)1295 }1296 }12971298 /*1299 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1300 for Runtime1301 {1302 fn call(1303 origin: AccountId,1304 dest: AccountId,1305 value: Balance,1306 gas_limit: u64,1307 input_data: Vec<u8>,1308 ) -> pallet_contracts_primitives::ContractExecResult {1309 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1310 }13111312 fn instantiate(1313 origin: AccountId,1314 endowment: Balance,1315 gas_limit: u64,1316 code: pallet_contracts_primitives::Code<Hash>,1317 data: Vec<u8>,1318 salt: Vec<u8>,1319 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1320 {1321 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1322 }13231324 fn get_storage(1325 address: AccountId,1326 key: [u8; 32],1327 ) -> pallet_contracts_primitives::GetStorageResult {1328 Contracts::get_storage(address, key)1329 }13301331 fn rent_projection(1332 address: AccountId,1333 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1334 Contracts::rent_projection(address)1335 }1336 }1337 */13381339 #[cfg(feature = "runtime-benchmarks")]1340 impl frame_benchmarking::Benchmark<Block> for Runtime {1341 fn benchmark_metadata(extra: bool) -> (1342 Vec<frame_benchmarking::BenchmarkList>,1343 Vec<frame_support::traits::StorageInfo>,1344 ) {1345 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1346 use frame_support::traits::StorageInfoTrait;13471348 let mut list = Vec::<BenchmarkList>::new();13491350 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1351 list_benchmark!(list, extra, pallet_nft, Nft);1352 list_benchmark!(list, extra, pallet_inflation, Inflation);1353 list_benchmark!(list, extra, pallet_fungible, Fungible);1354 list_benchmark!(list, extra, pallet_refungible, Refungible);1355 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);1356 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);13571358 let storage_info = AllPalletsWithSystem::storage_info();13591360 return (list, storage_info)1361 }13621363 fn dispatch_benchmark(1364 config: frame_benchmarking::BenchmarkConfig1365 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1366 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};13671368 let allowlist: Vec<TrackedStorageKey> = vec![1369 // Block Number1370 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1371 // Total Issuance1372 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1373 // Execution Phase1374 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1375 // Event Count1376 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1377 // System Events1378 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1379 ];13801381 let mut batches = Vec::<BenchmarkBatch>::new();1382 let params = (&config, &allowlist);13831384 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1385 add_benchmark!(params, batches, pallet_nft, Nft);1386 add_benchmark!(params, batches, pallet_inflation, Inflation);1387 add_benchmark!(params, batches, pallet_fungible, Fungible);1388 add_benchmark!(params, batches, pallet_refungible, Refungible);1389 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);1390 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);13911392 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1393 Ok(batches)1394 }1395 }1396}13971398struct CheckInherents;13991400impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1401 fn check_inherents(1402 block: &Block,1403 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1404 ) -> sp_inherents::CheckInherentsResult {1405 let relay_chain_slot = relay_state_proof1406 .read_slot()1407 .expect("Could not read the relay chain slot from the proof");14081409 let inherent_data =1410 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1411 relay_chain_slot,1412 sp_std::time::Duration::from_secs(6),1413 )1414 .create_inherent_data()1415 .expect("Could not create the timestamp inherent data");14161417 inherent_data.check_extrinsics(block)1418 }1419}14201421cumulus_pallet_parachain_system::register_validate_block!(1422 Runtime = Runtime,1423 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1424 CheckInherents = CheckInherents,1425);smart_contracs/transfer/lib.rsdiffbeforeafterboth--- a/smart_contracs/transfer/lib.rs
+++ b/smart_contracs/transfer/lib.rs
@@ -75,7 +75,7 @@
#[ink(extension = 5, returns_result = false)]
fn set_variable_meta_data(collection_id: u32, item_id: u32, data: Vec<u8>);
#[ink(extension = 6, returns_result = false)]
- fn toggle_white_list(collection_id: u32, address: DefaultAccountId, whitelisted: bool);
+ fn toggle_allow_list(collection_id: u32, address: DefaultAccountId, allowlisted: bool);
}
#[ink::contract(env = crate::NftEnvironment, dynamic_storage_allocator = true)]
@@ -135,10 +135,10 @@
.set_variable_meta_data(collection_id, item_id, data);
}
#[ink(message)]
- pub fn toggle_white_list(&mut self, collection_id: u32, address: AccountId, whitelisted: bool) {
+ pub fn toggle_allow_list(&mut self, collection_id: u32, address: AccountId, allowlisted: bool) {
let _ = self.env()
.extension()
- .toggle_white_list(collection_id, address, whitelisted);
+ .toggle_allow_list(collection_id, address, allowlisted);
}
}
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -42,7 +42,7 @@
"testConfirmSponsorship": "mocha --timeout 9999999 -r ts-node/register ./**/confirmSponsorship.test.ts",
"testRemoveCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionAdmin.test.ts",
"testRemoveCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionSponsor.test.ts",
- "testRemoveFromWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromWhiteList.test.ts",
+ "testRemoveFromAllowList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromAllowList.test.ts",
"testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",
"testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
"testContracts": "mocha --timeout 9999999 -r ts-node/register ./**/contracts.test.ts",
@@ -51,14 +51,14 @@
"testApprove": "mocha --timeout 9999999 -r ts-node/register ./**/approve.test.ts",
"testTransferFrom": "mocha --timeout 9999999 -r ts-node/register ./**/transferFrom.test.ts",
"testCreateCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
- "testToggleContractWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/toggleContractWhiteList.test.ts",
- "testAddToContractWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/addToContractWhiteList.test.ts",
+ "testToggleContractAllowList": "mocha --timeout 9999999 -r ts-node/register ./**/toggleContractAllowList.test.ts",
+ "testAddToContractAllowList": "mocha --timeout 9999999 -r ts-node/register ./**/addToContractAllowList.test.ts",
"testTransfer": "mocha --timeout 9999999 -r ts-node/register ./**/transfer.test.ts",
"testBurnItem": "mocha --timeout 9999999 -r ts-node/register ./**/burnItem.test.ts",
"testSetMintPermission": "mocha --timeout 9999999 -r ts-node/register ./**/setMintPermission.test.ts",
"testCreditFeesToTreasury": "mocha --timeout 9999999 -r ts-node/register ./**/creditFeesToTreasury.test.ts",
"testEnableContractSponsoring": "mocha --timeout 9999999 -r ts-node/register ./**/enableContractSponsoring.test.ts",
- "testRemoveFromContractWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromContractWhiteList.test.ts",
+ "testRemoveFromContractAllowList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromContractAllowList.test.ts",
"testSetContractSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setContractSponsoringRateLimit.test.ts",
"testSetOffchainSchema": "mocha --timeout 9999999 -r ts-node/register ./**/setOffchainSchema.test.ts",
"testOverflow": "mocha --timeout 9999999 -r ts-node/register ./**/overflow.test.ts",
tests/src/addToAllowList.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/addToAllowList.test.ts
@@ -0,0 +1,124 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import {IKeyringPair} from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from './substrate/privateKey';
+import usingApi, {submitTransactionExpectFailAsync} from './substrate/substrate-api';
+import {
+ addToAllowListExpectSuccess,
+ createCollectionExpectSuccess,
+ createItemExpectSuccess,
+ destroyCollectionExpectSuccess,
+ enablePublicMintingExpectSuccess,
+ enableAllowListExpectSuccess,
+ normalizeAccountId,
+ addCollectionAdminExpectSuccess,
+ addToAllowListExpectFail,
+} from './util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+let alice: IKeyringPair;
+let bob: IKeyringPair;
+let charlie: IKeyringPair;
+
+describe('Integration Test ext. addToAllowList()', () => {
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+ });
+
+ it('Execute the extrinsic with parameters: Collection ID and address to add to the allow list', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
+ });
+
+ it('Allowlisted minting: list restrictions', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await createItemExpectSuccess(bob, collectionId, 'NFT', bob.address);
+ });
+});
+
+describe('Negative Integration Test ext. addToAllowList()', () => {
+
+ it('Allow list an address in the collection that does not exist', async () => {
+ await usingApi(async (api) => {
+ // tslint:disable-next-line: no-bitwise
+ const collectionId = ((await api.query.common.createdCollectionCount()).toNumber()) + 1;
+ const bob = privateKey('//Bob');
+
+ const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(bob.address));
+ await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
+ });
+ });
+
+ it('Allow list an address in the collection that was destroyed', async () => {
+ await usingApi(async (api) => {
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ // tslint:disable-next-line: no-bitwise
+ const collectionId = await createCollectionExpectSuccess();
+ await destroyCollectionExpectSuccess(collectionId);
+ const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(bob.address));
+ await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
+ });
+ });
+
+ it('Allow list an address in the collection that does not have allow list access enabled', async () => {
+ await usingApi(async (api) => {
+ const alice = privateKey('//Alice');
+ const ferdie = privateKey('//Ferdie');
+ const collectionId = await createCollectionExpectSuccess();
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(ferdie.address), 'NFT');
+ await expect(submitTransactionExpectFailAsync(ferdie, tx)).to.be.rejected;
+ });
+ });
+
+});
+
+describe('Integration Test ext. addToAllowList() with collection admin permissions:', () => {
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ charlie = privateKey('//Charlie');
+ });
+ });
+
+ it('Negative. Add to the allow list by regular user', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addToAllowListExpectFail(bob, collectionId, charlie.address);
+ });
+
+ it('Execute the extrinsic with parameters: Collection ID and address to add to the allow list', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ await addToAllowListExpectSuccess(bob, collectionId, charlie.address);
+ });
+
+ it('Allowlisted minting: list restrictions', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ await addToAllowListExpectSuccess(bob, collectionId, charlie.address);
+
+ // allowed only for collection owner
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+
+ await createItemExpectSuccess(charlie, collectionId, 'NFT', charlie.address);
+ });
+});
tests/src/addToContractAllowList.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/addToContractAllowList.test.ts
@@ -0,0 +1,92 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import usingApi, {submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
+import privateKey from './substrate/privateKey';
+import {
+ deployFlipper,
+} from './util/contracthelpers';
+import {
+ getGenericResult,
+} from './util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe.skip('Integration Test addToContractAllowList', () => {
+
+ it('Add an address to a contract allow list', async () => {
+ await usingApi(async api => {
+ const bob = privateKey('//Bob');
+ const [contract, deployer] = await deployFlipper(api);
+
+ const allowListedBefore = (await api.query.nft.contractAllowList(contract.address, bob.address)).toJSON();
+ const addTx = api.tx.nft.addToContractAllowList(contract.address, bob.address);
+ const addEvents = await submitTransactionAsync(deployer, addTx);
+ const allowListedAfter = (await api.query.nft.contractAllowList(contract.address, bob.address)).toJSON();
+
+ expect(getGenericResult(addEvents).success).to.be.true;
+ expect(allowListedBefore).to.be.false;
+ expect(allowListedAfter).to.be.true;
+ });
+ });
+
+ it('Adding same address to allow list repeatedly should not produce errors', async () => {
+ await usingApi(async api => {
+ const bob = privateKey('//Bob');
+ const [contract, deployer] = await deployFlipper(api);
+
+ const allowListedBefore = (await api.query.nft.contractAllowList(contract.address, bob.address)).toJSON();
+ const addTx = api.tx.nft.addToContractAllowList(contract.address, bob.address);
+ const addEvents = await submitTransactionAsync(deployer, addTx);
+ const allowListedAfter = (await api.query.nft.contractAllowList(contract.address, bob.address)).toJSON();
+ const addAgainEvents = await submitTransactionAsync(deployer, addTx);
+ const allowListedAgainAfter = (await api.query.nft.contractAllowList(contract.address, bob.address)).toJSON();
+
+ expect(getGenericResult(addEvents).success).to.be.true;
+ expect(allowListedBefore).to.be.false;
+ expect(allowListedAfter).to.be.true;
+ expect(getGenericResult(addAgainEvents).success).to.be.true;
+ expect(allowListedAgainAfter).to.be.true;
+ });
+ });
+});
+
+describe.skip('Negative Integration Test addToContractAllowList', () => {
+
+ it('Add an address to a allow list of a non-contract', async () => {
+ await usingApi(async api => {
+ const alice = privateKey('//Bob');
+ const bob = privateKey('//Bob');
+ const charlieGuineaPig = privateKey('//Charlie');
+
+ const allowListedBefore = (await api.query.nft.contractAllowList(charlieGuineaPig.address, bob.address)).toJSON();
+ const addTx = api.tx.nft.addToContractAllowList(charlieGuineaPig.address, bob.address);
+ await expect(submitTransactionExpectFailAsync(alice, addTx)).to.be.rejected;
+ const allowListedAfter = (await api.query.nft.contractAllowList(charlieGuineaPig.address, bob.address)).toJSON();
+
+ expect(allowListedBefore).to.be.false;
+ expect(allowListedAfter).to.be.false;
+ });
+ });
+
+ it('Add to a contract allow list using a non-owner address', async () => {
+ await usingApi(async api => {
+ const bob = privateKey('//Bob');
+ const [contract] = await deployFlipper(api);
+
+ const allowListedBefore = (await api.query.nft.contractAllowList(contract.address, bob.address)).toJSON();
+ const addTx = api.tx.nft.addToContractAllowList(contract.address, bob.address);
+ await expect(submitTransactionExpectFailAsync(bob, addTx)).to.be.rejected;
+ const allowListedAfter = (await api.query.nft.contractAllowList(contract.address, bob.address)).toJSON();
+
+ expect(allowListedBefore).to.be.false;
+ expect(allowListedAfter).to.be.false;
+ });
+ });
+
+});
tests/src/addToContractWhiteList.test.tsdiffbeforeafterboth--- a/tests/src/addToContractWhiteList.test.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-//
-// This file is subject to the terms and conditions defined in
-// file 'LICENSE', which is part of this source code package.
-//
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import usingApi, {submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import privateKey from './substrate/privateKey';
-import {
- deployFlipper,
-} from './util/contracthelpers';
-import {
- getGenericResult,
-} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-describe.skip('Integration Test addToContractWhiteList', () => {
-
- it('Add an address to a contract white list', async () => {
- await usingApi(async api => {
- const bob = privateKey('//Bob');
- const [contract, deployer] = await deployFlipper(api);
-
- const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();
- const addTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);
- const addEvents = await submitTransactionAsync(deployer, addTx);
- const whiteListedAfter = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();
-
- expect(getGenericResult(addEvents).success).to.be.true;
- expect(whiteListedBefore).to.be.false;
- expect(whiteListedAfter).to.be.true;
- });
- });
-
- it('Adding same address to white list repeatedly should not produce errors', async () => {
- await usingApi(async api => {
- const bob = privateKey('//Bob');
- const [contract, deployer] = await deployFlipper(api);
-
- const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();
- const addTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);
- const addEvents = await submitTransactionAsync(deployer, addTx);
- const whiteListedAfter = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();
- const addAgainEvents = await submitTransactionAsync(deployer, addTx);
- const whiteListedAgainAfter = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();
-
- expect(getGenericResult(addEvents).success).to.be.true;
- expect(whiteListedBefore).to.be.false;
- expect(whiteListedAfter).to.be.true;
- expect(getGenericResult(addAgainEvents).success).to.be.true;
- expect(whiteListedAgainAfter).to.be.true;
- });
- });
-});
-
-describe.skip('Negative Integration Test addToContractWhiteList', () => {
-
- it('Add an address to a white list of a non-contract', async () => {
- await usingApi(async api => {
- const alice = privateKey('//Bob');
- const bob = privateKey('//Bob');
- const charlieGuineaPig = privateKey('//Charlie');
-
- const whiteListedBefore = (await api.query.nft.contractWhiteList(charlieGuineaPig.address, bob.address)).toJSON();
- const addTx = api.tx.nft.addToContractWhiteList(charlieGuineaPig.address, bob.address);
- await expect(submitTransactionExpectFailAsync(alice, addTx)).to.be.rejected;
- const whiteListedAfter = (await api.query.nft.contractWhiteList(charlieGuineaPig.address, bob.address)).toJSON();
-
- expect(whiteListedBefore).to.be.false;
- expect(whiteListedAfter).to.be.false;
- });
- });
-
- it('Add to a contract white list using a non-owner address', async () => {
- await usingApi(async api => {
- const bob = privateKey('//Bob');
- const [contract] = await deployFlipper(api);
-
- const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();
- const addTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);
- await expect(submitTransactionExpectFailAsync(bob, addTx)).to.be.rejected;
- const whiteListedAfter = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();
-
- expect(whiteListedBefore).to.be.false;
- expect(whiteListedAfter).to.be.false;
- });
- });
-
-});
tests/src/addToWhiteList.test.tsdiffbeforeafterboth--- a/tests/src/addToWhiteList.test.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-//
-// This file is subject to the terms and conditions defined in
-// file 'LICENSE', which is part of this source code package.
-//
-
-import {IKeyringPair} from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import privateKey from './substrate/privateKey';
-import usingApi, {submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {
- addToWhiteListExpectSuccess,
- createCollectionExpectSuccess,
- createItemExpectSuccess,
- destroyCollectionExpectSuccess,
- enablePublicMintingExpectSuccess,
- enableWhiteListExpectSuccess,
- normalizeAccountId,
- addCollectionAdminExpectSuccess,
- addToWhiteListExpectFail,
-} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-let charlie: IKeyringPair;
-
-describe('Integration Test ext. addToWhiteList()', () => {
-
- before(async () => {
- await usingApi(async () => {
- alice = privateKey('//Alice');
- bob = privateKey('//Bob');
- });
- });
-
- it('Execute the extrinsic with parameters: Collection ID and address to add to the white list', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
- });
-
- it('Whitelisted minting: list restrictions', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
- await enableWhiteListExpectSuccess(alice, collectionId);
- await enablePublicMintingExpectSuccess(alice, collectionId);
- await createItemExpectSuccess(bob, collectionId, 'NFT', bob.address);
- });
-});
-
-describe('Negative Integration Test ext. addToWhiteList()', () => {
-
- it('White list an address in the collection that does not exist', async () => {
- await usingApi(async (api) => {
- // tslint:disable-next-line: no-bitwise
- const collectionId = ((await api.query.common.createdCollectionCount()).toNumber()) + 1;
- const bob = privateKey('//Bob');
-
- const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(bob.address));
- await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
- });
- });
-
- it('White list an address in the collection that was destroyed', async () => {
- await usingApi(async (api) => {
- const alice = privateKey('//Alice');
- const bob = privateKey('//Bob');
- // tslint:disable-next-line: no-bitwise
- const collectionId = await createCollectionExpectSuccess();
- await destroyCollectionExpectSuccess(collectionId);
- const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(bob.address));
- await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
- });
- });
-
- it('White list an address in the collection that does not have white list access enabled', async () => {
- await usingApi(async (api) => {
- const alice = privateKey('//Alice');
- const ferdie = privateKey('//Ferdie');
- const collectionId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionId);
- await enablePublicMintingExpectSuccess(alice, collectionId);
- const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(ferdie.address), 'NFT');
- await expect(submitTransactionExpectFailAsync(ferdie, tx)).to.be.rejected;
- });
- });
-
-});
-
-describe('Integration Test ext. addToWhiteList() with collection admin permissions:', () => {
-
- before(async () => {
- await usingApi(async () => {
- alice = privateKey('//Alice');
- bob = privateKey('//Bob');
- charlie = privateKey('//Charlie');
- });
- });
-
- it('Negative. Add to the white list by regular user', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addToWhiteListExpectFail(bob, collectionId, charlie.address);
- });
-
- it('Execute the extrinsic with parameters: Collection ID and address to add to the white list', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- await addToWhiteListExpectSuccess(bob, collectionId, charlie.address);
- });
-
- it('Whitelisted minting: list restrictions', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- await addToWhiteListExpectSuccess(bob, collectionId, charlie.address);
-
- // allowed only for collection owner
- await enableWhiteListExpectSuccess(alice, collectionId);
- await enablePublicMintingExpectSuccess(alice, collectionId);
-
- await createItemExpectSuccess(charlie, collectionId, 'NFT', charlie.address);
- });
-});
tests/src/allowLists.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/allowLists.test.ts
@@ -0,0 +1,304 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import {IKeyringPair} from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from './substrate/privateKey';
+import usingApi, {submitTransactionExpectFailAsync} from './substrate/substrate-api';
+import {
+ addToAllowListExpectSuccess,
+ createCollectionExpectSuccess,
+ createItemExpectSuccess,
+ destroyCollectionExpectSuccess,
+ enableAllowListExpectSuccess,
+ normalizeAccountId,
+ addCollectionAdminExpectSuccess,
+ addToAllowListExpectFail,
+ removeFromAllowListExpectSuccess,
+ removeFromAllowListExpectFailure,
+ addToAllowListAgainExpectSuccess,
+ transferExpectFailure,
+ approveExpectSuccess,
+ approveExpectFail,
+ transferExpectSuccess,
+ transferFromExpectSuccess,
+ setMintPermissionExpectSuccess,
+ createItemExpectFailure,
+} from './util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+let alice: IKeyringPair;
+let bob: IKeyringPair;
+let charlie: IKeyringPair;
+
+describe('Integration Test ext. Allow list tests', () => {
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ charlie = privateKey('//Charlie');
+ });
+ });
+
+ it('Owner can add address to allow list', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
+ });
+
+ it('Admin can add address to allow list', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ await addToAllowListExpectSuccess(bob, collectionId, charlie.address);
+ });
+
+ it('Non-privileged user cannot add address to allow list', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addToAllowListExpectFail(bob, collectionId, charlie.address);
+ });
+
+ it('Nobody can add address to allow list of non-existing collection', async () => {
+ const collectionId = (1<<32) - 1;
+ await addToAllowListExpectFail(alice, collectionId, bob.address);
+ });
+
+ it('Nobody can add address to allow list of destroyed collection', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await destroyCollectionExpectSuccess(collectionId, '//Alice');
+ await addToAllowListExpectFail(alice, collectionId, bob.address);
+ });
+
+ it('If address is already added to allow list, nothing happens', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
+ await addToAllowListAgainExpectSuccess(alice, collectionId, bob.address);
+ });
+
+ it('Owner can remove address from allow list', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
+ await removeFromAllowListExpectSuccess(alice, collectionId, normalizeAccountId(bob));
+ });
+
+ it('Admin can remove address from allow list', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
+ await removeFromAllowListExpectSuccess(bob, collectionId, normalizeAccountId(charlie));
+ });
+
+ it('Non-privileged user cannot remove address from allow list', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
+ await removeFromAllowListExpectFailure(bob, collectionId, normalizeAccountId(charlie));
+ });
+
+ it('Nobody can remove address from allow list of non-existing collection', async () => {
+ const collectionId = (1<<32) - 1;
+ await removeFromAllowListExpectFailure(alice, collectionId, normalizeAccountId(charlie));
+ });
+
+ it('Nobody can remove address from allow list of deleted collection', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
+ await destroyCollectionExpectSuccess(collectionId, '//Alice');
+ await removeFromAllowListExpectFailure(alice, collectionId, normalizeAccountId(charlie));
+ });
+
+ it('If address is already removed from allow list, nothing happens', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
+ await removeFromAllowListExpectSuccess(alice, collectionId, normalizeAccountId(charlie));
+ await removeFromAllowListExpectSuccess(alice, collectionId, normalizeAccountId(charlie));
+ });
+
+ it('If Public Access mode is set to AllowList, tokens can’t be transferred from a non-allowlisted address with transfer or transferFrom. Test1', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
+
+ await transferExpectFailure(
+ collectionId,
+ itemId,
+ alice,
+ charlie,
+ 1,
+ );
+ });
+
+ it('If Public Access mode is set to AllowList, tokens can’t be transferred from a non-allowlisted address with transfer or transferFrom. Test2', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, alice.address);
+ await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
+ await approveExpectSuccess(collectionId, itemId, alice, charlie.address);
+ await removeFromAllowListExpectSuccess(alice, collectionId, normalizeAccountId(alice));
+
+ await transferExpectFailure(
+ collectionId,
+ itemId,
+ alice,
+ charlie,
+ 1,
+ );
+ });
+
+ it('If Public Access mode is set to AllowList, tokens can’t be transferred to a non-allowlisted address with transfer or transferFrom. Test1', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, alice.address);
+
+ await transferExpectFailure(
+ collectionId,
+ itemId,
+ alice,
+ charlie,
+ 1,
+ );
+ });
+
+ it('If Public Access mode is set to AllowList, tokens can’t be transferred to a non-allowlisted address with transfer or transferFrom. Test2', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, alice.address);
+ await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
+ await approveExpectSuccess(collectionId, itemId, alice, charlie.address);
+ await removeFromAllowListExpectSuccess(alice, collectionId, normalizeAccountId(alice));
+
+ await transferExpectFailure(
+ collectionId,
+ itemId,
+ alice,
+ charlie,
+ 1,
+ );
+ });
+
+ it('If Public Access mode is set to AllowList, tokens can’t be destroyed by a non-allowlisted address (even if it owned them before enabling AllowList mode)', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+ await enableAllowListExpectSuccess(alice, collectionId);
+
+ await usingApi(async (api) => {
+ const tx = api.tx.nft.burnItem(collectionId, itemId, /*normalizeAccountId(Alice.address),*/ 11);
+ const badTransaction = async function () {
+ await submitTransactionExpectFailAsync(alice, tx);
+ };
+ await expect(badTransaction()).to.be.rejected;
+ });
+ });
+
+ it('If Public Access mode is set to AllowList, token transfers can’t be Approved by a non-allowlisted address (see Approve method)', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await approveExpectFail(collectionId, itemId, alice, bob);
+ });
+
+ it('If Public Access mode is set to AllowList, tokens can be transferred to a allowlisted address with transfer.', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, alice.address);
+ await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
+ await transferExpectSuccess(collectionId, itemId, alice, charlie, 1, 'NFT');
+ });
+
+ it('If Public Access mode is set to AllowList, tokens can be transferred to a alowlisted address with transferFrom.', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, alice.address);
+ await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
+ await approveExpectSuccess(collectionId, itemId, alice, charlie.address);
+ await transferFromExpectSuccess(collectionId, itemId, alice, alice, charlie, 1, 'NFT');
+ });
+
+ it('If Public Access mode is set to AllowList, tokens can be transferred from a allowlisted address with transfer', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, alice.address);
+ await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
+ await transferExpectSuccess(collectionId, itemId, alice, charlie, 1, 'NFT');
+ });
+
+ it('If Public Access mode is set to AllowList, tokens can be transferred from a allowlisted address with transferFrom', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, alice.address);
+ await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
+ await approveExpectSuccess(collectionId, itemId, alice, charlie.address);
+ await transferFromExpectSuccess(collectionId, itemId, alice, alice, charlie, 1, 'NFT');
+ });
+
+ it('If Public Access mode is set to AllowList, and Mint Permission is set to false, tokens can be created by owner', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await setMintPermissionExpectSuccess(alice, collectionId, false);
+ await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+ });
+
+ it('If Public Access mode is set to AllowList, and Mint Permission is set to false, tokens can be created by admin', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await setMintPermissionExpectSuccess(alice, collectionId, false);
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ await createItemExpectSuccess(bob, collectionId, 'NFT', bob.address);
+ });
+
+ it('If Public Access mode is set to AllowList, and Mint Permission is set to false, tokens cannot be created by non-privileged and allow-listed address', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await setMintPermissionExpectSuccess(alice, collectionId, false);
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
+ await createItemExpectFailure(bob, collectionId, 'NFT', bob.address);
+ });
+
+ it('If Public Access mode is set to AllowList, and Mint Permission is set to false, tokens cannot be created by non-privileged and non-allow listed address', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await setMintPermissionExpectSuccess(alice, collectionId, false);
+ await createItemExpectFailure(bob, collectionId, 'NFT', bob.address);
+ });
+
+ it('If Public Access mode is set to AllowList, and Mint Permission is set to true, tokens can be created by owner', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await setMintPermissionExpectSuccess(alice, collectionId, true);
+ await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+ });
+
+ it('If Public Access mode is set to AllowList, and Mint Permission is set to true, tokens can be created by admin', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await setMintPermissionExpectSuccess(alice, collectionId, true);
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ await createItemExpectSuccess(bob, collectionId, 'NFT', bob.address);
+ });
+
+ it('If Public Access mode is set to AllowList, and Mint Permission is set to true, tokens cannot be created by non-privileged and non-allow listed address', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await setMintPermissionExpectSuccess(alice, collectionId, true);
+ await createItemExpectFailure(bob, collectionId, 'NFT', bob.address);
+ });
+
+ it('If Public Access mode is set to AllowList, and Mint Permission is set to true, tokens can be created by non-privileged and allow listed address', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await setMintPermissionExpectSuccess(alice, collectionId, true);
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
+ await createItemExpectSuccess(bob, collectionId, 'NFT', bob.address);
+ });
+});
tests/src/block-production.test.tsdiffbeforeafterboth--- a/tests/src/block-production.test.ts
+++ b/tests/src/block-production.test.ts
@@ -7,8 +7,8 @@
import {expect} from 'chai';
import {ApiPromise} from '@polkadot/api';
-const BLOCK_TIME_MS = 3000;
-const TOLERANCE_MS = 1000;
+const BLOCK_TIME_MS = 12000;
+const TOLERANCE_MS = 3000;
/* eslint no-async-promise-executor: "off" */
function getBlocks(api: ApiPromise): Promise<number[]> {
tests/src/change-collection-owner.test.tsdiffbeforeafterboth--- a/tests/src/change-collection-owner.test.ts
+++ b/tests/src/change-collection-owner.test.ts
@@ -12,13 +12,13 @@
setCollectionSponsorExpectSuccess,
confirmSponsorshipExpectSuccess,
removeCollectionSponsorExpectSuccess,
- enableWhiteListExpectSuccess,
+ enableAllowListExpectSuccess,
setMintPermissionExpectSuccess,
destroyCollectionExpectSuccess,
setCollectionSponsorExpectFailure,
confirmSponsorshipExpectFailure,
removeCollectionSponsorExpectFailure,
- enableWhiteListExpectFail,
+ enableAllowListExpectFail,
setMintPermissionExpectFailure,
destroyCollectionExpectFailure,
setPublicAccessModeExpectSuccess,
@@ -104,8 +104,8 @@
);
await submitTransactionAsync(bob, tx1);
- await setPublicAccessModeExpectSuccess(bob, collectionId, 'WhiteList');
- await enableWhiteListExpectSuccess(bob, collectionId);
+ await setPublicAccessModeExpectSuccess(bob, collectionId, 'AllowList');
+ await enableAllowListExpectSuccess(bob, collectionId);
await setMintPermissionExpectSuccess(bob, collectionId, true);
await destroyCollectionExpectSuccess(collectionId, '//Bob');
});
@@ -225,7 +225,7 @@
);
await expect(submitTransactionExpectFailAsync(alice, tx1)).to.be.rejected;
- await enableWhiteListExpectFail(alice, collectionId);
+ await enableAllowListExpectFail(alice, collectionId);
await setMintPermissionExpectFailure(alice, collectionId, true);
await destroyCollectionExpectFailure(collectionId, '//Alice');
});
tests/src/collision-tests/admVsOwnerChanges.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/admVsOwnerChanges.test.ts
+++ b/tests/src/collision-tests/admVsOwnerChanges.test.ts
@@ -1,3 +1,7 @@
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
import { IKeyringPair } from '@polkadot/types/types';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
@@ -50,3 +54,4 @@
});
});
});
+*/
\ No newline at end of file
tests/src/collision-tests/admVsOwnerData.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/admVsOwnerData.test.ts
+++ b/tests/src/collision-tests/admVsOwnerData.test.ts
@@ -1,3 +1,7 @@
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
import { IKeyringPair } from '@polkadot/types/types';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
@@ -46,3 +50,4 @@
});
});
});
+*/
\ No newline at end of file
tests/src/collision-tests/admVsOwnerTake.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/admVsOwnerTake.test.ts
+++ b/tests/src/collision-tests/admVsOwnerTake.test.ts
@@ -1,3 +1,7 @@
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
import { IKeyringPair } from '@polkadot/types/types';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
@@ -48,3 +52,4 @@
});
});
});
+*/
\ No newline at end of file
tests/src/collision-tests/adminDestroyCollection.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/adminDestroyCollection.test.ts
+++ b/tests/src/collision-tests/adminDestroyCollection.test.ts
@@ -1,3 +1,7 @@
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
import { IKeyringPair } from '@polkadot/types/types';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
@@ -23,27 +27,28 @@
});
});
-describe('Deleting a collection while add address to whitelist: ', () => {
+describe('Deleting a collection while add address to allowlist: ', () => {
// tslint:disable-next-line: max-line-length
- it('Adding an address to the collection whitelist in a block by the admin, and deleting the collection by the owner ', async () => {
+ it('Adding an address to the collection allowlist in a block by the admin, and deleting the collection by the owner ', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
await submitTransactionAsync(Alice, changeAdminTx);
await waitNewBlocks(1);
//
- const addWhitelistAdm = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(Ferdie.address));
+ const addAllowlistAdm = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(Ferdie.address));
const destroyCollection = api.tx.nft.destroyCollection(collectionId);
await Promise.all([
- addWhitelistAdm.signAndSend(Bob),
+ addAllowlistAdm.signAndSend(Bob),
destroyCollection.signAndSend(Alice),
]);
await waitNewBlocks(1);
- let whiteList = false;
- whiteList = (await api.query.nft.whiteList(collectionId, Ferdie.address)).toJSON() as boolean;
+ let allowList = false;
+ allowList = (await api.query.nft.allowList(collectionId, Ferdie.address)).toJSON() as boolean;
// tslint:disable-next-line: no-unused-expression
- expect(whiteList).to.be.false;
+ expect(allowList).to.be.false;
await waitNewBlocks(2);
});
});
});
+*/
\ No newline at end of file
tests/src/collision-tests/adminLimitsOff.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/adminLimitsOff.test.ts
+++ b/tests/src/collision-tests/adminLimitsOff.test.ts
@@ -1,3 +1,7 @@
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
import { IKeyringPair } from '@polkadot/types/types';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
@@ -63,3 +67,4 @@
});
});
});
+*/
\ No newline at end of file
tests/src/collision-tests/adminRightsOff.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/adminRightsOff.test.ts
+++ b/tests/src/collision-tests/adminRightsOff.test.ts
@@ -1,3 +1,7 @@
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
import { IKeyringPair } from '@polkadot/types/types';
import BN from 'bn.js';
import chai from 'chai';
@@ -46,3 +50,4 @@
});
});
});
+*/
\ No newline at end of file
tests/src/collision-tests/setSponsorNewOwner.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/setSponsorNewOwner.test.ts
+++ b/tests/src/collision-tests/setSponsorNewOwner.test.ts
@@ -1,3 +1,7 @@
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
import { IKeyringPair } from '@polkadot/types/types';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
@@ -44,3 +48,4 @@
});
});
});
+*/
\ No newline at end of file
tests/src/collision-tests/sponsorPayments.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/sponsorPayments.test.ts
+++ b/tests/src/collision-tests/sponsorPayments.test.ts
@@ -1,3 +1,7 @@
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
import { IKeyringPair } from '@polkadot/types/types';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
@@ -53,3 +57,4 @@
});
});
});
+*/
\ No newline at end of file
tests/src/collision-tests/tokenLimitsOff.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/tokenLimitsOff.test.ts
+++ b/tests/src/collision-tests/tokenLimitsOff.test.ts
@@ -1,3 +1,7 @@
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
import { IKeyringPair } from '@polkadot/types/types';
import BN from 'bn.js';
import chai from 'chai';
@@ -5,7 +9,7 @@
import privateKey from '../substrate/privateKey';
import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
import {
- addToWhiteListExpectSuccess,
+ addToAllowListExpectSuccess,
createCollectionExpectSuccess,
getCreateItemResult,
setMintPermissionExpectSuccess,
@@ -40,8 +44,8 @@
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
await setMintPermissionExpectSuccess(Alice, collectionId, true);
- await addToWhiteListExpectSuccess(Alice, collectionId, Ferdie.address);
- await addToWhiteListExpectSuccess(Alice, collectionId, Bob.address);
+ await addToAllowListExpectSuccess(Alice, collectionId, Ferdie.address);
+ await addToAllowListExpectSuccess(Alice, collectionId, Bob.address);
const setCollectionLim = api.tx.nft.setCollectionLimits(
collectionId,
{
@@ -77,3 +81,4 @@
});
});
});
+*/
tests/src/collision-tests/turnsOffMinting.test.tsdiffbeforeafterboth--- a/tests/src/collision-tests/turnsOffMinting.test.ts
+++ b/tests/src/collision-tests/turnsOffMinting.test.ts
@@ -1,10 +1,14 @@
+/* broken by design
+// substrate transactions are sequential, not parallel
+// the order of execution is indeterminate
+
import { IKeyringPair } from '@polkadot/types/types';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import privateKey from '../substrate/privateKey';
import usingApi from '../substrate/substrate-api';
import {
- addToWhiteListExpectSuccess,
+ addToAllowListExpectSuccess,
createCollectionExpectSuccess,
setMintPermissionExpectSuccess,
normalizeAccountId,
@@ -29,7 +33,7 @@
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
await setMintPermissionExpectSuccess(Alice, collectionId, true);
- await addToWhiteListExpectSuccess(Alice, collectionId, Ferdie.address);
+ await addToAllowListExpectSuccess(Alice, collectionId, Ferdie.address);
const mintItem = api.tx.nft.createItem(collectionId, normalizeAccountId(Ferdie.address), 'NFT');
const offMinting = api.tx.nft.setMintPermission(collectionId, false);
@@ -45,3 +49,4 @@
});
});
});
+*/
\ No newline at end of file
tests/src/confirmSponsorship.test.tsdiffbeforeafterboth--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -15,9 +15,9 @@
createItemExpectSuccess,
findUnusedAddress,
getGenericResult,
- enableWhiteListExpectSuccess,
+ enableAllowListExpectSuccess,
enablePublicMintingExpectSuccess,
- addToWhiteListExpectSuccess,
+ addToAllowListExpectSuccess,
normalizeAccountId,
addCollectionAdminExpectSuccess,
} from './util/helpers';
@@ -144,8 +144,8 @@
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
- // Enable collection white list
- await enableWhiteListExpectSuccess(alice, collectionId);
+ // Enable collection allow list
+ await enableAllowListExpectSuccess(alice, collectionId);
// Enable public minting
await enablePublicMintingExpectSuccess(alice, collectionId);
@@ -157,8 +157,8 @@
// Find unused address
const zeroBalance = await findUnusedAddress(api);
- // Add zeroBalance address to white list
- await addToWhiteListExpectSuccess(alice, collectionId, zeroBalance.address);
+ // Add zeroBalance address to allow list
+ await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
// Mint token using unused address as signer
await createItemExpectSuccess(zeroBalance, collectionId, 'NFT', zeroBalance.address);
@@ -285,8 +285,8 @@
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
- // Enable collection white list
- await enableWhiteListExpectSuccess(alice, collectionId);
+ // Enable collection allow list
+ await enableAllowListExpectSuccess(alice, collectionId);
// Enable public minting
await enablePublicMintingExpectSuccess(alice, collectionId);
@@ -295,8 +295,8 @@
// Find unused address
const zeroBalance = await findUnusedAddress(api);
- // Add zeroBalance address to white list
- await addToWhiteListExpectSuccess(alice, collectionId, zeroBalance.address);
+ // Add zeroBalance address to allow list
+ await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
// Mint token using unused address as signer - gets sponsored
await createItemExpectSuccess(zeroBalance, collectionId, 'NFT', zeroBalance.address);
tests/src/contracts.test.tsdiffbeforeafterboth--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -16,15 +16,15 @@
} from './util/contracthelpers';
import {
- addToWhiteListExpectSuccess,
+ addToAllowListExpectSuccess,
approveExpectSuccess,
createCollectionExpectSuccess,
createItemExpectSuccess,
enablePublicMintingExpectSuccess,
- enableWhiteListExpectSuccess,
+ enableAllowListExpectSuccess,
getGenericResult,
normalizeAccountId,
- isWhitelisted,
+ isAllowlisted,
transferFromExpectSuccess,
getTokenOwner,
} from './util/helpers';
@@ -96,9 +96,9 @@
const collectionId = await createCollectionExpectSuccess();
const [contract] = await deployTransferContract(api);
await enablePublicMintingExpectSuccess(alice, collectionId);
- await enableWhiteListExpectSuccess(alice, collectionId);
- await addToWhiteListExpectSuccess(alice, collectionId, contract.address);
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, contract.address);
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
const transferTx = contract.tx.createItem(value, gasLimit, bob.address, collectionId, {Nft: {const_data: '0x010203', variable_data: '0x020304'}});
const events = await submitTransactionAsync(alice, transferTx);
@@ -124,9 +124,9 @@
const collectionId = await createCollectionExpectSuccess();
const [contract] = await deployTransferContract(api);
await enablePublicMintingExpectSuccess(alice, collectionId);
- await enableWhiteListExpectSuccess(alice, collectionId);
- await addToWhiteListExpectSuccess(alice, collectionId, contract.address);
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, contract.address);
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
const transferTx = contract.tx.createMultipleItems(value, gasLimit, bob.address, collectionId, [
{Nft: {const_data: '0x010203', variable_data: '0x020304'}},
@@ -218,7 +218,7 @@
});
});
- it('ToggleWhiteList CE', async () => {
+ it('ToggleAllowList CE', async () => {
await usingApi(async api => {
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
@@ -228,23 +228,23 @@
const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);
await submitTransactionAsync(alice, changeAdminTx);
- expect(await isWhitelisted(collectionId, bob.address)).to.be.false;
+ expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
{
- const transferTx = contract.tx.toggleWhiteList(value, gasLimit, collectionId, bob.address, true);
+ const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, true);
const events = await submitTransactionAsync(alice, transferTx);
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isWhitelisted(collectionId, bob.address)).to.be.true;
+ expect(await isAllowlisted(collectionId, bob.address)).to.be.true;
}
{
- const transferTx = contract.tx.toggleWhiteList(value, gasLimit, collectionId, bob.address, false);
+ const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, false);
const events = await submitTransactionAsync(alice, transferTx);
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isWhitelisted(collectionId, bob.address)).to.be.false;
+ expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
}
});
});
tests/src/eth/allowlist.test.tsdiffbeforeafterboth--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -24,7 +24,7 @@
expect(await helpers.methods.allowed(flipper.options.address, randomUser).call()).to.be.true;
});
- itWeb3('Non-whitelisted user can\'t call contract with allowlist enabled', async ({api, web3}) => {
+ itWeb3('Non-allowlisted user can\'t call contract with allowlist enabled', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
const flipper = await deployFlipper(web3, owner);
const caller = await createEthAccountWithBalance(api, web3);
@@ -35,7 +35,7 @@
await flipper.methods.flip().send({from: caller});
expect(await flipper.methods.getValue().call()).to.be.true;
- // Tx will be reverted if user is not in whitelist
+ // Tx will be reverted if user is not in allowlist
await helpers.methods.toggleAllowlist(flipper.options.address, true).send({from: owner});
await expect(flipper.methods.flip().send({from: caller})).to.rejected;
expect(await flipper.methods.getValue().call()).to.be.true;
tests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -32,7 +32,7 @@
expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
});
- itWeb3('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should decrease (whitelisted)', async ({api, web3}) => {
+ itWeb3('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should decrease (allowlisted)', async ({api, web3}) => {
const alice = privateKey('//Alice');
const owner = await createEthAccountWithBalance(api, web3);
@@ -62,7 +62,7 @@
expect(+balanceAfter).to.be.lessThan(+originalFlipperBalance);
});
- itWeb3('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should not decrease (non-whitelisted)', async ({api, web3}) => {
+ itWeb3('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should not decrease (non-allowlisted)', async ({api, web3}) => {
const alice = privateKey('//Alice');
const owner = await createEthAccountWithBalance(api, web3);
@@ -158,7 +158,7 @@
expect(await helpers.methods.getSponsoringRateLimit(flipper.options.address).call()).to.be.equals('7200');
});
- itWeb3('If whitelist mode is off and sponsorship is on, sponsorship does not work', async ({api, web3}) => {
+ itWeb3('If allowlist mode is off and sponsorship is on, sponsorship does not work', async ({api, web3}) => {
const alice = privateKey('//Alice');
const owner = await createEthAccountWithBalance(api, web3);
tests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -53,7 +53,7 @@
**/
AddressIsZero: AugmentedError<ApiType>;
/**
- * Address is not in white list.
+ * Address is not in allow list.
**/
AddressNotInAllowlist: AugmentedError<ApiType>;
/**
tests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -219,7 +219,7 @@
**/
addCollectionAdmin: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, newAdminId: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, PalletCommonAccountBasicCrossAccountIdRepr]>;
/**
- * Add an address to white list.
+ * Add an address to allow list.
*
* # Permissions
*
@@ -232,7 +232,7 @@
*
* * address.
**/
- addToWhiteList: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, address: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, PalletCommonAccountBasicCrossAccountIdRepr]>;
+ addToAllowList: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, address: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, PalletCommonAccountBasicCrossAccountIdRepr]>;
/**
* Set, change, or remove approved address to transfer the ownership of the NFT.
*
@@ -336,8 +336,8 @@
* * Collection Owner.
* * Collection Admin.
* * Anyone if
- * * White List is enabled, and
- * * Address is added to white list, and
+ * * Allow List is enabled, and
+ * * Address is added to allow list, and
* * MintPermission is enabled (see SetMintPermission method)
*
* # Arguments
@@ -357,8 +357,8 @@
* * Collection Owner.
* * Collection Admin.
* * Anyone if
- * * White List is enabled, and
- * * Address is added to white list, and
+ * * Allow List is enabled, and
+ * * Address is added to allow list, and
* * MintPermission is enabled (see SetMintPermission method)
*
* # Arguments
@@ -410,7 +410,7 @@
**/
removeCollectionSponsor: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32]>;
/**
- * Remove an address from white list.
+ * Remove an address from allow list.
*
* # Permissions
*
@@ -423,7 +423,7 @@
*
* * address.
**/
- removeFromWhiteList: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, address: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, PalletCommonAccountBasicCrossAccountIdRepr]>;
+ removeFromAllowList: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, address: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, PalletCommonAccountBasicCrossAccountIdRepr]>;
setCollectionLimits: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, newLimit: NftDataStructsCollectionLimits | { accountTokenOwnershipLimit?: any; sponsoredDataSize?: any; sponsoredDataRateLimit?: any; tokenLimit?: any; sponsorTransferTimeout?: any; ownerCanTransfer?: any; ownerCanDestroy?: any; transfersEnabled?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, NftDataStructsCollectionLimits]>;
/**
* # Permissions
@@ -468,8 +468,8 @@
setMetaUpdatePermissionFlag: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, value: NftDataStructsMetaUpdatePermission | 'ItemOwner' | 'Admin' | 'None' | number | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, NftDataStructsMetaUpdatePermission]>;
/**
* Allows Anyone to create tokens if:
- * * White List is enabled, and
- * * Address is added to white list, and
+ * * Allow List is enabled, and
+ * * Address is added to allow list, and
* * This method was called with True parameter
*
* # Permissions
@@ -498,7 +498,7 @@
**/
setOffchainSchema: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, schema: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, Bytes]>;
/**
- * Toggle between normal and white list access for the methods with access for `Anyone`.
+ * Toggle between normal and allow list access for the methods with access for `Anyone`.
*
* # Permissions
*
@@ -510,7 +510,7 @@
*
* * mode: [AccessMode]
**/
- setPublicAccessMode: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, mode: NftDataStructsAccessMode | 'Normal' | 'WhiteList' | number | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, NftDataStructsAccessMode]>;
+ setPublicAccessMode: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, mode: NftDataStructsAccessMode | 'Normal' | 'AllowList' | number | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, NftDataStructsAccessMode]>;
/**
* Set schema standard
* ImageURL
tests/src/interfaces/nft/definitions.tsdiffbeforeafterboth--- a/tests/src/interfaces/nft/definitions.ts
+++ b/tests/src/interfaces/nft/definitions.ts
@@ -91,7 +91,7 @@
},
},
NftDataStructsAccessMode: {
- _enum: ['Normal', 'WhiteList'],
+ _enum: ['Normal', 'AllowList'],
},
NftDataStructsSchemaVersion: mkDummy('SchemaVersion'),
tests/src/interfaces/nft/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/nft/types.ts
+++ b/tests/src/interfaces/nft/types.ts
@@ -7,7 +7,7 @@
/** @name NftDataStructsAccessMode */
export interface NftDataStructsAccessMode extends Enum {
readonly isNormal: boolean;
- readonly isWhiteList: boolean;
+ readonly isAllowList: boolean;
}
/** @name NftDataStructsCollection */
tests/src/metadataUpdate.test.tsdiffbeforeafterboth--- a/tests/src/metadataUpdate.test.ts
+++ b/tests/src/metadataUpdate.test.ts
@@ -12,11 +12,11 @@
createItemExpectSuccess,
createCollectionExpectSuccess,
enablePublicMintingExpectSuccess,
- enableWhiteListExpectSuccess,
+ enableAllowListExpectSuccess,
setMetadataUpdatePermissionFlagExpectSuccess,
setVariableMetaDataExpectSuccess,
setMintPermissionExpectSuccess,
- addToWhiteListExpectSuccess,
+ addToAllowListExpectSuccess,
addCollectionAdminExpectSuccess,
setVariableMetaDataExpectFailure,
setMetadataUpdatePermissionFlagExpectFailure,
@@ -53,7 +53,7 @@
await setMetadataUpdatePermissionFlagExpectSuccess(alice, nftCollectionId, 'ItemOwner');
await setMintPermissionExpectSuccess(alice, nftCollectionId, true);
- await addToWhiteListExpectSuccess(alice, nftCollectionId, bob.address);
+ await addToAllowListExpectSuccess(alice, nftCollectionId, bob.address);
await addCollectionAdminExpectSuccess(alice, nftCollectionId, bob.address);
await setVariableMetaDataExpectFailure(bob, nftCollectionId, newNftTokenId, data);
@@ -92,7 +92,7 @@
await setMetadataUpdatePermissionFlagExpectSuccess(alice, nftCollectionId, 'Admin');
await setMintPermissionExpectSuccess(alice, nftCollectionId, true);
- await addToWhiteListExpectSuccess(alice, nftCollectionId, bob.address);
+ await addToAllowListExpectSuccess(alice, nftCollectionId, bob.address);
await addCollectionAdminExpectSuccess(alice, nftCollectionId, bob.address);
await setVariableMetaDataExpectSuccess(bob, nftCollectionId, newNftTokenId, data);
@@ -112,7 +112,7 @@
await setMetadataUpdatePermissionFlagExpectSuccess(alice, nftCollectionId, 'Admin');
await setMintPermissionExpectSuccess(alice, nftCollectionId, true);
- await addToWhiteListExpectSuccess(alice, nftCollectionId, bob.address);
+ await addToAllowListExpectSuccess(alice, nftCollectionId, bob.address);
await addCollectionAdminExpectSuccess(alice, nftCollectionId, bob.address);
await setVariableMetaDataExpectSuccess(bob, nftCollectionId, newNftTokenId, data);
@@ -129,8 +129,8 @@
// nft
const nftCollectionId = await createCollectionExpectSuccess();
await enablePublicMintingExpectSuccess(alice, nftCollectionId);
- await addToWhiteListExpectSuccess(alice, nftCollectionId, bob.address);
- await enableWhiteListExpectSuccess(alice, nftCollectionId);
+ await addToAllowListExpectSuccess(alice, nftCollectionId, bob.address);
+ await enableAllowListExpectSuccess(alice, nftCollectionId);
const newNftTokenId = await createItemExpectSuccess(bob, nftCollectionId, 'NFT');
await setMetadataUpdatePermissionFlagExpectSuccess(alice, nftCollectionId, 'Admin');
@@ -169,7 +169,7 @@
await setMetadataUpdatePermissionFlagExpectSuccess(alice, nftCollectionId, 'None');
await setMintPermissionExpectSuccess(alice, nftCollectionId, true);
- await addToWhiteListExpectSuccess(alice, nftCollectionId, bob.address);
+ await addToAllowListExpectSuccess(alice, nftCollectionId, bob.address);
await addCollectionAdminExpectSuccess(alice, nftCollectionId, bob.address);
await setVariableMetaDataExpectFailure(bob, nftCollectionId, newNftTokenId, data);
tests/src/mintModes.test.tsdiffbeforeafterboth--- a/tests/src/mintModes.test.ts
+++ b/tests/src/mintModes.test.ts
@@ -7,14 +7,14 @@
import privateKey from './substrate/privateKey';
import usingApi from './substrate/substrate-api';
import {
- addToWhiteListExpectSuccess,
+ addToAllowListExpectSuccess,
createCollectionExpectSuccess,
createItemExpectFailure,
createItemExpectSuccess,
- enableWhiteListExpectSuccess,
+ enableAllowListExpectSuccess,
setMintPermissionExpectSuccess,
addCollectionAdminExpectSuccess,
- disableWhiteListExpectSuccess,
+ disableAllowListExpectSuccess,
} from './util/helpers';
describe('Integration Test public minting', () => {
@@ -28,40 +28,40 @@
});
});
- it('If the AllowList mode is enabled, then the address added to the whitelist and not the owner or administrator can create tokens', async () => {
+ it('If the AllowList mode is enabled, then the address added to the allowlist and not the owner or administrator can create tokens', async () => {
await usingApi(async () => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableWhiteListExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
await setMintPermissionExpectSuccess(alice, collectionId, true);
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
await createItemExpectSuccess(bob, collectionId, 'NFT');
});
});
- it('If the AllowList mode is enabled, address not included in whitelist that is regular user cannot create tokens', async () => {
+ it('If the AllowList mode is enabled, address not included in allowlist that is regular user cannot create tokens', async () => {
await usingApi(async () => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableWhiteListExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
await setMintPermissionExpectSuccess(alice, collectionId, true);
await createItemExpectFailure(bob, collectionId, 'NFT');
});
});
- it('If the AllowList mode is enabled, address not included in whitelist that is admin can create tokens', async () => {
+ it('If the AllowList mode is enabled, address not included in allowlist that is admin can create tokens', async () => {
await usingApi(async () => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableWhiteListExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
await setMintPermissionExpectSuccess(alice, collectionId, true);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
await createItemExpectSuccess(bob, collectionId, 'NFT');
});
});
- it('If the AllowList mode is enabled, address not included in whitelist that is owner can create tokens', async () => {
+ it('If the AllowList mode is enabled, address not included in allowlist that is owner can create tokens', async () => {
await usingApi(async () => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableWhiteListExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
await setMintPermissionExpectSuccess(alice, collectionId, true);
await createItemExpectSuccess(alice, collectionId, 'NFT');
});
@@ -70,7 +70,7 @@
it('If the AllowList mode is disabled, owner can create tokens', async () => {
await usingApi(async () => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await disableWhiteListExpectSuccess(alice, collectionId);
+ await disableAllowListExpectSuccess(alice, collectionId);
await setMintPermissionExpectSuccess(alice, collectionId, true);
await createItemExpectSuccess(alice, collectionId, 'NFT');
});
@@ -79,7 +79,7 @@
it('If the AllowList mode is disabled, collection admin can create tokens', async () => {
await usingApi(async () => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await disableWhiteListExpectSuccess(alice, collectionId);
+ await disableAllowListExpectSuccess(alice, collectionId);
await setMintPermissionExpectSuccess(alice, collectionId, true);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
await createItemExpectSuccess(bob, collectionId, 'NFT');
@@ -89,7 +89,7 @@
it('If the AllowList mode is disabled, regular user can`t create tokens', async () => {
await usingApi(async () => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await disableWhiteListExpectSuccess(alice, collectionId);
+ await disableAllowListExpectSuccess(alice, collectionId);
await setMintPermissionExpectSuccess(alice, collectionId, true);
await createItemExpectFailure(bob, collectionId, 'NFT');
});
@@ -110,9 +110,9 @@
it('Address that is the not owner or not admin cannot create tokens', async () => {
await usingApi(async () => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableWhiteListExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
await setMintPermissionExpectSuccess(alice, collectionId, false);
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
await createItemExpectFailure(bob, collectionId, 'NFT');
});
});
@@ -120,7 +120,7 @@
it('Address that is collection owner can create tokens', async () => {
await usingApi(async () => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await disableWhiteListExpectSuccess(alice, collectionId);
+ await disableAllowListExpectSuccess(alice, collectionId);
await setMintPermissionExpectSuccess(alice, collectionId, false);
await createItemExpectSuccess(alice, collectionId, 'NFT');
});
@@ -129,7 +129,7 @@
it('Address that is admin can create tokens', async () => {
await usingApi(async () => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await disableWhiteListExpectSuccess(alice, collectionId);
+ await disableAllowListExpectSuccess(alice, collectionId);
await setMintPermissionExpectSuccess(alice, collectionId, false);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
await createItemExpectSuccess(bob, collectionId, 'NFT');
tests/src/removeFromAllowList.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/removeFromAllowList.test.ts
@@ -0,0 +1,136 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import {default as usingApi} from './substrate/substrate-api';
+import {
+ createCollectionExpectSuccess,
+ destroyCollectionExpectSuccess,
+ enableAllowListExpectSuccess,
+ addToAllowListExpectSuccess,
+ removeFromAllowListExpectSuccess,
+ isAllowlisted,
+ findNotExistingCollection,
+ removeFromAllowListExpectFailure,
+ disableAllowListExpectSuccess,
+ normalizeAccountId,
+ addCollectionAdminExpectSuccess,
+} from './util/helpers';
+import {IKeyringPair} from '@polkadot/types/types';
+import privateKey from './substrate/privateKey';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('Integration Test removeFromAllowList', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+ });
+
+ it('ensure bob is not in allowlist after removal', async () => {
+ await usingApi(async () => {
+ const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
+
+ await removeFromAllowListExpectSuccess(alice, collectionId, normalizeAccountId(bob.address));
+ expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
+ });
+ });
+
+ it('allows removal from collection with unset allowlist status', async () => {
+ await usingApi(async () => {
+ const collectionWithoutAllowlistId = await createCollectionExpectSuccess();
+ await enableAllowListExpectSuccess(alice, collectionWithoutAllowlistId);
+ await addToAllowListExpectSuccess(alice, collectionWithoutAllowlistId, bob.address);
+ await disableAllowListExpectSuccess(alice, collectionWithoutAllowlistId);
+
+ await removeFromAllowListExpectSuccess(alice, collectionWithoutAllowlistId, normalizeAccountId(bob.address));
+ });
+ });
+});
+
+describe('Negative Integration Test removeFromAllowList', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+ });
+
+ it('fails on removal from not existing collection', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await findNotExistingCollection(api);
+
+ await removeFromAllowListExpectFailure(alice, collectionId, normalizeAccountId(bob.address));
+ });
+ });
+
+ it('fails on removal from removed collection', async () => {
+ await usingApi(async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
+ await destroyCollectionExpectSuccess(collectionId);
+
+ await removeFromAllowListExpectFailure(alice, collectionId, normalizeAccountId(bob.address));
+ });
+ });
+});
+
+describe('Integration Test removeFromAllowList with collection admin permissions', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ charlie = privateKey('//Charlie');
+ });
+ });
+
+ it('ensure address is not in allowlist after removal', async () => {
+ await usingApi(async () => {
+ const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
+ await removeFromAllowListExpectSuccess(bob, collectionId, normalizeAccountId(charlie.address));
+ expect(await isAllowlisted(collectionId, charlie.address)).to.be.false;
+ });
+ });
+
+ it('Collection admin allowed to remove from allowlist with unset allowlist status', async () => {
+ await usingApi(async () => {
+ const collectionWithoutAllowlistId = await createCollectionExpectSuccess();
+ await enableAllowListExpectSuccess(alice, collectionWithoutAllowlistId);
+ await addCollectionAdminExpectSuccess(alice, collectionWithoutAllowlistId, bob.address);
+ await addToAllowListExpectSuccess(alice, collectionWithoutAllowlistId, charlie.address);
+ await disableAllowListExpectSuccess(alice, collectionWithoutAllowlistId);
+ await removeFromAllowListExpectSuccess(bob, collectionWithoutAllowlistId, normalizeAccountId(charlie.address));
+ });
+ });
+
+ it('Regular user can`t remove from allowlist', async () => {
+ await usingApi(async () => {
+ const collectionWithoutAllowlistId = await createCollectionExpectSuccess();
+ await enableAllowListExpectSuccess(alice, collectionWithoutAllowlistId);
+ await addToAllowListExpectSuccess(alice, collectionWithoutAllowlistId, charlie.address);
+ await removeFromAllowListExpectFailure(bob, collectionWithoutAllowlistId, normalizeAccountId(charlie.address));
+ });
+ });
+});
tests/src/removeFromContractAllowList.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/removeFromContractAllowList.test.ts
@@ -0,0 +1,81 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import privateKey from './substrate/privateKey';
+import usingApi from './substrate/substrate-api';
+import {deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess} from './util/contracthelpers';
+import {addToContractAllowListExpectSuccess, isAllowlistedInContract, removeFromContractAllowListExpectFailure, removeFromContractAllowListExpectSuccess, toggleContractAllowlistExpectSuccess} from './util/helpers';
+import {IKeyringPair} from '@polkadot/types/types';
+import {expect} from 'chai';
+
+describe.skip('Integration Test removeFromContractAllowList', () => {
+ let bob: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ bob = privateKey('//Bob');
+ });
+ });
+
+ it('user is no longer allowlisted after removal', async () => {
+ await usingApi(async (api) => {
+ const [flipper, deployer] = await deployFlipper(api);
+
+ await addToContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+ await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+
+ expect(await isAllowlistedInContract(flipper.address, bob.address)).to.be.false;
+ });
+ });
+
+ it('user can\'t execute contract after removal', async () => {
+ await usingApi(async (api) => {
+ const [flipper, deployer] = await deployFlipper(api);
+ await toggleContractAllowlistExpectSuccess(deployer, flipper.address.toString(), true);
+
+ await addToContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+ await toggleFlipValueExpectSuccess(bob, flipper);
+
+ await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+ await toggleFlipValueExpectFailure(bob, flipper);
+ });
+ });
+
+ it('can be called twice', async () => {
+ await usingApi(async (api) => {
+ const [flipper, deployer] = await deployFlipper(api);
+
+ await addToContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+ await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+ await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
+ });
+ });
+});
+
+describe.skip('Negative Integration Test removeFromContractAllowList', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+ });
+
+ it('fails when called with non-contract address', async () => {
+ await usingApi(async () => {
+ await removeFromContractAllowListExpectFailure(alice, alice.address, bob.address);
+ });
+ });
+
+ it('fails when executed by non owner', async () => {
+ await usingApi(async (api) => {
+ const [flipper] = await deployFlipper(api);
+
+ await removeFromContractAllowListExpectFailure(alice, flipper.address.toString(), bob.address);
+ });
+ });
+});
tests/src/removeFromContractWhiteList.test.tsdiffbeforeafterboth--- a/tests/src/removeFromContractWhiteList.test.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-//
-// This file is subject to the terms and conditions defined in
-// file 'LICENSE', which is part of this source code package.
-//
-
-import privateKey from './substrate/privateKey';
-import usingApi from './substrate/substrate-api';
-import {deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess} from './util/contracthelpers';
-import {addToContractWhiteListExpectSuccess, isWhitelistedInContract, removeFromContractWhiteListExpectFailure, removeFromContractWhiteListExpectSuccess, toggleContractWhitelistExpectSuccess} from './util/helpers';
-import {IKeyringPair} from '@polkadot/types/types';
-import {expect} from 'chai';
-
-describe.skip('Integration Test removeFromContractWhiteList', () => {
- let bob: IKeyringPair;
-
- before(async () => {
- await usingApi(async () => {
- bob = privateKey('//Bob');
- });
- });
-
- it('user is no longer whitelisted after removal', async () => {
- await usingApi(async (api) => {
- const [flipper, deployer] = await deployFlipper(api);
-
- await addToContractWhiteListExpectSuccess(deployer, flipper.address.toString(), bob.address);
- await removeFromContractWhiteListExpectSuccess(deployer, flipper.address.toString(), bob.address);
-
- expect(await isWhitelistedInContract(flipper.address, bob.address)).to.be.false;
- });
- });
-
- it('user can\'t execute contract after removal', async () => {
- await usingApi(async (api) => {
- const [flipper, deployer] = await deployFlipper(api);
- await toggleContractWhitelistExpectSuccess(deployer, flipper.address.toString(), true);
-
- await addToContractWhiteListExpectSuccess(deployer, flipper.address.toString(), bob.address);
- await toggleFlipValueExpectSuccess(bob, flipper);
-
- await removeFromContractWhiteListExpectSuccess(deployer, flipper.address.toString(), bob.address);
- await toggleFlipValueExpectFailure(bob, flipper);
- });
- });
-
- it('can be called twice', async () => {
- await usingApi(async (api) => {
- const [flipper, deployer] = await deployFlipper(api);
-
- await addToContractWhiteListExpectSuccess(deployer, flipper.address.toString(), bob.address);
- await removeFromContractWhiteListExpectSuccess(deployer, flipper.address.toString(), bob.address);
- await removeFromContractWhiteListExpectSuccess(deployer, flipper.address.toString(), bob.address);
- });
- });
-});
-
-describe.skip('Negative Integration Test removeFromContractWhiteList', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
-
- before(async () => {
- await usingApi(async () => {
- alice = privateKey('//Alice');
- bob = privateKey('//Bob');
- });
- });
-
- it('fails when called with non-contract address', async () => {
- await usingApi(async () => {
- await removeFromContractWhiteListExpectFailure(alice, alice.address, bob.address);
- });
- });
-
- it('fails when executed by non owner', async () => {
- await usingApi(async (api) => {
- const [flipper] = await deployFlipper(api);
-
- await removeFromContractWhiteListExpectFailure(alice, flipper.address.toString(), bob.address);
- });
- });
-});
tests/src/removeFromWhiteList.test.tsdiffbeforeafterboth--- a/tests/src/removeFromWhiteList.test.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-//
-// This file is subject to the terms and conditions defined in
-// file 'LICENSE', which is part of this source code package.
-//
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi} from './substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- destroyCollectionExpectSuccess,
- enableWhiteListExpectSuccess,
- addToWhiteListExpectSuccess,
- removeFromWhiteListExpectSuccess,
- isWhitelisted,
- findNotExistingCollection,
- removeFromWhiteListExpectFailure,
- disableWhiteListExpectSuccess,
- normalizeAccountId,
- addCollectionAdminExpectSuccess,
-} from './util/helpers';
-import {IKeyringPair} from '@polkadot/types/types';
-import privateKey from './substrate/privateKey';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-describe('Integration Test removeFromWhiteList', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
-
- before(async () => {
- await usingApi(async () => {
- alice = privateKey('//Alice');
- bob = privateKey('//Bob');
- });
- });
-
- it('ensure bob is not in whitelist after removal', async () => {
- await usingApi(async () => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableWhiteListExpectSuccess(alice, collectionId);
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
-
- await removeFromWhiteListExpectSuccess(alice, collectionId, normalizeAccountId(bob.address));
- expect(await isWhitelisted(collectionId, bob.address)).to.be.false;
- });
- });
-
- it('allows removal from collection with unset whitelist status', async () => {
- await usingApi(async () => {
- const collectionWithoutWhitelistId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionWithoutWhitelistId);
- await addToWhiteListExpectSuccess(alice, collectionWithoutWhitelistId, bob.address);
- await disableWhiteListExpectSuccess(alice, collectionWithoutWhitelistId);
-
- await removeFromWhiteListExpectSuccess(alice, collectionWithoutWhitelistId, normalizeAccountId(bob.address));
- });
- });
-});
-
-describe('Negative Integration Test removeFromWhiteList', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
-
- before(async () => {
- await usingApi(async () => {
- alice = privateKey('//Alice');
- bob = privateKey('//Bob');
- });
- });
-
- it('fails on removal from not existing collection', async () => {
- await usingApi(async (api) => {
- const collectionId = await findNotExistingCollection(api);
-
- await removeFromWhiteListExpectFailure(alice, collectionId, normalizeAccountId(bob.address));
- });
- });
-
- it('fails on removal from removed collection', async () => {
- await usingApi(async () => {
- const collectionId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionId);
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
- await destroyCollectionExpectSuccess(collectionId);
-
- await removeFromWhiteListExpectFailure(alice, collectionId, normalizeAccountId(bob.address));
- });
- });
-});
-
-describe('Integration Test removeFromWhiteList with collection admin permissions', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
-
- before(async () => {
- await usingApi(async () => {
- alice = privateKey('//Alice');
- bob = privateKey('//Bob');
- charlie = privateKey('//Charlie');
- });
- });
-
- it('ensure address is not in whitelist after removal', async () => {
- await usingApi(async () => {
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableWhiteListExpectSuccess(alice, collectionId);
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- await addToWhiteListExpectSuccess(alice, collectionId, charlie.address);
- await removeFromWhiteListExpectSuccess(bob, collectionId, normalizeAccountId(charlie.address));
- expect(await isWhitelisted(collectionId, charlie.address)).to.be.false;
- });
- });
-
- it('Collection admin allowed to remove from whitelist with unset whitelist status', async () => {
- await usingApi(async () => {
- const collectionWithoutWhitelistId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionWithoutWhitelistId);
- await addCollectionAdminExpectSuccess(alice, collectionWithoutWhitelistId, bob.address);
- await addToWhiteListExpectSuccess(alice, collectionWithoutWhitelistId, charlie.address);
- await disableWhiteListExpectSuccess(alice, collectionWithoutWhitelistId);
- await removeFromWhiteListExpectSuccess(bob, collectionWithoutWhitelistId, normalizeAccountId(charlie.address));
- });
- });
-
- it('Regular user can`t remove from whitelist', async () => {
- await usingApi(async () => {
- const collectionWithoutWhitelistId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionWithoutWhitelistId);
- await addToWhiteListExpectSuccess(alice, collectionWithoutWhitelistId, charlie.address);
- await removeFromWhiteListExpectFailure(bob, collectionWithoutWhitelistId, normalizeAccountId(charlie.address));
- });
- });
-});
tests/src/setMintPermission.test.tsdiffbeforeafterboth--- a/tests/src/setMintPermission.test.ts
+++ b/tests/src/setMintPermission.test.ts
@@ -7,12 +7,12 @@
import privateKey from './substrate/privateKey';
import usingApi from './substrate/substrate-api';
import {
- addToWhiteListExpectSuccess,
+ addToAllowListExpectSuccess,
createCollectionExpectSuccess,
createItemExpectFailure,
createItemExpectSuccess,
destroyCollectionExpectSuccess,
- enableWhiteListExpectSuccess,
+ enableAllowListExpectSuccess,
findNotExistingCollection,
setMintPermissionExpectFailure,
setMintPermissionExpectSuccess,
@@ -30,12 +30,12 @@
});
});
- it('ensure white-listed non-privileged address can mint tokens', async () => {
+ it('ensure allow-listed non-privileged address can mint tokens', async () => {
await usingApi(async () => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableWhiteListExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
await setMintPermissionExpectSuccess(alice, collectionId, true);
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
await createItemExpectSuccess(bob, collectionId, 'NFT');
});
@@ -88,7 +88,7 @@
it('fails when not collection owner tries to set mint status', async () => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableWhiteListExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
await setMintPermissionExpectFailure(bob, collectionId, true);
});
@@ -100,10 +100,10 @@
});
});
- it('ensure non-white-listed non-privileged address can\'t mint tokens', async () => {
+ it('ensure non-allow-listed non-privileged address can\'t mint tokens', async () => {
await usingApi(async () => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- await enableWhiteListExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
await setMintPermissionExpectSuccess(alice, collectionId, true);
await createItemExpectFailure(bob, collectionId, 'NFT');
tests/src/setPublicAccessMode.test.tsdiffbeforeafterboth--- a/tests/src/setPublicAccessMode.test.ts
+++ b/tests/src/setPublicAccessMode.test.ts
@@ -11,12 +11,12 @@
import privateKey from './substrate/privateKey';
import usingApi, {submitTransactionExpectFailAsync} from './substrate/substrate-api';
import {
- addToWhiteListExpectSuccess,
+ addToAllowListExpectSuccess,
createCollectionExpectSuccess,
createItemExpectSuccess,
destroyCollectionExpectSuccess,
enablePublicMintingExpectSuccess,
- enableWhiteListExpectSuccess,
+ enableAllowListExpectSuccess,
normalizeAccountId,
addCollectionAdminExpectSuccess,
} from './util/helpers';
@@ -35,20 +35,20 @@
});
});
- it('Run extrinsic with collection id parameters, set the whitelist mode for the collection', async () => {
+ it('Run extrinsic with collection id parameters, set the allowlist mode for the collection', async () => {
await usingApi(async () => {
const collectionId: number = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
await enablePublicMintingExpectSuccess(alice, collectionId);
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
+ await addToAllowListExpectSuccess(alice, collectionId, bob.address);
await createItemExpectSuccess(bob, collectionId, 'NFT', bob.address);
});
});
- it('Whitelisted collection limits', async () => {
+ it('Allowlisted collection limits', async () => {
await usingApi(async (api: ApiPromise) => {
const collectionId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
await enablePublicMintingExpectSuccess(alice, collectionId);
const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(bob.address), 'NFT');
await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;
@@ -61,7 +61,7 @@
await usingApi(async (api: ApiPromise) => {
// tslint:disable-next-line: radix
const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
- const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');
+ const tx = api.tx.nft.setPublicAccessMode(collectionId, 'AllowList');
await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
});
});
@@ -71,7 +71,7 @@
// tslint:disable-next-line: no-bitwise
const collectionId = await createCollectionExpectSuccess();
await destroyCollectionExpectSuccess(collectionId);
- const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');
+ const tx = api.tx.nft.setPublicAccessMode(collectionId, 'AllowList');
await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
});
});
@@ -79,8 +79,8 @@
it('Re-set the list mode already set in quantity', async () => {
await usingApi(async () => {
const collectionId: number = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionId);
- await enableWhiteListExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
+ await enableAllowListExpectSuccess(alice, collectionId);
});
});
@@ -88,7 +88,7 @@
await usingApi(async (api: ApiPromise) => {
// tslint:disable-next-line: no-bitwise
const collectionId = await createCollectionExpectSuccess();
- const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');
+ const tx = api.tx.nft.setPublicAccessMode(collectionId, 'AllowList');
await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;
});
});
@@ -106,7 +106,7 @@
// tslint:disable-next-line: no-bitwise
const collectionId = await createCollectionExpectSuccess();
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');
+ const tx = api.tx.nft.setPublicAccessMode(collectionId, 'AllowList');
await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;
});
});
tests/src/toggleContractAllowList.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/toggleContractAllowList.test.ts
@@ -0,0 +1,156 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import usingApi, {submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
+import privateKey from './substrate/privateKey';
+import {
+ deployFlipper,
+ getFlipValue,
+} from './util/contracthelpers';
+import {
+ getGenericResult,
+} from './util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+const value = 0;
+const gasLimit = 3000n * 1000000n;
+
+describe.skip('Integration Test toggleContractAllowList', () => {
+
+ it('Enable allow list contract mode', async () => {
+ await usingApi(async api => {
+ const [contract, deployer] = await deployFlipper(api);
+
+ const enabledBefore = (await api.query.nft.contractAllowListEnabled(contract.address)).toJSON();
+ const enableAllowListTx = api.tx.nft.toggleContractAllowList(contract.address, true);
+ const enableEvents = await submitTransactionAsync(deployer, enableAllowListTx);
+ const enabled = (await api.query.nft.contractAllowListEnabled(contract.address)).toJSON();
+
+ expect(getGenericResult(enableEvents).success).to.be.true;
+ expect(enabledBefore).to.be.false;
+ expect(enabled).to.be.true;
+ });
+ });
+
+ it('Only allowlisted account can call contract', async () => {
+ await usingApi(async api => {
+ const bob = privateKey('//Bob');
+
+ const [contract, deployer] = await deployFlipper(api);
+
+ let flipValueBefore = await getFlipValue(contract, deployer);
+ const flip = contract.tx.flip(value, gasLimit);
+ await submitTransactionAsync(bob, flip);
+ const flipValueAfter = await getFlipValue(contract,deployer);
+ expect(flipValueAfter).to.be.eq(!flipValueBefore, 'Anyone can call new contract.');
+
+ const deployerCanFlip = async () => {
+ const flipValueBefore = await getFlipValue(contract, deployer);
+ const deployerFlip = contract.tx.flip(value, gasLimit);
+ await submitTransactionAsync(deployer, deployerFlip);
+ const aliceFlip1Response = await getFlipValue(contract, deployer);
+ expect(aliceFlip1Response).to.be.eq(!flipValueBefore, 'Deployer always can flip.');
+ };
+ await deployerCanFlip();
+
+ flipValueBefore = await getFlipValue(contract, deployer);
+ const enableAllowListTx = api.tx.nft.toggleContractAllowList(contract.address, true);
+ await submitTransactionAsync(deployer, enableAllowListTx);
+ const flipWithEnabledAllowList = contract.tx.flip(value, gasLimit);
+ await expect(submitTransactionExpectFailAsync(bob, flipWithEnabledAllowList)).to.be.rejected;
+ const flipValueAfterEnableAllowList = await getFlipValue(contract, deployer);
+ expect(flipValueAfterEnableAllowList).to.be.eq(flipValueBefore, 'Enabling allowlist doesn\'t make it possible to call contract for everyone.');
+
+ await deployerCanFlip();
+
+ flipValueBefore = await getFlipValue(contract, deployer);
+ const addBobToAllowListTx = api.tx.nft.addToContractAllowList(contract.address, bob.address);
+ await submitTransactionAsync(deployer, addBobToAllowListTx);
+ const flipWithAllowlistedBob = contract.tx.flip(value, gasLimit);
+ await submitTransactionAsync(bob, flipWithAllowlistedBob);
+ const flipAfterAllowListed = await getFlipValue(contract,deployer);
+ expect(flipAfterAllowListed).to.be.eq(!flipValueBefore, 'Bob was allowlisted, now he can flip.');
+
+ await deployerCanFlip();
+
+ flipValueBefore = await getFlipValue(contract, deployer);
+ const removeBobFromAllowListTx = api.tx.nft.removeFromContractAllowList(contract.address, bob.address);
+ await submitTransactionAsync(deployer, removeBobFromAllowListTx);
+ const bobRemoved = contract.tx.flip(value, gasLimit);
+ await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;
+ const afterBobRemoved = await getFlipValue(contract, deployer);
+ expect(afterBobRemoved).to.be.eq(flipValueBefore, 'Bob can\'t call contract, now when he is removeed from allow list.');
+
+ await deployerCanFlip();
+
+ flipValueBefore = await getFlipValue(contract, deployer);
+ const disableAllowListTx = api.tx.nft.toggleContractAllowList(contract.address, false);
+ await submitTransactionAsync(deployer, disableAllowListTx);
+ const allowListDisabledFlip = contract.tx.flip(value, gasLimit);
+ await submitTransactionAsync(bob, allowListDisabledFlip);
+ const afterAllowListDisabled = await getFlipValue(contract,deployer);
+ expect(afterAllowListDisabled).to.be.eq(!flipValueBefore, 'Anyone can call contract with disabled allowlist.');
+
+ });
+ });
+
+ it('Enabling allow list repeatedly should not produce errors', async () => {
+ await usingApi(async api => {
+ const [contract, deployer] = await deployFlipper(api);
+
+ const enabledBefore = (await api.query.nft.contractAllowListEnabled(contract.address)).toJSON();
+ const enableAllowListTx = api.tx.nft.toggleContractAllowList(contract.address, true);
+ const enableEvents = await submitTransactionAsync(deployer, enableAllowListTx);
+ const enabled = (await api.query.nft.contractAllowListEnabled(contract.address)).toJSON();
+ const enableAgainEvents = await submitTransactionAsync(deployer, enableAllowListTx);
+ const enabledAgain = (await api.query.nft.contractAllowListEnabled(contract.address)).toJSON();
+
+ expect(getGenericResult(enableEvents).success).to.be.true;
+ expect(enabledBefore).to.be.false;
+ expect(enabled).to.be.true;
+ expect(getGenericResult(enableAgainEvents).success).to.be.true;
+ expect(enabledAgain).to.be.true;
+ });
+ });
+
+});
+
+describe.skip('Negative Integration Test toggleContractAllowList', () => {
+
+ it('Enable allow list for a non-contract', async () => {
+ await usingApi(async api => {
+ const alice = privateKey('//Alice');
+ const bobGuineaPig = privateKey('//Bob');
+
+ const enabledBefore = (await api.query.nft.contractAllowListEnabled(bobGuineaPig.address)).toJSON();
+ const enableAllowListTx = api.tx.nft.toggleContractAllowList(bobGuineaPig.address, true);
+ await expect(submitTransactionExpectFailAsync(alice, enableAllowListTx)).to.be.rejected;
+ const enabled = (await api.query.nft.contractAllowListEnabled(bobGuineaPig.address)).toJSON();
+
+ expect(enabledBefore).to.be.false;
+ expect(enabled).to.be.false;
+ });
+ });
+
+ it('Enable allow list using a non-owner address', async () => {
+ await usingApi(async api => {
+ const bob = privateKey('//Bob');
+ const [contract] = await deployFlipper(api);
+
+ const enabledBefore = (await api.query.nft.contractAllowListEnabled(contract.address)).toJSON();
+ const enableAllowListTx = api.tx.nft.toggleContractAllowList(contract.address, true);
+ await expect(submitTransactionExpectFailAsync(bob, enableAllowListTx)).to.be.rejected;
+ const enabled = (await api.query.nft.contractAllowListEnabled(contract.address)).toJSON();
+
+ expect(enabledBefore).to.be.false;
+ expect(enabled).to.be.false;
+ });
+ });
+
+});
tests/src/toggleContractWhiteList.test.tsdiffbeforeafterboth--- a/tests/src/toggleContractWhiteList.test.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-//
-// This file is subject to the terms and conditions defined in
-// file 'LICENSE', which is part of this source code package.
-//
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import usingApi, {submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import privateKey from './substrate/privateKey';
-import {
- deployFlipper,
- getFlipValue,
-} from './util/contracthelpers';
-import {
- getGenericResult,
-} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-const value = 0;
-const gasLimit = 3000n * 1000000n;
-
-describe.skip('Integration Test toggleContractWhiteList', () => {
-
- it('Enable white list contract mode', async () => {
- await usingApi(async api => {
- const [contract, deployer] = await deployFlipper(api);
-
- const enabledBefore = (await api.query.nft.contractWhiteListEnabled(contract.address)).toJSON();
- const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);
- const enableEvents = await submitTransactionAsync(deployer, enableWhiteListTx);
- const enabled = (await api.query.nft.contractWhiteListEnabled(contract.address)).toJSON();
-
- expect(getGenericResult(enableEvents).success).to.be.true;
- expect(enabledBefore).to.be.false;
- expect(enabled).to.be.true;
- });
- });
-
- it('Only whitelisted account can call contract', async () => {
- await usingApi(async api => {
- const bob = privateKey('//Bob');
-
- const [contract, deployer] = await deployFlipper(api);
-
- let flipValueBefore = await getFlipValue(contract, deployer);
- const flip = contract.tx.flip(value, gasLimit);
- await submitTransactionAsync(bob, flip);
- const flipValueAfter = await getFlipValue(contract,deployer);
- expect(flipValueAfter).to.be.eq(!flipValueBefore, 'Anyone can call new contract.');
-
- const deployerCanFlip = async () => {
- const flipValueBefore = await getFlipValue(contract, deployer);
- const deployerFlip = contract.tx.flip(value, gasLimit);
- await submitTransactionAsync(deployer, deployerFlip);
- const aliceFlip1Response = await getFlipValue(contract, deployer);
- expect(aliceFlip1Response).to.be.eq(!flipValueBefore, 'Deployer always can flip.');
- };
- await deployerCanFlip();
-
- flipValueBefore = await getFlipValue(contract, deployer);
- const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);
- await submitTransactionAsync(deployer, enableWhiteListTx);
- const flipWithEnabledWhiteList = contract.tx.flip(value, gasLimit);
- await expect(submitTransactionExpectFailAsync(bob, flipWithEnabledWhiteList)).to.be.rejected;
- const flipValueAfterEnableWhiteList = await getFlipValue(contract, deployer);
- expect(flipValueAfterEnableWhiteList).to.be.eq(flipValueBefore, 'Enabling whitelist doesn\'t make it possible to call contract for everyone.');
-
- await deployerCanFlip();
-
- flipValueBefore = await getFlipValue(contract, deployer);
- const addBobToWhiteListTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);
- await submitTransactionAsync(deployer, addBobToWhiteListTx);
- const flipWithWhitelistedBob = contract.tx.flip(value, gasLimit);
- await submitTransactionAsync(bob, flipWithWhitelistedBob);
- const flipAfterWhiteListed = await getFlipValue(contract,deployer);
- expect(flipAfterWhiteListed).to.be.eq(!flipValueBefore, 'Bob was whitelisted, now he can flip.');
-
- await deployerCanFlip();
-
- flipValueBefore = await getFlipValue(contract, deployer);
- const removeBobFromWhiteListTx = api.tx.nft.removeFromContractWhiteList(contract.address, bob.address);
- await submitTransactionAsync(deployer, removeBobFromWhiteListTx);
- const bobRemoved = contract.tx.flip(value, gasLimit);
- await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;
- const afterBobRemoved = await getFlipValue(contract, deployer);
- expect(afterBobRemoved).to.be.eq(flipValueBefore, 'Bob can\'t call contract, now when he is removeed from white list.');
-
- await deployerCanFlip();
-
- flipValueBefore = await getFlipValue(contract, deployer);
- const disableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, false);
- await submitTransactionAsync(deployer, disableWhiteListTx);
- const whiteListDisabledFlip = contract.tx.flip(value, gasLimit);
- await submitTransactionAsync(bob, whiteListDisabledFlip);
- const afterWhiteListDisabled = await getFlipValue(contract,deployer);
- expect(afterWhiteListDisabled).to.be.eq(!flipValueBefore, 'Anyone can call contract with disabled whitelist.');
-
- });
- });
-
- it('Enabling white list repeatedly should not produce errors', async () => {
- await usingApi(async api => {
- const [contract, deployer] = await deployFlipper(api);
-
- const enabledBefore = (await api.query.nft.contractWhiteListEnabled(contract.address)).toJSON();
- const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);
- const enableEvents = await submitTransactionAsync(deployer, enableWhiteListTx);
- const enabled = (await api.query.nft.contractWhiteListEnabled(contract.address)).toJSON();
- const enableAgainEvents = await submitTransactionAsync(deployer, enableWhiteListTx);
- const enabledAgain = (await api.query.nft.contractWhiteListEnabled(contract.address)).toJSON();
-
- expect(getGenericResult(enableEvents).success).to.be.true;
- expect(enabledBefore).to.be.false;
- expect(enabled).to.be.true;
- expect(getGenericResult(enableAgainEvents).success).to.be.true;
- expect(enabledAgain).to.be.true;
- });
- });
-
-});
-
-describe.skip('Negative Integration Test toggleContractWhiteList', () => {
-
- it('Enable white list for a non-contract', async () => {
- await usingApi(async api => {
- const alice = privateKey('//Alice');
- const bobGuineaPig = privateKey('//Bob');
-
- const enabledBefore = (await api.query.nft.contractWhiteListEnabled(bobGuineaPig.address)).toJSON();
- const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(bobGuineaPig.address, true);
- await expect(submitTransactionExpectFailAsync(alice, enableWhiteListTx)).to.be.rejected;
- const enabled = (await api.query.nft.contractWhiteListEnabled(bobGuineaPig.address)).toJSON();
-
- expect(enabledBefore).to.be.false;
- expect(enabled).to.be.false;
- });
- });
-
- it('Enable white list using a non-owner address', async () => {
- await usingApi(async api => {
- const bob = privateKey('//Bob');
- const [contract] = await deployFlipper(api);
-
- const enabledBefore = (await api.query.nft.contractWhiteListEnabled(contract.address)).toJSON();
- const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);
- await expect(submitTransactionExpectFailAsync(bob, enableWhiteListTx)).to.be.rejected;
- const enabled = (await api.query.nft.contractWhiteListEnabled(contract.address)).toJSON();
-
- expect(enabledBefore).to.be.false;
- expect(enabled).to.be.false;
- });
- });
-
-});
tests/src/transfer_contract/metadata.jsondiffbeforeafterboth--- a/tests/src/transfer_contract/metadata.json
+++ b/tests/src/transfer_contract/metadata.json
@@ -323,7 +323,7 @@
}
},
{
- "name": "whitelisted",
+ "name": "allowlisted",
"type": {
"displayName": [
"bool"
@@ -335,7 +335,7 @@
"docs": [],
"mutates": true,
"name": [
- "toggle_white_list"
+ "toggle_allow_list"
],
"payable": false,
"returnType": null,
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -597,9 +597,9 @@
});
}
-export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {
+export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {
await usingApi(async (api) => {
- const tx = api.tx.nft.toggleContractWhiteList(contractAddress, value);
+ const tx = api.tx.nft.toggleContractAllowList(contractAddress, value);
const events = await submitTransactionAsync(sender, tx);
const result = getGenericResult(events);
@@ -607,17 +607,17 @@
});
}
-export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {
- let whitelisted = false;
+export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {
+ let allowlisted = false;
await usingApi(async (api) => {
- whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;
+ allowlisted = (await api.query.nft.contractAllowList(contractAddress, user)).toJSON() as boolean;
});
- return whitelisted;
+ return allowlisted;
}
-export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
+export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
await usingApi(async (api) => {
- const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());
+ const tx = api.tx.nft.addToContractAllowList(contractAddress.toString(), user.toString());
const events = await submitTransactionAsync(sender, tx);
const result = getGenericResult(events);
@@ -625,9 +625,9 @@
});
}
-export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
+export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
await usingApi(async (api) => {
- const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());
+ const tx = api.tx.nft.removeFromContractAllowList(contractAddress.toString(), user.toString());
const events = await submitTransactionAsync(sender, tx);
const result = getGenericResult(events);
@@ -635,9 +635,9 @@
});
}
-export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
+export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
await usingApi(async (api) => {
- const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());
+ const tx = api.tx.nft.removeFromContractAllowList(contractAddress.toString(), user.toString());
const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
const result = getGenericResult(events);
@@ -1047,7 +1047,7 @@
export async function setPublicAccessModeExpectSuccess(
sender: IKeyringPair, collectionId: number,
- accessMode: 'Normal' | 'WhiteList',
+ accessMode: 'Normal' | 'AllowList',
) {
await usingApi(async (api) => {
@@ -1068,7 +1068,7 @@
export async function setPublicAccessModeExpectFail(
sender: IKeyringPair, collectionId: number,
- accessMode: 'Normal' | 'WhiteList',
+ accessMode: 'Normal' | 'AllowList',
) {
await usingApi(async (api) => {
@@ -1083,15 +1083,15 @@
});
}
-export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {
- await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');
+export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {
+ await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');
}
-export async function enableWhiteListExpectFail(sender: IKeyringPair, collectionId: number) {
- await setPublicAccessModeExpectFail(sender, collectionId, 'WhiteList');
+export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {
+ await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');
}
-export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {
+export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {
await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');
}
@@ -1137,46 +1137,46 @@
});
}
-export async function isWhitelisted(collectionId: number, address: string | CrossAccountId) {
+export async function isAllowlisted(collectionId: number, address: string | CrossAccountId) {
return await usingApi(async (api) => {
return (await api.query.common.allowlist(collectionId, normalizeAccountId(address))).toJSON();
});
}
-export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {
+export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {
await usingApi(async (api) => {
- expect(await isWhitelisted(collectionId, normalizeAccountId(address))).to.be.false;
+ expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.false;
// Run the transaction
- const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));
+ const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));
const events = await submitTransactionAsync(sender, tx);
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isWhitelisted(collectionId, normalizeAccountId(address))).to.be.true;
+ expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;
});
}
-export async function addToWhiteListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
+export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
await usingApi(async (api) => {
- expect(await isWhitelisted(collectionId, normalizeAccountId(address))).to.be.true;
+ expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;
// Run the transaction
- const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));
+ const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));
const events = await submitTransactionAsync(sender, tx);
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isWhitelisted(collectionId, normalizeAccountId(address))).to.be.true;
+ expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;
});
}
-export async function addToWhiteListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
+export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
await usingApi(async (api) => {
// Run the transaction
- const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));
+ const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));
const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
const result = getGenericResult(events);
@@ -1186,10 +1186,10 @@
});
}
-export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
+export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
await usingApi(async (api) => {
// Run the transaction
- const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));
+ const tx = api.tx.nft.removeFromAllowList(collectionId, normalizeAccountId(address));
const events = await submitTransactionAsync(sender, tx);
const result = getGenericResult(events);
@@ -1199,10 +1199,10 @@
});
}
-export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
+export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
await usingApi(async (api) => {
// Run the transaction
- const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));
+ const tx = api.tx.nft.removeFromAllowList(collectionId, normalizeAccountId(address));
const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
const result = getGenericResult(events);
tests/src/whiteLists.test.tsdiffbeforeafterboth--- a/tests/src/whiteLists.test.ts
+++ /dev/null
@@ -1,304 +0,0 @@
-//
-// This file is subject to the terms and conditions defined in
-// file 'LICENSE', which is part of this source code package.
-//
-
-import {IKeyringPair} from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import privateKey from './substrate/privateKey';
-import usingApi, {submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {
- addToWhiteListExpectSuccess,
- createCollectionExpectSuccess,
- createItemExpectSuccess,
- destroyCollectionExpectSuccess,
- enableWhiteListExpectSuccess,
- normalizeAccountId,
- addCollectionAdminExpectSuccess,
- addToWhiteListExpectFail,
- removeFromWhiteListExpectSuccess,
- removeFromWhiteListExpectFailure,
- addToWhiteListAgainExpectSuccess,
- transferExpectFailure,
- approveExpectSuccess,
- approveExpectFail,
- transferExpectSuccess,
- transferFromExpectSuccess,
- setMintPermissionExpectSuccess,
- createItemExpectFailure,
-} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-let charlie: IKeyringPair;
-
-describe('Integration Test ext. White list tests', () => {
-
- before(async () => {
- await usingApi(async () => {
- alice = privateKey('//Alice');
- bob = privateKey('//Bob');
- charlie = privateKey('//Charlie');
- });
- });
-
- it('Owner can add address to white list', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
- });
-
- it('Admin can add address to white list', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- await addToWhiteListExpectSuccess(bob, collectionId, charlie.address);
- });
-
- it('Non-privileged user cannot add address to white list', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addToWhiteListExpectFail(bob, collectionId, charlie.address);
- });
-
- it('Nobody can add address to white list of non-existing collection', async () => {
- const collectionId = (1<<32) - 1;
- await addToWhiteListExpectFail(alice, collectionId, bob.address);
- });
-
- it('Nobody can add address to white list of destroyed collection', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await destroyCollectionExpectSuccess(collectionId, '//Alice');
- await addToWhiteListExpectFail(alice, collectionId, bob.address);
- });
-
- it('If address is already added to white list, nothing happens', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
- await addToWhiteListAgainExpectSuccess(alice, collectionId, bob.address);
- });
-
- it('Owner can remove address from white list', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
- await removeFromWhiteListExpectSuccess(alice, collectionId, normalizeAccountId(bob));
- });
-
- it('Admin can remove address from white list', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- await addToWhiteListExpectSuccess(alice, collectionId, charlie.address);
- await removeFromWhiteListExpectSuccess(bob, collectionId, normalizeAccountId(charlie));
- });
-
- it('Non-privileged user cannot remove address from white list', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addToWhiteListExpectSuccess(alice, collectionId, charlie.address);
- await removeFromWhiteListExpectFailure(bob, collectionId, normalizeAccountId(charlie));
- });
-
- it('Nobody can remove address from white list of non-existing collection', async () => {
- const collectionId = (1<<32) - 1;
- await removeFromWhiteListExpectFailure(alice, collectionId, normalizeAccountId(charlie));
- });
-
- it('Nobody can remove address from white list of deleted collection', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addToWhiteListExpectSuccess(alice, collectionId, charlie.address);
- await destroyCollectionExpectSuccess(collectionId, '//Alice');
- await removeFromWhiteListExpectFailure(alice, collectionId, normalizeAccountId(charlie));
- });
-
- it('If address is already removed from white list, nothing happens', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await addToWhiteListExpectSuccess(alice, collectionId, charlie.address);
- await removeFromWhiteListExpectSuccess(alice, collectionId, normalizeAccountId(charlie));
- await removeFromWhiteListExpectSuccess(alice, collectionId, normalizeAccountId(charlie));
- });
-
- it('If Public Access mode is set to WhiteList, tokens can’t be transferred from a non-whitelisted address with transfer or transferFrom. Test1', async () => {
- const collectionId = await createCollectionExpectSuccess();
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
- await enableWhiteListExpectSuccess(alice, collectionId);
- await addToWhiteListExpectSuccess(alice, collectionId, charlie.address);
-
- await transferExpectFailure(
- collectionId,
- itemId,
- alice,
- charlie,
- 1,
- );
- });
-
- it('If Public Access mode is set to WhiteList, tokens can’t be transferred from a non-whitelisted address with transfer or transferFrom. Test2', async () => {
- const collectionId = await createCollectionExpectSuccess();
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
- await enableWhiteListExpectSuccess(alice, collectionId);
- await addToWhiteListExpectSuccess(alice, collectionId, alice.address);
- await addToWhiteListExpectSuccess(alice, collectionId, charlie.address);
- await approveExpectSuccess(collectionId, itemId, alice, charlie.address);
- await removeFromWhiteListExpectSuccess(alice, collectionId, normalizeAccountId(alice));
-
- await transferExpectFailure(
- collectionId,
- itemId,
- alice,
- charlie,
- 1,
- );
- });
-
- it('If Public Access mode is set to WhiteList, tokens can’t be transferred to a non-whitelisted address with transfer or transferFrom. Test1', async () => {
- const collectionId = await createCollectionExpectSuccess();
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
- await enableWhiteListExpectSuccess(alice, collectionId);
- await addToWhiteListExpectSuccess(alice, collectionId, alice.address);
-
- await transferExpectFailure(
- collectionId,
- itemId,
- alice,
- charlie,
- 1,
- );
- });
-
- it('If Public Access mode is set to WhiteList, tokens can’t be transferred to a non-whitelisted address with transfer or transferFrom. Test2', async () => {
- const collectionId = await createCollectionExpectSuccess();
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
- await enableWhiteListExpectSuccess(alice, collectionId);
- await addToWhiteListExpectSuccess(alice, collectionId, alice.address);
- await addToWhiteListExpectSuccess(alice, collectionId, charlie.address);
- await approveExpectSuccess(collectionId, itemId, alice, charlie.address);
- await removeFromWhiteListExpectSuccess(alice, collectionId, normalizeAccountId(alice));
-
- await transferExpectFailure(
- collectionId,
- itemId,
- alice,
- charlie,
- 1,
- );
- });
-
- it('If Public Access mode is set to WhiteList, tokens can’t be destroyed by a non-whitelisted address (even if it owned them before enabling WhiteList mode)', async () => {
- const collectionId = await createCollectionExpectSuccess();
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
- await enableWhiteListExpectSuccess(alice, collectionId);
-
- await usingApi(async (api) => {
- const tx = api.tx.nft.burnItem(collectionId, itemId, /*normalizeAccountId(Alice.address),*/ 11);
- const badTransaction = async function () {
- await submitTransactionExpectFailAsync(alice, tx);
- };
- await expect(badTransaction()).to.be.rejected;
- });
- });
-
- it('If Public Access mode is set to WhiteList, token transfers can’t be Approved by a non-whitelisted address (see Approve method)', async () => {
- const collectionId = await createCollectionExpectSuccess();
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
- await enableWhiteListExpectSuccess(alice, collectionId);
- await approveExpectFail(collectionId, itemId, alice, bob);
- });
-
- it('If Public Access mode is set to WhiteList, tokens can be transferred to a whitelisted address with transfer.', async () => {
- const collectionId = await createCollectionExpectSuccess();
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
- await enableWhiteListExpectSuccess(alice, collectionId);
- await addToWhiteListExpectSuccess(alice, collectionId, alice.address);
- await addToWhiteListExpectSuccess(alice, collectionId, charlie.address);
- await transferExpectSuccess(collectionId, itemId, alice, charlie, 1, 'NFT');
- });
-
- it('If Public Access mode is set to WhiteList, tokens can be transferred to a whitelisted address with transferFrom.', async () => {
- const collectionId = await createCollectionExpectSuccess();
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
- await enableWhiteListExpectSuccess(alice, collectionId);
- await addToWhiteListExpectSuccess(alice, collectionId, alice.address);
- await addToWhiteListExpectSuccess(alice, collectionId, charlie.address);
- await approveExpectSuccess(collectionId, itemId, alice, charlie.address);
- await transferFromExpectSuccess(collectionId, itemId, alice, alice, charlie, 1, 'NFT');
- });
-
- it('If Public Access mode is set to WhiteList, tokens can be transferred from a whitelisted address with transfer', async () => {
- const collectionId = await createCollectionExpectSuccess();
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
- await enableWhiteListExpectSuccess(alice, collectionId);
- await addToWhiteListExpectSuccess(alice, collectionId, alice.address);
- await addToWhiteListExpectSuccess(alice, collectionId, charlie.address);
- await transferExpectSuccess(collectionId, itemId, alice, charlie, 1, 'NFT');
- });
-
- it('If Public Access mode is set to WhiteList, tokens can be transferred from a whitelisted address with transferFrom', async () => {
- const collectionId = await createCollectionExpectSuccess();
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
- await enableWhiteListExpectSuccess(alice, collectionId);
- await addToWhiteListExpectSuccess(alice, collectionId, alice.address);
- await addToWhiteListExpectSuccess(alice, collectionId, charlie.address);
- await approveExpectSuccess(collectionId, itemId, alice, charlie.address);
- await transferFromExpectSuccess(collectionId, itemId, alice, alice, charlie, 1, 'NFT');
- });
-
- it('If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens can be created by owner', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionId);
- await setMintPermissionExpectSuccess(alice, collectionId, false);
- await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
- });
-
- it('If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens can be created by admin', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionId);
- await setMintPermissionExpectSuccess(alice, collectionId, false);
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- await createItemExpectSuccess(bob, collectionId, 'NFT', bob.address);
- });
-
- it('If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens cannot be created by non-privileged and white-listed address', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionId);
- await setMintPermissionExpectSuccess(alice, collectionId, false);
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
- await createItemExpectFailure(bob, collectionId, 'NFT', bob.address);
- });
-
- it('If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens cannot be created by non-privileged and non-white listed address', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionId);
- await setMintPermissionExpectSuccess(alice, collectionId, false);
- await createItemExpectFailure(bob, collectionId, 'NFT', bob.address);
- });
-
- it('If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by owner', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionId);
- await setMintPermissionExpectSuccess(alice, collectionId, true);
- await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
- });
-
- it('If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by admin', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionId);
- await setMintPermissionExpectSuccess(alice, collectionId, true);
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- await createItemExpectSuccess(bob, collectionId, 'NFT', bob.address);
- });
-
- it('If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens cannot be created by non-privileged and non-white listed address', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionId);
- await setMintPermissionExpectSuccess(alice, collectionId, true);
- await createItemExpectFailure(bob, collectionId, 'NFT', bob.address);
- });
-
- it('If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by non-privileged and white listed address', async () => {
- const collectionId = await createCollectionExpectSuccess();
- await enableWhiteListExpectSuccess(alice, collectionId);
- await setMintPermissionExpectSuccess(alice, collectionId, true);
- await addToWhiteListExpectSuccess(alice, collectionId, bob.address);
- await createItemExpectSuccess(bob, collectionId, 'NFT', bob.address);
- });
-});