difftreelog
Merge branch 'develop' into feature/internal-audit
in: master
57 files changed
.devcontainer/devcontainer.jsondiffbeforeafterboth--- a/.devcontainer/devcontainer.json
+++ b/.devcontainer/devcontainer.json
@@ -1,8 +1,8 @@
{
"name": "Rust",
"dockerComposeFile": "./docker-compose.yml",
- "service": "nft_private",
- "workspaceFolder": "/workspaces/nft_private",
+ "service": "unique-chain",
+ "workspaceFolder": "/workspaces/unique-chain",
"settings": {
"terminal.integrated.shell.linux": "/bin/bash",
"lldb.executable": "/usr/bin/lldb",
.devcontainer/docker-compose.ymldiffbeforeafterboth--- a/.devcontainer/docker-compose.yml
+++ b/.devcontainer/docker-compose.yml
@@ -1,13 +1,13 @@
version: '3'
services:
- nft_private:
+ unique-chain:
build:
context: .
environment:
- JAEGER_AGENT_HOST=jaeger
- JAEGER_AGENT_PORT=6831
volumes:
- - ..:/workspaces/nft_private:cached
+ - ..:/workspaces/unique-chain:cached
- ../../polkadot:/workspaces/polkadot:cached
- ../../polkadot-launch:/workspaces/polkadot-launch:cached
#- ../../frontier:/workspaces/frontier
.github/workflows/node_build_test.ymldiffbeforeafterboth--- a/.github/workflows/node_build_test.yml
+++ b/.github/workflows/node_build_test.yml
@@ -35,10 +35,10 @@
script: |
eval $(ssh-agent -s)
ssh-add /home/devops/.ssh/git_hub
- git clone git@github.com:UniqueNetwork/nft_private.git
- cd nft_private
+ git clone git@github.com:UniqueNetwork/unique-chain.git
+ cd unique-chain
git checkout develop
# git pull --all
chmod +x ci_node.sh
./ci_node.sh
- rm -rf /home/polkadot/nft_private
+ rm -rf /home/polkadot/unique-chain
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5097,6 +5097,7 @@
"frame-system-rpc-runtime-api",
"hex-literal",
"nft-data-structs",
+ "orml-vesting",
"pallet-aura",
"pallet-balances",
"pallet-common",
@@ -5109,7 +5110,6 @@
"pallet-fungible",
"pallet-inflation",
"pallet-nft",
- "pallet-nft-transaction-payment",
"pallet-nonfungible",
"pallet-randomness-collective-flip",
"pallet-refungible",
@@ -5120,7 +5120,6 @@
"pallet-transaction-payment-rpc-runtime-api",
"pallet-treasury",
"pallet-unq-scheduler",
- "pallet-vesting",
"pallet-xcm",
"parachain-info",
"parity-scale-codec",
@@ -5142,6 +5141,7 @@
"sp-transaction-pool",
"sp-version",
"substrate-wasm-builder",
+ "up-evm-mapping",
"up-rpc",
"xcm",
"xcm-builder",
@@ -5308,6 +5308,21 @@
]
[[package]]
+name = "orml-vesting"
+version = "0.4.1-dev"
+source = "git+https://github.com/UniqueNetwork/open-runtime-module-library#d69f226e332ae29b7b33d53d2f06f309d2986ea0"
+dependencies = [
+ "frame-support",
+ "frame-system",
+ "parity-scale-codec",
+ "scale-info",
+ "serde",
+ "sp-io",
+ "sp-runtime",
+ "sp-std",
+]
+
+[[package]]
name = "owning_ref"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -5575,6 +5590,7 @@
"sp-core",
"sp-runtime",
"sp-std",
+ "up-evm-mapping",
]
[[package]]
@@ -5824,6 +5840,7 @@
"sp-io",
"sp-runtime",
"sp-std",
+ "up-evm-mapping",
"up-sponsorship",
]
@@ -6072,24 +6089,7 @@
"sp-io",
"sp-runtime",
"sp-std",
- "up-sponsorship",
-]
-
-[[package]]
-name = "pallet-nft-transaction-payment"
-version = "3.0.0"
-dependencies = [
- "frame-benchmarking",
- "frame-support",
- "frame-system",
- "pallet-transaction-payment",
- "parity-scale-codec",
- "scale-info",
- "serde",
- "sp-core",
- "sp-io",
- "sp-runtime",
- "sp-std",
+ "up-evm-mapping",
"up-sponsorship",
]
@@ -11832,6 +11832,14 @@
checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
[[package]]
+name = "up-evm-mapping"
+version = "0.1.0"
+dependencies = [
+ "frame-support",
+ "sp-core",
+]
+
+[[package]]
name = "up-rpc"
version = "0.1.0"
dependencies = [
Dockerfile-parachaindiffbeforeafterboth--- a/Dockerfile-parachain
+++ b/Dockerfile-parachain
@@ -98,7 +98,7 @@
npm install --global yarn && \
yarn
-COPY --from=builder /nft_parachain/target/$PROFILE/nft /nft_private/target/$PROFILE/
+COPY --from=builder /nft_parachain/target/$PROFILE/nft /unique-chain/target/$PROFILE/
COPY --from=builder-polkadot /nft_parachain/polkadot/target/$PROFILE/polkadot /polkadot/target/$PROFILE/
CMD export NVM_DIR="$HOME/.nvm" && \
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -3,7 +3,7 @@
use codec::Decode;
use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
use jsonrpc_derive::rpc;
-use nft_data_structs::{CollectionId, TokenId};
+use nft_data_structs::{Collection, CollectionId, CollectionStats, TokenId};
use sp_api::{BlockId, BlockT, ProvideRuntimeApi};
use sp_blockchain::HeaderBackend;
use up_rpc::NftApi as NftRuntimeApi;
@@ -86,8 +86,23 @@
collection: CollectionId,
at: Option<BlockHash>,
) -> Result<Vec<CrossAccountId>>;
+ #[rpc(name = "nft_allowed")]
+ fn allowed(
+ &self,
+ collection: CollectionId,
+ user: CrossAccountId,
+ at: Option<BlockHash>,
+ ) -> Result<bool>;
#[rpc(name = "nft_lastTokenId")]
fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;
+ #[rpc(name = "nft_collectionById")]
+ fn collection_by_id(
+ &self,
+ collection: CollectionId,
+ at: Option<BlockHash>,
+ ) -> Result<Option<Collection<AccountId>>>;
+ #[rpc(name = "nft_collectionStats")]
+ fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;
}
pub struct Nft<C, P> {
@@ -160,5 +175,8 @@
pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>);
pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>);
+ pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool);
pass_method!(last_token_id(collection: CollectionId) -> TokenId);
+ pass_method!(collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>>);
+ pass_method!(collection_stats() -> CollectionStats);
}
launch-config.jsondiffbeforeafterboth--- a/launch-config.json
+++ b/launch-config.json
@@ -55,7 +55,7 @@
},
"parachains": [
{
- "bin": "../nft_private/target/release/nft",
+ "bin": "../unique-chain/target/release/nft",
"id": "2000",
"balance": "1000000000000000000000",
"nodes": [
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -15,10 +15,10 @@
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' }
sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+up-evm-mapping = { default-features = false, path = '../../primitives/evm-mapping' }
nft-data-structs = { default-features = false, path = '../../primitives/nft' }
pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
-
pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
serde = { version = "1.0.130", default-features = false }
scale-info = { version = "1.0.0", default-features = false, features = [
@@ -32,6 +32,7 @@
"frame-system/std",
"sp-runtime/std",
"sp-std/std",
+ "up-evm-mapping/std",
"nft-data-structs/std",
"pallet-evm/std",
]
pallets/common/src/account.rsdiffbeforeafterboth--- a/pallets/common/src/account.rs
+++ b/pallets/common/src/account.rs
@@ -2,12 +2,12 @@
use codec::{Encode, EncodeLike, Decode};
use sp_core::H160;
use scale_info::{Type, TypeInfo};
-use sp_core::crypto::AccountId32;
use core::cmp::Ordering;
use serde::{Serialize, Deserialize};
use pallet_evm::AddressMapping;
use sp_std::vec::Vec;
use sp_std::clone::Clone;
+use up_evm_mapping::EvmBackwardsAddressMapping;
pub trait CrossAccountId<AccountId>:
Encode + EncodeLike + Decode + TypeInfo + Clone + PartialEq + Ord + core::fmt::Debug + Default
@@ -174,19 +174,5 @@
} else {
BasicCrossAccountIdRepr::Substrate(v.as_sub().clone())
}
- }
-}
-
-pub trait EvmBackwardsAddressMapping<AccountId> {
- fn from_account_id(account_id: AccountId) -> H160;
-}
-
-/// Should have same mapping as EnsureAddressTruncated
-pub struct MapBackwardsAddressTruncated;
-impl EvmBackwardsAddressMapping<AccountId32> for MapBackwardsAddressTruncated {
- fn from_account_id(account_id: AccountId32) -> H160 {
- let mut out = [0; 20];
- out.copy_from_slice(&(account_id.as_ref() as &[u8])[0..20]);
- H160(out)
}
}
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -19,7 +19,7 @@
pub fn create_collection_raw<T: Config, R>(
owner: T::AccountId,
mode: CollectionMode,
- handler: impl FnOnce(Collection<T>) -> Result<CollectionId, DispatchError>,
+ handler: impl FnOnce(Collection<T::AccountId>) -> Result<CollectionId, DispatchError>,
cast: impl FnOnce(CollectionHandle<T>) -> R,
) -> Result<R, DispatchError> {
T::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -12,7 +12,7 @@
COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,
- WithdrawReasons,
+ WithdrawReasons, CollectionStats,
};
pub use pallet::*;
use sp_core::H160;
@@ -26,7 +26,7 @@
#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]
pub struct CollectionHandle<T: Config> {
pub id: CollectionId,
- collection: Collection<T>,
+ collection: Collection<T::AccountId>,
pub recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,
}
impl<T: Config> CollectionHandle<T> {
@@ -78,7 +78,7 @@
}
}
impl<T: Config> Deref for CollectionHandle<T> {
- type Target = Collection<T>;
+ type Target = Collection<T::AccountId>;
fn deref(&self) -> &Self::Target {
&self.collection
@@ -141,7 +141,7 @@
pub mod pallet {
use super::*;
use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};
- use account::{EvmBackwardsAddressMapping, CrossAccountId};
+ use account::CrossAccountId;
use frame_support::traits::Currency;
use nft_data_structs::TokenId;
use scale_info::TypeInfo;
@@ -153,7 +153,7 @@
type CrossAccountId: CrossAccountId<Self::AccountId>;
type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;
- type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;
+ type EvmBackwardsAddressMapping: up_evm_mapping::EvmBackwardsAddressMapping<Self::AccountId>;
type Currency: Currency<Self::AccountId>;
type CollectionCreationPrice: Get<
@@ -311,7 +311,7 @@
pub type CollectionById<T> = StorageMap<
Hasher = Blake2_128Concat,
Key = CollectionId,
- Value = Collection<T>,
+ Value = Collection<<T as frame_system::Config>::AccountId>,
QueryKind = OptionQuery,
>;
@@ -344,6 +344,11 @@
Value = bool,
QueryKind = ValueQuery,
>;
+
+ /// Not used by code, exists only to provide some types to metadata
+ #[pallet::storage]
+ pub type DummyStorageValue<T> =
+ StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;
}
impl<T: Config> Pallet<T> {
@@ -355,10 +360,32 @@
);
Ok(())
}
+ pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
+ <IsAdmin<T>>::iter_prefix((collection,))
+ .map(|(a, _)| a)
+ .collect()
+ }
+ pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
+ <Allowlist<T>>::iter_prefix((collection,))
+ .map(|(a, _)| a)
+ .collect()
+ }
+ pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {
+ <Allowlist<T>>::get((collection, user))
+ }
+ pub fn collection_stats() -> CollectionStats {
+ let created = <CreatedCollectionCount<T>>::get();
+ let destroyed = <DestroyedCollectionCount<T>>::get();
+ CollectionStats {
+ created: created.0,
+ destroyed: destroyed.0,
+ alive: created.0 - destroyed.0,
+ }
+ }
}
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
+ pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
{
ensure!(
data.name.len() <= MAX_COLLECTION_NAME_LENGTH,
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -59,7 +59,8 @@
fn allowed(&self, contract_address: address, user: address) -> Result<bool> {
self.0.consume_sload()?;
- Ok(<Pallet<T>>::allowed(contract_address, user, true))
+ Ok(<Pallet<T>>::allowed(contract_address, user)
+ || !<AllowlistEnabled<T>>::get(contract_address))
}
fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {
@@ -113,7 +114,7 @@
value: sp_core::U256,
) -> Option<PrecompileOutput> {
// TODO: Extract to another OnMethodCall handler
- if !<Pallet<T>>::allowed(*target, *source, true) {
+ if <AllowlistEnabled<T>>::get(target) && !<Pallet<T>>::allowed(*target, *source) {
return Some(PrecompileOutput {
exit_status: ExitReason::Revert(ExitRevert::Reverted),
cost: 0,
@@ -151,22 +152,26 @@
pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);
impl<T: Config> SponsorshipHandler<H160, (H160, Vec<u8>)> for HelpersContractSponsoring<T> {
fn get_sponsor(who: &H160, call: &(H160, Vec<u8>)) -> Option<H160> {
- if <SelfSponsoring<T>>::get(&call.0) && <Pallet<T>>::allowed(call.0, *who, false) {
- let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
- if let Some(last_tx_block) = <SponsorBasket<T>>::get(&call.0, who) {
- let rate_limit = <SponsoringRateLimit<T>>::get(&call.0);
- let limit_time = last_tx_block + rate_limit;
+ if !<SelfSponsoring<T>>::get(&call.0) {
+ return None;
+ }
+ if !<Pallet<T>>::allowed(call.0, *who) {
+ return None;
+ }
+ let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
- if block_number > limit_time {
- <SponsorBasket<T>>::insert(&call.0, who, block_number);
- return Some(call.0);
- }
- } else {
- <SponsorBasket<T>>::insert(&call.0, who, block_number);
- return Some(call.0);
+ if let Some(last_tx_block) = <SponsorBasket<T>>::get(&call.0, who) {
+ let limit = <SponsoringRateLimit<T>>::get(&call.0);
+
+ let timeout = last_tx_block + limit.into();
+ if block_number < timeout {
+ return None;
}
}
- None
+
+ <SponsorBasket<T>>::insert(&call.0, who, block_number);
+
+ Some(call.0)
}
}
pallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -76,11 +76,7 @@
<SponsoringRateLimit<T>>::insert(contract, rate_limit);
}
- /// Default is returned if allowlist is disabled
- pub fn allowed(contract: H160, user: H160, default: bool) -> bool {
- if !<AllowlistEnabled<T>>::get(contract) {
- return default;
- }
+ pub fn allowed(contract: H160, user: H160) -> bool {
<Allowlist<T>>::get(&contract, &user) || <Owner<T>>::get(&contract) == user
}
pallets/evm-transaction-payment/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-transaction-payment/Cargo.toml
+++ b/pallets/evm-transaction-payment/Cargo.toml
@@ -15,6 +15,7 @@
fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring" }
+up-evm-mapping = { default-features = false, path = "../../primitives/evm-mapping" }
[dependencies.codec]
default-features = false
@@ -35,4 +36,5 @@
"pallet-ethereum/std",
"fp-evm/std",
"up-sponsorship/std",
+ "up-evm-mapping/std",
]
pallets/evm-transaction-payment/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-transaction-payment/src/lib.rs
+++ b/pallets/evm-transaction-payment/src/lib.rs
@@ -1,98 +1,140 @@
#![cfg_attr(not(feature = "std"), no_std)]
+use core::marker::PhantomData;
+use fp_evm::WithdrawReason;
+use frame_support::traits::{Currency, IsSubType};
pub use pallet::*;
+use pallet_evm::{EVMCurrencyAdapter, EnsureAddressOrigin};
+use sp_core::{H160, U256};
+use sp_runtime::TransactionOutcome;
+use up_sponsorship::SponsorshipHandler;
+use up_evm_mapping::EvmBackwardsAddressMapping;
+use pallet_evm::AddressMapping;
#[frame_support::pallet]
pub mod pallet {
- use core::marker::PhantomData;
+ use super::*;
+
use frame_support::traits::Currency;
- use pallet_evm::EVMCurrencyAdapter;
- use fp_evm::WithdrawReason;
- use sp_core::{H160, U256};
- use sp_runtime::TransactionOutcome;
- use up_sponsorship::SponsorshipHandler;
use sp_std::vec::Vec;
- type NegativeImbalanceOf<C, T> =
- <C as Currency<<T as frame_system::Config>::AccountId>>::NegativeImbalance;
-
#[pallet::config]
pub trait Config: frame_system::Config {
- type SponsorshipHandler: SponsorshipHandler<H160, (H160, Vec<u8>)>;
+ type EvmSponsorshipHandler: SponsorshipHandler<H160, (H160, Vec<u8>)>;
type Currency: Currency<Self::AccountId>;
+ type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;
+ type EvmAddressMapping: AddressMapping<Self::AccountId>;
}
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
+}
- pub struct ChargeEvmLiquidityInfo<T>
- where
- T: Config,
- T: pallet_evm::Config,
- {
- who: H160,
- negative_imbalance: NegativeImbalanceOf<<T as Config>::Currency, T>,
- }
+type NegativeImbalanceOf<C, T> =
+ <C as Currency<<T as frame_system::Config>::AccountId>>::NegativeImbalance;
- pub struct TransactionValidityHack<T: Config>(PhantomData<*const T>);
- impl<T: Config> fp_evm::TransactionValidityHack for TransactionValidityHack<T> {
- fn who_pays_fee(origin: H160, reason: &WithdrawReason) -> Option<H160> {
- match reason {
- WithdrawReason::Call { target, input } => {
- // This method is only used for checking, we shouldn't touch storage in it
- frame_support::storage::with_transaction(|| {
- TransactionOutcome::Rollback(T::SponsorshipHandler::get_sponsor(
- &origin,
- &(*target, input.clone()),
- ))
- })
- }
- _ => None,
+pub struct ChargeEvmLiquidityInfo<T>
+where
+ T: Config,
+ T: pallet_evm::Config,
+{
+ who: H160,
+ negative_imbalance: NegativeImbalanceOf<<T as Config>::Currency, T>,
+}
+
+pub struct TransactionValidityHack<T: Config>(PhantomData<*const T>);
+impl<T: Config> fp_evm::TransactionValidityHack for TransactionValidityHack<T> {
+ fn who_pays_fee(origin: H160, reason: &WithdrawReason) -> Option<H160> {
+ match reason {
+ WithdrawReason::Call { target, input } => {
+ // This method is only used for checking, we shouldn't touch storage in it
+ frame_support::storage::with_transaction(|| {
+ TransactionOutcome::Rollback(T::EvmSponsorshipHandler::get_sponsor(
+ &origin,
+ &(*target, input.clone()),
+ ))
+ })
}
+ _ => None,
+ }
+ }
+}
+pub struct OnChargeTransaction<T: Config>(PhantomData<*const T>);
+impl<T> pallet_evm::OnChargeEVMTransaction<T> for OnChargeTransaction<T>
+where
+ T: Config,
+ T: pallet_evm::Config,
+{
+ type LiquidityInfo = Option<ChargeEvmLiquidityInfo<T>>;
+
+ fn withdraw_fee(
+ who: &H160,
+ reason: WithdrawReason,
+ fee: U256,
+ ) -> core::result::Result<Self::LiquidityInfo, pallet_evm::Error<T>> {
+ let mut who_pays_fee = *who;
+ if let WithdrawReason::Call { target, input } = &reason {
+ who_pays_fee = T::EvmSponsorshipHandler::get_sponsor(who, &(*target, input.clone()))
+ .unwrap_or(who_pays_fee);
}
+ let negative_imbalance = EVMCurrencyAdapter::<<T as Config>::Currency, ()>::withdraw_fee(
+ &who_pays_fee,
+ reason,
+ fee,
+ )?;
+ Ok(negative_imbalance.map(|i| ChargeEvmLiquidityInfo {
+ who: who_pays_fee,
+ negative_imbalance: i,
+ }))
}
- pub struct OnChargeTransaction<T: Config>(PhantomData<*const T>);
- impl<T> pallet_evm::OnChargeEVMTransaction<T> for OnChargeTransaction<T>
- where
- T: Config,
- T: pallet_evm::Config,
- {
- type LiquidityInfo = Option<ChargeEvmLiquidityInfo<T>>;
+ fn correct_and_deposit_fee(
+ who: &H160,
+ corrected_fee: U256,
+ already_withdrawn: Self::LiquidityInfo,
+ ) {
+ <EVMCurrencyAdapter<<T as Config>::Currency, ()> as pallet_evm::OnChargeEVMTransaction<T>>::correct_and_deposit_fee(
+ &already_withdrawn.as_ref().map(|e| e.who).unwrap_or(*who),
+ corrected_fee,
+ already_withdrawn.map(|e| e.negative_imbalance),
+ )
+ }
+}
- fn withdraw_fee(
- who: &H160,
- reason: WithdrawReason,
- fee: U256,
- ) -> core::result::Result<Self::LiquidityInfo, pallet_evm::Error<T>> {
- let mut who_pays_fee = *who;
- if let WithdrawReason::Call { target, input } = &reason {
- who_pays_fee = T::SponsorshipHandler::get_sponsor(who, &(*target, input.clone()))
- .unwrap_or(who_pays_fee);
+/// Implements sponsoring for evm calls performed from pallet-evm (via api.tx.ethereum.transact/api.tx.evm.call)
+pub struct BridgeSponsorshipHandler<T>(PhantomData<T>);
+impl<T, C> SponsorshipHandler<T::AccountId, C> for BridgeSponsorshipHandler<T>
+where
+ T: Config + pallet_evm::Config,
+ C: IsSubType<pallet_evm::Call<T>>,
+{
+ fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {
+ match call.is_sub_type()? {
+ pallet_evm::Call::call {
+ source,
+ target,
+ input,
+ ..
+ } => {
+ let _ = T::CallOrigin::ensure_address_origin(
+ source,
+ <frame_system::RawOrigin<T::AccountId>>::Signed(who.clone()).into(),
+ )
+ .ok()?;
+ let who = T::EvmBackwardsAddressMapping::from_account_id(who.clone());
+ // Effects from EvmSponsorshipHandler are applied in OnChargeEvmTransaction by pallet_evm::runner
+ // TODO: Should we implement simulation mode (test, but do not apply effects) in `up-sponsorship`?
+ let sponsor = frame_support::storage::with_transaction(|| {
+ TransactionOutcome::Rollback(T::EvmSponsorshipHandler::get_sponsor(
+ &who,
+ &(target.clone(), input.clone()),
+ ))
+ })?;
+ let sponsor = T::EvmAddressMapping::into_account_id(sponsor);
+ Some(sponsor)
}
- let negative_imbalance =
- EVMCurrencyAdapter::<<T as Config>::Currency, ()>::withdraw_fee(
- &who_pays_fee,
- reason,
- fee,
- )?;
- Ok(negative_imbalance.map(|i| ChargeEvmLiquidityInfo {
- who: who_pays_fee,
- negative_imbalance: i,
- }))
- }
-
- fn correct_and_deposit_fee(
- who: &H160,
- corrected_fee: U256,
- already_withdrawn: Self::LiquidityInfo,
- ) {
- <EVMCurrencyAdapter<<T as Config>::Currency, ()> as pallet_evm::OnChargeEVMTransaction<T>>::correct_and_deposit_fee(
- &already_withdrawn.as_ref().map(|e| e.who).unwrap_or(*who),
- corrected_fee,
- already_withdrawn.map(|e| e.negative_imbalance),
- )
+ _ => None,
}
}
}
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -52,7 +52,7 @@
StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;
#[pallet::storage]
- pub(super) type Balance<T: Config> = StorageNMap<
+ pub type Balance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
Key<Blake2_128Concat, T::CrossAccountId>,
@@ -91,8 +91,8 @@
}
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
- PalletCommon::init_collection(data)
+ pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(data)
}
pub fn destroy_collection(
collection: FungibleHandle<T>,
pallets/nft-transaction-payment/Cargo.tomldiffbeforeafterboth--- a/pallets/nft-transaction-payment/Cargo.toml
+++ /dev/null
@@ -1,51 +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-transaction-payment'
-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-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' }
-
-up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring" }
-
-[features]
-default = ['std']
-std = [
- 'codec/std',
- 'serde/std',
- 'frame-support/std',
- 'frame-system/std',
- 'sp-core/std',
- 'sp-io/std',
- 'pallet-transaction-payment/std',
- 'sp-std/std',
- 'sp-runtime/std',
- 'frame-benchmarking/std',
-
- 'up-sponsorship/std',
-]
-runtime-benchmarks = ["frame-benchmarking"]
pallets/nft-transaction-payment/README.mddiffbeforeafterboth--- a/pallets/nft-transaction-payment/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Nft Transaction Payment
-
-## Overview
-
-A module containing the sponsoring logic for paying for sponsored collections
-
-**NOTE:** The scheduled calls will be dispatched with the default filter
-for the origin: namely `frame_system::Config::BaseCallFilter` for all origin
-except root which will get no filter. And not the filter contained in origin
-use to call `fn schedule`.
-
-If a call is scheduled using proxy or whatever mecanism which adds filter,
-then those filter will not be used when dispatching the schedule call.
pallets/nft-transaction-payment/src/lib.rsdiffbeforeafterboth--- a/pallets/nft-transaction-payment/src/lib.rs
+++ /dev/null
@@ -1,39 +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::*;
-
-#[cfg(feature = "std")]
-pub use serde::*;
-
-use frame_support::{decl_module, decl_storage};
-use sp_std::prelude::*;
-use up_sponsorship::SponsorshipHandler;
-
-pub trait Config: frame_system::Config + pallet_transaction_payment::Config {
- type SponsorshipHandler: SponsorshipHandler<Self::AccountId, Self::Call>;
-}
-
-decl_storage! {
- trait Store for Module<T: Config> as NftTransactionPayment{
- }
-}
-
-decl_module! {
- pub struct Module<T: Config> for enum Call
- where
- origin: T::Origin,
- {
- }
-}
-
-impl<T: Config> Module<T> {
- pub fn withdraw_type(who: &T::AccountId, call: &T::Call) -> Option<T::AccountId> {
- T::SponsorshipHandler::get_sponsor(who, call)
- }
-}
pallets/nft/Cargo.tomldiffbeforeafterboth--- a/pallets/nft/Cargo.toml
+++ b/pallets/nft/Cargo.toml
@@ -34,6 +34,7 @@
'fp-evm/std',
'nft-data-structs/std',
'up-sponsorship/std',
+ 'up-evm-mapping/std',
'sp-std/std',
'sp-api/std',
'sp-runtime/std',
@@ -135,7 +136,7 @@
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" }
-
+up-evm-mapping = { default-features = false, path = "../../primitives/evm-mapping" }
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/eth/sponsoring.rsdiffbeforeafterboth--- a/pallets/nft/src/eth/sponsoring.rs
+++ b/pallets/nft/src/eth/sponsoring.rs
@@ -1,123 +1,74 @@
//! Implements EVM sponsoring logic via OnChargeEVMTransaction
-use crate::{Collection, Config, FungibleTransferBasket, NftTransferBasket};
+use crate::{Config, sponsorship::*};
use evm_coder::{Call, abi::AbiReader};
-use frame_support::{
- storage::{StorageDoubleMap},
-};
-use pallet_common::eth::map_eth_to_id;
+use pallet_common::{CollectionHandle, eth::map_eth_to_id};
use sp_core::H160;
use sp_std::prelude::*;
use up_sponsorship::SponsorshipHandler;
use core::marker::PhantomData;
use core::convert::TryInto;
-use nft_data_structs::{CollectionId, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT};
-use pallet_common::{
- CollectionById,
- account::{CrossAccountId, EvmBackwardsAddressMapping},
-};
+use nft_data_structs::TokenId;
+use up_evm_mapping::EvmBackwardsAddressMapping;
+use pallet_common::account::CrossAccountId;
use pallet_nonfungible::erc::{UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721Call};
use pallet_fungible::erc::{UniqueFungibleCall, ERC20Call};
-struct AnyError;
-
-fn try_sponsor<T: Config>(
- caller: &H160,
- collection_id: CollectionId,
- collection: &Collection<T>,
- call: &[u8],
-) -> Result<(), AnyError> {
- let (method_id, mut reader) = AbiReader::new_call(call).map_err(|_| AnyError)?;
- match &collection.mode {
- crate::CollectionMode::NFT => {
- let call: UniqueNFTCall = UniqueNFTCall::parse(method_id, &mut reader)
- .map_err(|_| AnyError)?
- .ok_or(AnyError)?;
- match call {
- UniqueNFTCall::ERC721UniqueExtensions(ERC721UniqueExtensionsCall::Transfer {
- token_id,
- ..
- })
- | UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, .. }) => {
- let token_id: u32 = token_id.try_into().map_err(|_| AnyError)?;
- let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
- let collection_limits = &collection.limits;
- let limit =
- collection_limits.sponsor_transfer_timeout(NFT_SPONSOR_TRANSFER_TIMEOUT);
-
- let mut sponsor = true;
- if <NftTransferBasket<T>>::contains_key(collection_id, token_id) {
- let last_tx_block = <NftTransferBasket<T>>::get(collection_id, token_id);
- let limit_time = last_tx_block + limit.into();
- if block_number <= limit_time {
- sponsor = false;
- }
+pub struct NftEthSponsorshipHandler<T: Config>(PhantomData<*const T>);
+impl<T: Config> SponsorshipHandler<H160, (H160, Vec<u8>)> for NftEthSponsorshipHandler<T> {
+ fn get_sponsor(who: &H160, call: &(H160, Vec<u8>)) -> Option<H160> {
+ let collection_id = map_eth_to_id(&call.0)?;
+ let collection = <CollectionHandle<T>>::new(collection_id)?;
+ let sponsor = collection.sponsorship.sponsor()?.clone();
+ let sponsor =
+ <T as pallet_common::Config>::EvmBackwardsAddressMapping::from_account_id(sponsor);
+ let who = T::CrossAccountId::from_eth(*who);
+ let (method_id, mut reader) = AbiReader::new_call(&call.1).ok()?;
+ match &collection.mode {
+ crate::CollectionMode::NFT => {
+ let call = UniqueNFTCall::parse(method_id, &mut reader).ok()??;
+ match call {
+ UniqueNFTCall::ERC721UniqueExtensions(
+ ERC721UniqueExtensionsCall::Transfer { token_id, .. },
+ ) => {
+ let token_id: TokenId = token_id.try_into().ok()?;
+ withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)
}
- if sponsor {
- <NftTransferBasket<T>>::insert(collection_id, token_id, block_number);
- return Ok(());
+ UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, from, .. }) => {
+ let token_id: TokenId = token_id.try_into().ok()?;
+ let from = T::CrossAccountId::from_eth(from);
+ withdraw_transfer::<T>(&collection, &from, &token_id).map(|()| sponsor)
}
+ UniqueNFTCall::ERC721(ERC721Call::Approve { token_id, .. }) => {
+ let token_id: TokenId = token_id.try_into().ok()?;
+ withdraw_approve::<T>(&collection, who.as_sub(), &token_id)
+ .map(|()| sponsor)
+ }
+ _ => None,
}
- _ => {}
}
- }
- crate::CollectionMode::Fungible(_) => {
- let call: UniqueFungibleCall = UniqueFungibleCall::parse(method_id, &mut reader)
- .map_err(|_| AnyError)?
- .ok_or(AnyError)?;
- #[allow(clippy::single_match)]
- match call {
- UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {
- let who = T::CrossAccountId::from_eth(*caller);
- let collection_limits = &collection.limits;
- let limit = collection_limits
- .sponsor_transfer_timeout(FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT);
-
- let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
- let mut sponsored = true;
- if <FungibleTransferBasket<T>>::contains_key(collection_id, who.as_sub()) {
- let last_tx_block =
- <FungibleTransferBasket<T>>::get(collection_id, who.as_sub());
- let limit_time = last_tx_block + limit.into();
- if block_number <= limit_time {
- sponsored = false;
- }
+ crate::CollectionMode::Fungible(_) => {
+ let call = UniqueFungibleCall::parse(method_id, &mut reader).ok()??;
+ #[allow(clippy::single_match)]
+ match call {
+ UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {
+ withdraw_transfer::<T>(&collection, &who, &TokenId::default())
+ .map(|()| sponsor)
}
- if sponsored {
- <FungibleTransferBasket<T>>::insert(
- collection_id,
- who.as_sub(),
- block_number,
- );
- return Ok(());
+ UniqueFungibleCall::ERC20(ERC20Call::TransferFrom { from, .. }) => {
+ let from = T::CrossAccountId::from_eth(from);
+ withdraw_transfer::<T>(&collection, &from, &TokenId::default())
+ .map(|()| sponsor)
}
- }
- _ => {}
- }
- }
- _ => {}
- }
- Err(AnyError)
-}
-
-pub struct NftEthSponsorshipHandler<T: Config>(PhantomData<*const T>);
-impl<T: Config> SponsorshipHandler<H160, (H160, Vec<u8>)> for NftEthSponsorshipHandler<T> {
- fn get_sponsor(who: &H160, call: &(H160, Vec<u8>)) -> Option<H160> {
- if let Some(collection_id) = map_eth_to_id(&call.0) {
- if let Some(collection) = <CollectionById<T>>::get(collection_id) {
- if !collection.sponsorship.confirmed() {
- return None;
+ UniqueFungibleCall::ERC20(ERC20Call::Approve { .. }) => {
+ withdraw_approve::<T>(&collection, who.as_sub(), &TokenId::default())
+ .map(|()| sponsor)
+ }
+ _ => None,
}
- if try_sponsor(who, collection_id, &collection, &call.1).is_ok() {
- return collection
- .sponsorship
- .sponsor()
- .cloned()
- .map(T::EvmBackwardsAddressMapping::from_account_id);
- }
}
+ _ => None,
}
- None
}
}
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -42,8 +42,8 @@
CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
};
use pallet_common::{
- account::CrossAccountId, CollectionHandle, IsAdmin, Pallet as PalletCommon,
- Error as CommonError, CommonWeightInfo, Allowlist,
+ account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
+ CommonWeightInfo,
};
use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};
use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
@@ -136,18 +136,22 @@
//#region Tokens transfer rate limit baskets
/// (Collection id (controlled?2), who created (real))
/// TODO: Off chain worker should remove from this map when collection gets removed
- pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => T::BlockNumber;
+ pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => Option<T::BlockNumber>;
/// Collection id (controlled?2), token id (controlled?2)
- pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;
+ pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;
/// Collection id (controlled?2), owning user (real)
- pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;
+ pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;
/// Collection id (controlled?2), token id (controlled?2)
- pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;
+ pub ReFungibleTransferBasket get(fn refungible_transfer_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;
//#endregion
/// Variable metadata sponsoring
/// Collection id (controlled?2), token id (controlled?2)
- pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;
+ pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;
+ /// Approval sponsoring
+ pub NftApproveBasket get(fn nft_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;
+ pub FungibleApproveBasket get(fn fungible_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;
+ pub RefungibleApproveBasket get(fn refungible_approve_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;
}
}
@@ -190,7 +194,7 @@
let who = ensure_signed(origin)?;
// Create new collection
- let new_collection = Collection::<T> {
+ let new_collection = Collection {
owner: who.clone(),
name: collection_name,
mode: mode.clone(),
@@ -208,14 +212,14 @@
};
let _id = match mode {
- CollectionMode::NFT => {PalletNonfungible::init_collection(new_collection)?},
+ CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(new_collection)?},
CollectionMode::Fungible(decimal_points) => {
// check params
ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
- PalletFungible::init_collection(new_collection)?
+ <PalletFungible<T>>::init_collection(new_collection)?
}
CollectionMode::ReFungible => {
- PalletRefungible::init_collection(new_collection)?
+ <PalletRefungible<T>>::init_collection(new_collection)?
}
};
@@ -249,9 +253,12 @@
<NftTransferBasket<T>>::remove_prefix(collection_id, None);
<FungibleTransferBasket<T>>::remove_prefix(collection_id, None);
- <ReFungibleTransferBasket<T>>::remove_prefix(collection_id, None);
+ <ReFungibleTransferBasket<T>>::remove_prefix((collection_id,), None);
<VariableMetaDataBasket<T>>::remove_prefix(collection_id, None);
+ <NftApproveBasket<T>>::remove_prefix(collection_id, None);
+ <FungibleApproveBasket<T>>::remove_prefix(collection_id, None);
+ <RefungibleApproveBasket<T>>::remove_prefix((collection_id,), None);
Ok(())
}
@@ -592,7 +599,15 @@
pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- dispatch_call::<T, _>(collection_id, |d| d.burn_item(sender, item_id, value))
+ let post_info = dispatch_call::<T, _>(collection_id, |d| d.burn_item(sender, item_id, value))?;
+ if value == 1 {
+ <NftTransferBasket<T>>::remove(collection_id, item_id);
+ <NftApproveBasket<T>>::remove(collection_id, item_id);
+ }
+ // Those maps should be cleared only if token disappears completly, need to move this part of logic to pallets?
+ // <FungibleApproveBasket<T>>::remove(collection_id, sender.as_sub());
+ // <RefungibleApproveBasket<T>>::remove((collection_id, item_id, sender.as_sub()));
+ Ok(post_info)
}
/// Destroys a concrete instance of NFT on behalf of the owner
@@ -936,19 +951,5 @@
target_collection.save()
}
- }
-}
-
-// TODO: limit returned entries?
-impl<T: Config> Pallet<T> {
- pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
- <IsAdmin<T>>::iter_prefix((collection,))
- .map(|(a, _)| a)
- .collect()
- }
- pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
- <Allowlist<T>>::iter_prefix((collection,))
- .map(|(a, _)| a)
- .collect()
}
}
pallets/nft/src/sponsorship.rsdiffbeforeafterboth1use crate::{1use crate::{2 Config, Call, CreateItemBasket, VariableMetaDataBasket, ReFungibleTransferBasket,2 Config, Call, CreateItemBasket, VariableMetaDataBasket, ReFungibleTransferBasket,3 FungibleTransferBasket, NftTransferBasket, CreateItemData, CollectionMode,3 FungibleTransferBasket, NftTransferBasket, CreateItemData, CollectionMode, NftApproveBasket,4 FungibleApproveBasket, RefungibleApproveBasket,4};5};5use core::marker::PhantomData;6use core::marker::PhantomData;6use up_sponsorship::SponsorshipHandler;7use up_sponsorship::SponsorshipHandler;7use frame_support::{8use frame_support::{8 traits::{IsSubType},9 traits::{IsSubType},9 storage::{StorageMap, StorageDoubleMap},10 storage::{StorageMap, StorageDoubleMap, StorageNMap},10};11};11use nft_data_structs::{12use nft_data_structs::{12 TokenId, CollectionId, NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,13 CollectionId, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MetaUpdatePermission,13 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,14 NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, TokenId,14};15};15use pallet_common::{CollectionById};16use pallet_common::{CollectionHandle};17use pallet_common::account::CrossAccountId;1819pub fn withdraw_transfer<T: Config>(20 collection: &CollectionHandle<T>,21 who: &T::CrossAccountId,22 item_id: &TokenId,23) -> Option<()> {24 // preliminary sponsoring correctness check25 match collection.mode {26 CollectionMode::NFT => {27 let owner = pallet_nonfungible::TokenData::<T>::get((collection.id, item_id))?.owner;28 if !owner.conv_eq(who) {29 return None;30 }31 }32 CollectionMode::Fungible(_) => {33 if item_id != &TokenId::default() {34 return None;35 }36 if <pallet_fungible::Balance<T>>::get((collection.id, who)) == 0 {37 return None;38 }39 }40 CollectionMode::ReFungible => {41 if !<pallet_refungible::Owned<T>>::get((collection.id, who, item_id)) {42 return None;43 }44 }45 }4647 // sponsor timeout48 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;49 let limit = collection50 .limits51 .sponsor_transfer_timeout(match collection.mode {52 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,53 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,54 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,55 });5657 let last_tx_block = match collection.mode {58 CollectionMode::NFT => <NftTransferBasket<T>>::get(collection.id, item_id),59 CollectionMode::Fungible(_) => {60 <FungibleTransferBasket<T>>::get(collection.id, who.as_sub())61 }62 CollectionMode::ReFungible => {63 <ReFungibleTransferBasket<T>>::get((collection.id, item_id, who.as_sub()))64 }65 };6667 if let Some(last_tx_block) = last_tx_block {68 let timeout = last_tx_block + limit.into();69 if block_number < timeout {70 return None;71 }72 }7374 match collection.mode {75 CollectionMode::NFT => <NftTransferBasket<T>>::insert(collection.id, item_id, block_number),76 CollectionMode::Fungible(_) => {77 <FungibleTransferBasket<T>>::insert(collection.id, who.as_sub(), block_number)78 }79 CollectionMode::ReFungible => <ReFungibleTransferBasket<T>>::insert(80 (collection.id, item_id, who.as_sub()),81 block_number,82 ),83 };8485 Some(())86}8788pub fn withdraw_create_item<T: Config>(89 collection: &CollectionHandle<T>,90 who: &T::AccountId,91 _properties: &CreateItemData,92) -> Option<()> {93 if _properties.data_size() as u32 > collection.limits.sponsored_data_size() {94 return None;95 }9697 // sponsor timeout98 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;99 let limit = collection100 .limits101 .sponsor_transfer_timeout(match _properties {102 CreateItemData::NFT(_) => NFT_SPONSOR_TRANSFER_TIMEOUT,103 CreateItemData::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,104 CreateItemData::ReFungible(_) => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,105 });106107 if let Some(last_tx_block) = <CreateItemBasket<T>>::get((collection.id, &who)) {108 let timeout = last_tx_block + limit.into();109 if block_number < timeout {110 return None;111 }112 }113114 CreateItemBasket::<T>::insert((collection.id, who.clone()), block_number);115116 Some(())117}118119pub fn withdraw_set_variable_meta_data<T: Config>(120 who: &T::CrossAccountId,121 collection: &CollectionHandle<T>,122 item_id: &TokenId,123 data: &[u8],124) -> Option<()> {125 // TODO: make it work for admins126 if collection.meta_update_permission != MetaUpdatePermission::ItemOwner {127 return None;128 }129 // preliminary sponsoring correctness check130 match collection.mode {131 CollectionMode::NFT => {132 let owner = pallet_nonfungible::TokenData::<T>::get((collection.id, item_id))?.owner;133 if !owner.conv_eq(who) {134 return None;135 }136 }137 CollectionMode::Fungible(_) => {138 if item_id != &TokenId::default() {139 return None;140 }141 if <pallet_fungible::Balance<T>>::get((collection.id, who)) == 0 {142 return None;143 }144 }145 CollectionMode::ReFungible => {146 if !<pallet_refungible::Owned<T>>::get((collection.id, who, item_id)) {147 return None;148 }149 }150 }151152 // Can't sponsor fungible collection, this tx will be rejected153 // as invalid154 if matches!(collection.mode, CollectionMode::Fungible(_)) {155 return None;156 }157 if data.len() > collection.limits.sponsored_data_size() as usize {158 return None;159 }160161 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;162 let limit = collection.limits.sponsored_data_rate_limit()?;163164 if let Some(last_tx_block) = VariableMetaDataBasket::<T>::get(collection.id, item_id) {165 let timeout = last_tx_block + limit.into();166 if block_number < timeout {167 return None;168 }169 }170171 <VariableMetaDataBasket<T>>::insert(collection.id, item_id, block_number);172173 Some(())174}175176pub fn withdraw_approve<T: Config>(177 collection: &CollectionHandle<T>,178 who: &T::AccountId,179 item_id: &TokenId,180) -> Option<()> {181 // sponsor timeout182 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;183 let limit = collection.limits.sponsor_approve_timeout();184185 let last_tx_block = match collection.mode {186 CollectionMode::NFT => <NftApproveBasket<T>>::get(collection.id, item_id),187 CollectionMode::Fungible(_) => <FungibleApproveBasket<T>>::get(collection.id, who),188 CollectionMode::ReFungible => {189 <RefungibleApproveBasket<T>>::get((collection.id, item_id, who))190 }191 };192193 if let Some(last_tx_block) = last_tx_block {194 let timeout = last_tx_block + limit.into();195 if block_number < timeout {196 return None;197 }198 }199200 match collection.mode {201 CollectionMode::NFT => <NftApproveBasket<T>>::insert(collection.id, item_id, block_number),202 CollectionMode::Fungible(_) => {203 <FungibleApproveBasket<T>>::insert(collection.id, who, block_number)204 }205 CollectionMode::ReFungible => {206 <RefungibleApproveBasket<T>>::insert((collection.id, item_id, who), block_number)207 }208 };209210 Some(())211}212213fn load<T: Config>(id: CollectionId) -> Option<(T::AccountId, CollectionHandle<T>)> {214 let collection = CollectionHandle::new(id)?;215 let sponsor = collection.sponsorship.sponsor().cloned()?;216 Some((sponsor, collection))217}1621817pub struct NftSponsorshipHandler<T>(PhantomData<T>);219pub struct NftSponsorshipHandler<T>(PhantomData<T>);18impl<T: Config> NftSponsorshipHandler<T> {19 pub fn withdraw_create_item(20 who: &T::AccountId,21 collection_id: &CollectionId,22 _properties: &CreateItemData,23 ) -> Option<T::AccountId> {24 let collection = CollectionById::<T>::get(collection_id)?;2526 // sponsor timeout27 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;2829 let limit = collection30 .limits31 .sponsor_transfer_timeout(match _properties {32 CreateItemData::NFT(_) => NFT_SPONSOR_TRANSFER_TIMEOUT,33 CreateItemData::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,34 CreateItemData::ReFungible(_) => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,35 });36 if CreateItemBasket::<T>::contains_key((collection_id, &who)) {37 let last_tx_block = CreateItemBasket::<T>::get((collection_id, &who));38 let limit_time = last_tx_block + limit.into();39 if block_number <= limit_time {40 return None;41 }42 }43 CreateItemBasket::<T>::insert((collection_id, who.clone()), block_number);4445 // check free create limit46 if collection.limits.sponsored_data_size() >= (_properties.data_size() as u32) {47 collection.sponsorship.sponsor().cloned()48 } else {49 None50 }51 }5253 pub fn withdraw_transfer(54 who: &T::AccountId,55 collection_id: &CollectionId,56 item_id: &TokenId,57 ) -> Option<T::AccountId> {58 let collection = CollectionById::<T>::get(collection_id)?;5960 let mut sponsor_transfer = false;61 if collection.sponsorship.confirmed() {62 let collection_limits = collection.limits.clone();63 let collection_mode = collection.mode.clone();6465 // sponsor timeout66 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;67 sponsor_transfer = match collection_mode {68 CollectionMode::NFT => {69 // get correct limit70 let limit =71 collection_limits.sponsor_transfer_timeout(NFT_SPONSOR_TRANSFER_TIMEOUT);7273 let mut sponsored = true;74 if NftTransferBasket::<T>::contains_key(collection_id, item_id) {75 let last_tx_block = NftTransferBasket::<T>::get(collection_id, item_id);76 let limit_time = last_tx_block + limit.into();77 if block_number <= limit_time {78 sponsored = false;79 }80 }81 if sponsored {82 NftTransferBasket::<T>::insert(collection_id, item_id, block_number);83 }8485 sponsored86 }87 CollectionMode::Fungible(_) => {88 // get correct limit89 let limit = collection_limits90 .sponsor_transfer_timeout(FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT);9192 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;93 let mut sponsored = true;94 if FungibleTransferBasket::<T>::contains_key(collection_id, who) {95 let last_tx_block = FungibleTransferBasket::<T>::get(collection_id, who);96 let limit_time = last_tx_block + limit.into();97 if block_number <= limit_time {98 sponsored = false;99 }100 }101 if sponsored {102 FungibleTransferBasket::<T>::insert(collection_id, who, block_number);103 }104105 sponsored106 }107 CollectionMode::ReFungible => {108 // get correct limit109 let limit = collection_limits110 .sponsor_transfer_timeout(REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT);111112 let mut sponsored = true;113 if ReFungibleTransferBasket::<T>::contains_key(collection_id, item_id) {114 let last_tx_block =115 ReFungibleTransferBasket::<T>::get(collection_id, item_id);116 let limit_time = last_tx_block + limit.into();117 if block_number <= limit_time {118 sponsored = false;119 }120 }121 if sponsored {122 ReFungibleTransferBasket::<T>::insert(collection_id, item_id, block_number);123 }124125 sponsored126 }127 };128 }129130 if !sponsor_transfer {131 None132 } else {133 collection.sponsorship.sponsor().cloned()134 }135 }136137 pub fn withdraw_set_variable_meta_data(138 collection_id: &CollectionId,139 item_id: &TokenId,140 data: &[u8],141 ) -> Option<T::AccountId> {142 let mut sponsor_metadata_changes = false;143144 let collection = CollectionById::<T>::get(collection_id)?;145146 if collection.sponsorship.confirmed() &&147 // Can't sponsor fungible collection, this tx will be rejected148 // as invalid149 !matches!(collection.mode, CollectionMode::Fungible(_)) &&150 data.len() <= collection.limits.sponsored_data_size() as usize151 {152 if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit() {153 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;154155 if VariableMetaDataBasket::<T>::get(collection_id, item_id)156 .map(|last_block| block_number - last_block > rate_limit.into())157 .unwrap_or(true)158 {159 sponsor_metadata_changes = true;160 VariableMetaDataBasket::<T>::insert(collection_id, item_id, block_number);161 }162 }163 }164165 if !sponsor_metadata_changes {166 None167 } else {168 collection.sponsorship.sponsor().cloned()169 }170 }171}172173impl<T, C> SponsorshipHandler<T::AccountId, C> for NftSponsorshipHandler<T>220impl<T, C> SponsorshipHandler<T::AccountId, C> for NftSponsorshipHandler<T>174where221where181 collection_id,228 collection_id,182 data,229 data,183 ..230 ..184 } => Self::withdraw_create_item(who, collection_id, data),231 } => {232 let (sponsor, collection) = load(*collection_id)?;233 withdraw_create_item::<T>(&collection, who, data).map(|()| sponsor)234 }185 Call::transfer {235 Call::transfer {186 collection_id,236 collection_id,187 item_id,237 item_id,188 ..238 ..189 } => Self::withdraw_transfer(who, collection_id, item_id),239 } => {240 let (sponsor, collection) = load(*collection_id)?;241 withdraw_transfer::<T>(242 &collection,243 &T::CrossAccountId::from_sub(who.clone()),244 item_id,245 )246 .map(|()| sponsor)247 }248 Call::transfer_from {249 collection_id,250 item_id,251 from,252 ..253 } => {254 let (sponsor, collection) = load(*collection_id)?;255 withdraw_transfer::<T>(&collection, from, item_id).map(|()| sponsor)256 }257 Call::approve {258 collection_id,259 item_id,260 ..261 } => {262 let (sponsor, collection) = load(*collection_id)?;263 withdraw_approve::<T>(&collection, who, item_id).map(|()| sponsor)264 }190 Call::set_variable_meta_data {265 Call::set_variable_meta_data {191 collection_id,266 collection_id,192 item_id,267 item_id,193 data,268 data,194 } => Self::withdraw_set_variable_meta_data(collection_id, item_id, data),269 } => {270 let (sponsor, collection) = load(*collection_id)?;271 withdraw_set_variable_meta_data::<T>(272 &T::CrossAccountId::from_sub(who.clone()),273 &collection,274 item_id,275 data,276 )277 .map(|()| sponsor)278 }195 _ => None,279 _ => None,196 }280 }197 }281 }pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -58,18 +58,18 @@
}
#[pallet::pallet]
- #[pallet::generate_store(pub(super) trait Store)]
+ #[pallet::generate_store(pub trait Store)]
pub struct Pallet<T>(_);
#[pallet::storage]
- pub(super) type TokensMinted<T: Config> =
+ pub type TokensMinted<T: Config> =
StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
#[pallet::storage]
- pub(super) type TokensBurnt<T: Config> =
+ pub type TokensBurnt<T: Config> =
StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
#[pallet::storage]
- pub(super) type TokenData<T: Config> = StorageNMap<
+ pub type TokenData<T: Config> = StorageNMap<
Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
Value = ItemData<T>,
QueryKind = OptionQuery,
@@ -77,7 +77,7 @@
/// Used to enumerate tokens owned by account
#[pallet::storage]
- pub(super) type Owned<T: Config> = StorageNMap<
+ pub type Owned<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
Key<Blake2_128Concat, T::CrossAccountId>,
@@ -88,7 +88,7 @@
>;
#[pallet::storage]
- pub(super) type AccountBalance<T: Config> = StorageNMap<
+ pub type AccountBalance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
Key<Blake2_128Concat, T::CrossAccountId>,
@@ -98,7 +98,7 @@
>;
#[pallet::storage]
- pub(super) type Allowance<T: Config> = StorageNMap<
+ pub type Allowance<T: Config> = StorageNMap<
Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
Value = T::CrossAccountId,
QueryKind = OptionQuery,
@@ -133,8 +133,8 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
- PalletCommon::init_collection(data)
+ pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(data)
}
pub fn destroy_collection(
collection: NonfungibleHandle<T>,
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -54,25 +54,25 @@
}
#[pallet::pallet]
- #[pallet::generate_store(pub(super) trait Store)]
+ #[pallet::generate_store(pub trait Store)]
pub struct Pallet<T>(_);
#[pallet::storage]
- pub(super) type TokensMinted<T: Config> =
+ pub type TokensMinted<T: Config> =
StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
#[pallet::storage]
- pub(super) type TokensBurnt<T: Config> =
+ pub type TokensBurnt<T: Config> =
StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
#[pallet::storage]
- pub(super) type TokenData<T: Config> = StorageNMap<
+ pub type TokenData<T: Config> = StorageNMap<
Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
Value = ItemData,
QueryKind = ValueQuery,
>;
#[pallet::storage]
- pub(super) type TotalSupply<T: Config> = StorageNMap<
+ pub type TotalSupply<T: Config> = StorageNMap<
Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
Value = u128,
QueryKind = ValueQuery,
@@ -80,7 +80,7 @@
/// Used to enumerate tokens owned by account
#[pallet::storage]
- pub(super) type Owned<T: Config> = StorageNMap<
+ pub type Owned<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
Key<Blake2_128Concat, T::CrossAccountId>,
@@ -91,7 +91,7 @@
>;
#[pallet::storage]
- pub(super) type AccountBalance<T: Config> = StorageNMap<
+ pub type AccountBalance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
// Owner
@@ -102,7 +102,7 @@
>;
#[pallet::storage]
- pub(super) type Balance<T: Config> = StorageNMap<
+ pub type Balance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
Key<Twox64Concat, TokenId>,
@@ -114,7 +114,7 @@
>;
#[pallet::storage]
- pub(super) type Allowance<T: Config> = StorageNMap<
+ pub type Allowance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
Key<Twox64Concat, TokenId>,
@@ -156,8 +156,8 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
- PalletCommon::init_collection(data)
+ pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(data)
}
pub fn destroy_collection(
collection: RefungibleHandle<T>,
primitives/evm-mapping/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/primitives/evm-mapping/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "up-evm-mapping"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies]
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+
+[features]
+default = ["std"]
+std = [
+ "sp-core/std",
+ "frame-support/std",
+]
primitives/evm-mapping/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/primitives/evm-mapping/src/lib.rs
@@ -0,0 +1,23 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use frame_support::sp_runtime::AccountId32;
+use sp_core::H160;
+
+/// Transforms substrate addresses to ethereum (Reverse of `EvmAddressMapping`)
+/// pallet_evm doesn't have this, as it only checks if eth address
+/// is owned by substrate via `EnsureAddressOrigin` trait
+///
+/// This trait implementations shouldn't conflict with used `EnsureAddressOrigin`
+pub trait EvmBackwardsAddressMapping<AccountId> {
+ fn from_account_id(account_id: AccountId) -> H160;
+}
+
+/// Should have same mapping as EnsureAddressTruncated
+pub struct MapBackwardsAddressTruncated;
+impl EvmBackwardsAddressMapping<AccountId32> for MapBackwardsAddressTruncated {
+ fn from_account_id(account_id: AccountId32) -> H160 {
+ let mut out = [0; 20];
+ out.copy_from_slice(&(account_id.as_ref() as &[u8])[0..20]);
+ H160(out)
+ }
+}
primitives/nft/src/lib.rsdiffbeforeafterboth--- a/primitives/nft/src/lib.rs
+++ b/primitives/nft/src/lib.rs
@@ -54,6 +54,8 @@
pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;
pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;
+pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;
+
// Schema limits
pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 1024;
pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 1024;
@@ -207,8 +209,8 @@
#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub struct Collection<T: frame_system::Config> {
- pub owner: T::AccountId,
+pub struct Collection<AccountId> {
+ pub owner: AccountId,
pub mode: CollectionMode,
pub access: AccessMode,
pub name: Vec<u16>, // 64 include null escape char
@@ -217,7 +219,7 @@
pub mint_mode: bool,
pub offchain_schema: Vec<u8>,
pub schema_version: SchemaVersion,
- pub sponsorship: SponsorshipState<T::AccountId>,
+ pub sponsorship: SponsorshipState<AccountId>,
pub limits: CollectionLimits, // Collection private restrictions
pub variable_on_chain_schema: Vec<u8>, //
pub const_on_chain_schema: Vec<u8>, //
@@ -246,6 +248,7 @@
pub variable_data: Vec<u8>,
}
+/// All fields are wrapped in `Option`s, where None means chain default
#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct CollectionLimits {
@@ -254,11 +257,12 @@
/// None - setVariableMetadata is not sponsored
/// Some(v) - setVariableMetadata is sponsored
/// if there is v block between txs
- pub sponsored_data_rate_limit: Option<u32>,
+ pub sponsored_data_rate_limit: Option<(Option<u32>,)>,
pub token_limit: Option<u32>,
// Timeouts for item types in passed blocks
pub sponsor_transfer_timeout: Option<u32>,
+ pub sponsor_approve_timeout: Option<u32>,
pub owner_can_transfer: Option<bool>,
pub owner_can_destroy: Option<bool>,
pub transfers_enabled: Option<bool>,
@@ -285,6 +289,11 @@
.unwrap_or(default)
.min(MAX_SPONSOR_TIMEOUT)
}
+ pub fn sponsor_approve_timeout(&self) -> u32 {
+ self.sponsor_approve_timeout
+ .unwrap_or(SPONSOR_APPROVE_TIMEOUT)
+ .min(MAX_SPONSOR_TIMEOUT)
+ }
pub fn owner_can_transfer(&self) -> bool {
self.owner_can_transfer.unwrap_or(true)
}
@@ -296,6 +305,8 @@
}
pub fn sponsored_data_rate_limit(&self) -> Option<u32> {
self.sponsored_data_rate_limit
+ .unwrap_or((None,))
+ .0
.map(|v| v.min(MAX_SPONSOR_TIMEOUT))
}
}
@@ -413,3 +424,11 @@
CreateItemData::Fungible(item)
}
}
+
+#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct CollectionStats {
+ pub created: u32,
+ pub destroyed: u32,
+ pub alive: u32,
+}
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -1,6 +1,6 @@
#![cfg_attr(not(feature = "std"), no_std)]
-use nft_data_structs::{CollectionId, TokenId};
+use nft_data_structs::{CollectionId, TokenId, Collection, CollectionStats};
use sp_std::vec::Vec;
use sp_core::H160;
use codec::Decode;
@@ -32,6 +32,9 @@
fn adminlist(collection: CollectionId) -> Vec<CrossAccountId>;
fn allowlist(collection: CollectionId) -> Vec<CrossAccountId>;
+ fn allowed(collection: CollectionId, user: CrossAccountId) -> bool;
fn last_token_id(collection: CollectionId) -> TokenId;
+ fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>>;
+ fn collection_stats() -> CollectionStats;
}
}
runtime/Cargo.tomldiffbeforeafterboth--- a/runtime/Cargo.toml
+++ b/runtime/Cargo.toml
@@ -69,6 +69,7 @@
'pallet-ethereum/std',
'fp-rpc/std',
'up-rpc/std',
+ 'up-evm-mapping/std',
'fp-self-contained/std',
'parachain-info/std',
'serde',
@@ -80,7 +81,6 @@
'pallet-nft/std',
'pallet-unq-scheduler/std',
'pallet-nft-charge-transaction/std',
- 'pallet-nft-transaction-payment/std',
'nft-data-structs/std',
'sp-api/std',
'sp-block-builder/std',
@@ -362,7 +362,7 @@
default-features = false
[dependencies.orml-vesting]
-git = "https://github.com/open-web3-stack/open-runtime-module-library"
+git = 'https://github.com/UniqueNetwork/open-runtime-module-library'
version = "0.4.1-dev"
default-features = false
@@ -376,6 +376,7 @@
derivative = "2.2.0"
pallet-nft = { path = '../pallets/nft', default-features = false, version = '3.0.0' }
up-rpc = { path = "../primitives/rpc", default-features = false }
+up-evm-mapping = { path = "../primitives/evm-mapping", default-features = false }
pallet-inflation = { path = '../pallets/inflation', default-features = false, version = '3.0.0' }
nft-data-structs = { path = '../primitives/nft', default-features = false, version = '0.9.0' }
pallet-common = { default-features = false, path = "../pallets/common" }
@@ -384,8 +385,7 @@
pallet-nonfungible = { default-features = false, path = "../pallets/nonfungible" }
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 = {git = "https://github.com/UniqueNetwork/pallet-sponsoring", package = "pallet-template-transaction-payment", 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/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -736,7 +736,7 @@
impl pallet_common::Config for Runtime {
type Event = Event;
- type EvmBackwardsAddressMapping = pallet_common::account::MapBackwardsAddressTruncated;
+ type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;
type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;
type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;
@@ -771,54 +771,43 @@
type InflationBlockInterval = InflationBlockInterval;
}
-parameter_types! {
- pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
- RuntimeBlockWeights::get().max_block;
- pub const MaxScheduledPerBlock: u32 = 50;
-}
+// parameter_types! {
+// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
+// RuntimeBlockWeights::get().max_block;
+// pub const MaxScheduledPerBlock: u32 = 50;
+// }
-pub struct Sponsoring;
-impl SponsoringResolve<AccountId, Call> for Sponsoring {
- fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>
- where
- Call: Dispatchable<Info = DispatchInfo>,
- AccountId: AsRef<[u8]>,
- {
- pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)
- }
-}
-
+type EvmSponsorshipHandler = (
+ pallet_nft::NftEthSponsorshipHandler<Runtime>,
+ pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
+);
type SponsorshipHandler = (
pallet_nft::NftSponsorshipHandler<Runtime>,
//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
+ pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
);
-impl pallet_unq_scheduler::Config for Runtime {
- type Event = Event;
- type Origin = Origin;
- type PalletsOrigin = OriginCaller;
- type Call = Call;
- type MaximumWeight = MaximumSchedulerWeight;
- type ScheduleOrigin = EnsureSigned<AccountId>;
- type MaxScheduledPerBlock = MaxScheduledPerBlock;
- type SponsorshipHandler = SponsorshipHandler;
- type WeightInfo = ();
-}
+// impl pallet_unq_scheduler::Config for Runtime {
+// type Event = Event;
+// type Origin = Origin;
+// type PalletsOrigin = OriginCaller;
+// type Call = Call;
+// type MaximumWeight = MaximumSchedulerWeight;
+// type ScheduleOrigin = EnsureSigned<AccountId>;
+// type MaxScheduledPerBlock = MaxScheduledPerBlock;
+// type SponsorshipHandler = SponsorshipHandler;
+// type WeightInfo = ();
+// }
-impl pallet_nft_transaction_payment::Config for Runtime {
- type SponsorshipHandler = SponsorshipHandler;
-}
-
impl pallet_evm_transaction_payment::Config for Runtime {
- type SponsorshipHandler = (
- pallet_nft::NftEthSponsorshipHandler<Self>,
- pallet_evm_contract_helpers::HelpersContractSponsoring<Self>,
- );
+ type EvmSponsorshipHandler = EvmSponsorshipHandler;
type Currency = Balances;
+ type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;
+ type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;
}
impl pallet_nft_charge_transaction::Config for Runtime {
- type SponsorshipHandler = pallet_nft::NftSponsorshipHandler<Runtime>;
+ type SponsorshipHandler = SponsorshipHandler;
}
// impl pallet_contract_helpers::Config for Runtime {
@@ -869,8 +858,8 @@
// Unique Pallets
Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
Nft: pallet_nft::{Pallet, Call, Storage} = 61,
- Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
- NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,
+ // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+ // free = 63
Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,
// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
Common: pallet_common::{Pallet, Storage, Event<T>} = 66,
@@ -1056,14 +1045,23 @@
.or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))
}
fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {
- <pallet_nft::Pallet<Runtime>>::adminlist(collection)
+ <pallet_common::Pallet<Runtime>>::adminlist(collection)
}
fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {
- <pallet_nft::Pallet<Runtime>>::allowlist(collection)
+ <pallet_common::Pallet<Runtime>>::allowlist(collection)
}
+ fn allowed(collection: CollectionId, user: CrossAccountId) -> bool {
+ <pallet_common::Pallet<Runtime>>::allowed(collection, user)
+ }
fn last_token_id(collection: CollectionId) -> TokenId {
dispatch_nft_runtime!(collection.last_token_id())
}
+ fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>> {
+ <pallet_common::CollectionById<Runtime>>::get(collection)
+ }
+ fn collection_stats() -> CollectionStats {
+ <pallet_common::Pallet<Runtime>>::collection_stats()
+ }
}
impl sp_api::Core<Block> for Runtime {
tests/src/addCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/addCollectionAdmin.test.ts
+++ b/tests/src/addCollectionAdmin.test.ts
@@ -8,7 +8,7 @@
import chaiAsPromised from 'chai-as-promised';
import privateKey from './substrate/privateKey';
import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId} from './util/helpers';
+import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId, queryCollectionExpectSuccess} from './util/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -20,7 +20,7 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.equal(alice.address);
const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
@@ -38,7 +38,7 @@
const bob = privateKey('//Bob');
const charlie = privateKey('//CHARLIE');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.equal(alice.address);
const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
tests/src/addToAllowList.test.tsdiffbeforeafterboth--- a/tests/src/addToAllowList.test.ts
+++ b/tests/src/addToAllowList.test.ts
@@ -18,6 +18,7 @@
normalizeAccountId,
addCollectionAdminExpectSuccess,
addToAllowListExpectFail,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -55,7 +56,7 @@
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 collectionId = await getCreatedCollectionCount(api) + 1;
const bob = privateKey('//Bob');
const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(bob.address));
tests/src/approve.test.tsdiffbeforeafterboth--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -18,9 +18,13 @@
transferExpectSuccess,
addCollectionAdminExpectSuccess,
adminApproveFromExpectSuccess,
+ getCreatedCollectionCount,
+ transferFromExpectSuccess,
+ transferFromExpectFail,
} from './util/helpers';
chai.use(chaiAsPromised);
+const expect = chai.expect;
describe('Integration Test approve(spender, collection_id, item_id, amount):', () => {
let alice: IKeyringPair;
@@ -78,6 +82,320 @@
});
});
+describe('Normal user can approve other users to transfer:', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ charlie = privateKey('//Charlie');
+ });
+ });
+
+ it('NFT', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
+ await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+ });
+
+ it('Fungible up to an approved amount', async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'Fungible', bob.address);
+ await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+ });
+
+ it('ReFungible up to an approved amount', async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'ReFungible' } });
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', bob.address);
+ await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+ });
+});
+
+describe('Approved users can transferFrom up to approved amount:', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ charlie = privateKey('//Charlie');
+ });
+ });
+
+ it('NFT', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
+ await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+ await transferFromExpectSuccess(collectionId, itemId, charlie, bob, alice, 1, 'NFT');
+ });
+
+ it('Fungible up to an approved amount', async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'Fungible', bob.address);
+ await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+ await transferFromExpectSuccess(collectionId, itemId, charlie, bob, alice, 1, 'Fungible');
+ });
+
+ it('ReFungible up to an approved amount', async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'ReFungible' } });
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', bob.address);
+ await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+ await transferFromExpectSuccess(collectionId, itemId, charlie, bob, alice, 1, 'ReFungible');
+ });
+});
+
+describe('Approved users cannot use transferFrom to repeat transfers if approved amount was already transferred:', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ charlie = privateKey('//Charlie');
+ });
+ });
+
+ it('NFT', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
+ await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+ await transferFromExpectSuccess(collectionId, itemId, charlie, bob, alice, 1, 'NFT');
+ await transferFromExpectFail(collectionId, itemId, charlie, bob, alice, 1);
+ });
+
+ it('Fungible up to an approved amount', async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'Fungible', bob.address);
+ await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+ await transferFromExpectSuccess(collectionId, itemId, charlie, bob, alice, 1, 'Fungible');
+ await transferFromExpectFail(collectionId, itemId, charlie, bob, alice, 1);
+ });
+
+ it('ReFungible up to an approved amount', async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'ReFungible' } });
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', bob.address);
+ await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+ await transferFromExpectSuccess(collectionId, itemId, charlie, bob, alice, 1, 'ReFungible');
+ await transferFromExpectFail(collectionId, itemId, charlie, bob, alice, 1);
+ });
+});
+
+describe('Approved amount decreases by the transferred amount.:', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+ let dave: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ charlie = privateKey('//Charlie');
+ dave = privateKey('//Dave');
+ });
+ });
+
+ it('If a user B is approved to transfer 10 Fungible tokens from user A, they can transfer 2 tokens to user C, which will result in decreasing approval from 10 to 8. Then user B can transfer 8 tokens to user D.', async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'Fungible', alice.address);
+ await approveExpectSuccess(collectionId, itemId, alice, bob.address, 10);
+ await transferFromExpectSuccess(collectionId, itemId, bob, alice, charlie, 2, 'Fungible');
+ await transferFromExpectSuccess(collectionId, itemId, bob, alice, dave, 8, 'Fungible');
+ });
+});
+
+describe('User may clear the approvals to approving for 0 amount:', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ charlie = privateKey('//Charlie');
+ });
+ });
+
+ it('NFT', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT');
+ await approveExpectSuccess(collectionId, itemId, alice, bob.address, 1);
+ await approveExpectSuccess(collectionId, itemId, alice, bob.address, 0);
+ await transferFromExpectFail(collectionId, itemId, bob, bob, charlie, 1);
+ });
+
+ it('Fungible', async () => {
+ const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+ const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
+ await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, alice, bob.address, 1);
+ await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, alice, bob.address, 0);
+ await transferFromExpectFail(fungibleCollectionId, newFungibleTokenId, bob, bob, charlie, 1);
+ });
+
+ it('ReFungible', async () => {
+ const reFungibleCollectionId =
+ await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+ const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
+ await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, alice, bob.address, 1);
+ await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, alice, bob.address, 0);
+ await transferFromExpectFail(reFungibleCollectionId, newReFungibleTokenId, bob, bob, charlie, 1);
+ });
+});
+
+describe('User cannot approve for the amount greater than they own:', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ charlie = privateKey('//Charlie');
+ });
+ });
+
+ it('1 for NFT', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
+ await approveExpectFail(collectionId, itemId, bob, charlie, 2);
+ });
+
+ it('Fungible', async () => {
+ const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+ const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
+ await approveExpectFail(fungibleCollectionId, newFungibleTokenId, bob, charlie, 11);
+ });
+
+ it('ReFungible', async () => {
+ const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+ const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
+ await approveExpectFail(reFungibleCollectionId, newReFungibleTokenId, bob, charlie, 101);
+ });
+});
+
+describe('Administrator and collection owner do not need approval in order to execute TransferFrom:', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+ let dave: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ charlie = privateKey('//Charlie');
+ dave = privateKey('//Dave');
+ });
+ });
+
+ it('NFT', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', charlie.address);
+ await transferFromExpectSuccess(collectionId, itemId, alice, charlie, dave, 1, 'NFT');
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ await transferFromExpectSuccess(collectionId, itemId, bob, dave, alice, 1, 'NFT');
+ });
+
+ it('Fungible up to an approved amount', async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'Fungible', charlie.address);
+ await transferFromExpectSuccess(collectionId, itemId, alice, charlie, dave, 1, 'Fungible');
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ await transferFromExpectSuccess(collectionId, itemId, bob, dave, alice, 1, 'Fungible');
+ });
+
+ it('ReFungible up to an approved amount', async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'ReFungible' } });
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', charlie.address);
+ await transferFromExpectSuccess(collectionId, itemId, alice, charlie, dave, 1, 'ReFungible');
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ await transferFromExpectSuccess(collectionId, itemId, bob, dave, alice, 1, 'ReFungible');
+ });
+});
+
+describe('Repeated approvals add up', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+ let dave: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ charlie = privateKey('//Charlie');
+ dave = privateKey('//Dave');
+ });
+ });
+
+ it.skip('Owned 10, approval 1: 1, approval 2: 1, resulting approved value: 2. Fungible', async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+ await createItemExpectSuccess(alice, collectionId, 'Fungible', alice.address);
+ await approveExpectSuccess(collectionId, 0, alice, bob.address, 1);
+ await approveExpectSuccess(collectionId, 0, alice, charlie.address, 1);
+ // const allowances1 = await getAllowance(collectionId, 0, Alice.address, Bob.address);
+ // const allowances2 = await getAllowance(collectionId, 0, Alice.address, Charlie.address);
+ // expect(allowances1 + allowances2).to.be.eq(BigInt(2));
+ });
+
+ it.skip('Owned 10, approval 1: 1, approval 2: 1, resulting approved value: 2. ReFungible', async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'ReFungible' } });
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', alice.address);
+ await approveExpectSuccess(collectionId, itemId, alice, bob.address, 1);
+ await approveExpectSuccess(collectionId, itemId, alice, charlie.address, 1);
+ // const allowances1 = await getAllowance(collectionId, itemId, Alice.address, Bob.address);
+ // const allowances2 = await getAllowance(collectionId, itemId, Alice.address, Charlie.address);
+ // expect(allowances1 + allowances2).to.be.eq(BigInt(2));
+ });
+
+ // Canceled by changing approve logic
+ it.skip('Cannot approve for more than total user`s amount (owned: 10, approval 1: 5 - should succeed, approval 2: 6 - should fail). Fungible', async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+ await createItemExpectSuccess(alice, collectionId, 'Fungible', dave.address);
+ await approveExpectSuccess(collectionId, 0, dave, bob.address, 5);
+ await approveExpectFail(collectionId, 0, dave, charlie, 6);
+ });
+
+ // Canceled by changing approve logic
+ it.skip('Cannot approve for more than total users amount (owned: 100, approval 1: 50 - should succeed, approval 2: 51 - should fail). ReFungible', async () => {
+ const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'ReFungible' } });
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', dave.address);
+ await approveExpectSuccess(collectionId, itemId, dave, bob.address, 50);
+ await approveExpectFail(collectionId, itemId, dave, charlie, 51);
+ });
+});
+
+describe('Integration Test approve(spender, collection_id, item_id, amount) 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('can be called by collection admin on non-owned item', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ await adminApproveFromExpectSuccess(collectionId, itemId, bob, alice.address, charlie.address);
+ });
+});
+
describe('Negative Integration Test approve(spender, collection_id, item_id, amount):', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
@@ -94,13 +412,13 @@
it('Approve for a collection that does not exist', async () => {
await usingApi(async (api: ApiPromise) => {
// nft
- const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const nftCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(nftCollectionCount + 1, 1, alice, bob);
// fungible
- const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const fungibleCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(fungibleCollectionCount + 1, 0, alice, bob);
// reFungible
- const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const reFungibleCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(reFungibleCollectionCount + 1, 1, alice, bob);
});
});
@@ -169,27 +487,5 @@
await setCollectionLimitsExpectSuccess(alice, collectionId, {ownerCanTransfer: false});
await approveExpectFail(collectionId, itemId, alice, charlie);
- });
-});
-
-describe('Integration Test approve(spender, collection_id, item_id, amount) 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('can be called by collection admin on non-owned item', async () => {
- const collectionId = await createCollectionExpectSuccess();
- const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
-
- await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
- await adminApproveFromExpectSuccess(collectionId, itemId, bob, alice.address, charlie.address);
});
});
tests/src/change-collection-owner.test.tsdiffbeforeafterboth--- a/tests/src/change-collection-owner.test.ts
+++ b/tests/src/change-collection-owner.test.ts
@@ -22,6 +22,7 @@
setMintPermissionExpectFailure,
destroyCollectionExpectFailure,
setPublicAccessModeExpectSuccess,
+ queryCollectionExpectSuccess,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -34,13 +35,13 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection =await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await submitTransactionAsync(alice, changeOwnerTx);
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
});
});
@@ -53,7 +54,7 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
@@ -62,7 +63,7 @@
const badChangeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, alice.address);
await expect(submitTransactionExpectFailAsync(alice, badChangeOwnerTx)).to.be.rejected;
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
});
});
@@ -74,13 +75,13 @@
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await submitTransactionAsync(alice, changeOwnerTx);
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
// After changing the owner of the collection, all privileged methods are available to the new owner
@@ -118,20 +119,20 @@
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await submitTransactionAsync(alice, changeOwnerTx);
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
const changeOwnerTx2 = api.tx.nft.changeCollectionOwner(collectionId, charlie.address);
await submitTransactionAsync(bob, changeOwnerTx2);
// ownership lost
- const collectionAfterOwnerChange2 = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange2 = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange2.owner.toString()).to.be.deep.eq(charlie.address);
});
});
@@ -147,7 +148,7 @@
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(alice.address);
// Verifying that nothing bad happened (network is live, new collections can be created, etc.)
@@ -166,7 +167,7 @@
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(alice.address);
// Verifying that nothing bad happened (network is live, new collections can be created, etc.)
@@ -195,7 +196,7 @@
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
@@ -204,7 +205,7 @@
const badChangeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, alice.address);
await expect(submitTransactionExpectFailAsync(alice, badChangeOwnerTx)).to.be.rejected;
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
await setCollectionSponsorExpectFailure(collectionId, charlie.address, '//Alice');
tests/src/confirmSponsorship.test.tsdiffbeforeafterboth--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -20,6 +20,7 @@
addToAllowListExpectSuccess,
normalizeAccountId,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
import {Keyring} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
@@ -251,23 +252,20 @@
const zeroBalance = await findUnusedAddress(api);
// Mint token for alice
- const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', alice.address);
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', zeroBalance.address);
- // Transfer this token from Alice to unused address and back
- // Alice to Zero gets sponsored
- const aliceToZero = api.tx.nft.transfer(normalizeAccountId(zeroBalance.address), collectionId, itemId, 1);
- const events1 = await submitTransactionAsync(alice, aliceToZero);
+ const zeroToAlice = api.tx.nft.transfer(normalizeAccountId(alice.address), collectionId, itemId, 1);
+
+ // Zero to alice gets sponsored
+ const events1 = await submitTransactionAsync(zeroBalance, zeroToAlice);
const result1 = getGenericResult(events1);
expect(result1.success).to.be.true;
// Second transfer should fail
const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
- const zeroToAlice = api.tx.nft.transfer(normalizeAccountId(alice.address), collectionId, itemId, 1);
- const badTransaction = async function () {
- await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
- };
- await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');
+ await expect(submitTransactionExpectFailAsync(zeroBalance, zeroToAlice)).to.be.rejectedWith('Inability to pay some fees');
const sponsorBalanceAfter = (await api.query.system.account(bob.address)).data.free.toBigInt();
+ expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);
// Try again after Zero gets some balance - now it should succeed
const balancetx = api.tx.balances.transfer(zeroBalance.address, 1e15);
@@ -275,8 +273,6 @@
const events2 = await submitTransactionAsync(zeroBalance, zeroToAlice);
const result2 = getGenericResult(events2);
expect(result2.success).to.be.true;
-
- expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);
});
});
@@ -335,7 +331,7 @@
// Find the collection that never existed
let collectionId = 0;
await usingApi(async (api) => {
- collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ collectionId = await getCreatedCollectionCount(api) + 1;
});
await confirmSponsorshipExpectFailure(collectionId, '//Bob');
tests/src/contracts.test.tsdiffbeforeafterboth--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -228,7 +228,7 @@
const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);
await submitTransactionAsync(alice, changeAdminTx);
- expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
{
const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, true);
@@ -236,7 +236,7 @@
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isAllowlisted(collectionId, bob.address)).to.be.true;
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.true;
}
{
const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, false);
@@ -244,7 +244,7 @@
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
}
});
});
tests/src/createMultipleItems.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -20,6 +20,7 @@
getLastTokenId,
getVariableMetadata,
getConstMetadata,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -273,7 +274,7 @@
it('Create token in not existing collection', async () => {
await usingApi(async (api: ApiPromise) => {
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const createMultipleItemsTx = api.tx.nft
.createMultipleItems(collectionId, normalizeAccountId(alice.address), ['NFT', 'NFT', 'NFT']);
await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTx)).to.be.rejected;
tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -14,6 +14,7 @@
createItemExpectSuccess,
getGenericResult,
transferExpectSuccess,
+ UNIQUE,
} from './util/helpers';
import {default as waitNewBlocks} from './substrate/wait-new-blocks';
@@ -169,12 +170,11 @@
const aliceBalanceBefore: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
await transferExpectSuccess(collectionId, tokenId, alice, bob, 1, 'NFT');
const aliceBalanceAfter: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
- const fee = aliceBalanceBefore - aliceBalanceAfter;
+ const fee = Number(aliceBalanceBefore - aliceBalanceAfter) / Number(UNIQUE);
- // console.log(fee.toString());
const expectedTransferFee = 0.1;
const tolerance = 0.001;
- expect(Number(fee) / 1e15 - expectedTransferFee).to.be.lessThan(tolerance);
+ expect(Number(fee) / Number(UNIQUE) - expectedTransferFee).to.be.lessThan(tolerance);
});
});
tests/src/destroyCollection.test.tsdiffbeforeafterboth--- a/tests/src/destroyCollection.test.ts
+++ b/tests/src/destroyCollection.test.ts
@@ -13,6 +13,7 @@
destroyCollectionExpectFailure,
setCollectionLimitsExpectSuccess,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -46,7 +47,7 @@
it('(!negative test!) Destroy a collection that never existed', async () => {
await usingApi(async (api) => {
// Find the collection that never existed
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
await destroyCollectionExpectFailure(collectionId);
});
});
tests/src/eth/marketplace/marketplace.test.tsdiffbeforeafterboth--- a/tests/src/eth/marketplace/marketplace.test.ts
+++ b/tests/src/eth/marketplace/marketplace.test.ts
@@ -2,7 +2,7 @@
import {getBalanceSingle, transferBalanceExpectSuccess} from '../../substrate/get-balance';
import privateKey from '../../substrate/privateKey';
import {addToAllowListExpectSuccess, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, createItemExpectSuccess, getTokenOwner, setCollectionSponsorExpectSuccess, transferExpectSuccess, transferFromExpectSuccess} from '../../util/helpers';
-import {collectionIdToAddress, contractHelpers, createEthAccountWithBalance, executeEthTxOnSub, GAS_ARGS, itWeb3, subToEth, subToEthLowercase} from '../util/helpers';
+import {collectionIdToAddress, contractHelpers, createEthAccountWithBalance, executeEthTxOnSub, GAS_ARGS, itWeb3, subToEth, subToEthLowercase, transferBalanceToEth} from '../util/helpers';
import {evmToAddress} from '@polkadot/util-crypto';
import nonFungibleAbi from '../nonFungibleAbi.json';
import fungibleAbi from '../fungibleAbi.json';
@@ -12,35 +12,33 @@
describe('Matcher contract usage', () => {
itWeb3('With UNQ', async ({api, web3}) => {
+ const alice = privateKey('//Alice');
+ const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId));
const matcherOwner = await createEthAccountWithBalance(api, web3);
+ const helpers = contractHelpers(web3, matcherOwner);
+
const matcherContract = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/MarketPlace.abi`)).toString()), undefined, {
from: matcherOwner,
...GAS_ARGS,
});
const matcher = await matcherContract.deploy({data: (await readFile(`${__dirname}/MarketPlace.bin`)).toString(), arguments:[matcherOwner]}).send({from: matcherOwner});
- const helpers = contractHelpers(web3, matcherOwner);
+
+ await transferBalanceToEth(api, alice, matcher.options.address);
await helpers.methods.toggleSponsoring(matcher.options.address, true).send({from: matcherOwner});
- await helpers.methods.setSponsoringRateLimit(matcher.options.address, 1).send({from: matcherOwner});
- const alice = privateKey('//Alice');
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId), {from: matcherOwner});
+ await transferBalanceToEth(api, alice, subToEth(alice.address));
await setCollectionSponsorExpectSuccess(collectionId, alice.address);
await confirmSponsorshipExpectSuccess(collectionId);
- await helpers.methods.toggleAllowed(matcher.options.address, subToEth(alice.address), true).send({from: matcherOwner});
- await addToAllowListExpectSuccess(alice, collectionId, evmToAddress(subToEth(alice.address)));
-
- const seller = privateKey('//Bob');
+ const seller = privateKey('//Seller/' + Date.now());
+ await addToAllowListExpectSuccess(alice, collectionId, {Ethereum:subToEth(seller.address)});
await helpers.methods.toggleAllowed(matcher.options.address, subToEth(seller.address), true).send({from: matcherOwner});
- await addToAllowListExpectSuccess(alice, collectionId, evmToAddress(subToEth(seller.address)));
const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', seller.address);
- // To transfer item to matcher it first needs to be transfered to EVM account of bob
+ // To transfer item to matcher it first needs to be transfered to EVM account of seller
await transferExpectSuccess(collectionId, tokenId, seller, {Ethereum: subToEth(seller.address)});
-
- // Token is owned by seller initially
expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: subToEthLowercase(seller.address)});
// Ask
@@ -55,14 +53,12 @@
// Buy
{
const sellerBalanceBeforePurchase = await getBalanceSingle(api, seller.address);
- // There is two functions named 'buy', so we should provide full signature
- await executeEthTxOnSub(api, alice, matcher, m => m['buy(address,uint256)'](evmCollection.options.address, tokenId), {value: PRICE});
+ await executeEthTxOnSub(api, alice, matcher, m => m.buy(evmCollection.options.address, tokenId), {value: PRICE});
expect(await getBalanceSingle(api, seller.address) - sellerBalanceBeforePurchase === PRICE);
}
// Token is transferred to evm account of alice
expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: subToEthLowercase(alice.address)});
-
// Transfer token to substrate side of alice
await transferFromExpectSuccess(collectionId, tokenId, alice, {Ethereum: subToEth(alice.address)}, {Substrate: alice.address});
@@ -137,37 +133,35 @@
});
itWeb3('With escrow', async ({api, web3}) => {
+ const alice = privateKey('//Alice');
+ const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId));
const matcherOwner = await createEthAccountWithBalance(api, web3);
+ const helpers = contractHelpers(web3, matcherOwner);
const escrow = await createEthAccountWithBalance(api, web3);
+
const matcherContract = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/MarketPlace.abi`)).toString()), undefined, {
from: matcherOwner,
...GAS_ARGS,
});
const matcher = await matcherContract.deploy({data: (await readFile(`${__dirname}/MarketPlace.bin`)).toString(), arguments: [matcherOwner]}).send({from: matcherOwner});
await matcher.methods.setEscrow(escrow).send({from: matcherOwner});
- const helpers = contractHelpers(web3, matcherOwner);
+
+ await transferBalanceToEth(api, alice, matcher.options.address);
await helpers.methods.toggleSponsoring(matcher.options.address, true).send({from: matcherOwner});
- await helpers.methods.setSponsoringRateLimit(matcher.options.address, 1).send({from: matcherOwner});
- const alice = privateKey('//Alice');
- const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
- const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId), {from: matcherOwner});
+ await transferBalanceToEth(api, alice, subToEth(alice.address));
await setCollectionSponsorExpectSuccess(collectionId, alice.address);
await confirmSponsorshipExpectSuccess(collectionId);
-
- await helpers.methods.toggleAllowed(matcher.options.address, subToEth(alice.address), true).send({from: matcherOwner});
- await addToAllowListExpectSuccess(alice, collectionId, evmToAddress(subToEth(alice.address)));
- const seller = privateKey('//Bob');
+ const seller = privateKey('//Seller/' + Date.now());
await helpers.methods.toggleAllowed(matcher.options.address, subToEth(seller.address), true).send({from: matcherOwner});
await addToAllowListExpectSuccess(alice, collectionId, evmToAddress(subToEth(seller.address)));
const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', seller.address);
- // To transfer item to matcher it first needs to be transfered to EVM account of bob
+ // To transfer item to matcher it first needs to be transfered to EVM account of seller
await transferExpectSuccess(collectionId, tokenId, seller, {Ethereum: subToEth(seller.address)});
-
- // Token is owned by seller initially
expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: subToEthLowercase(seller.address)});
// Ask
tests/src/eth/util/helpers.tsdiffbeforeafterboth--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -228,6 +228,18 @@
return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});
}
+/**
+ * Execute ethereum method call using substrate account
+ * @param to target contract
+ * @param mkTx - closure, receiving `contract.methods`, and returning method call,
+ * to be used as following (assuming `to` = erc20 contract):
+ * `m => m.transfer(to, amount)`
+ *
+ * # Example
+ * ```ts
+ * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));
+ * ```
+ */
export async function executeEthTxOnSub(api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {
const tx = api.tx.evm.call(
subToEth(from.address),
@@ -246,6 +258,11 @@
return (await getBalance(api, [evmToAddress(address)]))[0];
}
+/**
+ * Measure how much gas given closure consumes
+ *
+ * @param user which user balance will be checked
+ */
export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {
const before = await ethBalanceViaSub(api, user);
tests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-rpc.ts
+++ b/tests/src/interfaces/augment-api-rpc.ts
@@ -1,7 +1,7 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
-import type { NftDataStructsCollectionId, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr } from './nft';
+import type { NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionStats, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr } from './nft';
import type { Bytes, HashMap, Json, Metadata, Null, Option, StorageKey, Text, U256, U64, Vec, bool, u128, u32, u64 } from '@polkadot/types';
import type { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';
import type { EpochAuthorship } from '@polkadot/types/interfaces/babe';
@@ -373,6 +373,10 @@
**/
allowance: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, sender: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, spender: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: NftDataStructsTokenId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
/**
+ * Check if user is allowed to use collection
+ **/
+ allowed: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, account: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<bool>>;
+ /**
* Get allowlist
**/
allowlist: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<PalletCommonAccountBasicCrossAccountIdRepr>>>;
@@ -381,6 +385,14 @@
**/
balance: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, account: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: NftDataStructsTokenId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
/**
+ * Get collection by specified id
+ **/
+ collectionById: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<NftDataStructsCollection>>>;
+ /**
+ * Get collection stats
+ **/
+ collectionStats: AugmentedRpc<(at?: Hash | string | Uint8Array) => Observable<NftDataStructsCollectionStats>>;
+ /**
* Get tokens contained in collection
**/
collectionTokens: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<NftDataStructsTokenId>>>;
tests/src/interfaces/augment-types.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -2,7 +2,7 @@
/* eslint-disable */
import type { EthereumBlock, EthereumLog, EthereumReceipt, EthereumTransactionLegacyTransaction, EvmCoreErrorExitReason, FpRpcTransactionStatus } from './ethereum';
-import type { NftDataStructsAccessMode, NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionLimits, NftDataStructsCollectionMode, NftDataStructsCreateItemData, NftDataStructsMetaUpdatePermission, NftDataStructsSchemaVersion, NftDataStructsSponsorshipState, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2 } from './nft';
+import type { NftDataStructsAccessMode, NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionLimits, NftDataStructsCollectionMode, NftDataStructsCollectionStats, NftDataStructsCreateItemData, NftDataStructsMetaUpdatePermission, NftDataStructsSchemaVersion, NftDataStructsSponsorshipState, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2 } from './nft';
import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundStatus, CumulusPalletXcmpQueueOutboundStatus, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV1AbridgedHostConfiguration, PolkadotPrimitivesV1PersistedValidationData } from './polkadot';
import type { BitVec, Bool, Bytes, Data, I128, I16, I256, I32, I64, I8, Json, Null, Raw, StorageKey, Text, Type, U128, U16, U256, U32, U64, U8, USize, bool, i128, i16, i256, i32, i64, i8, u128, u16, u256, u32, u64, u8, usize } from '@polkadot/types';
import type { AssetApproval, AssetApprovalKey, AssetBalance, AssetDestroyWitness, AssetDetails, AssetMetadata, TAssetBalance, TAssetDepositBalance } from '@polkadot/types/interfaces/assets';
@@ -627,6 +627,7 @@
NftDataStructsCollectionId: NftDataStructsCollectionId;
NftDataStructsCollectionLimits: NftDataStructsCollectionLimits;
NftDataStructsCollectionMode: NftDataStructsCollectionMode;
+ NftDataStructsCollectionStats: NftDataStructsCollectionStats;
NftDataStructsCreateItemData: NftDataStructsCreateItemData;
NftDataStructsMetaUpdatePermission: NftDataStructsMetaUpdatePermission;
NftDataStructsSchemaVersion: NftDataStructsSchemaVersion;
tests/src/interfaces/nft/definitions.tsdiffbeforeafterboth--- a/tests/src/interfaces/nft/definitions.ts
+++ b/tests/src/interfaces/nft/definitions.ts
@@ -40,6 +40,9 @@
constMetadata: fun('Get token constant metadata', [collectionParam, tokenParam], 'Vec<u8>'),
variableMetadata: fun('Get token variable metadata', [collectionParam, tokenParam], 'Vec<u8>'),
tokenExists: fun('Check if token exists', [collectionParam, tokenParam], 'bool'),
+ collectionById: fun('Get collection by specified id', [collectionParam], 'Option<NftDataStructsCollection>'),
+ collectionStats: fun('Get collection stats', [], 'NftDataStructsCollectionStats'),
+ allowed: fun('Check if user is allowed to use collection', [collectionParam, crossAccountParam()], 'bool'),
},
types: {
PalletCommonAccountBasicCrossAccountIdRepr: {
@@ -64,6 +67,11 @@
constOnChainSchema: 'Vec<u8>',
metaUpdatePermission: 'NftDataStructsMetaUpdatePermission',
},
+ NftDataStructsCollectionStats: {
+ created: 'u32',
+ destroyed: 'u32',
+ alive: 'u32',
+ },
NftDataStructsCollectionId: 'u32',
NftDataStructsTokenId: 'u32',
PalletNonfungibleItemData: mkDummy('NftItemData'),
tests/src/interfaces/nft/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/nft/types.ts
+++ b/tests/src/interfaces/nft/types.ts
@@ -48,6 +48,13 @@
readonly dummyCollectionMode: u32;
}
+/** @name NftDataStructsCollectionStats */
+export interface NftDataStructsCollectionStats extends Struct {
+ readonly created: u32;
+ readonly destroyed: u32;
+ readonly alive: u32;
+}
+
/** @name NftDataStructsCreateItemData */
export interface NftDataStructsCreateItemData extends Struct {
readonly dummyCreateItemData: u32;
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -39,7 +39,6 @@
'nonfungible',
'refungible',
'scheduler',
- 'nftpayment',
'charging',
];
tests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionAdmin.test.ts
+++ b/tests/src/removeCollectionAdmin.test.ts
@@ -8,7 +8,7 @@
import chaiAsPromised from 'chai-as-promised';
import privateKey from './substrate/privateKey';
import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId} from './util/helpers';
+import {createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId, queryCollectionExpectSuccess} from './util/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -19,7 +19,7 @@
const collectionId = await createCollectionExpectSuccess();
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
// first - add collection admin Bob
const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
@@ -43,7 +43,7 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
// first - add collection admin Bob
const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
tests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionSponsor.test.ts
+++ b/tests/src/removeCollectionSponsor.test.ts
@@ -18,6 +18,7 @@
removeCollectionSponsorExpectFailure,
normalizeAccountId,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
import {Keyring} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
@@ -98,7 +99,7 @@
// Find the collection that never existed
let collectionId = 0;
await usingApi(async (api) => {
- collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ collectionId = await getCreatedCollectionCount(api) + 1;
});
await removeCollectionSponsorExpectFailure(collectionId);
tests/src/removeFromAllowList.test.tsdiffbeforeafterboth--- a/tests/src/removeFromAllowList.test.ts
+++ b/tests/src/removeFromAllowList.test.ts
@@ -37,13 +37,13 @@
});
it('ensure bob is not in allowlist after removal', async () => {
- await usingApi(async () => {
+ await usingApi(async api => {
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;
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
});
});
@@ -104,13 +104,13 @@
});
it('ensure address is not in allowlist after removal', async () => {
- await usingApi(async () => {
+ await usingApi(async api => {
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;
+ expect(await isAllowlisted(api, collectionId, charlie.address)).to.be.false;
});
});
tests/src/setCollectionSponsor.test.tsdiffbeforeafterboth--- a/tests/src/setCollectionSponsor.test.ts
+++ b/tests/src/setCollectionSponsor.test.ts
@@ -11,6 +11,7 @@
destroyCollectionExpectSuccess,
setCollectionSponsorExpectFailure,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
import {Keyring} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
@@ -77,7 +78,7 @@
// Find the collection that never existed
let collectionId = 0;
await usingApi(async (api) => {
- collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ collectionId = await getCreatedCollectionCount(api) + 1;
});
await setCollectionSponsorExpectFailure(collectionId, bob.address);
tests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth--- a/tests/src/setConstOnChainSchema.test.ts
+++ b/tests/src/setConstOnChainSchema.test.ts
@@ -12,6 +12,8 @@
createCollectionExpectSuccess,
destroyCollectionExpectSuccess,
addCollectionAdminExpectSuccess,
+ queryCollectionExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -37,7 +39,7 @@
it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
await submitTransactionAsync(alice, setShema);
@@ -47,7 +49,7 @@
it('Collection admin can set the scheme', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
@@ -60,7 +62,7 @@
const collectionId = await createCollectionExpectSuccess();
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
await submitTransactionAsync(alice, setShema);
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.constOnChainSchema.toString()).to.be.eq(shema);
});
});
@@ -71,7 +73,7 @@
it('Set a non-existent collection', async () => {
await usingApi(async (api) => {
// tslint:disable-next-line: radix
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;
});
@@ -97,7 +99,7 @@
it('Execute method not on behalf of the collection owner', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
await expect(submitTransactionExpectFailAsync(bob, setShema)).to.be.rejected;
tests/src/setPublicAccessMode.test.tsdiffbeforeafterboth--- a/tests/src/setPublicAccessMode.test.ts
+++ b/tests/src/setPublicAccessMode.test.ts
@@ -19,6 +19,7 @@
enableAllowListExpectSuccess,
normalizeAccountId,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -60,7 +61,7 @@
it('Set a non-existent collection', async () => {
await usingApi(async (api: ApiPromise) => {
// tslint:disable-next-line: radix
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const tx = api.tx.nft.setPublicAccessMode(collectionId, 'AllowList');
await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
});
tests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth--- a/tests/src/setVariableOnChainSchema.test.ts
+++ b/tests/src/setVariableOnChainSchema.test.ts
@@ -12,6 +12,8 @@
createCollectionExpectSuccess,
destroyCollectionExpectSuccess,
addCollectionAdminExpectSuccess,
+ queryCollectionExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -37,7 +39,7 @@
it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await submitTransactionAsync(alice, setSchema);
@@ -49,7 +51,7 @@
const collectionId = await createCollectionExpectSuccess();
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await submitTransactionAsync(alice, setSchema);
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);
});
@@ -61,7 +63,7 @@
it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
@@ -75,7 +77,7 @@
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await submitTransactionAsync(bob, setSchema);
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);
});
@@ -87,7 +89,7 @@
it('Set a non-existent collection', async () => {
await usingApi(async (api) => {
// tslint:disable-next-line: radix
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
});
@@ -113,7 +115,7 @@
it('Execute method not on behalf of the collection owner', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await expect(submitTransactionExpectFailAsync(bob, setSchema)).to.be.rejected;
tests/src/transfer.test.tsdiffbeforeafterboth--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -19,6 +19,11 @@
transferExpectFailure,
transferExpectSuccess,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
+ toSubstrateAddress,
+ getTokenOwner,
+ normalizeAccountId,
+ getBalance as getTokenBalance,
} from './util/helpers';
let alice: IKeyringPair;
@@ -132,13 +137,13 @@
it('Transfer with not existed collection_id', async () => {
await usingApi(async (api) => {
// nft
- const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const nftCollectionCount = await getCreatedCollectionCount(api);
await transferExpectFailure(nftCollectionCount + 1, 1, alice, bob, 1);
// fungible
- const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const fungibleCollectionCount = await getCreatedCollectionCount(api);
await transferExpectFailure(fungibleCollectionCount + 1, 0, alice, bob, 1);
// reFungible
- const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const reFungibleCollectionCount = await getCreatedCollectionCount(api);
await transferExpectFailure(reFungibleCollectionCount + 1, 1, alice, bob, 1);
});
});
@@ -230,3 +235,61 @@
);
});
});
+
+describe('Zero value transfer(From)', () => {
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+ });
+
+ it('NFT', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const nftCollectionId = await createCollectionExpectSuccess();
+ const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
+
+ const transferTx = api.tx.nft.transfer(normalizeAccountId(bob), nftCollectionId, newNftTokenId, 0);
+ await submitTransactionAsync(alice, transferTx);
+ const address = normalizeAccountId(await getTokenOwner(api, nftCollectionId, newNftTokenId));
+
+ expect(toSubstrateAddress(address)).to.be.equal(alice.address);
+ });
+ });
+
+ it('RFT', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+ const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
+ const balanceBeforeAlice = await getTokenBalance(api, reFungibleCollectionId, normalizeAccountId(alice), newReFungibleTokenId);
+ const balanceBeforeBob = await getTokenBalance(api, reFungibleCollectionId, normalizeAccountId(bob), newReFungibleTokenId);
+
+ const transferTx = api.tx.nft.transfer(normalizeAccountId(bob), reFungibleCollectionId, newReFungibleTokenId, 0);
+ await submitTransactionAsync(alice, transferTx);
+
+ const balanceAfterAlice = await getTokenBalance(api, reFungibleCollectionId, normalizeAccountId(alice), newReFungibleTokenId);
+ const balanceAfterBob = await getTokenBalance(api, reFungibleCollectionId, normalizeAccountId(bob), newReFungibleTokenId);
+
+ expect((balanceBeforeAlice)).to.be.equal(balanceAfterAlice);
+ expect((balanceBeforeBob)).to.be.equal(balanceAfterBob);
+ });
+ });
+
+ it('Fungible', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+ const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
+ const balanceBeforeAlice = await getTokenBalance(api, fungibleCollectionId, normalizeAccountId(alice), newFungibleTokenId);
+ const balanceBeforeBob = await getTokenBalance(api, fungibleCollectionId, normalizeAccountId(bob), newFungibleTokenId);
+
+ const transferTx = api.tx.nft.transfer(normalizeAccountId(bob), fungibleCollectionId, newFungibleTokenId, 0);
+ await submitTransactionAsync(alice, transferTx);
+
+ const balanceAfterAlice = await getTokenBalance(api, fungibleCollectionId, normalizeAccountId(alice), newFungibleTokenId);
+ const balanceAfterBob = await getTokenBalance(api, fungibleCollectionId, normalizeAccountId(bob), newFungibleTokenId);
+
+ expect((balanceBeforeAlice)).to.be.equal(balanceAfterAlice);
+ expect((balanceBeforeBob)).to.be.equal(balanceAfterBob);
+ });
+ });
+});
\ No newline at end of file
tests/src/transferFrom.test.tsdiffbeforeafterboth--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -19,6 +19,7 @@
transferFromExpectSuccess,
burnItemExpectSuccess,
setCollectionLimitsExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -109,18 +110,18 @@
it('transferFrom for a collection that does not exist', async () => {
await usingApi(async (api: ApiPromise) => {
// nft
- const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const nftCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(nftCollectionCount + 1, 1, alice, bob);
await transferFromExpectFail(nftCollectionCount + 1, 1, bob, alice, charlie, 1);
// fungible
- const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const fungibleCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(fungibleCollectionCount + 1, 0, alice, bob);
await transferFromExpectFail(fungibleCollectionCount + 1, 0, bob, alice, charlie, 1);
// reFungible
- const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const reFungibleCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(reFungibleCollectionCount + 1, 1, alice, bob);
await transferFromExpectFail(reFungibleCollectionCount + 1, 1, bob, alice, charlie, 1);
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -269,7 +269,7 @@
let collectionId = 0;
await usingApi(async (api) => {
// Get number of collections before the transaction
- const collectionCountBefore = (await api.query.common.createdCollectionCount()).toNumber();
+ const collectionCountBefore = await getCreatedCollectionCount(api);
// Run the CreateCollection transaction
const alicePrivateKey = privateKey('//Alice');
@@ -288,10 +288,10 @@
const result = getCreateCollectionResult(events);
// Get number of collections after the transaction
- const collectionCountAfter = (await api.query.common.createdCollectionCount()).toNumber();
+ const collectionCountAfter = await getCreatedCollectionCount(api);
// Get the collection
- const collection = (await api.query.common.collectionById(result.collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, result.collectionId);
// What to expect
// tslint:disable-next-line:no-unused-expression
@@ -325,7 +325,7 @@
await usingApi(async (api) => {
// Get number of collections before the transaction
- const collectionCountBefore = (await api.query.common.createdCollectionCount()).toNumber();
+ const collectionCountBefore = await getCreatedCollectionCount(api);
// Run the CreateCollection transaction
const alicePrivateKey = privateKey('//Alice');
@@ -334,7 +334,7 @@
const result = getCreateCollectionResult(events);
// Get number of collections after the transaction
- const collectionCountAfter = (await api.query.common.createdCollectionCount()).toNumber();
+ const collectionCountAfter = await getCreatedCollectionCount(api);
// What to expect
// tslint:disable-next-line:no-unused-expression
@@ -364,7 +364,7 @@
}
export async function findNotExistingCollection(api: ApiPromise): Promise<number> {
- const totalNumber = (await api.query.common.createdCollectionCount()).toNumber();
+ const totalNumber = await getCreatedCollectionCount(api);
const newCollection: number = totalNumber + 1;
return newCollection;
}
@@ -398,7 +398,7 @@
expect(result).to.be.true;
// What to expect
- expect((await api.query.common.collectionById(collectionId)).isNone).to.be.true;
+ expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;
});
}
@@ -432,7 +432,7 @@
const result = getGenericResult(events);
// Get the collection
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
// What to expect
expect(result.success).to.be.true;
@@ -452,7 +452,7 @@
const result = getGenericResult(events);
// Get the collection
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
// What to expect
expect(result.success).to.be.true;
@@ -490,7 +490,7 @@
const result = getGenericResult(events);
// Get the collection
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
// What to expect
expect(result.success).to.be.true;
@@ -1058,7 +1058,7 @@
const result = getGenericResult(events);
// Get the collection
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
// What to expect
// tslint:disable-next-line:no-unused-expression
@@ -1106,7 +1106,7 @@
expect(result.success).to.be.true;
// Get the collection
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.mintMode.toHuman()).to.be.equal(enabled);
});
@@ -1138,15 +1138,13 @@
});
}
-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 isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {
+ return (await api.rpc.nft.allowed(collectionId, normalizeAccountId(address))).toJSON();
}
export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {
await usingApi(async (api) => {
- expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.false;
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;
// Run the transaction
const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));
@@ -1154,14 +1152,14 @@
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
});
}
export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
await usingApi(async (api) => {
- expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
// Run the transaction
const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));
@@ -1169,7 +1167,7 @@
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
});
}
@@ -1215,16 +1213,16 @@
export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)
: Promise<NftDataStructsCollection | null> => {
- return (await api.query.common.collectionById(collectionId)).unwrapOr(null);
+ return (await api.rpc.nft.collectionById(collectionId)).unwrapOr(null);
};
export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {
// set global object - collectionsCount
- return (await api.query.common.createdCollectionCount()).toNumber();
+ return (await api.rpc.nft.collectionStats()).created.toNumber();
};
export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<NftDataStructsCollection> {
- return (await api.query.common.collectionById(collectionId)).unwrap();
+ return (await api.rpc.nft.collectionById(collectionId)).unwrap();
}
export async function waitNewBlocks(blocksCount = 1): Promise<void> {