difftreelog
Merge commit '4359d76172511a9ab73cac61957cc6ddf47a2653' into feature/evm-call-sponsoring
in: master
31 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -196,6 +196,7 @@
const_on_chain_schema: vec![],
variable_on_chain_schema: vec![],
limits: CollectionLimits::default(),
+ transfers_enabled: true,
},
)],
nft_item_id: vec![],
pallets/inflation/src/tests.rsdiffbeforeafterboth--- a/pallets/inflation/src/tests.rs
+++ b/pallets/inflation/src/tests.rs
@@ -31,6 +31,8 @@
type ExistentialDeposit = ExistentialDeposit;
type WeightInfo = ();
type MaxLocks = MaxLocks;
+ type MaxReserves = ();
+ type ReserveIdentifier = ();
}
frame_support::construct_runtime!(
@@ -89,7 +91,6 @@
type InflationBlockInterval = InflationBlockInterval;
}
-// Build genesis storage according to the mock runtime.
pub fn new_test_ext() -> sp_io::TestExternalities {
frame_system::GenesisConfig::default()
.build_storage::<Test>()
@@ -108,7 +109,9 @@
// BlockInflation should be set after 1st block and
// first inflation deposit should be equal to BlockInflation
Inflation::on_initialize(1);
- assert!(Inflation::block_inflation() > 0);
+
+ // SBP M2 review: Verify expected block inflation for year 1
+ assert_eq!(Inflation::block_inflation(), 1901);
assert_eq!(
Balances::free_balance(1234) - initial_issuance,
Inflation::block_inflation()
@@ -155,11 +158,24 @@
Inflation::on_initialize(1);
let block_inflation_year_0 = Inflation::block_inflation();
+ // SBP M2 review: go through all the block inflations for year 1,
+ // total issuance will be updated accordingly
+ for block in (100..YEAR).step_by(100) {
+ Inflation::on_initialize(block);
+ }
+ assert_eq!(
+ initial_issuance + (1901 * (YEAR / 100)),
+ <Balances as Currency<_>>::total_issuance()
+ );
+
Inflation::on_initialize(YEAR);
let block_inflation_year_1 = Inflation::block_inflation();
+ // SBP M2 review: Verify expected block inflation for year 2
+ assert_eq!(block_inflation_year_1, 1952);
+ // SBP M2 review: this is actually not true
// Assert that year 1 inflation is less than year 0
- assert!(block_inflation_year_0 > block_inflation_year_1);
+ // assert!(block_inflation_year_0 > block_inflation_year_1);
});
}
@@ -177,6 +193,7 @@
Inflation::on_initialize(YEAR * year);
let block_inflation_year_after = Inflation::block_inflation();
+ // SBP M2 review: this is actually not true (not for the first few years)
// Assert that next year inflation is less than previous year inflation
assert!(block_inflation_year_before > block_inflation_year_after);
}
pallets/nft/src/lib.rsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56#![recursion_limit = "1024"]7#![cfg_attr(not(feature = "std"), no_std)]8#![allow(9 clippy::too_many_arguments,10 clippy::unnecessary_mut_passed,11 clippy::unused_unit12)]1314extern crate alloc;1516pub use serde::{Serialize, Deserialize};1718pub use frame_support::{19 construct_runtime, decl_event, decl_module, decl_storage, decl_error,20 dispatch::DispatchResult,21 ensure, fail, parameter_types,22 traits::{23 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,24 Randomness, IsSubType, WithdrawReasons,25 },26 weights::{27 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},28 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,29 WeightToFeePolynomial, DispatchClass,30 },31 StorageValue, transactional,32};3334use frame_system::{self as system, ensure_signed, ensure_root};35use sp_core::H160;36use sp_std::vec;37use sp_runtime::sp_std::prelude::Vec;38use core::ops::{Deref, DerefMut};39use nft_data_structs::{40 MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_REFUNGIBLE_PIECES,41 AccessMode, ChainLimits, Collection, CreateItemData, CollectionLimits, CollectionId,42 CollectionMode, TokenId, SchemaVersion, SponsorshipState, Ownership, NftItemType,43 FungibleItemType, ReFungibleItemType,44};4546#[cfg(test)]47mod mock;4849#[cfg(test)]50mod tests;5152mod default_weights;53mod eth;54mod sponsorship;55pub use sponsorship::NftSponsorshipHandler;56pub use eth::sponsoring::NftEthSponsorshipHandler;5758pub use eth::NftErcSupport;59pub use eth::account::*;60use eth::erc::{ERC20Events, ERC721Events};6162#[cfg(feature = "runtime-benchmarks")]63mod benchmarking;6465pub trait WeightInfo {66 fn create_collection() -> Weight;67 fn destroy_collection() -> Weight;68 fn add_to_white_list() -> Weight;69 fn remove_from_white_list() -> Weight;70 fn set_public_access_mode() -> Weight;71 fn set_mint_permission() -> Weight;72 fn change_collection_owner() -> Weight;73 fn add_collection_admin() -> Weight;74 fn remove_collection_admin() -> Weight;75 fn set_collection_sponsor() -> Weight;76 fn confirm_sponsorship() -> Weight;77 fn remove_collection_sponsor() -> Weight;78 fn create_item(s: usize) -> Weight;79 fn burn_item() -> Weight;80 fn transfer() -> Weight;81 fn approve() -> Weight;82 fn transfer_from() -> Weight;83 fn set_offchain_schema() -> Weight;84 fn set_const_on_chain_schema() -> Weight;85 fn set_variable_on_chain_schema() -> Weight;86 fn set_variable_meta_data() -> Weight;87 fn enable_contract_sponsoring() -> Weight;88 fn set_schema_version() -> Weight;89 fn set_chain_limits() -> Weight;90 fn set_contract_sponsoring_rate_limit() -> Weight;91 fn set_variable_meta_data_sponsoring_rate_limit() -> Weight;92 fn toggle_contract_white_list() -> Weight;93 fn add_to_contract_white_list() -> Weight;94 fn remove_from_contract_white_list() -> Weight;95 fn set_collection_limits() -> Weight;96}9798decl_error! {99 /// Error for non-fungible-token module.100 pub enum Error for Module<T: Config> {101 /// Total collections bound exceeded.102 TotalCollectionsLimitExceeded,103 /// Decimal_points parameter must be lower than MAX_DECIMAL_POINTS constant, currently it is 30.104 CollectionDecimalPointLimitExceeded,105 /// Collection name can not be longer than 63 char.106 CollectionNameLimitExceeded,107 /// Collection description can not be longer than 255 char.108 CollectionDescriptionLimitExceeded,109 /// Token prefix can not be longer than 15 char.110 CollectionTokenPrefixLimitExceeded,111 /// This collection does not exist.112 CollectionNotFound,113 /// Item not exists.114 TokenNotFound,115 /// Admin not found116 AdminNotFound,117 /// Arithmetic calculation overflow.118 NumOverflow,119 /// Account already has admin role.120 AlreadyAdmin,121 /// You do not own this collection.122 NoPermission,123 /// This address is not set as sponsor, use setCollectionSponsor first.124 ConfirmUnsetSponsorFail,125 /// Collection is not in mint mode.126 PublicMintingNotAllowed,127 /// Sender parameter and item owner must be equal.128 MustBeTokenOwner,129 /// Item balance not enough.130 TokenValueTooLow,131 /// Size of item is too large.132 NftSizeLimitExceeded,133 /// No approve found134 ApproveNotFound,135 /// Requested value more than approved.136 TokenValueNotEnough,137 /// Only approved addresses can call this method.138 ApproveRequired,139 /// Address is not in white list.140 AddresNotInWhiteList,141 /// Number of collection admins bound exceeded.142 CollectionAdminsLimitExceeded,143 /// Owned tokens by a single address bound exceeded.144 AddressOwnershipLimitExceeded,145 /// Length of items properties must be greater than 0.146 EmptyArgument,147 /// const_data exceeded data limit.148 TokenConstDataLimitExceeded,149 /// variable_data exceeded data limit.150 TokenVariableDataLimitExceeded,151 /// Not NFT item data used to mint in NFT collection.152 NotNftDataUsedToMintNftCollectionToken,153 /// Not Fungible item data used to mint in Fungible collection.154 NotFungibleDataUsedToMintFungibleCollectionToken,155 /// Not Re Fungible item data used to mint in Re Fungible collection.156 NotReFungibleDataUsedToMintReFungibleCollectionToken,157 /// Unexpected collection type.158 UnexpectedCollectionType,159 /// Can't store metadata in fungible tokens.160 CantStoreMetadataInFungibleTokens,161 /// Collection token limit exceeded162 CollectionTokenLimitExceeded,163 /// Account token limit exceeded per collection164 AccountTokenLimitExceeded,165 /// Collection limit bounds per collection exceeded166 CollectionLimitBoundsExceeded,167 /// Tried to enable permissions which are only permitted to be disabled168 OwnerPermissionsCantBeReverted,169 /// Schema data size limit bound exceeded170 SchemaDataLimitExceeded,171 /// Maximum refungibility exceeded172 WrongRefungiblePieces,173 /// createRefungible should be called with one owner174 BadCreateRefungibleCall,175 /// Gas limit exceeded176 OutOfGas,177 }178}179180#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]181pub struct CollectionHandle<T: Config> {182 pub id: CollectionId,183 collection: Collection<T>,184 recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,185}186impl<T: Config> CollectionHandle<T> {187 pub fn get_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {188 <CollectionById<T>>::get(id).map(|collection| Self {189 id,190 collection,191 recorder: pallet_evm_coder_substrate::SubstrateRecorder::new(192 eth::collection_id_to_address(id),193 gas_limit,194 ),195 })196 }197 pub fn get(id: CollectionId) -> Option<Self> {198 Self::get_with_gas_limit(id, u64::MAX)199 }200 pub fn log(&self, log: impl evm_coder::ToLog) -> DispatchResult {201 self.recorder.log_sub(log)202 }203 fn consume_gas(&self, gas: u64) -> DispatchResult {204 self.recorder.consume_gas_sub(gas)205 }206 pub fn submit_logs(self) -> DispatchResult {207 self.recorder.submit_logs()208 }209 pub fn save(self) -> DispatchResult {210 self.recorder.submit_logs()?;211 <CollectionById<T>>::insert(self.id, self.collection);212 Ok(())213 }214}215impl<T: Config> Deref for CollectionHandle<T> {216 type Target = Collection<T>;217218 fn deref(&self) -> &Self::Target {219 &self.collection220 }221}222223impl<T: Config> DerefMut for CollectionHandle<T> {224 fn deref_mut(&mut self) -> &mut Self::Target {225 &mut self.collection226 }227}228229pub trait Config: system::Config + pallet_evm_coder_substrate::Config + Sized {230 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;231232 /// Weight information for extrinsics in this pallet.233 type WeightInfo: WeightInfo;234235 type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;236 type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;237238 type CrossAccountId: CrossAccountId<Self::AccountId>;239 type Currency: Currency<Self::AccountId>;240 type CollectionCreationPrice: Get<241 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,242 >;243 type TreasuryAccountId: Get<Self::AccountId>;244}245246// # Used definitions247//248// ## User control levels249//250// chain-controlled - key is uncontrolled by user251// i.e autoincrementing index252// can use non-cryptographic hash253// real - key is controlled by user254// but it is hard to generate enough colliding values, i.e owner of signed txs255// can use non-cryptographic hash256// controlled - key is completly controlled by users257// i.e maps with mutable keys258// should use cryptographic hash259//260// ## User control level downgrade reasons261//262// ?1 - chain-controlled -> controlled263// collections/tokens can be destroyed, resulting in massive holes264// ?2 - chain-controlled -> controlled265// same as ?1, but can be only added, resulting in easier exploitation266// ?3 - real -> controlled267// no confirmation required, so addresses can be easily generated268decl_storage! {269 trait Store for Module<T: Config> as Nft {270271 //#region Private members272 /// Id of next collection273 CreatedCollectionCount: u32;274 /// Used for migrations275 ChainVersion: u64;276 /// Id of last collection token277 /// Collection id (controlled?1)278 ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;279 //#endregion280281 //#region Chain limits struct282 pub ChainLimit get(fn chain_limit) config(): ChainLimits;283 //#endregion284285 //#region Bound counters286 /// Amount of collections destroyed, used for total amount tracking with287 /// CreatedCollectionCount288 DestroyedCollectionCount: u32;289 /// Total amount of account owned tokens (NFTs + RFTs + unique fungibles)290 /// Account id (real)291 pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;292 //#endregion293294 //#region Basic collections295 /// Collection info296 /// Collection id (controlled?1)297 pub CollectionById get(fn collection_id) config(): map hasher(blake2_128_concat) CollectionId => Option<Collection<T>> = None;298 /// List of collection admins299 /// Collection id (controlled?2)300 pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::CrossAccountId>;301 /// Whitelisted collection users302 /// Collection id (controlled?2), user id (controlled?3)303 pub WhiteList get(fn white_list): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => bool;304 //#endregion305306 /// How many of collection items user have307 /// Collection id (controlled?2), account id (real)308 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => u128;309310 /// Amount of items which spender can transfer out of owners account (via transferFrom)311 /// Collection id (controlled?2), (token id (controlled ?2) + owner account id (real) + spender account id (controlled?3))312 /// TODO: Off chain worker should remove from this map when token gets removed313 pub Allowances get(fn approved): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) (TokenId, T::AccountId, T::AccountId) => u128;314315 //#region Item collections316 /// Collection id (controlled?2), token id (controlled?1)317 pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<NftItemType<T::CrossAccountId>>;318 /// Collection id (controlled?2), owner (controlled?2)319 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;320 /// Collection id (controlled?2), token id (controlled?1)321 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<ReFungibleItemType<T::CrossAccountId>>;322 //#endregion323324 //#region Index list325 /// Collection id (controlled?2), tokens owner (controlled?2)326 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => Vec<TokenId>;327 //#endregion328329 //#region Tokens transfer rate limit baskets330 /// (Collection id (controlled?2), who created (real))331 /// TODO: Off chain worker should remove from this map when collection gets removed332 pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => T::BlockNumber;333 /// Collection id (controlled?2), token id (controlled?2)334 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;335 /// Collection id (controlled?2), owning user (real)336 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;337 /// Collection id (controlled?2), token id (controlled?2)338 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;339 //#endregion340341 /// Variable metadata sponsoring342 /// Collection id (controlled?2), token id (controlled?2)343 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;344 }345 add_extra_genesis {346 build(|config: &GenesisConfig<T>| {347 // Modification of storage348 for (_num, _c) in &config.collection_id {349 <Module<T>>::init_collection(_c);350 }351352 for (_num, _c, _i) in &config.nft_item_id {353 <Module<T>>::init_nft_token(*_c, _i);354 }355356 for (collection_id, account_id, fungible_item) in &config.fungible_item_id {357 <Module<T>>::init_fungible_token(*collection_id, &T::CrossAccountId::from_sub(account_id.clone()), fungible_item);358 }359360 for (_num, _c, _i) in &config.refungible_item_id {361 <Module<T>>::init_refungible_token(*_c, _i);362 }363 })364 }365}366367decl_event!(368 pub enum Event<T>369 where370 AccountId = <T as frame_system::Config>::AccountId,371 CrossAccountId = <T as Config>::CrossAccountId,372 {373 /// New collection was created374 ///375 /// # Arguments376 ///377 /// * collection_id: Globally unique identifier of newly created collection.378 ///379 /// * mode: [CollectionMode] converted into u8.380 ///381 /// * account_id: Collection owner.382 CollectionCreated(CollectionId, u8, AccountId),383384 /// New item was created.385 ///386 /// # Arguments387 ///388 /// * collection_id: Id of the collection where item was created.389 ///390 /// * item_id: Id of an item. Unique within the collection.391 ///392 /// * recipient: Owner of newly created item393 ItemCreated(CollectionId, TokenId, CrossAccountId),394395 /// Collection item was burned.396 ///397 /// # Arguments398 ///399 /// collection_id.400 ///401 /// item_id: Identifier of burned NFT.402 ItemDestroyed(CollectionId, TokenId),403404 /// Item was transferred405 ///406 /// * collection_id: Id of collection to which item is belong407 ///408 /// * item_id: Id of an item409 ///410 /// * sender: Original owner of item411 ///412 /// * recipient: New owner of item413 ///414 /// * amount: Always 1 for NFT415 Transfer(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),416417 /// * collection_id418 ///419 /// * item_id420 ///421 /// * sender422 ///423 /// * spender424 ///425 /// * amount426 Approved(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),427 }428);429430decl_module! {431 pub struct Module<T: Config> for enum Call432 where433 origin: T::Origin434 {435 fn deposit_event() = default;436 type Error = Error<T>;437438 fn on_initialize(_now: T::BlockNumber) -> Weight {439 0440 }441442 /// This method creates a Collection of NFTs. Each Token may have multiple properties encoded as an array of bytes of certain length. The initial owner and admin of the collection are set to the address that signed the transaction. Both addresses can be changed later.443 ///444 /// # Permissions445 ///446 /// * Anyone.447 ///448 /// # Arguments449 ///450 /// * collection_name: UTF-16 string with collection name (limit 64 characters), will be stored as zero-terminated.451 ///452 /// * collection_description: UTF-16 string with collection description (limit 256 characters), will be stored as zero-terminated.453 ///454 /// * token_prefix: UTF-8 string with token prefix.455 ///456 /// * mode: [CollectionMode] collection type and type dependent data.457 // returns collection ID458 #[weight = <T as Config>::WeightInfo::create_collection()]459 #[transactional]460 pub fn create_collection(origin,461 collection_name: Vec<u16>,462 collection_description: Vec<u16>,463 token_prefix: Vec<u8>,464 mode: CollectionMode) -> DispatchResult {465466 // Anyone can create a collection467 let who = ensure_signed(origin)?;468469 // Take a (non-refundable) deposit of collection creation470 let mut imbalance = <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();471 imbalance.subsume(<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(472 &T::TreasuryAccountId::get(),473 T::CollectionCreationPrice::get(),474 ));475 <T as Config>::Currency::settle(476 &who,477 imbalance,478 WithdrawReasons::TRANSFER,479 ExistenceRequirement::KeepAlive,480 ).map_err(|_| Error::<T>::NoPermission)?;481482 let decimal_points = match mode {483 CollectionMode::Fungible(points) => points,484 _ => 0485 };486487 let chain_limit = ChainLimit::get();488489 let created_count = CreatedCollectionCount::get();490 let destroyed_count = DestroyedCollectionCount::get();491492 // bound Total number of collections493 ensure!(created_count - destroyed_count < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);494495 // check params496 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);497 ensure!(collection_name.len() <= 64, Error::<T>::CollectionNameLimitExceeded);498 ensure!(collection_description.len() <= 256, Error::<T>::CollectionDescriptionLimitExceeded);499 ensure!(token_prefix.len() <= 16, Error::<T>::CollectionTokenPrefixLimitExceeded);500501 // Generate next collection ID502 let next_id = created_count503 .checked_add(1)504 .ok_or(Error::<T>::NumOverflow)?;505506 CreatedCollectionCount::put(next_id);507508 let limits = CollectionLimits {509 sponsored_data_size: chain_limit.custom_data_limit,510 ..Default::default()511 };512513 // Create new collection514 let new_collection = Collection {515 owner: who.clone(),516 name: collection_name,517 mode: mode.clone(),518 mint_mode: false,519 access: AccessMode::Normal,520 description: collection_description,521 decimal_points,522 token_prefix,523 offchain_schema: Vec::new(),524 schema_version: SchemaVersion::ImageURL,525 sponsorship: SponsorshipState::Disabled,526 variable_on_chain_schema: Vec::new(),527 const_on_chain_schema: Vec::new(),528 limits,529 };530531 // Add new collection to map532 <CollectionById<T>>::insert(next_id, new_collection);533534 // call event535 Self::deposit_event(RawEvent::CollectionCreated(next_id, mode.id(), who));536537 Ok(())538 }539540 /// **DANGEROUS**: Destroys collection and all NFTs within this collection. Users irrecoverably lose their assets and may lose real money.541 ///542 /// # Permissions543 ///544 /// * Collection Owner.545 ///546 /// # Arguments547 ///548 /// * collection_id: collection to destroy.549 #[weight = <T as Config>::WeightInfo::destroy_collection()]550 #[transactional]551 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {552553 let sender = ensure_signed(origin)?;554 let collection = Self::get_collection(collection_id)?;555 Self::check_owner_permissions(&collection, &sender)?;556 if !collection.limits.owner_can_destroy {557 fail!(Error::<T>::NoPermission);558 }559560 <AddressTokens<T>>::remove_prefix(collection_id, None);561 <Allowances<T>>::remove_prefix(collection_id, None);562 <Balance<T>>::remove_prefix(collection_id, None);563 <ItemListIndex>::remove(collection_id);564 <AdminList<T>>::remove(collection_id);565 <CollectionById<T>>::remove(collection_id);566 <WhiteList<T>>::remove_prefix(collection_id, None);567568 <NftItemList<T>>::remove_prefix(collection_id, None);569 <FungibleItemList<T>>::remove_prefix(collection_id, None);570 <ReFungibleItemList<T>>::remove_prefix(collection_id, None);571572 <NftTransferBasket<T>>::remove_prefix(collection_id, None);573 <FungibleTransferBasket<T>>::remove_prefix(collection_id, None);574 <ReFungibleTransferBasket<T>>::remove_prefix(collection_id, None);575576 <VariableMetaDataBasket<T>>::remove_prefix(collection_id, None);577578 DestroyedCollectionCount::put(DestroyedCollectionCount::get()579 .checked_add(1)580 .ok_or(Error::<T>::NumOverflow)?);581582 Ok(())583 }584585 /// Add an address to white list.586 ///587 /// # Permissions588 ///589 /// * Collection Owner590 /// * Collection Admin591 ///592 /// # Arguments593 ///594 /// * collection_id.595 ///596 /// * address.597 #[weight = <T as Config>::WeightInfo::add_to_white_list()]598 #[transactional]599 pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{600601 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);602 let collection = Self::get_collection(collection_id)?;603604 Self::toggle_white_list_internal(605 &sender,606 &collection,607 &address,608 true,609 )?;610611 Ok(())612 }613614 /// Remove an address from white list.615 ///616 /// # Permissions617 ///618 /// * Collection Owner619 /// * Collection Admin620 ///621 /// # Arguments622 ///623 /// * collection_id.624 ///625 /// * address.626 #[weight = <T as Config>::WeightInfo::remove_from_white_list()]627 #[transactional]628 pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{629630 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);631 let collection = Self::get_collection(collection_id)?;632633 Self::toggle_white_list_internal(634 &sender,635 &collection,636 &address,637 false,638 )?;639640 Ok(())641 }642643 /// Toggle between normal and white list access for the methods with access for `Anyone`.644 ///645 /// # Permissions646 ///647 /// * Collection Owner.648 ///649 /// # Arguments650 ///651 /// * collection_id.652 ///653 /// * mode: [AccessMode]654 #[weight = <T as Config>::WeightInfo::set_public_access_mode()]655 #[transactional]656 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult657 {658 let sender = ensure_signed(origin)?;659660 let mut target_collection = Self::get_collection(collection_id)?;661 Self::check_owner_permissions(&target_collection, &sender)?;662 target_collection.access = mode;663 target_collection.save()664 }665666 /// Allows Anyone to create tokens if:667 /// * White List is enabled, and668 /// * Address is added to white list, and669 /// * This method was called with True parameter670 ///671 /// # Permissions672 /// * Collection Owner673 ///674 /// # Arguments675 ///676 /// * collection_id.677 ///678 /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.679 #[weight = <T as Config>::WeightInfo::set_mint_permission()]680 #[transactional]681 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult682 {683 let sender = ensure_signed(origin)?;684685 let mut target_collection = Self::get_collection(collection_id)?;686 Self::check_owner_permissions(&target_collection, &sender)?;687 target_collection.mint_mode = mint_permission;688 target_collection.save()689 }690691 /// Change the owner of the collection.692 ///693 /// # Permissions694 ///695 /// * Collection Owner.696 ///697 /// # Arguments698 ///699 /// * collection_id.700 ///701 /// * new_owner.702 #[weight = <T as Config>::WeightInfo::change_collection_owner()]703 #[transactional]704 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {705706 let sender = ensure_signed(origin)?;707 let mut target_collection = Self::get_collection(collection_id)?;708 Self::check_owner_permissions(&target_collection, &sender)?;709 target_collection.owner = new_owner;710 target_collection.save()711 }712713 /// Adds an admin of the Collection.714 /// NFT Collection can be controlled by multiple admin addresses (some which can also be servers, for example). Admins can issue and burn NFTs, as well as add and remove other admins, but cannot change NFT or Collection ownership.715 ///716 /// # Permissions717 ///718 /// * Collection Owner.719 /// * Collection Admin.720 ///721 /// # Arguments722 ///723 /// * collection_id: ID of the Collection to add admin for.724 ///725 /// * new_admin_id: Address of new admin to add.726 #[weight = <T as Config>::WeightInfo::add_collection_admin()]727 #[transactional]728 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {729 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);730 let collection = Self::get_collection(collection_id)?;731 Self::check_owner_or_admin_permissions(&collection, &sender)?;732 let mut admin_arr = <AdminList<T>>::get(collection_id);733734 match admin_arr.binary_search(&new_admin_id) {735 Ok(_) => {},736 Err(idx) => {737 let limits = ChainLimit::get();738 ensure!(admin_arr.len() < limits.collections_admins_limit as usize, Error::<T>::CollectionAdminsLimitExceeded);739 admin_arr.insert(idx, new_admin_id);740 <AdminList<T>>::insert(collection_id, admin_arr);741 }742 }743 Ok(())744 }745746 /// Remove admin address of the Collection. An admin address can remove itself. List of admins may become empty, in which case only Collection Owner will be able to add an Admin.747 ///748 /// # Permissions749 ///750 /// * Collection Owner.751 /// * Collection Admin.752 ///753 /// # Arguments754 ///755 /// * collection_id: ID of the Collection to remove admin for.756 ///757 /// * account_id: Address of admin to remove.758 #[weight = <T as Config>::WeightInfo::remove_collection_admin()]759 #[transactional]760 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {761 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);762 let collection = Self::get_collection(collection_id)?;763 Self::check_owner_or_admin_permissions(&collection, &sender)?;764 let mut admin_arr = <AdminList<T>>::get(collection_id);765766 if let Ok(idx) = admin_arr.binary_search(&account_id) {767 admin_arr.remove(idx);768 <AdminList<T>>::insert(collection_id, admin_arr);769 }770 Ok(())771 }772773 /// # Permissions774 ///775 /// * Collection Owner776 ///777 /// # Arguments778 ///779 /// * collection_id.780 ///781 /// * new_sponsor.782 #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]783 #[transactional]784 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {785 let sender = ensure_signed(origin)?;786 let mut target_collection = Self::get_collection(collection_id)?;787 Self::check_owner_permissions(&target_collection, &sender)?;788789 target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);790 target_collection.save()791 }792793 /// # Permissions794 ///795 /// * Sponsor.796 ///797 /// # Arguments798 ///799 /// * collection_id.800 #[weight = <T as Config>::WeightInfo::confirm_sponsorship()]801 #[transactional]802 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {803 let sender = ensure_signed(origin)?;804805 let mut target_collection = Self::get_collection(collection_id)?;806 ensure!(807 target_collection.sponsorship.pending_sponsor() == Some(&sender),808 Error::<T>::ConfirmUnsetSponsorFail809 );810811 target_collection.sponsorship = SponsorshipState::Confirmed(sender);812 target_collection.save()813 }814815 /// Switch back to pay-per-own-transaction model.816 ///817 /// # Permissions818 ///819 /// * Collection owner.820 ///821 /// # Arguments822 ///823 /// * collection_id.824 #[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]825 #[transactional]826 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {827 let sender = ensure_signed(origin)?;828829 let mut target_collection = Self::get_collection(collection_id)?;830 Self::check_owner_permissions(&target_collection, &sender)?;831832 target_collection.sponsorship = SponsorshipState::Disabled;833 target_collection.save()834 }835836 /// This method creates a concrete instance of NFT Collection created with CreateCollection method.837 ///838 /// # Permissions839 ///840 /// * Collection Owner.841 /// * Collection Admin.842 /// * Anyone if843 /// * White List is enabled, and844 /// * Address is added to white list, and845 /// * MintPermission is enabled (see SetMintPermission method)846 ///847 /// # Arguments848 ///849 /// * collection_id: ID of the collection.850 ///851 /// * owner: Address, initial owner of the NFT.852 ///853 /// * data: Token data to store on chain.854 // #[weight =855 // (130_000_000 as Weight)856 // .saturating_add((2135 as Weight).saturating_mul((properties.len() as u64) as Weight))857 // .saturating_add(RocksDbWeight::get().reads(10 as Weight))858 // .saturating_add(RocksDbWeight::get().writes(8 as Weight))]859860 #[weight = <T as Config>::WeightInfo::create_item(data.data_size())]861 #[transactional]862 pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResult {863 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);864 let collection = Self::get_collection(collection_id)?;865866 Self::create_item_internal(&sender, &collection, &owner, data)?;867868 collection.submit_logs()869 }870871 /// This method creates multiple items in a collection created with CreateCollection method.872 ///873 /// # Permissions874 ///875 /// * Collection Owner.876 /// * Collection Admin.877 /// * Anyone if878 /// * White List is enabled, and879 /// * Address is added to white list, and880 /// * MintPermission is enabled (see SetMintPermission method)881 ///882 /// # Arguments883 ///884 /// * collection_id: ID of the collection.885 ///886 /// * itemsData: Array items properties. Each property is an array of bytes itself, see [create_item].887 ///888 /// * owner: Address, initial owner of the NFT.889 #[weight = <T as Config>::WeightInfo::create_item(items_data.iter()890 .map(|data| { data.data_size() })891 .sum())]892 #[transactional]893 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResult {894895 ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);896 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);897 let collection = Self::get_collection(collection_id)?;898899 Self::create_multiple_items_internal(&sender, &collection, &owner, items_data)?;900901 collection.submit_logs()902 }903904 /// Destroys a concrete instance of NFT.905 ///906 /// # Permissions907 ///908 /// * Collection Owner.909 /// * Collection Admin.910 /// * Current NFT Owner.911 ///912 /// # Arguments913 ///914 /// * collection_id: ID of the collection.915 ///916 /// * item_id: ID of NFT to burn.917 #[weight = <T as Config>::WeightInfo::burn_item()]918 #[transactional]919 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {920921 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);922 let target_collection = Self::get_collection(collection_id)?;923924 Self::burn_item_internal(&sender, &target_collection, item_id, value)?;925926 target_collection.submit_logs()927 }928929 /// Change ownership of the token.930 ///931 /// # Permissions932 ///933 /// * Collection Owner934 /// * Collection Admin935 /// * Current NFT owner936 ///937 /// # Arguments938 ///939 /// * recipient: Address of token recipient.940 ///941 /// * collection_id.942 ///943 /// * item_id: ID of the item944 /// * Non-Fungible Mode: Required.945 /// * Fungible Mode: Ignored.946 /// * Re-Fungible Mode: Required.947 ///948 /// * value: Amount to transfer.949 /// * Non-Fungible Mode: Ignored950 /// * Fungible Mode: Must specify transferred amount951 /// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)952 #[weight = <T as Config>::WeightInfo::transfer()]953 #[transactional]954 pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {955 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);956 let collection = Self::get_collection(collection_id)?;957958 Self::transfer_internal(&sender, &recipient, &collection, item_id, value)?;959960 collection.submit_logs()961 }962963 /// Set, change, or remove approved address to transfer the ownership of the NFT.964 ///965 /// # Permissions966 ///967 /// * Collection Owner968 /// * Collection Admin969 /// * Current NFT owner970 ///971 /// # Arguments972 ///973 /// * approved: Address that is approved to transfer this NFT or zero (if needed to remove approval).974 ///975 /// * collection_id.976 ///977 /// * item_id: ID of the item.978 #[weight = <T as Config>::WeightInfo::approve()]979 #[transactional]980 pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {981 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);982 let collection = Self::get_collection(collection_id)?;983984 Self::approve_internal(&sender, &spender, &collection, item_id, amount)?;985986 collection.submit_logs()987 }988989 /// Change ownership of a NFT on behalf of the owner. See Approve method for additional information. After this method executes, the approval is removed so that the approved address will not be able to transfer this NFT again from this owner.990 ///991 /// # Permissions992 /// * Collection Owner993 /// * Collection Admin994 /// * Current NFT owner995 /// * Address approved by current NFT owner996 ///997 /// # Arguments998 ///999 /// * from: Address that owns token.1000 ///1001 /// * recipient: Address of token recipient.1002 ///1003 /// * collection_id.1004 ///1005 /// * item_id: ID of the item.1006 ///1007 /// * value: Amount to transfer.1008 #[weight = <T as Config>::WeightInfo::transfer_from()]1009 #[transactional]1010 pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {1011 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1012 let collection = Self::get_collection(collection_id)?;10131014 Self::transfer_from_internal(&sender, &from, &recipient, &collection, item_id, value)?;10151016 collection.submit_logs()1017 }1018 // #[weight = 0]1019 // // let no_perm_mes = "You do not have permissions to modify this collection";1020 // // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);1021 // // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));1022 // // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);10231024 // // // on_nft_received call10251026 // // Self::transfer(origin, collection_id, item_id, new_owner)?;10271028 // Ok(())1029 // }10301031 /// Set off-chain data schema.1032 ///1033 /// # Permissions1034 ///1035 /// * Collection Owner1036 /// * Collection Admin1037 ///1038 /// # Arguments1039 ///1040 /// * collection_id.1041 ///1042 /// * schema: String representing the offchain data schema.1043 #[weight = <T as Config>::WeightInfo::set_variable_meta_data()]1044 #[transactional]1045 pub fn set_variable_meta_data (1046 origin,1047 collection_id: CollectionId,1048 item_id: TokenId,1049 data: Vec<u8>1050 ) -> DispatchResult {1051 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);10521053 let collection = Self::get_collection(collection_id)?;10541055 Self::set_variable_meta_data_internal(&sender, &collection, item_id, data)?;10561057 Ok(())1058 }10591060 /// Set schema standard1061 /// ImageURL1062 /// Unique1063 ///1064 /// # Permissions1065 ///1066 /// * Collection Owner1067 /// * Collection Admin1068 ///1069 /// # Arguments1070 ///1071 /// * collection_id.1072 ///1073 /// * schema: SchemaVersion: enum1074 #[weight = <T as Config>::WeightInfo::set_schema_version()]1075 #[transactional]1076 pub fn set_schema_version(1077 origin,1078 collection_id: CollectionId,1079 version: SchemaVersion1080 ) -> DispatchResult {1081 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1082 let mut target_collection = Self::get_collection(collection_id)?;1083 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;1084 target_collection.schema_version = version;1085 target_collection.save()1086 }10871088 /// Set off-chain data schema.1089 ///1090 /// # Permissions1091 ///1092 /// * Collection Owner1093 /// * Collection Admin1094 ///1095 /// # Arguments1096 ///1097 /// * collection_id.1098 ///1099 /// * schema: String representing the offchain data schema.1100 #[weight = <T as Config>::WeightInfo::set_offchain_schema()]1101 #[transactional]1102 pub fn set_offchain_schema(1103 origin,1104 collection_id: CollectionId,1105 schema: Vec<u8>1106 ) -> DispatchResult {1107 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1108 let mut target_collection = Self::get_collection(collection_id)?;1109 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;11101111 // check schema limit1112 ensure!(schema.len() as u32 <= ChainLimit::get().offchain_schema_limit, "");11131114 target_collection.offchain_schema = schema;1115 target_collection.save()1116 }11171118 /// Set const on-chain data schema.1119 ///1120 /// # Permissions1121 ///1122 /// * Collection Owner1123 /// * Collection Admin1124 ///1125 /// # Arguments1126 ///1127 /// * collection_id.1128 ///1129 /// * schema: String representing the const on-chain data schema.1130 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1131 #[transactional]1132 pub fn set_const_on_chain_schema (1133 origin,1134 collection_id: CollectionId,1135 schema: Vec<u8>1136 ) -> DispatchResult {1137 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1138 let mut target_collection = Self::get_collection(collection_id)?;1139 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;11401141 // check schema limit1142 ensure!(schema.len() as u32 <= ChainLimit::get().const_on_chain_schema_limit, "");11431144 target_collection.const_on_chain_schema = schema;1145 target_collection.save()1146 }11471148 /// Set variable on-chain data schema.1149 ///1150 /// # Permissions1151 ///1152 /// * Collection Owner1153 /// * Collection Admin1154 ///1155 /// # Arguments1156 ///1157 /// * collection_id.1158 ///1159 /// * schema: String representing the variable on-chain data schema.1160 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1161 #[transactional]1162 pub fn set_variable_on_chain_schema (1163 origin,1164 collection_id: CollectionId,1165 schema: Vec<u8>1166 ) -> DispatchResult {1167 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1168 let mut target_collection = Self::get_collection(collection_id)?;1169 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;11701171 // check schema limit1172 ensure!(schema.len() as u32 <= ChainLimit::get().variable_on_chain_schema_limit, "");11731174 target_collection.variable_on_chain_schema = schema;1175 target_collection.save()1176 }11771178 // Sudo permissions function1179 #[weight = <T as Config>::WeightInfo::set_chain_limits()]1180 #[transactional]1181 pub fn set_chain_limits(1182 origin,1183 limits: ChainLimits1184 ) -> DispatchResult {11851186 #[cfg(not(feature = "runtime-benchmarks"))]1187 ensure_root(origin)?;11881189 <ChainLimit>::put(limits);1190 Ok(())1191 }11921193 #[weight = <T as Config>::WeightInfo::set_collection_limits()]1194 #[transactional]1195 pub fn set_collection_limits(1196 origin,1197 collection_id: u32,1198 new_limits: CollectionLimits<T::BlockNumber>,1199 ) -> DispatchResult {1200 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1201 let mut target_collection = Self::get_collection(collection_id)?;1202 Self::check_owner_permissions(&target_collection, sender.as_sub())?;1203 let old_limits = &target_collection.limits;1204 let chain_limits = ChainLimit::get();12051206 // collection bounds1207 ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&1208 new_limits.account_token_ownership_limit <= MAX_TOKEN_OWNERSHIP &&1209 new_limits.sponsored_data_size <= chain_limits.custom_data_limit,1210 Error::<T>::CollectionLimitBoundsExceeded);12111212 // token_limit check prev1213 ensure!(old_limits.token_limit >= new_limits.token_limit, Error::<T>::CollectionTokenLimitExceeded);1214 ensure!(new_limits.token_limit > 0, Error::<T>::CollectionTokenLimitExceeded);12151216 ensure!(1217 (old_limits.owner_can_transfer || !new_limits.owner_can_transfer) &&1218 (old_limits.owner_can_destroy || !new_limits.owner_can_destroy),1219 Error::<T>::OwnerPermissionsCantBeReverted,1220 );12211222 target_collection.limits = new_limits;12231224 target_collection.save()1225 }1226 }1227}12281229impl<T: Config> Module<T> {1230 pub fn create_item_internal(1231 sender: &T::CrossAccountId,1232 collection: &CollectionHandle<T>,1233 owner: &T::CrossAccountId,1234 data: CreateItemData,1235 ) -> DispatchResult {1236 Self::can_create_items_in_collection(collection, sender, owner, 1)?;1237 Self::validate_create_item_args(collection, &data)?;1238 Self::create_item_no_validation(collection, owner, data)?;12391240 Ok(())1241 }12421243 pub fn transfer_internal(1244 sender: &T::CrossAccountId,1245 recipient: &T::CrossAccountId,1246 target_collection: &CollectionHandle<T>,1247 item_id: TokenId,1248 value: u128,1249 ) -> DispatchResult {1250 target_collection.consume_gas(2000000)?;1251 // Limits check1252 Self::is_correct_transfer(target_collection, recipient)?;12531254 // Transfer permissions check1255 ensure!(1256 Self::is_item_owner(sender, target_collection, item_id)1257 || Self::is_owner_or_admin_permissions(target_collection, sender),1258 Error::<T>::NoPermission1259 );12601261 if target_collection.access == AccessMode::WhiteList {1262 Self::check_white_list(target_collection, sender)?;1263 Self::check_white_list(target_collection, recipient)?;1264 }12651266 match target_collection.mode {1267 CollectionMode::NFT => Self::transfer_nft(1268 target_collection,1269 item_id,1270 sender.clone(),1271 recipient.clone(),1272 )?,1273 CollectionMode::Fungible(_) => {1274 Self::transfer_fungible(target_collection, value, sender, recipient)?1275 }1276 CollectionMode::ReFungible => Self::transfer_refungible(1277 target_collection,1278 item_id,1279 value,1280 sender.clone(),1281 recipient.clone(),1282 )?,1283 _ => (),1284 };12851286 Self::deposit_event(RawEvent::Transfer(1287 target_collection.id,1288 item_id,1289 sender.clone(),1290 recipient.clone(),1291 value,1292 ));12931294 Ok(())1295 }12961297 pub fn approve_internal(1298 sender: &T::CrossAccountId,1299 spender: &T::CrossAccountId,1300 collection: &CollectionHandle<T>,1301 item_id: TokenId,1302 amount: u128,1303 ) -> DispatchResult {1304 collection.consume_gas(2000000)?;1305 Self::token_exists(collection, item_id)?;13061307 // Transfer permissions check1308 let bypasses_limits = collection.limits.owner_can_transfer1309 && Self::is_owner_or_admin_permissions(collection, sender);13101311 let allowance_limit = if bypasses_limits {1312 None1313 } else if let Some(amount) = Self::owned_amount(sender, collection, item_id) {1314 Some(amount)1315 } else {1316 fail!(Error::<T>::NoPermission);1317 };13181319 if collection.access == AccessMode::WhiteList {1320 Self::check_white_list(collection, sender)?;1321 Self::check_white_list(collection, spender)?;1322 }13231324 let allowance: u128 = amount1325 .checked_add(<Allowances<T>>::get(1326 collection.id,1327 (item_id, sender.as_sub(), spender.as_sub()),1328 ))1329 .ok_or(Error::<T>::NumOverflow)?;1330 if let Some(limit) = allowance_limit {1331 ensure!(limit >= allowance, Error::<T>::TokenValueTooLow);1332 }1333 <Allowances<T>>::insert(1334 collection.id,1335 (item_id, sender.as_sub(), spender.as_sub()),1336 allowance,1337 );13381339 if matches!(collection.mode, CollectionMode::NFT) {1340 // TODO: NFT: only one owner may exist for token in ERC7211341 collection.log(ERC721Events::Approval {1342 owner: *sender.as_eth(),1343 approved: *spender.as_eth(),1344 token_id: item_id.into(),1345 })?;1346 }13471348 if matches!(collection.mode, CollectionMode::Fungible(_)) {1349 // TODO: NFT: only one owner may exist for token in ERC201350 collection.log(ERC20Events::Approval {1351 owner: *sender.as_eth(),1352 spender: *spender.as_eth(),1353 value: allowance.into(),1354 })?;1355 }13561357 Self::deposit_event(RawEvent::Approved(1358 collection.id,1359 item_id,1360 sender.clone(),1361 spender.clone(),1362 allowance,1363 ));1364 Ok(())1365 }13661367 pub fn transfer_from_internal(1368 sender: &T::CrossAccountId,1369 from: &T::CrossAccountId,1370 recipient: &T::CrossAccountId,1371 collection: &CollectionHandle<T>,1372 item_id: TokenId,1373 amount: u128,1374 ) -> DispatchResult {1375 collection.consume_gas(2000000)?;1376 // Check approval1377 let approval: u128 =1378 <Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));13791380 // Limits check1381 Self::is_correct_transfer(collection, recipient)?;13821383 // Transfer permissions check1384 ensure!(1385 approval >= amount1386 || (collection.limits.owner_can_transfer1387 && Self::is_owner_or_admin_permissions(collection, sender)),1388 Error::<T>::NoPermission1389 );13901391 if collection.access == AccessMode::WhiteList {1392 Self::check_white_list(collection, sender)?;1393 Self::check_white_list(collection, recipient)?;1394 }13951396 // Reduce approval by transferred amount or remove if remaining approval drops to 01397 let allowance = approval.saturating_sub(amount);1398 if allowance > 0 {1399 <Allowances<T>>::insert(1400 collection.id,1401 (item_id, from.as_sub(), sender.as_sub()),1402 allowance,1403 );1404 } else {1405 <Allowances<T>>::remove(collection.id, (item_id, from.as_sub(), sender.as_sub()));1406 }14071408 match collection.mode {1409 CollectionMode::NFT => {1410 Self::transfer_nft(collection, item_id, from.clone(), recipient.clone())?1411 }1412 CollectionMode::Fungible(_) => {1413 Self::transfer_fungible(collection, amount, from, recipient)?1414 }1415 CollectionMode::ReFungible => Self::transfer_refungible(1416 collection,1417 item_id,1418 amount,1419 from.clone(),1420 recipient.clone(),1421 )?,1422 _ => (),1423 };14241425 if matches!(collection.mode, CollectionMode::Fungible(_)) {1426 collection.log(ERC20Events::Approval {1427 owner: *from.as_eth(),1428 spender: *sender.as_eth(),1429 value: allowance.into(),1430 })?;1431 }14321433 Ok(())1434 }14351436 pub fn set_variable_meta_data_internal(1437 sender: &T::CrossAccountId,1438 collection: &CollectionHandle<T>,1439 item_id: TokenId,1440 data: Vec<u8>,1441 ) -> DispatchResult {1442 Self::token_exists(collection, item_id)?;14431444 ensure!(1445 ChainLimit::get().custom_data_limit >= data.len() as u32,1446 Error::<T>::TokenVariableDataLimitExceeded1447 );14481449 // Modify permissions check1450 ensure!(1451 Self::is_item_owner(sender, collection, item_id)1452 || Self::is_owner_or_admin_permissions(collection, sender),1453 Error::<T>::NoPermission1454 );14551456 match collection.mode {1457 CollectionMode::NFT => Self::set_nft_variable_data(collection, item_id, data)?,1458 CollectionMode::ReFungible => {1459 Self::set_re_fungible_variable_data(collection, item_id, data)?1460 }1461 CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),1462 _ => fail!(Error::<T>::UnexpectedCollectionType),1463 };14641465 Ok(())1466 }14671468 pub fn create_multiple_items_internal(1469 sender: &T::CrossAccountId,1470 collection: &CollectionHandle<T>,1471 owner: &T::CrossAccountId,1472 items_data: Vec<CreateItemData>,1473 ) -> DispatchResult {1474 Self::can_create_items_in_collection(collection, sender, owner, items_data.len() as u32)?;14751476 for data in &items_data {1477 Self::validate_create_item_args(collection, data)?;1478 }1479 for data in &items_data {1480 Self::create_item_no_validation(collection, owner, data.clone())?;1481 }14821483 Ok(())1484 }14851486 pub fn burn_item_internal(1487 sender: &T::CrossAccountId,1488 collection: &CollectionHandle<T>,1489 item_id: TokenId,1490 value: u128,1491 ) -> DispatchResult {1492 ensure!(1493 Self::is_item_owner(sender, collection, item_id)1494 || (collection.limits.owner_can_transfer1495 && Self::is_owner_or_admin_permissions(collection, sender)),1496 Error::<T>::NoPermission1497 );14981499 if collection.access == AccessMode::WhiteList {1500 Self::check_white_list(collection, sender)?;1501 }15021503 match collection.mode {1504 CollectionMode::NFT => Self::burn_nft_item(collection, item_id)?,1505 CollectionMode::Fungible(_) => Self::burn_fungible_item(sender, collection, value)?,1506 CollectionMode::ReFungible => Self::burn_refungible_item(collection, item_id, sender)?,1507 _ => (),1508 };15091510 Ok(())1511 }15121513 pub fn toggle_white_list_internal(1514 sender: &T::CrossAccountId,1515 collection: &CollectionHandle<T>,1516 address: &T::CrossAccountId,1517 whitelisted: bool,1518 ) -> DispatchResult {1519 Self::check_owner_or_admin_permissions(collection, sender)?;15201521 if whitelisted {1522 <WhiteList<T>>::insert(collection.id, address.as_sub(), true);1523 } else {1524 <WhiteList<T>>::remove(collection.id, address.as_sub());1525 }15261527 Ok(())1528 }15291530 fn is_correct_transfer(1531 collection: &CollectionHandle<T>,1532 recipient: &T::CrossAccountId,1533 ) -> DispatchResult {1534 let collection_id = collection.id;15351536 // check token limit and account token limit1537 let account_items: u32 =1538 <AddressTokens<T>>::get(collection_id, recipient.as_sub()).len() as u32;1539 ensure!(1540 collection.limits.account_token_ownership_limit > account_items,1541 Error::<T>::AccountTokenLimitExceeded1542 );15431544 Ok(())1545 }15461547 fn can_create_items_in_collection(1548 collection: &CollectionHandle<T>,1549 sender: &T::CrossAccountId,1550 owner: &T::CrossAccountId,1551 amount: u32,1552 ) -> DispatchResult {1553 let collection_id = collection.id;15541555 // check token limit and account token limit1556 let total_items: u32 = ItemListIndex::get(collection_id)1557 .checked_add(amount)1558 .ok_or(Error::<T>::CollectionTokenLimitExceeded)?;1559 let account_items: u32 = (<AddressTokens<T>>::get(collection_id, owner.as_sub()).len()1560 as u32)1561 .checked_add(amount)1562 .ok_or(Error::<T>::AccountTokenLimitExceeded)?;1563 ensure!(1564 collection.limits.token_limit >= total_items,1565 Error::<T>::CollectionTokenLimitExceeded1566 );1567 ensure!(1568 collection.limits.account_token_ownership_limit >= account_items,1569 Error::<T>::AccountTokenLimitExceeded1570 );15711572 if !Self::is_owner_or_admin_permissions(collection, sender) {1573 ensure!(collection.mint_mode, Error::<T>::PublicMintingNotAllowed);1574 Self::check_white_list(collection, owner)?;1575 Self::check_white_list(collection, sender)?;1576 }15771578 Ok(())1579 }15801581 fn validate_create_item_args(1582 target_collection: &CollectionHandle<T>,1583 data: &CreateItemData,1584 ) -> DispatchResult {1585 match target_collection.mode {1586 CollectionMode::NFT => {1587 if let CreateItemData::NFT(data) = data {1588 // check sizes1589 ensure!(1590 ChainLimit::get().custom_data_limit >= data.const_data.len() as u32,1591 Error::<T>::TokenConstDataLimitExceeded1592 );1593 ensure!(1594 ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32,1595 Error::<T>::TokenVariableDataLimitExceeded1596 );1597 } else {1598 fail!(Error::<T>::NotNftDataUsedToMintNftCollectionToken);1599 }1600 }1601 CollectionMode::Fungible(_) => {1602 if let CreateItemData::Fungible(_) = data {1603 } else {1604 fail!(Error::<T>::NotFungibleDataUsedToMintFungibleCollectionToken);1605 }1606 }1607 CollectionMode::ReFungible => {1608 if let CreateItemData::ReFungible(data) = data {1609 // check sizes1610 ensure!(1611 ChainLimit::get().custom_data_limit >= data.const_data.len() as u32,1612 Error::<T>::TokenConstDataLimitExceeded1613 );1614 ensure!(1615 ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32,1616 Error::<T>::TokenVariableDataLimitExceeded1617 );16181619 // Check refungibility limits1620 ensure!(1621 data.pieces <= MAX_REFUNGIBLE_PIECES,1622 Error::<T>::WrongRefungiblePieces1623 );1624 ensure!(data.pieces > 0, Error::<T>::WrongRefungiblePieces);1625 } else {1626 fail!(Error::<T>::NotReFungibleDataUsedToMintReFungibleCollectionToken);1627 }1628 }1629 _ => {1630 fail!(Error::<T>::UnexpectedCollectionType);1631 }1632 };16331634 Ok(())1635 }16361637 fn create_item_no_validation(1638 collection: &CollectionHandle<T>,1639 owner: &T::CrossAccountId,1640 data: CreateItemData,1641 ) -> DispatchResult {1642 match data {1643 CreateItemData::NFT(data) => {1644 let item = NftItemType {1645 owner: owner.clone(),1646 const_data: data.const_data,1647 variable_data: data.variable_data,1648 };16491650 Self::add_nft_item(collection, item)?;1651 }1652 CreateItemData::Fungible(data) => {1653 Self::add_fungible_item(collection, owner, data.value)?;1654 }1655 CreateItemData::ReFungible(data) => {1656 let owner_list = vec![Ownership {1657 owner: owner.clone(),1658 fraction: data.pieces,1659 }];16601661 let item = ReFungibleItemType {1662 owner: owner_list,1663 const_data: data.const_data,1664 variable_data: data.variable_data,1665 };16661667 Self::add_refungible_item(collection, item)?;1668 }1669 };16701671 Ok(())1672 }16731674 fn add_fungible_item(1675 collection: &CollectionHandle<T>,1676 owner: &T::CrossAccountId,1677 value: u128,1678 ) -> DispatchResult {1679 let collection_id = collection.id;16801681 // Does new owner already have an account?1682 let balance: u128 = <FungibleItemList<T>>::get(collection_id, owner.as_sub()).value;16831684 // Mint1685 let item = FungibleItemType {1686 value: balance.checked_add(value).ok_or(Error::<T>::NumOverflow)?,1687 };1688 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), item);16891690 // Update balance1691 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1692 .checked_add(value)1693 .ok_or(Error::<T>::NumOverflow)?;1694 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);16951696 Self::deposit_event(RawEvent::ItemCreated(collection_id, 0, owner.clone()));1697 Ok(())1698 }16991700 fn add_refungible_item(1701 collection: &CollectionHandle<T>,1702 item: ReFungibleItemType<T::CrossAccountId>,1703 ) -> DispatchResult {1704 let collection_id = collection.id;17051706 let current_index = <ItemListIndex>::get(collection_id)1707 .checked_add(1)1708 .ok_or(Error::<T>::NumOverflow)?;1709 let itemcopy = item.clone();17101711 ensure!(item.owner.len() == 1, Error::<T>::BadCreateRefungibleCall,);1712 let item_owner = item.owner.first().expect("only one owner is defined");17131714 let value = item_owner.fraction;1715 let owner = item_owner.owner.clone();17161717 Self::add_token_index(collection_id, current_index, &owner)?;17181719 <ItemListIndex>::insert(collection_id, current_index);1720 <ReFungibleItemList<T>>::insert(collection_id, current_index, itemcopy);17211722 // Update balance1723 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1724 .checked_add(value)1725 .ok_or(Error::<T>::NumOverflow)?;1726 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);17271728 Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, owner));1729 Ok(())1730 }17311732 fn add_nft_item(1733 collection: &CollectionHandle<T>,1734 item: NftItemType<T::CrossAccountId>,1735 ) -> DispatchResult {1736 let collection_id = collection.id;17371738 let current_index = <ItemListIndex>::get(collection_id)1739 .checked_add(1)1740 .ok_or(Error::<T>::NumOverflow)?;17411742 let item_owner = item.owner.clone();1743 Self::add_token_index(collection_id, current_index, &item.owner)?;17441745 <ItemListIndex>::insert(collection_id, current_index);1746 <NftItemList<T>>::insert(collection_id, current_index, item);17471748 // Update balance1749 let new_balance = <Balance<T>>::get(collection_id, item_owner.as_sub())1750 .checked_add(1)1751 .ok_or(Error::<T>::NumOverflow)?;1752 <Balance<T>>::insert(collection_id, item_owner.as_sub(), new_balance);17531754 collection.log(ERC721Events::Transfer {1755 from: H160::default(),1756 to: *item_owner.as_eth(),1757 token_id: current_index.into(),1758 })?;1759 Self::deposit_event(RawEvent::ItemCreated(1760 collection_id,1761 current_index,1762 item_owner,1763 ));1764 Ok(())1765 }17661767 fn burn_refungible_item(1768 collection: &CollectionHandle<T>,1769 item_id: TokenId,1770 owner: &T::CrossAccountId,1771 ) -> DispatchResult {1772 let collection_id = collection.id;17731774 let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id)1775 .ok_or(Error::<T>::TokenNotFound)?;1776 let rft_balance = token1777 .owner1778 .iter()1779 .find(|&i| i.owner == *owner)1780 .ok_or(Error::<T>::TokenNotFound)?;1781 Self::remove_token_index(collection_id, item_id, owner)?;17821783 // update balance1784 let new_balance = <Balance<T>>::get(collection_id, rft_balance.owner.as_sub())1785 .checked_sub(rft_balance.fraction)1786 .ok_or(Error::<T>::NumOverflow)?;1787 <Balance<T>>::insert(collection_id, rft_balance.owner.as_sub(), new_balance);17881789 // Re-create owners list with sender removed1790 let index = token1791 .owner1792 .iter()1793 .position(|i| i.owner == *owner)1794 .expect("owned item is exists");1795 token.owner.remove(index);1796 let owner_count = token.owner.len();17971798 // Burn the token completely if this was the last (only) owner1799 if owner_count == 0 {1800 <ReFungibleItemList<T>>::remove(collection_id, item_id);1801 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);1802 } else {1803 <ReFungibleItemList<T>>::insert(collection_id, item_id, token);1804 }18051806 Ok(())1807 }18081809 fn burn_nft_item(collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {1810 let collection_id = collection.id;18111812 let item =1813 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;1814 Self::remove_token_index(collection_id, item_id, &item.owner)?;18151816 // update balance1817 let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())1818 .checked_sub(1)1819 .ok_or(Error::<T>::NumOverflow)?;1820 <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);1821 <NftItemList<T>>::remove(collection_id, item_id);1822 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);18231824 Self::deposit_event(RawEvent::ItemDestroyed(collection.id, item_id));1825 Ok(())1826 }18271828 fn burn_fungible_item(1829 owner: &T::CrossAccountId,1830 collection: &CollectionHandle<T>,1831 value: u128,1832 ) -> DispatchResult {1833 let collection_id = collection.id;18341835 let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());1836 ensure!(balance.value >= value, Error::<T>::TokenValueNotEnough);18371838 // update balance1839 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1840 .checked_sub(value)1841 .ok_or(Error::<T>::NumOverflow)?;1842 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);18431844 if balance.value - value > 0 {1845 balance.value -= value;1846 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);1847 } else {1848 <FungibleItemList<T>>::remove(collection_id, owner.as_sub());1849 }18501851 collection.log(ERC20Events::Transfer {1852 from: *owner.as_eth(),1853 to: H160::default(),1854 value: value.into(),1855 })?;1856 Ok(())1857 }18581859 pub fn get_collection(1860 collection_id: CollectionId,1861 ) -> Result<CollectionHandle<T>, sp_runtime::DispatchError> {1862 Ok(<CollectionHandle<T>>::get(collection_id).ok_or(Error::<T>::CollectionNotFound)?)1863 }18641865 fn check_owner_permissions(1866 target_collection: &CollectionHandle<T>,1867 subject: &T::AccountId,1868 ) -> DispatchResult {1869 ensure!(1870 *subject == target_collection.owner,1871 Error::<T>::NoPermission1872 );18731874 Ok(())1875 }18761877 fn is_owner_or_admin_permissions(1878 collection: &CollectionHandle<T>,1879 subject: &T::CrossAccountId,1880 ) -> bool {1881 *subject.as_sub() == collection.owner1882 || <AdminList<T>>::get(collection.id).contains(subject)1883 }18841885 fn check_owner_or_admin_permissions(1886 collection: &CollectionHandle<T>,1887 subject: &T::CrossAccountId,1888 ) -> DispatchResult {1889 ensure!(1890 Self::is_owner_or_admin_permissions(collection, subject),1891 Error::<T>::NoPermission1892 );18931894 Ok(())1895 }18961897 fn owned_amount(1898 subject: &T::CrossAccountId,1899 target_collection: &CollectionHandle<T>,1900 item_id: TokenId,1901 ) -> Option<u128> {1902 let collection_id = target_collection.id;19031904 match target_collection.mode {1905 CollectionMode::NFT => {1906 (<NftItemList<T>>::get(collection_id, item_id)?.owner == *subject).then(|| 1)1907 }1908 CollectionMode::Fungible(_) => {1909 Some(<FungibleItemList<T>>::get(collection_id, &subject.as_sub()).value)1910 }1911 CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)?1912 .owner1913 .iter()1914 .find(|i| i.owner == *subject)1915 .map(|i| i.fraction),1916 CollectionMode::Invalid => None,1917 }1918 }19191920 fn is_item_owner(1921 subject: &T::CrossAccountId,1922 target_collection: &CollectionHandle<T>,1923 item_id: TokenId,1924 ) -> bool {1925 match target_collection.mode {1926 CollectionMode::Fungible(_) => true,1927 _ => Self::owned_amount(subject, target_collection, item_id).is_some(),1928 }1929 }19301931 fn check_white_list(1932 collection: &CollectionHandle<T>,1933 address: &T::CrossAccountId,1934 ) -> DispatchResult {1935 let collection_id = collection.id;19361937 let mes = Error::<T>::AddresNotInWhiteList;1938 ensure!(1939 <WhiteList<T>>::contains_key(collection_id, address.as_sub()),1940 mes1941 );19421943 Ok(())1944 }19451946 /// Check if token exists. In case of Fungible, check if there is an entry for1947 /// the owner in fungible balances double map1948 fn token_exists(target_collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {1949 let collection_id = target_collection.id;1950 let exists = match target_collection.mode {1951 CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),1952 CollectionMode::Fungible(_) => true,1953 CollectionMode::ReFungible => {1954 <ReFungibleItemList<T>>::contains_key(collection_id, item_id)1955 }1956 _ => false,1957 };19581959 ensure!(exists, Error::<T>::TokenNotFound);1960 Ok(())1961 }19621963 fn transfer_fungible(1964 collection: &CollectionHandle<T>,1965 value: u128,1966 owner: &T::CrossAccountId,1967 recipient: &T::CrossAccountId,1968 ) -> DispatchResult {1969 let collection_id = collection.id;19701971 let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());1972 ensure!(balance.value >= value, Error::<T>::TokenValueTooLow);19731974 // Send balance to recipient (updates balanceOf of recipient)1975 Self::add_fungible_item(collection, recipient, value)?;19761977 // update balanceOf of sender1978 <Balance<T>>::insert(collection_id, owner.as_sub(), balance.value - value);19791980 // Reduce or remove sender1981 if balance.value == value {1982 <FungibleItemList<T>>::remove(collection_id, owner.as_sub());1983 } else {1984 balance.value -= value;1985 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);1986 }19871988 collection.log(ERC20Events::Transfer {1989 from: *owner.as_eth(),1990 to: *recipient.as_eth(),1991 value: value.into(),1992 })?;1993 Self::deposit_event(RawEvent::Transfer(1994 collection.id,1995 1,1996 owner.clone(),1997 recipient.clone(),1998 value,1999 ));20002001 Ok(())2002 }20032004 fn transfer_refungible(2005 collection: &CollectionHandle<T>,2006 item_id: TokenId,2007 value: u128,2008 owner: T::CrossAccountId,2009 new_owner: T::CrossAccountId,2010 ) -> DispatchResult {2011 let collection_id = collection.id;2012 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id)2013 .ok_or(Error::<T>::TokenNotFound)?;20142015 let item = full_item2016 .owner2017 .iter()2018 .find(|i| i.owner == owner)2019 .ok_or(Error::<T>::TokenNotFound)?;2020 let amount = item.fraction;20212022 ensure!(amount >= value, Error::<T>::TokenValueTooLow);20232024 // update balance2025 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())2026 .checked_sub(value)2027 .ok_or(Error::<T>::NumOverflow)?;2028 <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);20292030 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())2031 .checked_add(value)2032 .ok_or(Error::<T>::NumOverflow)?;2033 <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);20342035 let old_owner = item.owner.clone();2036 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);20372038 let mut new_full_item = full_item.clone();2039 // transfer2040 if amount == value && !new_owner_has_account {2041 // change owner2042 // new owner do not have account2043 new_full_item2044 .owner2045 .iter_mut()2046 .find(|i| i.owner == owner)2047 .expect("old owner does present in refungible")2048 .owner = new_owner.clone();2049 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);20502051 // update index collection2052 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;2053 } else {2054 new_full_item2055 .owner2056 .iter_mut()2057 .find(|i| i.owner == owner)2058 .expect("old owner does present in refungible")2059 .fraction -= value;20602061 // separate amount2062 if new_owner_has_account {2063 // new owner has account2064 new_full_item2065 .owner2066 .iter_mut()2067 .find(|i| i.owner == new_owner)2068 .expect("new owner has account")2069 .fraction += value;2070 } else {2071 // new owner do not have account2072 new_full_item.owner.push(Ownership {2073 owner: new_owner.clone(),2074 fraction: value,2075 });2076 Self::add_token_index(collection_id, item_id, &new_owner)?;2077 }20782079 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);2080 }20812082 Self::deposit_event(RawEvent::Transfer(2083 collection.id,2084 item_id,2085 owner,2086 new_owner,2087 amount,2088 ));20892090 Ok(())2091 }20922093 fn transfer_nft(2094 collection: &CollectionHandle<T>,2095 item_id: TokenId,2096 sender: T::CrossAccountId,2097 new_owner: T::CrossAccountId,2098 ) -> DispatchResult {2099 let collection_id = collection.id;2100 let mut item =2101 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;21022103 ensure!(sender == item.owner, Error::<T>::MustBeTokenOwner);21042105 // update balance2106 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())2107 .checked_sub(1)2108 .ok_or(Error::<T>::NumOverflow)?;2109 <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);21102111 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())2112 .checked_add(1)2113 .ok_or(Error::<T>::NumOverflow)?;2114 <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);21152116 // change owner2117 let old_owner = item.owner.clone();2118 item.owner = new_owner.clone();2119 <NftItemList<T>>::insert(collection_id, item_id, item);21202121 // update index collection2122 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;21232124 collection.log(ERC721Events::Transfer {2125 from: *sender.as_eth(),2126 to: *new_owner.as_eth(),2127 token_id: item_id.into(),2128 })?;2129 Self::deposit_event(RawEvent::Transfer(2130 collection.id,2131 item_id,2132 sender,2133 new_owner,2134 1,2135 ));21362137 Ok(())2138 }21392140 fn set_re_fungible_variable_data(2141 collection: &CollectionHandle<T>,2142 item_id: TokenId,2143 data: Vec<u8>,2144 ) -> DispatchResult {2145 let collection_id = collection.id;2146 let mut item = <ReFungibleItemList<T>>::get(collection_id, item_id)2147 .ok_or(Error::<T>::TokenNotFound)?;21482149 item.variable_data = data;21502151 <ReFungibleItemList<T>>::insert(collection_id, item_id, item);21522153 Ok(())2154 }21552156 fn set_nft_variable_data(2157 collection: &CollectionHandle<T>,2158 item_id: TokenId,2159 data: Vec<u8>,2160 ) -> DispatchResult {2161 let collection_id = collection.id;2162 let mut item =2163 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;21642165 item.variable_data = data;21662167 <NftItemList<T>>::insert(collection_id, item_id, item);21682169 Ok(())2170 }21712172 #[allow(dead_code)]2173 fn init_collection(item: &Collection<T>) {2174 // check params2175 assert!(2176 item.decimal_points <= MAX_DECIMAL_POINTS,2177 "decimal_points parameter must be lower than MAX_DECIMAL_POINTS"2178 );2179 assert!(2180 item.name.len() <= 64,2181 "Collection name can not be longer than 63 char"2182 );2183 assert!(2184 item.name.len() <= 256,2185 "Collection description can not be longer than 255 char"2186 );2187 assert!(2188 item.token_prefix.len() <= 16,2189 "Token prefix can not be longer than 15 char"2190 );21912192 // Generate next collection ID2193 let next_id = CreatedCollectionCount::get().checked_add(1).unwrap();21942195 CreatedCollectionCount::put(next_id);2196 }21972198 #[allow(dead_code)]2199 fn init_nft_token(collection_id: CollectionId, item: &NftItemType<T::CrossAccountId>) {2200 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();22012202 Self::add_token_index(collection_id, current_index, &item.owner).unwrap();22032204 <ItemListIndex>::insert(collection_id, current_index);22052206 // Update balance2207 let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())2208 .checked_add(1)2209 .unwrap();2210 <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);2211 }22122213 #[allow(dead_code)]2214 fn init_fungible_token(2215 collection_id: CollectionId,2216 owner: &T::CrossAccountId,2217 item: &FungibleItemType,2218 ) {2219 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();22202221 Self::add_token_index(collection_id, current_index, owner).unwrap();22222223 <ItemListIndex>::insert(collection_id, current_index);22242225 // Update balance2226 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())2227 .checked_add(item.value)2228 .unwrap();2229 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);2230 }22312232 #[allow(dead_code)]2233 fn init_refungible_token(2234 collection_id: CollectionId,2235 item: &ReFungibleItemType<T::CrossAccountId>,2236 ) {2237 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();22382239 let value = item.owner.first().unwrap().fraction;2240 let owner = item.owner.first().unwrap().owner.clone();22412242 Self::add_token_index(collection_id, current_index, &owner).unwrap();22432244 <ItemListIndex>::insert(collection_id, current_index);22452246 // Update balance2247 let new_balance = <Balance<T>>::get(collection_id, &owner.as_sub())2248 .checked_add(value)2249 .unwrap();2250 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);2251 }22522253 fn add_token_index(2254 collection_id: CollectionId,2255 item_index: TokenId,2256 owner: &T::CrossAccountId,2257 ) -> DispatchResult {2258 // add to account limit2259 if <AccountItemCount<T>>::contains_key(owner.as_sub()) {2260 // bound Owned tokens by a single address2261 let count = <AccountItemCount<T>>::get(owner.as_sub());2262 ensure!(2263 count < ChainLimit::get().account_token_ownership_limit,2264 Error::<T>::AddressOwnershipLimitExceeded2265 );22662267 <AccountItemCount<T>>::insert(2268 owner.as_sub(),2269 count.checked_add(1).ok_or(Error::<T>::NumOverflow)?,2270 );2271 } else {2272 <AccountItemCount<T>>::insert(owner.as_sub(), 1);2273 }22742275 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.as_sub());2276 if list_exists {2277 let mut list = <AddressTokens<T>>::get(collection_id, owner.as_sub());2278 let item_contains = list.contains(&item_index.clone());22792280 if !item_contains {2281 list.push(item_index);2282 }22832284 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), list);2285 } else {2286 let itm = vec![item_index];2287 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), itm);2288 }22892290 Ok(())2291 }22922293 fn remove_token_index(2294 collection_id: CollectionId,2295 item_index: TokenId,2296 owner: &T::CrossAccountId,2297 ) -> DispatchResult {2298 // update counter2299 <AccountItemCount<T>>::insert(2300 owner.as_sub(),2301 <AccountItemCount<T>>::get(owner.as_sub())2302 .checked_sub(1)2303 .ok_or(Error::<T>::NumOverflow)?,2304 );23052306 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.as_sub());2307 if list_exists {2308 let mut list = <AddressTokens<T>>::get(collection_id, owner.as_sub());2309 let item_contains = list.contains(&item_index.clone());23102311 if item_contains {2312 list.retain(|&item| item != item_index);2313 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), list);2314 }2315 }23162317 Ok(())2318 }23192320 fn move_token_index(2321 collection_id: CollectionId,2322 item_index: TokenId,2323 old_owner: &T::CrossAccountId,2324 new_owner: &T::CrossAccountId,2325 ) -> DispatchResult {2326 Self::remove_token_index(collection_id, item_index, old_owner)?;2327 Self::add_token_index(collection_id, item_index, new_owner)?;23282329 Ok(())2330 }2331}23322333sp_api::decl_runtime_apis! {2334 pub trait NftApi {2335 /// Used for ethereum integration2336 fn eth_contract_code(account: H160) -> Option<Vec<u8>>;2337 }2338}1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56#![recursion_limit = "1024"]7#![cfg_attr(not(feature = "std"), no_std)]8#![allow(9 clippy::too_many_arguments,10 clippy::unnecessary_mut_passed,11 clippy::unused_unit12)]1314extern crate alloc;1516pub use serde::{Serialize, Deserialize};1718pub use frame_support::{19 construct_runtime, decl_event, decl_module, decl_storage, decl_error,20 dispatch::DispatchResult,21 ensure, fail, parameter_types,22 traits::{23 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,24 Randomness, IsSubType, WithdrawReasons,25 },26 weights::{27 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},28 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,29 WeightToFeePolynomial, DispatchClass,30 },31 StorageValue, transactional,32};3334use frame_system::{self as system, ensure_signed, ensure_root};35use sp_core::H160;36use sp_std::vec;37use sp_runtime::sp_std::prelude::Vec;38use core::ops::{Deref, DerefMut};39use nft_data_structs::{40 MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_REFUNGIBLE_PIECES,41 AccessMode, ChainLimits, Collection, CreateItemData, CollectionLimits, CollectionId,42 CollectionMode, TokenId, SchemaVersion, SponsorshipState, Ownership, NftItemType,43 FungibleItemType, ReFungibleItemType,44};4546#[cfg(test)]47mod mock;4849#[cfg(test)]50mod tests;5152mod default_weights;53mod eth;54mod sponsorship;55pub use sponsorship::NftSponsorshipHandler;56pub use eth::sponsoring::NftEthSponsorshipHandler;5758pub use eth::NftErcSupport;59pub use eth::account::*;60use eth::erc::{ERC20Events, ERC721Events};6162#[cfg(feature = "runtime-benchmarks")]63mod benchmarking;6465pub trait WeightInfo {66 fn create_collection() -> Weight;67 fn destroy_collection() -> Weight;68 fn add_to_white_list() -> Weight;69 fn remove_from_white_list() -> Weight;70 fn set_public_access_mode() -> Weight;71 fn set_mint_permission() -> Weight;72 fn change_collection_owner() -> Weight;73 fn add_collection_admin() -> Weight;74 fn remove_collection_admin() -> Weight;75 fn set_collection_sponsor() -> Weight;76 fn confirm_sponsorship() -> Weight;77 fn remove_collection_sponsor() -> Weight;78 fn create_item(s: usize) -> Weight;79 fn burn_item() -> Weight;80 fn transfer() -> Weight;81 fn approve() -> Weight;82 fn transfer_from() -> Weight;83 fn set_offchain_schema() -> Weight;84 fn set_const_on_chain_schema() -> Weight;85 fn set_variable_on_chain_schema() -> Weight;86 fn set_variable_meta_data() -> Weight;87 fn enable_contract_sponsoring() -> Weight;88 fn set_schema_version() -> Weight;89 fn set_chain_limits() -> Weight;90 fn set_contract_sponsoring_rate_limit() -> Weight;91 fn set_variable_meta_data_sponsoring_rate_limit() -> Weight;92 fn toggle_contract_white_list() -> Weight;93 fn add_to_contract_white_list() -> Weight;94 fn remove_from_contract_white_list() -> Weight;95 fn set_collection_limits() -> Weight;96}9798decl_error! {99 /// Error for non-fungible-token module.100 pub enum Error for Module<T: Config> {101 /// Total collections bound exceeded.102 TotalCollectionsLimitExceeded,103 /// Decimal_points parameter must be lower than MAX_DECIMAL_POINTS constant, currently it is 30.104 CollectionDecimalPointLimitExceeded,105 /// Collection name can not be longer than 63 char.106 CollectionNameLimitExceeded,107 /// Collection description can not be longer than 255 char.108 CollectionDescriptionLimitExceeded,109 /// Token prefix can not be longer than 15 char.110 CollectionTokenPrefixLimitExceeded,111 /// This collection does not exist.112 CollectionNotFound,113 /// Item not exists.114 TokenNotFound,115 /// Admin not found116 AdminNotFound,117 /// Arithmetic calculation overflow.118 NumOverflow,119 /// Account already has admin role.120 AlreadyAdmin,121 /// You do not own this collection.122 NoPermission,123 /// This address is not set as sponsor, use setCollectionSponsor first.124 ConfirmUnsetSponsorFail,125 /// Collection is not in mint mode.126 PublicMintingNotAllowed,127 /// Sender parameter and item owner must be equal.128 MustBeTokenOwner,129 /// Item balance not enough.130 TokenValueTooLow,131 /// Size of item is too large.132 NftSizeLimitExceeded,133 /// No approve found134 ApproveNotFound,135 /// Requested value more than approved.136 TokenValueNotEnough,137 /// Only approved addresses can call this method.138 ApproveRequired,139 /// Address is not in white list.140 AddresNotInWhiteList,141 /// Number of collection admins bound exceeded.142 CollectionAdminsLimitExceeded,143 /// Owned tokens by a single address bound exceeded.144 AddressOwnershipLimitExceeded,145 /// Length of items properties must be greater than 0.146 EmptyArgument,147 /// const_data exceeded data limit.148 TokenConstDataLimitExceeded,149 /// variable_data exceeded data limit.150 TokenVariableDataLimitExceeded,151 /// Not NFT item data used to mint in NFT collection.152 NotNftDataUsedToMintNftCollectionToken,153 /// Not Fungible item data used to mint in Fungible collection.154 NotFungibleDataUsedToMintFungibleCollectionToken,155 /// Not Re Fungible item data used to mint in Re Fungible collection.156 NotReFungibleDataUsedToMintReFungibleCollectionToken,157 /// Unexpected collection type.158 UnexpectedCollectionType,159 /// Can't store metadata in fungible tokens.160 CantStoreMetadataInFungibleTokens,161 /// Collection token limit exceeded162 CollectionTokenLimitExceeded,163 /// Account token limit exceeded per collection164 AccountTokenLimitExceeded,165 /// Collection limit bounds per collection exceeded166 CollectionLimitBoundsExceeded,167 /// Tried to enable permissions which are only permitted to be disabled168 OwnerPermissionsCantBeReverted,169 /// Schema data size limit bound exceeded170 SchemaDataLimitExceeded,171 /// Maximum refungibility exceeded172 WrongRefungiblePieces,173 /// createRefungible should be called with one owner174 BadCreateRefungibleCall,175 /// Gas limit exceeded176 OutOfGas,177 /// Collection settings not allowing items transferring178 TransferNotAllowed,179 }180}181182#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]183pub struct CollectionHandle<T: Config> {184 pub id: CollectionId,185 collection: Collection<T>,186 recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,187}188impl<T: Config> CollectionHandle<T> {189 pub fn get_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {190 <CollectionById<T>>::get(id).map(|collection| Self {191 id,192 collection,193 recorder: pallet_evm_coder_substrate::SubstrateRecorder::new(194 eth::collection_id_to_address(id),195 gas_limit,196 ),197 })198 }199 pub fn get(id: CollectionId) -> Option<Self> {200 Self::get_with_gas_limit(id, u64::MAX)201 }202 pub fn log(&self, log: impl evm_coder::ToLog) -> DispatchResult {203 self.recorder.log_sub(log)204 }205 fn consume_gas(&self, gas: u64) -> DispatchResult {206 self.recorder.consume_gas_sub(gas)207 }208 pub fn submit_logs(self) -> DispatchResult {209 self.recorder.submit_logs()210 }211 pub fn save(self) -> DispatchResult {212 self.recorder.submit_logs()?;213 <CollectionById<T>>::insert(self.id, self.collection);214 Ok(())215 }216}217impl<T: Config> Deref for CollectionHandle<T> {218 type Target = Collection<T>;219220 fn deref(&self) -> &Self::Target {221 &self.collection222 }223}224225impl<T: Config> DerefMut for CollectionHandle<T> {226 fn deref_mut(&mut self) -> &mut Self::Target {227 &mut self.collection228 }229}230231pub trait Config: system::Config + pallet_evm_coder_substrate::Config + Sized {232 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;233234 /// Weight information for extrinsics in this pallet.235 type WeightInfo: WeightInfo;236237 type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;238 type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;239240 type CrossAccountId: CrossAccountId<Self::AccountId>;241 type Currency: Currency<Self::AccountId>;242 type CollectionCreationPrice: Get<243 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,244 >;245 type TreasuryAccountId: Get<Self::AccountId>;246}247248// # Used definitions249//250// ## User control levels251//252// chain-controlled - key is uncontrolled by user253// i.e autoincrementing index254// can use non-cryptographic hash255// real - key is controlled by user256// but it is hard to generate enough colliding values, i.e owner of signed txs257// can use non-cryptographic hash258// controlled - key is completly controlled by users259// i.e maps with mutable keys260// should use cryptographic hash261//262// ## User control level downgrade reasons263//264// ?1 - chain-controlled -> controlled265// collections/tokens can be destroyed, resulting in massive holes266// ?2 - chain-controlled -> controlled267// same as ?1, but can be only added, resulting in easier exploitation268// ?3 - real -> controlled269// no confirmation required, so addresses can be easily generated270decl_storage! {271 trait Store for Module<T: Config> as Nft {272273 //#region Private members274 /// Id of next collection275 CreatedCollectionCount: u32;276 /// Used for migrations277 ChainVersion: u64;278 /// Id of last collection token279 /// Collection id (controlled?1)280 ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;281 //#endregion282283 //#region Chain limits struct284 pub ChainLimit get(fn chain_limit) config(): ChainLimits;285 //#endregion286287 //#region Bound counters288 /// Amount of collections destroyed, used for total amount tracking with289 /// CreatedCollectionCount290 DestroyedCollectionCount: u32;291 /// Total amount of account owned tokens (NFTs + RFTs + unique fungibles)292 /// Account id (real)293 pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;294 //#endregion295296 //#region Basic collections297 /// Collection info298 /// Collection id (controlled?1)299 pub CollectionById get(fn collection_id) config(): map hasher(blake2_128_concat) CollectionId => Option<Collection<T>> = None;300 /// List of collection admins301 /// Collection id (controlled?2)302 pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::CrossAccountId>;303 /// Whitelisted collection users304 /// Collection id (controlled?2), user id (controlled?3)305 pub WhiteList get(fn white_list): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => bool;306 //#endregion307308 /// How many of collection items user have309 /// Collection id (controlled?2), account id (real)310 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => u128;311312 /// Amount of items which spender can transfer out of owners account (via transferFrom)313 /// Collection id (controlled?2), (token id (controlled ?2) + owner account id (real) + spender account id (controlled?3))314 /// TODO: Off chain worker should remove from this map when token gets removed315 pub Allowances get(fn approved): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) (TokenId, T::AccountId, T::AccountId) => u128;316317 //#region Item collections318 /// Collection id (controlled?2), token id (controlled?1)319 pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<NftItemType<T::CrossAccountId>>;320 /// Collection id (controlled?2), owner (controlled?2)321 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;322 /// Collection id (controlled?2), token id (controlled?1)323 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<ReFungibleItemType<T::CrossAccountId>>;324 //#endregion325326 //#region Index list327 /// Collection id (controlled?2), tokens owner (controlled?2)328 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => Vec<TokenId>;329 //#endregion330331 //#region Tokens transfer rate limit baskets332 /// (Collection id (controlled?2), who created (real))333 /// TODO: Off chain worker should remove from this map when collection gets removed334 pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => T::BlockNumber;335 /// Collection id (controlled?2), token id (controlled?2)336 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;337 /// Collection id (controlled?2), owning user (real)338 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;339 /// Collection id (controlled?2), token id (controlled?2)340 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;341 //#endregion342343 /// Variable metadata sponsoring344 /// Collection id (controlled?2), token id (controlled?2)345 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;346 }347 add_extra_genesis {348 build(|config: &GenesisConfig<T>| {349 // Modification of storage350 for (_num, _c) in &config.collection_id {351 <Module<T>>::init_collection(_c);352 }353354 for (_num, _c, _i) in &config.nft_item_id {355 <Module<T>>::init_nft_token(*_c, _i);356 }357358 for (collection_id, account_id, fungible_item) in &config.fungible_item_id {359 <Module<T>>::init_fungible_token(*collection_id, &T::CrossAccountId::from_sub(account_id.clone()), fungible_item);360 }361362 for (_num, _c, _i) in &config.refungible_item_id {363 <Module<T>>::init_refungible_token(*_c, _i);364 }365 })366 }367}368369decl_event!(370 pub enum Event<T>371 where372 AccountId = <T as frame_system::Config>::AccountId,373 CrossAccountId = <T as Config>::CrossAccountId,374 {375 /// New collection was created376 ///377 /// # Arguments378 ///379 /// * collection_id: Globally unique identifier of newly created collection.380 ///381 /// * mode: [CollectionMode] converted into u8.382 ///383 /// * account_id: Collection owner.384 CollectionCreated(CollectionId, u8, AccountId),385386 /// New item was created.387 ///388 /// # Arguments389 ///390 /// * collection_id: Id of the collection where item was created.391 ///392 /// * item_id: Id of an item. Unique within the collection.393 ///394 /// * recipient: Owner of newly created item395 ItemCreated(CollectionId, TokenId, CrossAccountId),396397 /// Collection item was burned.398 ///399 /// # Arguments400 ///401 /// collection_id.402 ///403 /// item_id: Identifier of burned NFT.404 ItemDestroyed(CollectionId, TokenId),405406 /// Item was transferred407 ///408 /// * collection_id: Id of collection to which item is belong409 ///410 /// * item_id: Id of an item411 ///412 /// * sender: Original owner of item413 ///414 /// * recipient: New owner of item415 ///416 /// * amount: Always 1 for NFT417 Transfer(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),418419 /// * collection_id420 ///421 /// * item_id422 ///423 /// * sender424 ///425 /// * spender426 ///427 /// * amount428 Approved(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),429 }430);431432decl_module! {433 pub struct Module<T: Config> for enum Call434 where435 origin: T::Origin436 {437 fn deposit_event() = default;438 type Error = Error<T>;439440 fn on_initialize(_now: T::BlockNumber) -> Weight {441 0442 }443444 /// This method creates a Collection of NFTs. Each Token may have multiple properties encoded as an array of bytes of certain length. The initial owner and admin of the collection are set to the address that signed the transaction. Both addresses can be changed later.445 ///446 /// # Permissions447 ///448 /// * Anyone.449 ///450 /// # Arguments451 ///452 /// * collection_name: UTF-16 string with collection name (limit 64 characters), will be stored as zero-terminated.453 ///454 /// * collection_description: UTF-16 string with collection description (limit 256 characters), will be stored as zero-terminated.455 ///456 /// * token_prefix: UTF-8 string with token prefix.457 ///458 /// * mode: [CollectionMode] collection type and type dependent data.459 // returns collection ID460 #[weight = <T as Config>::WeightInfo::create_collection()]461 #[transactional]462 pub fn create_collection(origin,463 collection_name: Vec<u16>,464 collection_description: Vec<u16>,465 token_prefix: Vec<u8>,466 mode: CollectionMode) -> DispatchResult {467468 // Anyone can create a collection469 let who = ensure_signed(origin)?;470471 // Take a (non-refundable) deposit of collection creation472 let mut imbalance = <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();473 imbalance.subsume(<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(474 &T::TreasuryAccountId::get(),475 T::CollectionCreationPrice::get(),476 ));477 <T as Config>::Currency::settle(478 &who,479 imbalance,480 WithdrawReasons::TRANSFER,481 ExistenceRequirement::KeepAlive,482 ).map_err(|_| Error::<T>::NoPermission)?;483484 let decimal_points = match mode {485 CollectionMode::Fungible(points) => points,486 _ => 0487 };488489 let chain_limit = ChainLimit::get();490491 let created_count = CreatedCollectionCount::get();492 let destroyed_count = DestroyedCollectionCount::get();493494 // bound Total number of collections495 ensure!(created_count - destroyed_count < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);496497 // check params498 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);499 ensure!(collection_name.len() <= 64, Error::<T>::CollectionNameLimitExceeded);500 ensure!(collection_description.len() <= 256, Error::<T>::CollectionDescriptionLimitExceeded);501 ensure!(token_prefix.len() <= 16, Error::<T>::CollectionTokenPrefixLimitExceeded);502503 // Generate next collection ID504 let next_id = created_count505 .checked_add(1)506 .ok_or(Error::<T>::NumOverflow)?;507508 CreatedCollectionCount::put(next_id);509510 let limits = CollectionLimits {511 sponsored_data_size: chain_limit.custom_data_limit,512 ..Default::default()513 };514515 // Create new collection516 let new_collection = Collection {517 owner: who.clone(),518 name: collection_name,519 mode: mode.clone(),520 mint_mode: false,521 access: AccessMode::Normal,522 description: collection_description,523 decimal_points,524 token_prefix,525 offchain_schema: Vec::new(),526 schema_version: SchemaVersion::ImageURL,527 sponsorship: SponsorshipState::Disabled,528 variable_on_chain_schema: Vec::new(),529 const_on_chain_schema: Vec::new(),530 limits,531 transfers_enabled: true,532 };533534 // Add new collection to map535 <CollectionById<T>>::insert(next_id, new_collection);536537 // call event538 Self::deposit_event(RawEvent::CollectionCreated(next_id, mode.id(), who));539540 Ok(())541 }542543 /// **DANGEROUS**: Destroys collection and all NFTs within this collection. Users irrecoverably lose their assets and may lose real money.544 ///545 /// # Permissions546 ///547 /// * Collection Owner.548 ///549 /// # Arguments550 ///551 /// * collection_id: collection to destroy.552 #[weight = <T as Config>::WeightInfo::destroy_collection()]553 #[transactional]554 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {555556 let sender = ensure_signed(origin)?;557 let collection = Self::get_collection(collection_id)?;558 Self::check_owner_permissions(&collection, &sender)?;559 if !collection.limits.owner_can_destroy {560 fail!(Error::<T>::NoPermission);561 }562563 <AddressTokens<T>>::remove_prefix(collection_id, None);564 <Allowances<T>>::remove_prefix(collection_id, None);565 <Balance<T>>::remove_prefix(collection_id, None);566 <ItemListIndex>::remove(collection_id);567 <AdminList<T>>::remove(collection_id);568 <CollectionById<T>>::remove(collection_id);569 <WhiteList<T>>::remove_prefix(collection_id, None);570571 <NftItemList<T>>::remove_prefix(collection_id, None);572 <FungibleItemList<T>>::remove_prefix(collection_id, None);573 <ReFungibleItemList<T>>::remove_prefix(collection_id, None);574575 <NftTransferBasket<T>>::remove_prefix(collection_id, None);576 <FungibleTransferBasket<T>>::remove_prefix(collection_id, None);577 <ReFungibleTransferBasket<T>>::remove_prefix(collection_id, None);578579 <VariableMetaDataBasket<T>>::remove_prefix(collection_id, None);580581 DestroyedCollectionCount::put(DestroyedCollectionCount::get()582 .checked_add(1)583 .ok_or(Error::<T>::NumOverflow)?);584585 Ok(())586 }587588 /// Add an address to white list.589 ///590 /// # Permissions591 ///592 /// * Collection Owner593 /// * Collection Admin594 ///595 /// # Arguments596 ///597 /// * collection_id.598 ///599 /// * address.600 #[weight = <T as Config>::WeightInfo::add_to_white_list()]601 #[transactional]602 pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{603604 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);605 let collection = Self::get_collection(collection_id)?;606607 Self::toggle_white_list_internal(608 &sender,609 &collection,610 &address,611 true,612 )?;613614 Ok(())615 }616617 /// Remove an address from white list.618 ///619 /// # Permissions620 ///621 /// * Collection Owner622 /// * Collection Admin623 ///624 /// # Arguments625 ///626 /// * collection_id.627 ///628 /// * address.629 #[weight = <T as Config>::WeightInfo::remove_from_white_list()]630 #[transactional]631 pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{632633 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);634 let collection = Self::get_collection(collection_id)?;635636 Self::toggle_white_list_internal(637 &sender,638 &collection,639 &address,640 false,641 )?;642643 Ok(())644 }645646 /// Toggle between normal and white list access for the methods with access for `Anyone`.647 ///648 /// # Permissions649 ///650 /// * Collection Owner.651 ///652 /// # Arguments653 ///654 /// * collection_id.655 ///656 /// * mode: [AccessMode]657 #[weight = <T as Config>::WeightInfo::set_public_access_mode()]658 #[transactional]659 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult660 {661 let sender = ensure_signed(origin)?;662663 let mut target_collection = Self::get_collection(collection_id)?;664 Self::check_owner_permissions(&target_collection, &sender)?;665 target_collection.access = mode;666 target_collection.save()667 }668669 /// Allows Anyone to create tokens if:670 /// * White List is enabled, and671 /// * Address is added to white list, and672 /// * This method was called with True parameter673 ///674 /// # Permissions675 /// * Collection Owner676 ///677 /// # Arguments678 ///679 /// * collection_id.680 ///681 /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.682 #[weight = <T as Config>::WeightInfo::set_mint_permission()]683 #[transactional]684 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult685 {686 let sender = ensure_signed(origin)?;687688 let mut target_collection = Self::get_collection(collection_id)?;689 Self::check_owner_permissions(&target_collection, &sender)?;690 target_collection.mint_mode = mint_permission;691 target_collection.save()692 }693694 /// Change the owner of the collection.695 ///696 /// # Permissions697 ///698 /// * Collection Owner.699 ///700 /// # Arguments701 ///702 /// * collection_id.703 ///704 /// * new_owner.705 #[weight = <T as Config>::WeightInfo::change_collection_owner()]706 #[transactional]707 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {708709 let sender = ensure_signed(origin)?;710 let mut target_collection = Self::get_collection(collection_id)?;711 Self::check_owner_permissions(&target_collection, &sender)?;712 target_collection.owner = new_owner;713 target_collection.save()714 }715716 /// Adds an admin of the Collection.717 /// NFT Collection can be controlled by multiple admin addresses (some which can also be servers, for example). Admins can issue and burn NFTs, as well as add and remove other admins, but cannot change NFT or Collection ownership.718 ///719 /// # Permissions720 ///721 /// * Collection Owner.722 /// * Collection Admin.723 ///724 /// # Arguments725 ///726 /// * collection_id: ID of the Collection to add admin for.727 ///728 /// * new_admin_id: Address of new admin to add.729 #[weight = <T as Config>::WeightInfo::add_collection_admin()]730 #[transactional]731 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {732 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);733 let collection = Self::get_collection(collection_id)?;734 Self::check_owner_or_admin_permissions(&collection, &sender)?;735 let mut admin_arr = <AdminList<T>>::get(collection_id);736737 match admin_arr.binary_search(&new_admin_id) {738 Ok(_) => {},739 Err(idx) => {740 let limits = ChainLimit::get();741 ensure!(admin_arr.len() < limits.collections_admins_limit as usize, Error::<T>::CollectionAdminsLimitExceeded);742 admin_arr.insert(idx, new_admin_id);743 <AdminList<T>>::insert(collection_id, admin_arr);744 }745 }746 Ok(())747 }748749 /// Remove admin address of the Collection. An admin address can remove itself. List of admins may become empty, in which case only Collection Owner will be able to add an Admin.750 ///751 /// # Permissions752 ///753 /// * Collection Owner.754 /// * Collection Admin.755 ///756 /// # Arguments757 ///758 /// * collection_id: ID of the Collection to remove admin for.759 ///760 /// * account_id: Address of admin to remove.761 #[weight = <T as Config>::WeightInfo::remove_collection_admin()]762 #[transactional]763 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {764 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);765 let collection = Self::get_collection(collection_id)?;766 Self::check_owner_or_admin_permissions(&collection, &sender)?;767 let mut admin_arr = <AdminList<T>>::get(collection_id);768769 if let Ok(idx) = admin_arr.binary_search(&account_id) {770 admin_arr.remove(idx);771 <AdminList<T>>::insert(collection_id, admin_arr);772 }773 Ok(())774 }775776 /// # Permissions777 ///778 /// * Collection Owner779 ///780 /// # Arguments781 ///782 /// * collection_id.783 ///784 /// * new_sponsor.785 #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]786 #[transactional]787 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {788 let sender = ensure_signed(origin)?;789 let mut target_collection = Self::get_collection(collection_id)?;790 Self::check_owner_permissions(&target_collection, &sender)?;791792 target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);793 target_collection.save()794 }795796 /// # Permissions797 ///798 /// * Sponsor.799 ///800 /// # Arguments801 ///802 /// * collection_id.803 #[weight = <T as Config>::WeightInfo::confirm_sponsorship()]804 #[transactional]805 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {806 let sender = ensure_signed(origin)?;807808 let mut target_collection = Self::get_collection(collection_id)?;809 ensure!(810 target_collection.sponsorship.pending_sponsor() == Some(&sender),811 Error::<T>::ConfirmUnsetSponsorFail812 );813814 target_collection.sponsorship = SponsorshipState::Confirmed(sender);815 target_collection.save()816 }817818 /// Switch back to pay-per-own-transaction model.819 ///820 /// # Permissions821 ///822 /// * Collection owner.823 ///824 /// # Arguments825 ///826 /// * collection_id.827 #[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]828 #[transactional]829 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {830 let sender = ensure_signed(origin)?;831832 let mut target_collection = Self::get_collection(collection_id)?;833 Self::check_owner_permissions(&target_collection, &sender)?;834835 target_collection.sponsorship = SponsorshipState::Disabled;836 target_collection.save()837 }838839 /// This method creates a concrete instance of NFT Collection created with CreateCollection method.840 ///841 /// # Permissions842 ///843 /// * Collection Owner.844 /// * Collection Admin.845 /// * Anyone if846 /// * White List is enabled, and847 /// * Address is added to white list, and848 /// * MintPermission is enabled (see SetMintPermission method)849 ///850 /// # Arguments851 ///852 /// * collection_id: ID of the collection.853 ///854 /// * owner: Address, initial owner of the NFT.855 ///856 /// * data: Token data to store on chain.857 // #[weight =858 // (130_000_000 as Weight)859 // .saturating_add((2135 as Weight).saturating_mul((properties.len() as u64) as Weight))860 // .saturating_add(RocksDbWeight::get().reads(10 as Weight))861 // .saturating_add(RocksDbWeight::get().writes(8 as Weight))]862863 #[weight = <T as Config>::WeightInfo::create_item(data.data_size())]864 #[transactional]865 pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResult {866 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);867 let collection = Self::get_collection(collection_id)?;868869 Self::create_item_internal(&sender, &collection, &owner, data)?;870871 collection.submit_logs()872 }873874 /// This method creates multiple items in a collection created with CreateCollection method.875 ///876 /// # Permissions877 ///878 /// * Collection Owner.879 /// * Collection Admin.880 /// * Anyone if881 /// * White List is enabled, and882 /// * Address is added to white list, and883 /// * MintPermission is enabled (see SetMintPermission method)884 ///885 /// # Arguments886 ///887 /// * collection_id: ID of the collection.888 ///889 /// * itemsData: Array items properties. Each property is an array of bytes itself, see [create_item].890 ///891 /// * owner: Address, initial owner of the NFT.892 #[weight = <T as Config>::WeightInfo::create_item(items_data.iter()893 .map(|data| { data.data_size() })894 .sum())]895 #[transactional]896 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResult {897898 ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);899 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);900 let collection = Self::get_collection(collection_id)?;901902 Self::create_multiple_items_internal(&sender, &collection, &owner, items_data)?;903904 collection.submit_logs()905 }906907 // TODO! transaction weight908909 /// Set transfers_enabled value for particular collection910 ///911 /// # Permissions912 ///913 /// * Collection Owner.914 ///915 /// # Arguments916 ///917 /// * collection_id: ID of the collection.918 ///919 /// * value: New flag value.920 #[weight = <T as Config>::WeightInfo::burn_item()]921 #[transactional]922 pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {923924 let sender = ensure_signed(origin)?;925 let mut target_collection = Self::get_collection(collection_id)?;926927 Self::check_owner_permissions(&target_collection, &sender)?;928929 target_collection.transfers_enabled = value;930 target_collection.save()931 }932933 /// Destroys a concrete instance of NFT.934 ///935 /// # Permissions936 ///937 /// * Collection Owner.938 /// * Collection Admin.939 /// * Current NFT Owner.940 ///941 /// # Arguments942 ///943 /// * collection_id: ID of the collection.944 ///945 /// * item_id: ID of NFT to burn.946 #[weight = <T as Config>::WeightInfo::burn_item()]947 #[transactional]948 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {949950 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);951 let target_collection = Self::get_collection(collection_id)?;952953 Self::burn_item_internal(&sender, &target_collection, item_id, value)?;954955 target_collection.submit_logs()956 }957958 /// Change ownership of the token.959 ///960 /// # Permissions961 ///962 /// * Collection Owner963 /// * Collection Admin964 /// * Current NFT owner965 ///966 /// # Arguments967 ///968 /// * recipient: Address of token recipient.969 ///970 /// * collection_id.971 ///972 /// * item_id: ID of the item973 /// * Non-Fungible Mode: Required.974 /// * Fungible Mode: Ignored.975 /// * Re-Fungible Mode: Required.976 ///977 /// * value: Amount to transfer.978 /// * Non-Fungible Mode: Ignored979 /// * Fungible Mode: Must specify transferred amount980 /// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)981 #[weight = <T as Config>::WeightInfo::transfer()]982 #[transactional]983 pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {984 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);985 let collection = Self::get_collection(collection_id)?;986987 Self::transfer_internal(&sender, &recipient, &collection, item_id, value)?;988989 collection.submit_logs()990 }991992 /// Set, change, or remove approved address to transfer the ownership of the NFT.993 ///994 /// # Permissions995 ///996 /// * Collection Owner997 /// * Collection Admin998 /// * Current NFT owner999 ///1000 /// # Arguments1001 ///1002 /// * approved: Address that is approved to transfer this NFT or zero (if needed to remove approval).1003 ///1004 /// * collection_id.1005 ///1006 /// * item_id: ID of the item.1007 #[weight = <T as Config>::WeightInfo::approve()]1008 #[transactional]1009 pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {1010 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1011 let collection = Self::get_collection(collection_id)?;10121013 Self::approve_internal(&sender, &spender, &collection, item_id, amount)?;10141015 collection.submit_logs()1016 }10171018 /// Change ownership of a NFT on behalf of the owner. See Approve method for additional information. After this method executes, the approval is removed so that the approved address will not be able to transfer this NFT again from this owner.1019 ///1020 /// # Permissions1021 /// * Collection Owner1022 /// * Collection Admin1023 /// * Current NFT owner1024 /// * Address approved by current NFT owner1025 ///1026 /// # Arguments1027 ///1028 /// * from: Address that owns token.1029 ///1030 /// * recipient: Address of token recipient.1031 ///1032 /// * collection_id.1033 ///1034 /// * item_id: ID of the item.1035 ///1036 /// * value: Amount to transfer.1037 #[weight = <T as Config>::WeightInfo::transfer_from()]1038 #[transactional]1039 pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {1040 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1041 let collection = Self::get_collection(collection_id)?;10421043 Self::transfer_from_internal(&sender, &from, &recipient, &collection, item_id, value)?;10441045 collection.submit_logs()1046 }1047 // #[weight = 0]1048 // // let no_perm_mes = "You do not have permissions to modify this collection";1049 // // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);1050 // // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));1051 // // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);10521053 // // // on_nft_received call10541055 // // Self::transfer(origin, collection_id, item_id, new_owner)?;10561057 // Ok(())1058 // }10591060 /// Set off-chain data schema.1061 ///1062 /// # Permissions1063 ///1064 /// * Collection Owner1065 /// * Collection Admin1066 ///1067 /// # Arguments1068 ///1069 /// * collection_id.1070 ///1071 /// * schema: String representing the offchain data schema.1072 #[weight = <T as Config>::WeightInfo::set_variable_meta_data()]1073 #[transactional]1074 pub fn set_variable_meta_data (1075 origin,1076 collection_id: CollectionId,1077 item_id: TokenId,1078 data: Vec<u8>1079 ) -> DispatchResult {1080 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);10811082 let collection = Self::get_collection(collection_id)?;10831084 Self::set_variable_meta_data_internal(&sender, &collection, item_id, data)?;10851086 Ok(())1087 }10881089 /// Set schema standard1090 /// ImageURL1091 /// Unique1092 ///1093 /// # Permissions1094 ///1095 /// * Collection Owner1096 /// * Collection Admin1097 ///1098 /// # Arguments1099 ///1100 /// * collection_id.1101 ///1102 /// * schema: SchemaVersion: enum1103 #[weight = <T as Config>::WeightInfo::set_schema_version()]1104 #[transactional]1105 pub fn set_schema_version(1106 origin,1107 collection_id: CollectionId,1108 version: SchemaVersion1109 ) -> DispatchResult {1110 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1111 let mut target_collection = Self::get_collection(collection_id)?;1112 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;1113 target_collection.schema_version = version;1114 target_collection.save()1115 }11161117 /// Set off-chain data schema.1118 ///1119 /// # Permissions1120 ///1121 /// * Collection Owner1122 /// * Collection Admin1123 ///1124 /// # Arguments1125 ///1126 /// * collection_id.1127 ///1128 /// * schema: String representing the offchain data schema.1129 #[weight = <T as Config>::WeightInfo::set_offchain_schema()]1130 #[transactional]1131 pub fn set_offchain_schema(1132 origin,1133 collection_id: CollectionId,1134 schema: Vec<u8>1135 ) -> DispatchResult {1136 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1137 let mut target_collection = Self::get_collection(collection_id)?;1138 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;11391140 // check schema limit1141 ensure!(schema.len() as u32 <= ChainLimit::get().offchain_schema_limit, "");11421143 target_collection.offchain_schema = schema;1144 target_collection.save()1145 }11461147 /// Set const on-chain data schema.1148 ///1149 /// # Permissions1150 ///1151 /// * Collection Owner1152 /// * Collection Admin1153 ///1154 /// # Arguments1155 ///1156 /// * collection_id.1157 ///1158 /// * schema: String representing the const on-chain data schema.1159 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1160 #[transactional]1161 pub fn set_const_on_chain_schema (1162 origin,1163 collection_id: CollectionId,1164 schema: Vec<u8>1165 ) -> DispatchResult {1166 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1167 let mut target_collection = Self::get_collection(collection_id)?;1168 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;11691170 // check schema limit1171 ensure!(schema.len() as u32 <= ChainLimit::get().const_on_chain_schema_limit, "");11721173 target_collection.const_on_chain_schema = schema;1174 target_collection.save()1175 }11761177 /// Set variable on-chain data schema.1178 ///1179 /// # Permissions1180 ///1181 /// * Collection Owner1182 /// * Collection Admin1183 ///1184 /// # Arguments1185 ///1186 /// * collection_id.1187 ///1188 /// * schema: String representing the variable on-chain data schema.1189 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1190 #[transactional]1191 pub fn set_variable_on_chain_schema (1192 origin,1193 collection_id: CollectionId,1194 schema: Vec<u8>1195 ) -> DispatchResult {1196 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1197 let mut target_collection = Self::get_collection(collection_id)?;1198 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;11991200 // check schema limit1201 ensure!(schema.len() as u32 <= ChainLimit::get().variable_on_chain_schema_limit, "");12021203 target_collection.variable_on_chain_schema = schema;1204 target_collection.save()1205 }12061207 // Sudo permissions function1208 #[weight = <T as Config>::WeightInfo::set_chain_limits()]1209 #[transactional]1210 pub fn set_chain_limits(1211 origin,1212 limits: ChainLimits1213 ) -> DispatchResult {12141215 #[cfg(not(feature = "runtime-benchmarks"))]1216 ensure_root(origin)?;12171218 <ChainLimit>::put(limits);1219 Ok(())1220 }12211222 #[weight = <T as Config>::WeightInfo::set_collection_limits()]1223 #[transactional]1224 pub fn set_collection_limits(1225 origin,1226 collection_id: u32,1227 new_limits: CollectionLimits<T::BlockNumber>,1228 ) -> DispatchResult {1229 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1230 let mut target_collection = Self::get_collection(collection_id)?;1231 Self::check_owner_permissions(&target_collection, sender.as_sub())?;1232 let old_limits = &target_collection.limits;1233 let chain_limits = ChainLimit::get();12341235 // collection bounds1236 ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&1237 new_limits.account_token_ownership_limit <= MAX_TOKEN_OWNERSHIP &&1238 new_limits.sponsored_data_size <= chain_limits.custom_data_limit,1239 Error::<T>::CollectionLimitBoundsExceeded);12401241 // token_limit check prev1242 ensure!(old_limits.token_limit >= new_limits.token_limit, Error::<T>::CollectionTokenLimitExceeded);1243 ensure!(new_limits.token_limit > 0, Error::<T>::CollectionTokenLimitExceeded);12441245 ensure!(1246 (old_limits.owner_can_transfer || !new_limits.owner_can_transfer) &&1247 (old_limits.owner_can_destroy || !new_limits.owner_can_destroy),1248 Error::<T>::OwnerPermissionsCantBeReverted,1249 );12501251 target_collection.limits = new_limits;12521253 target_collection.save()1254 }1255 }1256}12571258impl<T: Config> Module<T> {1259 pub fn create_item_internal(1260 sender: &T::CrossAccountId,1261 collection: &CollectionHandle<T>,1262 owner: &T::CrossAccountId,1263 data: CreateItemData,1264 ) -> DispatchResult {1265 Self::can_create_items_in_collection(collection, sender, owner, 1)?;1266 Self::validate_create_item_args(collection, &data)?;1267 Self::create_item_no_validation(collection, owner, data)?;12681269 Ok(())1270 }12711272 pub fn transfer_internal(1273 sender: &T::CrossAccountId,1274 recipient: &T::CrossAccountId,1275 target_collection: &CollectionHandle<T>,1276 item_id: TokenId,1277 value: u128,1278 ) -> DispatchResult {1279 target_collection.consume_gas(2000000)?;1280 // Limits check1281 Self::is_correct_transfer(target_collection, recipient)?;12821283 // Transfer permissions check1284 ensure!(1285 Self::is_item_owner(sender, target_collection, item_id)1286 || Self::is_owner_or_admin_permissions(target_collection, sender),1287 Error::<T>::NoPermission1288 );12891290 if target_collection.access == AccessMode::WhiteList {1291 Self::check_white_list(target_collection, sender)?;1292 Self::check_white_list(target_collection, recipient)?;1293 }12941295 match target_collection.mode {1296 CollectionMode::NFT => Self::transfer_nft(1297 target_collection,1298 item_id,1299 sender.clone(),1300 recipient.clone(),1301 )?,1302 CollectionMode::Fungible(_) => {1303 Self::transfer_fungible(target_collection, value, sender, recipient)?1304 }1305 CollectionMode::ReFungible => Self::transfer_refungible(1306 target_collection,1307 item_id,1308 value,1309 sender.clone(),1310 recipient.clone(),1311 )?,1312 _ => (),1313 };13141315 Self::deposit_event(RawEvent::Transfer(1316 target_collection.id,1317 item_id,1318 sender.clone(),1319 recipient.clone(),1320 value,1321 ));13221323 Ok(())1324 }13251326 pub fn approve_internal(1327 sender: &T::CrossAccountId,1328 spender: &T::CrossAccountId,1329 collection: &CollectionHandle<T>,1330 item_id: TokenId,1331 amount: u128,1332 ) -> DispatchResult {1333 collection.consume_gas(2000000)?;1334 Self::token_exists(collection, item_id)?;13351336 // Transfer permissions check1337 let bypasses_limits = collection.limits.owner_can_transfer1338 && Self::is_owner_or_admin_permissions(collection, sender);13391340 let allowance_limit = if bypasses_limits {1341 None1342 } else if let Some(amount) = Self::owned_amount(sender, collection, item_id) {1343 Some(amount)1344 } else {1345 fail!(Error::<T>::NoPermission);1346 };13471348 if collection.access == AccessMode::WhiteList {1349 Self::check_white_list(collection, sender)?;1350 Self::check_white_list(collection, spender)?;1351 }13521353 let allowance: u128 = amount1354 .checked_add(<Allowances<T>>::get(1355 collection.id,1356 (item_id, sender.as_sub(), spender.as_sub()),1357 ))1358 .ok_or(Error::<T>::NumOverflow)?;1359 if let Some(limit) = allowance_limit {1360 ensure!(limit >= allowance, Error::<T>::TokenValueTooLow);1361 }1362 <Allowances<T>>::insert(1363 collection.id,1364 (item_id, sender.as_sub(), spender.as_sub()),1365 allowance,1366 );13671368 if matches!(collection.mode, CollectionMode::NFT) {1369 // TODO: NFT: only one owner may exist for token in ERC7211370 collection.log(ERC721Events::Approval {1371 owner: *sender.as_eth(),1372 approved: *spender.as_eth(),1373 token_id: item_id.into(),1374 })?;1375 }13761377 if matches!(collection.mode, CollectionMode::Fungible(_)) {1378 // TODO: NFT: only one owner may exist for token in ERC201379 collection.log(ERC20Events::Approval {1380 owner: *sender.as_eth(),1381 spender: *spender.as_eth(),1382 value: allowance.into(),1383 })?;1384 }13851386 Self::deposit_event(RawEvent::Approved(1387 collection.id,1388 item_id,1389 sender.clone(),1390 spender.clone(),1391 allowance,1392 ));1393 Ok(())1394 }13951396 pub fn transfer_from_internal(1397 sender: &T::CrossAccountId,1398 from: &T::CrossAccountId,1399 recipient: &T::CrossAccountId,1400 collection: &CollectionHandle<T>,1401 item_id: TokenId,1402 amount: u128,1403 ) -> DispatchResult {1404 collection.consume_gas(2000000)?;1405 // Check approval1406 let approval: u128 =1407 <Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));14081409 // Limits check1410 Self::is_correct_transfer(collection, recipient)?;14111412 // Transfer permissions check1413 ensure!(1414 approval >= amount1415 || (collection.limits.owner_can_transfer1416 && Self::is_owner_or_admin_permissions(collection, sender)),1417 Error::<T>::NoPermission1418 );14191420 if collection.access == AccessMode::WhiteList {1421 Self::check_white_list(collection, sender)?;1422 Self::check_white_list(collection, recipient)?;1423 }14241425 // Reduce approval by transferred amount or remove if remaining approval drops to 01426 let allowance = approval.saturating_sub(amount);1427 if allowance > 0 {1428 <Allowances<T>>::insert(1429 collection.id,1430 (item_id, from.as_sub(), sender.as_sub()),1431 allowance,1432 );1433 } else {1434 <Allowances<T>>::remove(collection.id, (item_id, from.as_sub(), sender.as_sub()));1435 }14361437 match collection.mode {1438 CollectionMode::NFT => {1439 Self::transfer_nft(collection, item_id, from.clone(), recipient.clone())?1440 }1441 CollectionMode::Fungible(_) => {1442 Self::transfer_fungible(collection, amount, from, recipient)?1443 }1444 CollectionMode::ReFungible => Self::transfer_refungible(1445 collection,1446 item_id,1447 amount,1448 from.clone(),1449 recipient.clone(),1450 )?,1451 _ => (),1452 };14531454 if matches!(collection.mode, CollectionMode::Fungible(_)) {1455 collection.log(ERC20Events::Approval {1456 owner: *from.as_eth(),1457 spender: *sender.as_eth(),1458 value: allowance.into(),1459 })?;1460 }14611462 Ok(())1463 }14641465 pub fn set_variable_meta_data_internal(1466 sender: &T::CrossAccountId,1467 collection: &CollectionHandle<T>,1468 item_id: TokenId,1469 data: Vec<u8>,1470 ) -> DispatchResult {1471 Self::token_exists(collection, item_id)?;14721473 ensure!(1474 ChainLimit::get().custom_data_limit >= data.len() as u32,1475 Error::<T>::TokenVariableDataLimitExceeded1476 );14771478 // Modify permissions check1479 ensure!(1480 Self::is_item_owner(sender, collection, item_id)1481 || Self::is_owner_or_admin_permissions(collection, sender),1482 Error::<T>::NoPermission1483 );14841485 match collection.mode {1486 CollectionMode::NFT => Self::set_nft_variable_data(collection, item_id, data)?,1487 CollectionMode::ReFungible => {1488 Self::set_re_fungible_variable_data(collection, item_id, data)?1489 }1490 CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),1491 _ => fail!(Error::<T>::UnexpectedCollectionType),1492 };14931494 Ok(())1495 }14961497 pub fn create_multiple_items_internal(1498 sender: &T::CrossAccountId,1499 collection: &CollectionHandle<T>,1500 owner: &T::CrossAccountId,1501 items_data: Vec<CreateItemData>,1502 ) -> DispatchResult {1503 Self::can_create_items_in_collection(collection, sender, owner, items_data.len() as u32)?;15041505 for data in &items_data {1506 Self::validate_create_item_args(collection, data)?;1507 }1508 for data in &items_data {1509 Self::create_item_no_validation(collection, owner, data.clone())?;1510 }15111512 Ok(())1513 }15141515 pub fn burn_item_internal(1516 sender: &T::CrossAccountId,1517 collection: &CollectionHandle<T>,1518 item_id: TokenId,1519 value: u128,1520 ) -> DispatchResult {1521 ensure!(1522 Self::is_item_owner(sender, collection, item_id)1523 || (collection.limits.owner_can_transfer1524 && Self::is_owner_or_admin_permissions(collection, sender)),1525 Error::<T>::NoPermission1526 );15271528 if collection.access == AccessMode::WhiteList {1529 Self::check_white_list(collection, sender)?;1530 }15311532 match collection.mode {1533 CollectionMode::NFT => Self::burn_nft_item(collection, item_id)?,1534 CollectionMode::Fungible(_) => Self::burn_fungible_item(sender, collection, value)?,1535 CollectionMode::ReFungible => Self::burn_refungible_item(collection, item_id, sender)?,1536 _ => (),1537 };15381539 Ok(())1540 }15411542 pub fn toggle_white_list_internal(1543 sender: &T::CrossAccountId,1544 collection: &CollectionHandle<T>,1545 address: &T::CrossAccountId,1546 whitelisted: bool,1547 ) -> DispatchResult {1548 Self::check_owner_or_admin_permissions(collection, sender)?;15491550 if whitelisted {1551 <WhiteList<T>>::insert(collection.id, address.as_sub(), true);1552 } else {1553 <WhiteList<T>>::remove(collection.id, address.as_sub());1554 }15551556 Ok(())1557 }15581559 fn is_correct_transfer(1560 collection: &CollectionHandle<T>,1561 recipient: &T::CrossAccountId,1562 ) -> DispatchResult {1563 let collection_id = collection.id;15641565 // check token limit and account token limit1566 let account_items: u32 =1567 <AddressTokens<T>>::get(collection_id, recipient.as_sub()).len() as u32;1568 ensure!(1569 collection.limits.account_token_ownership_limit > account_items,1570 Error::<T>::AccountTokenLimitExceeded1571 );15721573 // preliminary transfer check1574 ensure!(collection.transfers_enabled, Error::<T>::TransferNotAllowed);15751576 Ok(())1577 }15781579 fn can_create_items_in_collection(1580 collection: &CollectionHandle<T>,1581 sender: &T::CrossAccountId,1582 owner: &T::CrossAccountId,1583 amount: u32,1584 ) -> DispatchResult {1585 let collection_id = collection.id;15861587 // check token limit and account token limit1588 let total_items: u32 = ItemListIndex::get(collection_id)1589 .checked_add(amount)1590 .ok_or(Error::<T>::CollectionTokenLimitExceeded)?;1591 let account_items: u32 = (<AddressTokens<T>>::get(collection_id, owner.as_sub()).len()1592 as u32)1593 .checked_add(amount)1594 .ok_or(Error::<T>::AccountTokenLimitExceeded)?;1595 ensure!(1596 collection.limits.token_limit >= total_items,1597 Error::<T>::CollectionTokenLimitExceeded1598 );1599 ensure!(1600 collection.limits.account_token_ownership_limit >= account_items,1601 Error::<T>::AccountTokenLimitExceeded1602 );16031604 if !Self::is_owner_or_admin_permissions(collection, sender) {1605 ensure!(collection.mint_mode, Error::<T>::PublicMintingNotAllowed);1606 Self::check_white_list(collection, owner)?;1607 Self::check_white_list(collection, sender)?;1608 }16091610 Ok(())1611 }16121613 fn validate_create_item_args(1614 target_collection: &CollectionHandle<T>,1615 data: &CreateItemData,1616 ) -> DispatchResult {1617 match target_collection.mode {1618 CollectionMode::NFT => {1619 if let CreateItemData::NFT(data) = data {1620 // check sizes1621 ensure!(1622 ChainLimit::get().custom_data_limit >= data.const_data.len() as u32,1623 Error::<T>::TokenConstDataLimitExceeded1624 );1625 ensure!(1626 ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32,1627 Error::<T>::TokenVariableDataLimitExceeded1628 );1629 } else {1630 fail!(Error::<T>::NotNftDataUsedToMintNftCollectionToken);1631 }1632 }1633 CollectionMode::Fungible(_) => {1634 if let CreateItemData::Fungible(_) = data {1635 } else {1636 fail!(Error::<T>::NotFungibleDataUsedToMintFungibleCollectionToken);1637 }1638 }1639 CollectionMode::ReFungible => {1640 if let CreateItemData::ReFungible(data) = data {1641 // check sizes1642 ensure!(1643 ChainLimit::get().custom_data_limit >= data.const_data.len() as u32,1644 Error::<T>::TokenConstDataLimitExceeded1645 );1646 ensure!(1647 ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32,1648 Error::<T>::TokenVariableDataLimitExceeded1649 );16501651 // Check refungibility limits1652 ensure!(1653 data.pieces <= MAX_REFUNGIBLE_PIECES,1654 Error::<T>::WrongRefungiblePieces1655 );1656 ensure!(data.pieces > 0, Error::<T>::WrongRefungiblePieces);1657 } else {1658 fail!(Error::<T>::NotReFungibleDataUsedToMintReFungibleCollectionToken);1659 }1660 }1661 _ => {1662 fail!(Error::<T>::UnexpectedCollectionType);1663 }1664 };16651666 Ok(())1667 }16681669 fn create_item_no_validation(1670 collection: &CollectionHandle<T>,1671 owner: &T::CrossAccountId,1672 data: CreateItemData,1673 ) -> DispatchResult {1674 match data {1675 CreateItemData::NFT(data) => {1676 let item = NftItemType {1677 owner: owner.clone(),1678 const_data: data.const_data,1679 variable_data: data.variable_data,1680 };16811682 Self::add_nft_item(collection, item)?;1683 }1684 CreateItemData::Fungible(data) => {1685 Self::add_fungible_item(collection, owner, data.value)?;1686 }1687 CreateItemData::ReFungible(data) => {1688 let owner_list = vec![Ownership {1689 owner: owner.clone(),1690 fraction: data.pieces,1691 }];16921693 let item = ReFungibleItemType {1694 owner: owner_list,1695 const_data: data.const_data,1696 variable_data: data.variable_data,1697 };16981699 Self::add_refungible_item(collection, item)?;1700 }1701 };17021703 Ok(())1704 }17051706 fn add_fungible_item(1707 collection: &CollectionHandle<T>,1708 owner: &T::CrossAccountId,1709 value: u128,1710 ) -> DispatchResult {1711 let collection_id = collection.id;17121713 // Does new owner already have an account?1714 let balance: u128 = <FungibleItemList<T>>::get(collection_id, owner.as_sub()).value;17151716 // Mint1717 let item = FungibleItemType {1718 value: balance.checked_add(value).ok_or(Error::<T>::NumOverflow)?,1719 };1720 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), item);17211722 // Update balance1723 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1724 .checked_add(value)1725 .ok_or(Error::<T>::NumOverflow)?;1726 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);17271728 Self::deposit_event(RawEvent::ItemCreated(collection_id, 0, owner.clone()));1729 Ok(())1730 }17311732 fn add_refungible_item(1733 collection: &CollectionHandle<T>,1734 item: ReFungibleItemType<T::CrossAccountId>,1735 ) -> DispatchResult {1736 let collection_id = collection.id;17371738 let current_index = <ItemListIndex>::get(collection_id)1739 .checked_add(1)1740 .ok_or(Error::<T>::NumOverflow)?;1741 let itemcopy = item.clone();17421743 ensure!(item.owner.len() == 1, Error::<T>::BadCreateRefungibleCall,);1744 let item_owner = item.owner.first().expect("only one owner is defined");17451746 let value = item_owner.fraction;1747 let owner = item_owner.owner.clone();17481749 Self::add_token_index(collection_id, current_index, &owner)?;17501751 <ItemListIndex>::insert(collection_id, current_index);1752 <ReFungibleItemList<T>>::insert(collection_id, current_index, itemcopy);17531754 // Update balance1755 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1756 .checked_add(value)1757 .ok_or(Error::<T>::NumOverflow)?;1758 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);17591760 Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, owner));1761 Ok(())1762 }17631764 fn add_nft_item(1765 collection: &CollectionHandle<T>,1766 item: NftItemType<T::CrossAccountId>,1767 ) -> DispatchResult {1768 let collection_id = collection.id;17691770 let current_index = <ItemListIndex>::get(collection_id)1771 .checked_add(1)1772 .ok_or(Error::<T>::NumOverflow)?;17731774 let item_owner = item.owner.clone();1775 Self::add_token_index(collection_id, current_index, &item.owner)?;17761777 <ItemListIndex>::insert(collection_id, current_index);1778 <NftItemList<T>>::insert(collection_id, current_index, item);17791780 // Update balance1781 let new_balance = <Balance<T>>::get(collection_id, item_owner.as_sub())1782 .checked_add(1)1783 .ok_or(Error::<T>::NumOverflow)?;1784 <Balance<T>>::insert(collection_id, item_owner.as_sub(), new_balance);17851786 collection.log(ERC721Events::Transfer {1787 from: H160::default(),1788 to: *item_owner.as_eth(),1789 token_id: current_index.into(),1790 })?;1791 Self::deposit_event(RawEvent::ItemCreated(1792 collection_id,1793 current_index,1794 item_owner,1795 ));1796 Ok(())1797 }17981799 fn burn_refungible_item(1800 collection: &CollectionHandle<T>,1801 item_id: TokenId,1802 owner: &T::CrossAccountId,1803 ) -> DispatchResult {1804 let collection_id = collection.id;18051806 let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id)1807 .ok_or(Error::<T>::TokenNotFound)?;1808 let rft_balance = token1809 .owner1810 .iter()1811 .find(|&i| i.owner == *owner)1812 .ok_or(Error::<T>::TokenNotFound)?;1813 Self::remove_token_index(collection_id, item_id, owner)?;18141815 // update balance1816 let new_balance = <Balance<T>>::get(collection_id, rft_balance.owner.as_sub())1817 .checked_sub(rft_balance.fraction)1818 .ok_or(Error::<T>::NumOverflow)?;1819 <Balance<T>>::insert(collection_id, rft_balance.owner.as_sub(), new_balance);18201821 // Re-create owners list with sender removed1822 let index = token1823 .owner1824 .iter()1825 .position(|i| i.owner == *owner)1826 .expect("owned item is exists");1827 token.owner.remove(index);1828 let owner_count = token.owner.len();18291830 // Burn the token completely if this was the last (only) owner1831 if owner_count == 0 {1832 <ReFungibleItemList<T>>::remove(collection_id, item_id);1833 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);1834 } else {1835 <ReFungibleItemList<T>>::insert(collection_id, item_id, token);1836 }18371838 Ok(())1839 }18401841 fn burn_nft_item(collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {1842 let collection_id = collection.id;18431844 let item =1845 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;1846 Self::remove_token_index(collection_id, item_id, &item.owner)?;18471848 // update balance1849 let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())1850 .checked_sub(1)1851 .ok_or(Error::<T>::NumOverflow)?;1852 <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);1853 <NftItemList<T>>::remove(collection_id, item_id);1854 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);18551856 Self::deposit_event(RawEvent::ItemDestroyed(collection.id, item_id));1857 Ok(())1858 }18591860 fn burn_fungible_item(1861 owner: &T::CrossAccountId,1862 collection: &CollectionHandle<T>,1863 value: u128,1864 ) -> DispatchResult {1865 let collection_id = collection.id;18661867 let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());1868 ensure!(balance.value >= value, Error::<T>::TokenValueNotEnough);18691870 // update balance1871 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())1872 .checked_sub(value)1873 .ok_or(Error::<T>::NumOverflow)?;1874 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);18751876 if balance.value - value > 0 {1877 balance.value -= value;1878 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);1879 } else {1880 <FungibleItemList<T>>::remove(collection_id, owner.as_sub());1881 }18821883 collection.log(ERC20Events::Transfer {1884 from: *owner.as_eth(),1885 to: H160::default(),1886 value: value.into(),1887 })?;1888 Ok(())1889 }18901891 pub fn get_collection(1892 collection_id: CollectionId,1893 ) -> Result<CollectionHandle<T>, sp_runtime::DispatchError> {1894 Ok(<CollectionHandle<T>>::get(collection_id).ok_or(Error::<T>::CollectionNotFound)?)1895 }18961897 fn check_owner_permissions(1898 target_collection: &CollectionHandle<T>,1899 subject: &T::AccountId,1900 ) -> DispatchResult {1901 ensure!(1902 *subject == target_collection.owner,1903 Error::<T>::NoPermission1904 );19051906 Ok(())1907 }19081909 fn is_owner_or_admin_permissions(1910 collection: &CollectionHandle<T>,1911 subject: &T::CrossAccountId,1912 ) -> bool {1913 *subject.as_sub() == collection.owner1914 || <AdminList<T>>::get(collection.id).contains(subject)1915 }19161917 fn check_owner_or_admin_permissions(1918 collection: &CollectionHandle<T>,1919 subject: &T::CrossAccountId,1920 ) -> DispatchResult {1921 ensure!(1922 Self::is_owner_or_admin_permissions(collection, subject),1923 Error::<T>::NoPermission1924 );19251926 Ok(())1927 }19281929 fn owned_amount(1930 subject: &T::CrossAccountId,1931 target_collection: &CollectionHandle<T>,1932 item_id: TokenId,1933 ) -> Option<u128> {1934 let collection_id = target_collection.id;19351936 match target_collection.mode {1937 CollectionMode::NFT => {1938 (<NftItemList<T>>::get(collection_id, item_id)?.owner == *subject).then(|| 1)1939 }1940 CollectionMode::Fungible(_) => {1941 Some(<FungibleItemList<T>>::get(collection_id, &subject.as_sub()).value)1942 }1943 CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)?1944 .owner1945 .iter()1946 .find(|i| i.owner == *subject)1947 .map(|i| i.fraction),1948 CollectionMode::Invalid => None,1949 }1950 }19511952 fn is_item_owner(1953 subject: &T::CrossAccountId,1954 target_collection: &CollectionHandle<T>,1955 item_id: TokenId,1956 ) -> bool {1957 match target_collection.mode {1958 CollectionMode::Fungible(_) => true,1959 _ => Self::owned_amount(subject, target_collection, item_id).is_some(),1960 }1961 }19621963 fn check_white_list(1964 collection: &CollectionHandle<T>,1965 address: &T::CrossAccountId,1966 ) -> DispatchResult {1967 let collection_id = collection.id;19681969 let mes = Error::<T>::AddresNotInWhiteList;1970 ensure!(1971 <WhiteList<T>>::contains_key(collection_id, address.as_sub()),1972 mes1973 );19741975 Ok(())1976 }19771978 /// Check if token exists. In case of Fungible, check if there is an entry for1979 /// the owner in fungible balances double map1980 fn token_exists(target_collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {1981 let collection_id = target_collection.id;1982 let exists = match target_collection.mode {1983 CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),1984 CollectionMode::Fungible(_) => true,1985 CollectionMode::ReFungible => {1986 <ReFungibleItemList<T>>::contains_key(collection_id, item_id)1987 }1988 _ => false,1989 };19901991 ensure!(exists, Error::<T>::TokenNotFound);1992 Ok(())1993 }19941995 fn transfer_fungible(1996 collection: &CollectionHandle<T>,1997 value: u128,1998 owner: &T::CrossAccountId,1999 recipient: &T::CrossAccountId,2000 ) -> DispatchResult {2001 let collection_id = collection.id;20022003 let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());2004 ensure!(balance.value >= value, Error::<T>::TokenValueTooLow);20052006 // Send balance to recipient (updates balanceOf of recipient)2007 Self::add_fungible_item(collection, recipient, value)?;20082009 // update balanceOf of sender2010 <Balance<T>>::insert(collection_id, owner.as_sub(), balance.value - value);20112012 // Reduce or remove sender2013 if balance.value == value {2014 <FungibleItemList<T>>::remove(collection_id, owner.as_sub());2015 } else {2016 balance.value -= value;2017 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);2018 }20192020 collection.log(ERC20Events::Transfer {2021 from: *owner.as_eth(),2022 to: *recipient.as_eth(),2023 value: value.into(),2024 })?;2025 Self::deposit_event(RawEvent::Transfer(2026 collection.id,2027 1,2028 owner.clone(),2029 recipient.clone(),2030 value,2031 ));20322033 Ok(())2034 }20352036 fn transfer_refungible(2037 collection: &CollectionHandle<T>,2038 item_id: TokenId,2039 value: u128,2040 owner: T::CrossAccountId,2041 new_owner: T::CrossAccountId,2042 ) -> DispatchResult {2043 let collection_id = collection.id;2044 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id)2045 .ok_or(Error::<T>::TokenNotFound)?;20462047 let item = full_item2048 .owner2049 .iter()2050 .find(|i| i.owner == owner)2051 .ok_or(Error::<T>::TokenNotFound)?;2052 let amount = item.fraction;20532054 ensure!(amount >= value, Error::<T>::TokenValueTooLow);20552056 // update balance2057 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())2058 .checked_sub(value)2059 .ok_or(Error::<T>::NumOverflow)?;2060 <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);20612062 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())2063 .checked_add(value)2064 .ok_or(Error::<T>::NumOverflow)?;2065 <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);20662067 let old_owner = item.owner.clone();2068 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);20692070 let mut new_full_item = full_item.clone();2071 // transfer2072 if amount == value && !new_owner_has_account {2073 // change owner2074 // new owner do not have account2075 new_full_item2076 .owner2077 .iter_mut()2078 .find(|i| i.owner == owner)2079 .expect("old owner does present in refungible")2080 .owner = new_owner.clone();2081 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);20822083 // update index collection2084 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;2085 } else {2086 new_full_item2087 .owner2088 .iter_mut()2089 .find(|i| i.owner == owner)2090 .expect("old owner does present in refungible")2091 .fraction -= value;20922093 // separate amount2094 if new_owner_has_account {2095 // new owner has account2096 new_full_item2097 .owner2098 .iter_mut()2099 .find(|i| i.owner == new_owner)2100 .expect("new owner has account")2101 .fraction += value;2102 } else {2103 // new owner do not have account2104 new_full_item.owner.push(Ownership {2105 owner: new_owner.clone(),2106 fraction: value,2107 });2108 Self::add_token_index(collection_id, item_id, &new_owner)?;2109 }21102111 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);2112 }21132114 Self::deposit_event(RawEvent::Transfer(2115 collection.id,2116 item_id,2117 owner,2118 new_owner,2119 amount,2120 ));21212122 Ok(())2123 }21242125 fn transfer_nft(2126 collection: &CollectionHandle<T>,2127 item_id: TokenId,2128 sender: T::CrossAccountId,2129 new_owner: T::CrossAccountId,2130 ) -> DispatchResult {2131 let collection_id = collection.id;2132 let mut item =2133 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;21342135 ensure!(sender == item.owner, Error::<T>::MustBeTokenOwner);21362137 // update balance2138 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())2139 .checked_sub(1)2140 .ok_or(Error::<T>::NumOverflow)?;2141 <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);21422143 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())2144 .checked_add(1)2145 .ok_or(Error::<T>::NumOverflow)?;2146 <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);21472148 // change owner2149 let old_owner = item.owner.clone();2150 item.owner = new_owner.clone();2151 <NftItemList<T>>::insert(collection_id, item_id, item);21522153 // update index collection2154 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;21552156 collection.log(ERC721Events::Transfer {2157 from: *sender.as_eth(),2158 to: *new_owner.as_eth(),2159 token_id: item_id.into(),2160 })?;2161 Self::deposit_event(RawEvent::Transfer(2162 collection.id,2163 item_id,2164 sender,2165 new_owner,2166 1,2167 ));21682169 Ok(())2170 }21712172 fn set_re_fungible_variable_data(2173 collection: &CollectionHandle<T>,2174 item_id: TokenId,2175 data: Vec<u8>,2176 ) -> DispatchResult {2177 let collection_id = collection.id;2178 let mut item = <ReFungibleItemList<T>>::get(collection_id, item_id)2179 .ok_or(Error::<T>::TokenNotFound)?;21802181 item.variable_data = data;21822183 <ReFungibleItemList<T>>::insert(collection_id, item_id, item);21842185 Ok(())2186 }21872188 fn set_nft_variable_data(2189 collection: &CollectionHandle<T>,2190 item_id: TokenId,2191 data: Vec<u8>,2192 ) -> DispatchResult {2193 let collection_id = collection.id;2194 let mut item =2195 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;21962197 item.variable_data = data;21982199 <NftItemList<T>>::insert(collection_id, item_id, item);22002201 Ok(())2202 }22032204 #[allow(dead_code)]2205 fn init_collection(item: &Collection<T>) {2206 // check params2207 assert!(2208 item.decimal_points <= MAX_DECIMAL_POINTS,2209 "decimal_points parameter must be lower than MAX_DECIMAL_POINTS"2210 );2211 assert!(2212 item.name.len() <= 64,2213 "Collection name can not be longer than 63 char"2214 );2215 assert!(2216 item.name.len() <= 256,2217 "Collection description can not be longer than 255 char"2218 );2219 assert!(2220 item.token_prefix.len() <= 16,2221 "Token prefix can not be longer than 15 char"2222 );22232224 // Generate next collection ID2225 let next_id = CreatedCollectionCount::get().checked_add(1).unwrap();22262227 CreatedCollectionCount::put(next_id);2228 }22292230 #[allow(dead_code)]2231 fn init_nft_token(collection_id: CollectionId, item: &NftItemType<T::CrossAccountId>) {2232 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();22332234 Self::add_token_index(collection_id, current_index, &item.owner).unwrap();22352236 <ItemListIndex>::insert(collection_id, current_index);22372238 // Update balance2239 let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())2240 .checked_add(1)2241 .unwrap();2242 <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);2243 }22442245 #[allow(dead_code)]2246 fn init_fungible_token(2247 collection_id: CollectionId,2248 owner: &T::CrossAccountId,2249 item: &FungibleItemType,2250 ) {2251 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();22522253 Self::add_token_index(collection_id, current_index, owner).unwrap();22542255 <ItemListIndex>::insert(collection_id, current_index);22562257 // Update balance2258 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())2259 .checked_add(item.value)2260 .unwrap();2261 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);2262 }22632264 #[allow(dead_code)]2265 fn init_refungible_token(2266 collection_id: CollectionId,2267 item: &ReFungibleItemType<T::CrossAccountId>,2268 ) {2269 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();22702271 let value = item.owner.first().unwrap().fraction;2272 let owner = item.owner.first().unwrap().owner.clone();22732274 Self::add_token_index(collection_id, current_index, &owner).unwrap();22752276 <ItemListIndex>::insert(collection_id, current_index);22772278 // Update balance2279 let new_balance = <Balance<T>>::get(collection_id, &owner.as_sub())2280 .checked_add(value)2281 .unwrap();2282 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);2283 }22842285 fn add_token_index(2286 collection_id: CollectionId,2287 item_index: TokenId,2288 owner: &T::CrossAccountId,2289 ) -> DispatchResult {2290 // add to account limit2291 if <AccountItemCount<T>>::contains_key(owner.as_sub()) {2292 // bound Owned tokens by a single address2293 let count = <AccountItemCount<T>>::get(owner.as_sub());2294 ensure!(2295 count < ChainLimit::get().account_token_ownership_limit,2296 Error::<T>::AddressOwnershipLimitExceeded2297 );22982299 <AccountItemCount<T>>::insert(2300 owner.as_sub(),2301 count.checked_add(1).ok_or(Error::<T>::NumOverflow)?,2302 );2303 } else {2304 <AccountItemCount<T>>::insert(owner.as_sub(), 1);2305 }23062307 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.as_sub());2308 if list_exists {2309 let mut list = <AddressTokens<T>>::get(collection_id, owner.as_sub());2310 let item_contains = list.contains(&item_index.clone());23112312 if !item_contains {2313 list.push(item_index);2314 }23152316 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), list);2317 } else {2318 let itm = vec![item_index];2319 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), itm);2320 }23212322 Ok(())2323 }23242325 fn remove_token_index(2326 collection_id: CollectionId,2327 item_index: TokenId,2328 owner: &T::CrossAccountId,2329 ) -> DispatchResult {2330 // update counter2331 <AccountItemCount<T>>::insert(2332 owner.as_sub(),2333 <AccountItemCount<T>>::get(owner.as_sub())2334 .checked_sub(1)2335 .ok_or(Error::<T>::NumOverflow)?,2336 );23372338 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.as_sub());2339 if list_exists {2340 let mut list = <AddressTokens<T>>::get(collection_id, owner.as_sub());2341 let item_contains = list.contains(&item_index.clone());23422343 if item_contains {2344 list.retain(|&item| item != item_index);2345 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), list);2346 }2347 }23482349 Ok(())2350 }23512352 fn move_token_index(2353 collection_id: CollectionId,2354 item_index: TokenId,2355 old_owner: &T::CrossAccountId,2356 new_owner: &T::CrossAccountId,2357 ) -> DispatchResult {2358 Self::remove_token_index(collection_id, item_index, old_owner)?;2359 Self::add_token_index(collection_id, item_index, new_owner)?;23602361 Ok(())2362 }2363}23642365sp_api::decl_runtime_apis! {2366 pub trait NftApi {2367 /// Used for ethereum integration2368 fn eth_contract_code(account: H160) -> Option<Vec<u8>>;2369 }2370}pallets/nft/src/mock.rsdiffbeforeafterboth--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -74,6 +74,8 @@
type ExistentialDeposit = ExistentialDeposit;
type WeightInfo = ();
type MaxLocks = MaxLocks;
+ type MaxReserves = ();
+ type ReserveIdentifier = [u8; 8];
}
parameter_types! {
@@ -99,41 +101,6 @@
type Timestamp = pallet_timestamp::Pallet<Test>;
type Randomness = pallet_randomness_collective_flip::Pallet<Test>;
-
-parameter_types! {
- pub const TombstoneDeposit: u64 = 1;
- pub const DepositPerContract: u64 = 1;
- pub const DepositPerStorageByte: u64 = 1;
- pub const DepositPerStorageItem: u64 = 1;
- pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * 24 * 60 * 10);
- pub const SurchargeReward: u64 = 1;
- pub const SignedClaimHandicap: u32 = 2;
- pub DeletionWeightLimit: u64 = u64::MAX;//Perbill::from_percent(10);
- pub DeletionQueueDepth: u32 = 10;
- pub Schedule: pallet_contracts::Schedule<Test> = Default::default();
-}
-
-impl pallet_contracts::Config for Test {
- type Time = Timestamp;
- type Randomness = Randomness;
- type Currency = pallet_balances::Pallet<Test>;
- type Event = ();
- type RentPayment = ();
- type SignedClaimHandicap = SignedClaimHandicap;
- type TombstoneDeposit = TombstoneDeposit;
- type DepositPerContract = DepositPerContract;
- type DepositPerStorageByte = DepositPerStorageByte;
- type DepositPerStorageItem = DepositPerStorageItem;
- type RentFraction = RentFraction;
- type SurchargeReward = SurchargeReward;
- type DeletionWeightLimit = DeletionWeightLimit;
- type DeletionQueueDepth = DeletionQueueDepth;
- type ChainExtension = ();
- type WeightPrice = ();
- type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
- type Schedule = Schedule;
- type CallStack = [pallet_contracts::Frame<Self>; 31];
-}
parameter_types! {
pub const CollectionCreationPrice: u32 = 0;
pallets/nft/src/tests.rsdiffbeforeafterboth--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -2351,3 +2351,62 @@
);
});
}
+
+#[test]
+fn collection_transfer_flag_works() {
+ new_test_ext().execute_with(|| {
+ default_limits();
+
+ let origin1 = Origin::signed(1);
+
+ let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ assert_ok!(TemplateModule::set_transfers_enabled_flag(origin1, 1, true));
+
+ let data = default_nft_data();
+ create_test_item(collection_id, &data.into());
+ assert_eq!(TemplateModule::balance_count(1, 1), 1);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+
+ let origin1 = Origin::signed(1);
+
+ // default scenario
+ assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 1000));
+ assert_eq!(TemplateModule::nft_item_id(1, 1).unwrap().owner, account(2));
+ assert_eq!(TemplateModule::balance_count(1, 1), 0);
+ assert_eq!(TemplateModule::balance_count(1, 2), 1);
+
+ assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+ });
+}
+
+#[test]
+fn collection_transfer_flag_works_neg() {
+ new_test_ext().execute_with(|| {
+ default_limits();
+
+ let origin1 = Origin::signed(1);
+
+ let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+ assert_ok!(TemplateModule::set_transfers_enabled_flag(
+ origin1, 1, false
+ ));
+
+ let data = default_nft_data();
+ create_test_item(collection_id, &data.into());
+ assert_eq!(TemplateModule::balance_count(1, 1), 1);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+
+ let origin1 = Origin::signed(1);
+
+ // default scenario
+ assert_noop!(
+ TemplateModule::transfer(origin1, account(2), 1, 1, 1000),
+ Error::<Test>::TransferNotAllowed
+ );
+ assert_eq!(TemplateModule::nft_item_id(1, 1).unwrap().owner, account(1));
+ assert_eq!(TemplateModule::balance_count(1, 1), 1);
+ assert_eq!(TemplateModule::balance_count(1, 2), 0);
+
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+ });
+}
pallets/scheduler/src/lib.rsdiffbeforeafterboth--- a/pallets/scheduler/src/lib.rs
+++ b/pallets/scheduler/src/lib.rs
@@ -947,900 +947,4 @@
fn root() -> OriginCaller {
system::RawOrigin::Root.into()
}
-
- #[test]
- fn basic_scheduling_works() {
- new_test_ext().execute_with(|| {
- let call = Call::Logger(logger::Call::log(42, 1000));
- assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(
- &call
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 127,
- root(),
- call
- ));
- run_to_block(3);
- assert!(logger::log().is_empty());
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(100);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- });
- }
-
- #[test]
- fn schedule_after_works() {
- new_test_ext().execute_with(|| {
- run_to_block(2);
- let call = Call::Logger(logger::Call::log(42, 1000));
- assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(
- &call
- ));
- // This will schedule the call 3 blocks after the next block... so block 3 + 3 = 6
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::After(3),
- None,
- 127,
- root(),
- call
- ));
- run_to_block(5);
- assert!(logger::log().is_empty());
- run_to_block(6);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(100);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- });
- }
-
- #[test]
- fn schedule_after_zero_works() {
- new_test_ext().execute_with(|| {
- run_to_block(2);
- let call = Call::Logger(logger::Call::log(42, 1000));
- assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(
- &call
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::After(0),
- None,
- 127,
- root(),
- call
- ));
- // Will trigger on the next block.
- run_to_block(3);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(100);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- });
- }
-
- #[test]
- fn periodic_scheduling_works() {
- new_test_ext().execute_with(|| {
- // at #4, every 3 blocks, 3 times.
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- Some((3, 3)),
- 127,
- root(),
- Call::Logger(logger::Call::log(42, 1000))
- ));
- run_to_block(3);
- assert!(logger::log().is_empty());
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(6);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(7);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
- run_to_block(9);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
- run_to_block(10);
- assert_eq!(
- logger::log(),
- vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
- );
- run_to_block(100);
- assert_eq!(
- logger::log(),
- vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
- );
- });
- }
-
- #[test]
- fn reschedule_works() {
- new_test_ext().execute_with(|| {
- let call = Call::Logger(logger::Call::log(42, 1000));
- assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(
- &call
- ));
- assert_eq!(
- Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call).unwrap(),
- (4, 0)
- );
-
- run_to_block(3);
- assert!(logger::log().is_empty());
-
- assert_eq!(
- Scheduler::do_reschedule((4, 0), DispatchTime::At(6)).unwrap(),
- (6, 0)
- );
-
- assert_noop!(
- Scheduler::do_reschedule((6, 0), DispatchTime::At(6)),
- Error::<Test>::RescheduleNoChange
- );
-
- run_to_block(4);
- assert!(logger::log().is_empty());
-
- run_to_block(6);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
-
- run_to_block(100);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- });
- }
-
- #[test]
- fn reschedule_named_works() {
- new_test_ext().execute_with(|| {
- let call = Call::Logger(logger::Call::log(42, 1000));
- assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(
- &call
- ));
- assert_eq!(
- Scheduler::do_schedule_named(
- 1u32.encode(),
- DispatchTime::At(4),
- None,
- 127,
- root(),
- call
- )
- .unwrap(),
- (4, 0)
- );
-
- run_to_block(3);
- assert!(logger::log().is_empty());
-
- assert_eq!(
- Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(6)).unwrap(),
- (6, 0)
- );
-
- assert_noop!(
- Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(6)),
- Error::<Test>::RescheduleNoChange
- );
-
- run_to_block(4);
- assert!(logger::log().is_empty());
-
- run_to_block(6);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
-
- run_to_block(100);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- });
- }
-
- #[test]
- fn reschedule_named_perodic_works() {
- new_test_ext().execute_with(|| {
- let call = Call::Logger(logger::Call::log(42, 1000));
- assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(
- &call
- ));
- assert_eq!(
- Scheduler::do_schedule_named(
- 1u32.encode(),
- DispatchTime::At(4),
- Some((3, 3)),
- 127,
- root(),
- call
- )
- .unwrap(),
- (4, 0)
- );
-
- run_to_block(3);
- assert!(logger::log().is_empty());
-
- assert_eq!(
- Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(5)).unwrap(),
- (5, 0)
- );
- assert_eq!(
- Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(6)).unwrap(),
- (6, 0)
- );
-
- run_to_block(5);
- assert!(logger::log().is_empty());
-
- run_to_block(6);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
-
- assert_eq!(
- Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(10)).unwrap(),
- (10, 0)
- );
-
- run_to_block(9);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
-
- run_to_block(10);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
-
- run_to_block(13);
- assert_eq!(
- logger::log(),
- vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
- );
-
- run_to_block(100);
- assert_eq!(
- logger::log(),
- vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
- );
- });
- }
-
- #[test]
- fn cancel_named_scheduling_works_with_normal_cancel() {
- new_test_ext().execute_with(|| {
- // at #4.
- Scheduler::do_schedule_named(
- 1u32.encode(),
- DispatchTime::At(4),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(69, 1000)),
- )
- .unwrap();
- let i = Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(42, 1000)),
- )
- .unwrap();
- run_to_block(3);
- assert!(logger::log().is_empty());
- assert_ok!(Scheduler::do_cancel_named(None, 1u32.encode()));
- assert_ok!(Scheduler::do_cancel(None, i));
- run_to_block(100);
- assert!(logger::log().is_empty());
- });
- }
-
- #[test]
- fn cancel_named_periodic_scheduling_works() {
- new_test_ext().execute_with(|| {
- // at #4, every 3 blocks, 3 times.
- Scheduler::do_schedule_named(
- 1u32.encode(),
- DispatchTime::At(4),
- Some((3, 3)),
- 127,
- root(),
- Call::Logger(logger::Call::log(42, 1000)),
- )
- .unwrap();
- // same id results in error.
- assert!(Scheduler::do_schedule_named(
- 1u32.encode(),
- DispatchTime::At(4),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(69, 1000))
- )
- .is_err());
- // different id is ok.
- Scheduler::do_schedule_named(
- 2u32.encode(),
- DispatchTime::At(8),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(69, 1000)),
- )
- .unwrap();
- run_to_block(3);
- assert!(logger::log().is_empty());
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(6);
- assert_ok!(Scheduler::do_cancel_named(None, 1u32.encode()));
- run_to_block(100);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
- });
- }
-
- #[test]
- fn scheduler_respects_weight_limits() {
- new_test_ext().execute_with(|| {
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
- ));
- // 69 and 42 do not fit together
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 42u32)]);
- run_to_block(5);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
- });
- }
-
- #[test]
- fn scheduler_respects_hard_deadlines_more() {
- new_test_ext().execute_with(|| {
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 0,
- root(),
- Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 0,
- root(),
- Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
- ));
- // With base weights, 69 and 42 should not fit together, but do because of hard deadlines
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
- });
- }
-
- #[test]
- fn scheduler_respects_priority_ordering() {
- new_test_ext().execute_with(|| {
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 1,
- root(),
- Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 0,
- root(),
- Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
- ));
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 69u32), (root(), 42u32)]);
- });
- }
-
- #[test]
- fn scheduler_respects_priority_ordering_with_soft_deadlines() {
- new_test_ext().execute_with(|| {
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 255,
- root(),
- Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3))
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
- ));
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 126,
- root(),
- Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2))
- ));
-
- // 2600 does not fit with 69 or 42, but has higher priority, so will go through
- run_to_block(4);
- assert_eq!(logger::log(), vec![(root(), 2600u32)]);
- // 69 and 42 fit together
- run_to_block(5);
- assert_eq!(
- logger::log(),
- vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]
- );
- });
- }
-
- #[test]
- fn on_initialize_weight_is_correct() {
- new_test_ext().execute_with(|| {
- let base_weight: Weight =
- <Test as frame_system::Config>::DbWeight::get().reads_writes(1, 2);
- let base_multiplier = 0;
- let named_multiplier = <Test as frame_system::Config>::DbWeight::get().writes(1);
- let periodic_multiplier =
- <Test as frame_system::Config>::DbWeight::get().reads_writes(1, 1);
-
- // Named
- assert_ok!(Scheduler::do_schedule_named(
- 1u32.encode(),
- DispatchTime::At(1),
- None,
- 255,
- root(),
- Call::Logger(logger::Call::log(3, MaximumSchedulerWeight::get() / 3))
- ));
- // Anon Periodic
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(1),
- Some((1000, 3)),
- 128,
- root(),
- Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3))
- ));
- // Anon
- assert_ok!(Scheduler::do_schedule(
- DispatchTime::At(1),
- None,
- 127,
- root(),
- Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
- ));
- // Named Periodic
- assert_ok!(Scheduler::do_schedule_named(
- 2u32.encode(),
- DispatchTime::At(1),
- Some((1000, 3)),
- 126,
- root(),
- Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2))
- ));
-
- // Will include the named periodic only
- let actual_weight = Scheduler::on_initialize(1);
- let call_weight = MaximumSchedulerWeight::get() / 2;
- assert_eq!(
- actual_weight,
- call_weight
- + base_weight + base_multiplier
- + named_multiplier + periodic_multiplier
- );
- assert_eq!(logger::log(), vec![(root(), 2600u32)]);
-
- // Will include anon and anon periodic
- let actual_weight = Scheduler::on_initialize(2);
- let call_weight = MaximumSchedulerWeight::get() / 2 + MaximumSchedulerWeight::get() / 3;
- assert_eq!(
- actual_weight,
- call_weight + base_weight + base_multiplier * 2 + periodic_multiplier
- );
- assert_eq!(
- logger::log(),
- vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]
- );
-
- // Will include named only
- let actual_weight = Scheduler::on_initialize(3);
- let call_weight = MaximumSchedulerWeight::get() / 3;
- assert_eq!(
- actual_weight,
- call_weight + base_weight + base_multiplier + named_multiplier
- );
- assert_eq!(
- logger::log(),
- vec![
- (root(), 2600u32),
- (root(), 69u32),
- (root(), 42u32),
- (root(), 3u32)
- ]
- );
-
- // Will contain none
- let actual_weight = Scheduler::on_initialize(4);
- assert_eq!(actual_weight, 0);
- });
- }
-
- #[test]
- fn root_calls_works() {
- new_test_ext().execute_with(|| {
- let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
- let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));
- assert_ok!(Scheduler::schedule_named(
- Origin::root(),
- 1u32.encode(),
- 4,
- None,
- 127,
- call
- ));
- assert_ok!(Scheduler::schedule(Origin::root(), 4, None, 127, call2));
- run_to_block(3);
- // Scheduled calls are in the agenda.
- assert_eq!(Agenda::<Test>::get(4).len(), 2);
- assert!(logger::log().is_empty());
- assert_ok!(Scheduler::cancel_named(Origin::root(), 1u32.encode()));
- assert_ok!(Scheduler::cancel(Origin::root(), 4, 1));
- // Scheduled calls are made NONE, so should not effect state
- run_to_block(100);
- assert!(logger::log().is_empty());
- });
- }
-
- #[test]
- fn fails_to_schedule_task_in_the_past() {
- new_test_ext().execute_with(|| {
- run_to_block(3);
-
- let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
- let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));
-
- assert_err!(
- Scheduler::schedule_named(Origin::root(), 1u32.encode(), 2, None, 127, call),
- Error::<Test>::TargetBlockNumberInPast,
- );
-
- assert_err!(
- Scheduler::schedule(Origin::root(), 2, None, 127, call2.clone()),
- Error::<Test>::TargetBlockNumberInPast,
- );
-
- assert_err!(
- Scheduler::schedule(Origin::root(), 3, None, 127, call2),
- Error::<Test>::TargetBlockNumberInPast,
- );
- });
- }
-
- #[test]
- fn should_use_orign() {
- new_test_ext().execute_with(|| {
- let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
- let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));
- assert_ok!(Scheduler::schedule_named(
- system::RawOrigin::Signed(1).into(),
- 1u32.encode(),
- 4,
- None,
- 127,
- call
- ));
- assert_ok!(Scheduler::schedule(
- system::RawOrigin::Signed(1).into(),
- 4,
- None,
- 127,
- call2
- ));
- run_to_block(3);
- // Scheduled calls are in the agenda.
- assert_eq!(Agenda::<Test>::get(4).len(), 2);
- assert!(logger::log().is_empty());
- assert_ok!(Scheduler::cancel_named(
- system::RawOrigin::Signed(1).into(),
- 1u32.encode()
- ));
- assert_ok!(Scheduler::cancel(system::RawOrigin::Signed(1).into(), 4, 1));
- // Scheduled calls are made NONE, so should not effect state
- run_to_block(100);
- assert!(logger::log().is_empty());
- });
- }
-
- #[test]
- fn should_check_orign() {
- new_test_ext().execute_with(|| {
- let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
- let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));
- assert_noop!(
- Scheduler::schedule_named(
- system::RawOrigin::Signed(2).into(),
- 1u32.encode(),
- 4,
- None,
- 127,
- call
- ),
- BadOrigin
- );
- assert_noop!(
- Scheduler::schedule(system::RawOrigin::Signed(2).into(), 4, None, 127, call2),
- BadOrigin
- );
- });
- }
-
- #[test]
- fn should_check_orign_for_cancel() {
- new_test_ext().execute_with(|| {
- let call = Box::new(Call::Logger(logger::Call::log_without_filter(69, 1000)));
- let call2 = Box::new(Call::Logger(logger::Call::log_without_filter(42, 1000)));
- assert_ok!(Scheduler::schedule_named(
- system::RawOrigin::Signed(1).into(),
- 1u32.encode(),
- 4,
- None,
- 127,
- call
- ));
- assert_ok!(Scheduler::schedule(
- system::RawOrigin::Signed(1).into(),
- 4,
- None,
- 127,
- call2
- ));
- run_to_block(3);
- // Scheduled calls are in the agenda.
- assert_eq!(Agenda::<Test>::get(4).len(), 2);
- assert!(logger::log().is_empty());
- assert_noop!(
- Scheduler::cancel_named(system::RawOrigin::Signed(2).into(), 1u32.encode()),
- BadOrigin
- );
- assert_noop!(
- Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1),
- BadOrigin
- );
- assert_noop!(
- Scheduler::cancel_named(system::RawOrigin::Root.into(), 1u32.encode()),
- BadOrigin
- );
- assert_noop!(
- Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1),
- BadOrigin
- );
- run_to_block(5);
- assert_eq!(
- logger::log(),
- vec![
- (system::RawOrigin::Signed(1).into(), 69u32),
- (system::RawOrigin::Signed(1).into(), 42u32)
- ]
- );
- });
- }
-
- #[test]
- fn migration_to_v2_works() {
- new_test_ext().execute_with(|| {
- for i in 0..3u64 {
- let k = i.twox_64_concat();
- let old = vec![
- Some(ScheduledV1 {
- maybe_id: None,
- priority: i as u8 + 10,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- }),
- None,
- Some(ScheduledV1 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- }),
- ];
- frame_support::migration::put_storage_value(b"Scheduler", b"Agenda", &k, old);
- }
-
- assert_eq!(StorageVersion::get(), Releases::V1);
-
- assert!(Scheduler::migrate_v1_to_t2());
-
- assert_eq_uvec!(
- Agenda::<Test>::iter().collect::<Vec<_>>(),
- vec![
- (
- 0,
- vec![
- Some(ScheduledV2 {
- maybe_id: None,
- priority: 10,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- origin: root(),
- _phantom: PhantomData::<u64>::default(),
- }),
- None,
- Some(ScheduledV2 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- origin: root(),
- _phantom: PhantomData::<u64>::default(),
- }),
- ]
- ),
- (
- 1,
- vec![
- Some(ScheduledV2 {
- maybe_id: None,
- priority: 11,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- origin: root(),
- _phantom: PhantomData::<u64>::default(),
- }),
- None,
- Some(ScheduledV2 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- origin: root(),
- _phantom: PhantomData::<u64>::default(),
- }),
- ]
- ),
- (
- 2,
- vec![
- Some(ScheduledV2 {
- maybe_id: None,
- priority: 12,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- origin: root(),
- _phantom: PhantomData::<u64>::default(),
- }),
- None,
- Some(ScheduledV2 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- origin: root(),
- _phantom: PhantomData::<u64>::default(),
- }),
- ]
- )
- ]
- );
-
- assert_eq!(StorageVersion::get(), Releases::V2);
- });
- }
-
- #[test]
- fn test_migrate_origin() {
- new_test_ext().execute_with(|| {
- for i in 0..3u64 {
- let k = i.twox_64_concat();
- let old: Vec<Option<Scheduled<_, _, u32, u64>>> = vec![
- Some(Scheduled {
- maybe_id: None,
- priority: i as u8 + 10,
- call: Call::Logger(logger::Call::log(96, 100)),
- origin: 3u32,
- maybe_periodic: None,
- _phantom: Default::default(),
- }),
- None,
- Some(Scheduled {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- origin: 2u32,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- _phantom: Default::default(),
- }),
- ];
- frame_support::migration::put_storage_value(b"Scheduler", b"Agenda", &k, old);
- }
-
- impl From<u32> for OriginCaller {
- fn from(value: u32) -> Self {
- match value {
- 3 => system::RawOrigin::Root.into(),
- 2 => system::RawOrigin::None.into(),
- _ => unimplemented!(),
- }
- }
- }
-
- Scheduler::migrate_origin::<u32>();
-
- assert_eq_uvec!(
- Agenda::<Test>::iter().collect::<Vec<_>>(),
- vec![
- (
- 0,
- vec![
- Some(ScheduledV2::<_, _, OriginCaller, u64> {
- maybe_id: None,
- priority: 10,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- origin: system::RawOrigin::Root.into(),
- _phantom: PhantomData::<u64>::default(),
- }),
- None,
- Some(ScheduledV2 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- origin: system::RawOrigin::None.into(),
- _phantom: PhantomData::<u64>::default(),
- }),
- ]
- ),
- (
- 1,
- vec![
- Some(ScheduledV2 {
- maybe_id: None,
- priority: 11,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- origin: system::RawOrigin::Root.into(),
- _phantom: PhantomData::<u64>::default(),
- }),
- None,
- Some(ScheduledV2 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- origin: system::RawOrigin::None.into(),
- _phantom: PhantomData::<u64>::default(),
- }),
- ]
- ),
- (
- 2,
- vec![
- Some(ScheduledV2 {
- maybe_id: None,
- priority: 12,
- call: Call::Logger(logger::Call::log(96, 100)),
- maybe_periodic: None,
- origin: system::RawOrigin::Root.into(),
- _phantom: PhantomData::<u64>::default(),
- }),
- None,
- Some(ScheduledV2 {
- maybe_id: Some(b"test".to_vec()),
- priority: 123,
- call: Call::Logger(logger::Call::log(69, 1000)),
- maybe_periodic: Some((456u64, 10)),
- origin: system::RawOrigin::None.into(),
- _phantom: PhantomData::<u64>::default(),
- }),
- ]
- )
- ]
- );
- });
- }
}
primitives/nft/src/lib.rsdiffbeforeafterboth--- a/primitives/nft/src/lib.rs
+++ b/primitives/nft/src/lib.rs
@@ -144,6 +144,7 @@
pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions
pub variable_on_chain_schema: Vec<u8>, //
pub const_on_chain_schema: Vec<u8>, //
+ pub transfers_enabled: bool,
}
#[derive(Encode, Decode, Debug, Clone, PartialEq)]
runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -154,7 +154,7 @@
transaction_version: 1,
};
-pub const MILLISECS_PER_BLOCK: u64 = 12000;
+pub const MILLISECS_PER_BLOCK: u64 = 1200;
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
@@ -449,7 +449,7 @@
}
impl pallet_transaction_payment::Config for Runtime {
- type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, ()>;
+ type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = LinearFee<Balance>;
type FeeMultiplierUpdate = ();
runtime_types.jsondiffbeforeafterboth--- a/runtime_types.json
+++ b/runtime_types.json
@@ -62,7 +62,8 @@
"Sponsorship": "SponsorshipState",
"Limits": "CollectionLimits",
"VariableOnChainSchema": "Vec<u8>",
- "ConstOnChainSchema": "Vec<u8>"
+ "ConstOnChainSchema": "Vec<u8>",
+ "TransfersEnabled": "bool"
},
"RawData": "Vec<u8>",
"Address": "MultiAddress",
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -1,12 +1,12 @@
{
- "name": "NftTests",
+ "name": "nfttests",
"version": "1.0.0",
"description": "Substrate Nft tests",
"main": "",
"devDependencies": {
"@polkadot/dev": "0.62.43",
"@polkadot/ts": "0.3.89",
- "@polkadot/typegen": "4.15.1",
+ "@polkadot/typegen": "5.0.1",
"@types/chai": "^4.2.17",
"@types/chai-as-promised": "^7.1.3",
"@types/mocha": "^8.2.2",
@@ -59,15 +59,15 @@
"testSetVariableMetadataSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetadataSponsoringRateLimit.test.ts",
"testInflation": "mocha --timeout 9999999 -r ts-node/register ./**/inflation.test.ts",
"testPalletPresence": "mocha --timeout 9999999 -r ts-node/register ./**/pallet-presence.test.ts",
- "testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts"
+ "testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
+ "testEnableDisableTransfers": "mocha --timeout 9999999 -r ts-node/register ./**/enableDisableTransfer.test.ts"
},
"author": "",
"license": "SEE LICENSE IN ../LICENSE",
"homepage": "",
"dependencies": {
- "@polkadot/api": "4.15.1",
- "@polkadot/api-contract": "4.15.1",
- "@polkadot/util": "6.9.1",
+ "@polkadot/api": "5.0.1",
+ "@polkadot/api-contract": "5.0.1",
"bignumber.js": "^9.0.1",
"chai-as-promised": "^7.1.1",
"solc": "^0.8.6",
tests/src/addCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/addCollectionAdmin.test.ts
+++ b/tests/src/addCollectionAdmin.test.ts
@@ -22,7 +22,7 @@
const bob = privateKey('//Bob');
const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
- expect(collection.Owner).to.be.deep.eq(normalizeAccountId(alice.address));
+ expect(collection.Owner).to.be.equal(alice.address);
const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
await submitTransactionAsync(alice, changeAdminTx);
@@ -40,7 +40,7 @@
const Charlie = privateKey('//CHARLIE');
const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
- expect(collection.Owner).to.be.deep.eq(normalizeAccountId(Alice.address));
+ expect(collection.Owner).to.be.equal(Alice.address);
const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
await submitTransactionAsync(Alice, changeAdminTx);
tests/src/addToContractWhiteList.test.tsdiffbeforeafterboth--- a/tests/src/addToContractWhiteList.test.ts
+++ b/tests/src/addToContractWhiteList.test.ts
@@ -17,7 +17,7 @@
chai.use(chaiAsPromised);
const expect = chai.expect;
-describe('Integration Test addToContractWhiteList', () => {
+describe.skip('Integration Test addToContractWhiteList', () => {
it('Add an address to a contract white list', async () => {
await usingApi(async api => {
@@ -56,7 +56,7 @@
});
});
-describe('Negative Integration Test addToContractWhiteList', () => {
+describe.skip('Negative Integration Test addToContractWhiteList', () => {
it('Add an address to a white list of a non-contract', async () => {
await usingApi(async api => {
tests/src/change-collection-owner.test.tsdiffbeforeafterboth--- a/tests/src/change-collection-owner.test.ts
+++ b/tests/src/change-collection-owner.test.ts
@@ -7,26 +7,26 @@
import chaiAsPromised from 'chai-as-promised';
import privateKey from './substrate/privateKey';
import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';
-import { createCollectionExpectSuccess, normalizeAccountId } from './util/helpers';
+import { createCollectionExpectSuccess } from './util/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
describe('Integration Test changeCollectionOwner(collection_id, new_owner):', () => {
- it('Changing owner changes owner.', async () => {
+ it('Changing owner changes owner address', async () => {
await usingApi(async api => {
const collectionId = await createCollectionExpectSuccess();
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
- expect(collection.Owner).to.be.deep.eq(normalizeAccountId(alice.address));
+ expect(collection.Owner).to.be.deep.eq(alice.address);
- const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, normalizeAccountId(bob.address));
+ const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await submitTransactionAsync(alice, changeOwnerTx);
const collectionAfterOwnerChange: any = (await api.query.nft.collectionById(collectionId)).toJSON();
- expect(collectionAfterOwnerChange.Owner).to.be.deep.eq(normalizeAccountId(bob.address));
+ expect(collectionAfterOwnerChange.Owner).to.be.deep.eq(bob.address);
});
});
});
@@ -38,23 +38,23 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, normalizeAccountId(bob.address));
+ const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;
const collectionAfterOwnerChange: any = (await api.query.nft.collectionById(collectionId)).toJSON();
- expect(collectionAfterOwnerChange.Owner).to.be.deep.eq(normalizeAccountId(alice.address));
+ expect(collectionAfterOwnerChange.Owner).to.be.deep.eq(alice.address);
// Verifying that nothing bad happened (network is live, new collections can be created, etc.)
await createCollectionExpectSuccess();
});
});
- it('Can\'t change owner of not existing collection.', async () => {
+ it('Can\'t change owner of a non-existing collection.', async () => {
await usingApi(async api => {
const collectionId = (1<<32) - 1;
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, normalizeAccountId(bob.address));
+ const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await expect(submitTransactionExpectFailAsync(alice, changeOwnerTx)).to.be.rejected;
// Verifying that nothing bad happened (network is live, new collections can be created, etc.)
tests/src/confirmSponsorship.test.tsdiffbeforeafterboth--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -226,7 +226,7 @@
const result1 = getGenericResult(events1);
const AsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
- await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
+ await expect(submitTransactionExpectFailAsync(zeroBalance, zeroToAlice)).to.be.rejected;
const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
// Try again after Zero gets some balance - now it should succeed
@@ -327,7 +327,7 @@
});
-describe('(!negative test!) integration test: ext. removeCollectionSponsor():', () => {
+describe('(!negative test!) integration test: ext. confirmSponsorship():', () => {
before(async () => {
await usingApi(async () => {
const keyring = new Keyring({ type: 'sr25519' });
tests/src/contracts.test.tsdiffbeforeafterboth--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -36,7 +36,7 @@
const gasLimit = 9000n * 1000000n;
const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';
-describe('Contracts', () => {
+describe.skip('Contracts', () => {
it('Can deploy smart contract Flipper, instantiate it and call it\'s get and flip messages.', async () => {
await usingApi(async api => {
const [contract, deployer] = await deployFlipper(api);
@@ -62,7 +62,7 @@
});
});
-describe.only('Chain extensions', () => {
+describe.skip('Chain extensions', () => {
it('Transfer CE', async () => {
await usingApi(async api => {
const alice = privateKey('//Alice');
tests/src/enableContractSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/enableContractSponsoring.test.ts
+++ b/tests/src/enableContractSponsoring.test.ts
@@ -19,7 +19,7 @@
chai.use(chaiAsPromised);
const expect = chai.expect;
-describe('Integration Test enableContractSponsoring', () => {
+describe.skip('Integration Test enableContractSponsoring', () => {
it('ensure tx fee is paid from endowment', async () => {
await usingApi(async (api) => {
const user = await findUnusedAddress(api);
@@ -64,7 +64,7 @@
});
-describe('Negative Integration Test enableContractSponsoring', () => {
+describe.skip('Negative Integration Test enableContractSponsoring', () => {
let alice: IKeyringPair;
before(async () => {
tests/src/enableDisableTransfer.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/enableDisableTransfer.test.ts
@@ -0,0 +1,64 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from './substrate/privateKey';
+import usingApi from './substrate/substrate-api';
+import {
+ createItemExpectSuccess,
+ createCollectionExpectSuccess,
+ transferExpectSuccess,
+ transferExpectFailure,
+ setTransferFlagExpectSuccess,
+ setTransferFlagExpectFailure,
+} from './util/helpers';
+
+chai.use(chaiAsPromised);
+
+describe('Enable/Disable Transfers', () => {
+ it('User can transfer token with enabled transfer flag', async () => {
+ await usingApi(async () => {
+ const Alice = privateKey('//Alice');
+ const Bob = privateKey('//Bob');
+ // nft
+ const nftCollectionId = await createCollectionExpectSuccess();
+ const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
+
+ // explicitely set transfer flag
+ await setTransferFlagExpectSuccess(Alice, nftCollectionId, true);
+
+ await transferExpectSuccess(nftCollectionId, newNftTokenId, Alice, Bob, 1);
+ });
+ });
+
+ it('User can\'n transfer token with disabled transfer flag', async () => {
+ await usingApi(async () => {
+ const Alice = privateKey('//Alice');
+ const Bob = privateKey('//Bob');
+ // nft
+ const nftCollectionId = await createCollectionExpectSuccess();
+ const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
+
+ // explicitely set transfer flag
+ await setTransferFlagExpectSuccess(Alice, nftCollectionId, false);
+
+ await transferExpectFailure(nftCollectionId, newNftTokenId, Alice, Bob, 1);
+ });
+ });
+});
+
+describe('Negative Enable/Disable Transfers', () => {
+ it('Non-owner cannot change transfer flag', async () => {
+ await usingApi(async () => {
+ const Bob = privateKey('//Bob');
+ // nft
+ const nftCollectionId = await createCollectionExpectSuccess();
+
+ // Change transfer flag
+ await setTransferFlagExpectFailure(Bob, nftCollectionId, false);
+ });
+ });
+});
tests/src/overflow.test.tsdiffbeforeafterboth--- a/tests/src/overflow.test.ts
+++ b/tests/src/overflow.test.ts
@@ -8,7 +8,7 @@
import chaiAsPromised from 'chai-as-promised';
import privateKey from './substrate/privateKey';
import usingApi from './substrate/substrate-api';
-import { approveExpectFail, approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, getAllowance, getFungibleBalance, transferExpectFail, transferExpectSuccess, transferFromExpectFail, transferFromExpectSuccess, U128_MAX } from './util/helpers';
+import { approveExpectFail, approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, getAllowance, getFungibleBalance, transferExpectFailure, transferExpectSuccess, transferFromExpectFail, transferFromExpectSuccess, U128_MAX } from './util/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -33,7 +33,7 @@
await transferExpectSuccess(fungibleCollectionId, 0, alice, bob, U128_MAX, 'Fungible');
await createFungibleItemExpectSuccess(alice, fungibleCollectionId, { Value: 1n });
- await transferExpectFail(fungibleCollectionId, 0, alice, bob, 1, 'Fungible');
+ await transferExpectFailure(fungibleCollectionId, 0, alice, bob, 1);
expect(await getFungibleBalance(fungibleCollectionId, alice.address)).to.equal(1n);
expect(await getFungibleBalance(fungibleCollectionId, bob.address)).to.equal(U128_MAX);
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -13,13 +13,33 @@
// Pallets that must always be present
const requiredPallets = [
- 'nft', 'inflation', 'balances', 'contracts', 'randomnesscollectiveflip', 'system', 'timestamp', 'transactionpayment', 'treasury', 'vesting', 'evm', 'ethereum',
- 'scheduler', 'nftpayment', 'charging',
+ 'balances',
+ 'randomnesscollectiveflip',
+ 'timestamp',
+ 'transactionpayment',
+ 'treasury',
+ 'system',
+ 'vesting',
+ 'parachainsystem',
+ 'parachaininfo',
+ 'evm',
+ 'ethereum',
+ 'xcmpqueue',
+ 'polkadotxcm',
+ 'cumulusxcm',
+ 'dmpqueue',
+ 'inflation',
+ 'nft',
+ 'scheduler',
+ 'nftpayment',
+ 'charging',
];
// Pallets that depend on consensus and governance configuration
const consensusPallets = [
- 'sudo', 'aura',
+ 'sudo',
+ 'aura',
+ 'auraext',
];
describe('Pallet presence', () => {
tests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionAdmin.test.ts
+++ b/tests/src/removeCollectionAdmin.test.ts
@@ -20,7 +20,7 @@
const Alice = privateKey('//Alice');
const Bob = privateKey('//Bob');
const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
- expect(collection.Owner).to.be.deep.eq(normalizeAccountId(Alice.address));
+ expect(collection.Owner).to.be.deep.eq(Alice.address);
// first - add collection admin Bob
const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
await submitTransactionAsync(Alice, addAdminTx);
tests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionSponsor.test.ts
+++ b/tests/src/removeCollectionSponsor.test.ts
@@ -38,7 +38,7 @@
});
});
- it('Remove NFT collection sponsor stops sponsorship', async () => {
+ it('Removing NFT collection sponsor stops sponsorship', async () => {
const collectionId = await createCollectionExpectSuccess();
await setCollectionSponsorExpectSuccess(collectionId, bob.address);
await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
tests/src/removeFromContractWhiteList.test.tsdiffbeforeafterboth--- a/tests/src/removeFromContractWhiteList.test.ts
+++ b/tests/src/removeFromContractWhiteList.test.ts
@@ -10,7 +10,7 @@
import { IKeyringPair } from '@polkadot/types/types';
import { expect } from 'chai';
-describe('Integration Test removeFromContractWhiteList', () => {
+describe.skip('Integration Test removeFromContractWhiteList', () => {
let bob: IKeyringPair;
before(async () => {
@@ -54,7 +54,7 @@
});
});
-describe('Negative Integration Test removeFromContractWhiteList', () => {
+describe.skip('Negative Integration Test removeFromContractWhiteList', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
tests/src/scheduler.test.tsdiffbeforeafterboth--- a/tests/src/scheduler.test.ts
+++ b/tests/src/scheduler.test.ts
@@ -28,7 +28,7 @@
await setCollectionSponsorExpectSuccess(nftCollectionId, Alice.address);
await confirmSponsorshipExpectSuccess(nftCollectionId);
- await scheduleTransferExpectSuccess(nftCollectionId, newNftTokenId, Alice, Bob, 1, 'NFT');
+ await scheduleTransferExpectSuccess(nftCollectionId, newNftTokenId, Alice, Bob, 1, 6000, 4);
});
});
});
tests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth--- a/tests/src/setConstOnChainSchema.test.ts
+++ b/tests/src/setConstOnChainSchema.test.ts
@@ -11,7 +11,6 @@
import {
createCollectionExpectSuccess,
destroyCollectionExpectSuccess,
- normalizeAccountId,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -38,7 +37,7 @@
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
- expect(collection.Owner).to.be.deep.eq(normalizeAccountId(Alice.address));
+ expect(collection.Owner).to.be.eq(Alice.address);
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, Shema);
await submitTransactionAsync(Alice, setShema);
});
@@ -88,7 +87,7 @@
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
- expect(collection.Owner).to.be.deep.eq(normalizeAccountId(Alice.address));
+ expect(collection.Owner).to.be.eq(Alice.address);
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, Shema);
await expect(submitTransactionExpectFailAsync(Bob, setShema)).to.be.rejected;
});
tests/src/setContractSponsoringRateLimit.test.tsdiffbeforeafterboth--- a/tests/src/setContractSponsoringRateLimit.test.ts
+++ b/tests/src/setContractSponsoringRateLimit.test.ts
@@ -15,7 +15,7 @@
setContractSponsoringRateLimitExpectSuccess,
} from './util/helpers';
-describe('Integration Test setContractSponsoringRateLimit', () => {
+describe.skip('Integration Test setContractSponsoringRateLimit', () => {
it('ensure sponsored contract can\'t be called twice without pause for free', async () => {
await usingApi(async (api) => {
const user = await findUnusedAddress(api);
@@ -42,7 +42,7 @@
});
});
-describe('Negative Integration Test setContractSponsoringRateLimit', () => {
+describe.skip('Negative Integration Test setContractSponsoringRateLimit', () => {
let alice: IKeyringPair;
before(async () => {
tests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth--- a/tests/src/setVariableOnChainSchema.test.ts
+++ b/tests/src/setVariableOnChainSchema.test.ts
@@ -11,7 +11,6 @@
import {
createCollectionExpectSuccess,
destroyCollectionExpectSuccess,
- normalizeAccountId,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -38,7 +37,7 @@
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
- expect(collection.Owner).to.be.deep.eq(normalizeAccountId(Alice.address));
+ expect(collection.Owner).to.be.eq(Alice.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
await submitTransactionAsync(Alice, setSchema);
});
@@ -88,7 +87,7 @@
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
- expect(collection.Owner).to.be.deep.eq(normalizeAccountId(Alice.address));
+ expect(collection.Owner).to.be.eq(Alice.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
await expect(submitTransactionExpectFailAsync(Bob, setSchema)).to.be.rejected;
});
tests/src/substrate/substrate-api.tsdiffbeforeafterboth--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -33,11 +33,20 @@
// TODO: Remove, this is temporary: Filter unneeded API output
// (Jaco promised it will be removed in the next version)
const consoleErr = console.error;
- console.error = (message: string) => {
- if (!message.includes('StorageChangeSet:: WebSocket is not connected') || message.includes('2021-'))
+ const consoleLog = console.log;
+ const consoleWarn = console.warn;
+
+ const outFn = (message: string) => {
+ if (!message.includes('StorageChangeSet:: WebSocket is not connected') &&
+ !message.includes('2021-') &&
+ !message.includes('StorageChangeSet:: Normal connection closure'))
consoleErr(message);
};
+ console.error = outFn;
+ console.log = outFn;
+ console.warn = outFn;
+
try {
await promisifySubstrate(api, async () => {
if (api) {
@@ -48,6 +57,8 @@
} finally {
await api.disconnect();
console.error = consoleErr;
+ console.log = consoleLog;
+ console.warn = consoleWarn;
}
return result as T;
}
tests/src/toggleContractWhiteList.test.tsdiffbeforeafterboth--- a/tests/src/toggleContractWhiteList.test.ts
+++ b/tests/src/toggleContractWhiteList.test.ts
@@ -21,7 +21,7 @@
const value = 0;
const gasLimit = 3000n * 1000000n;
-describe('Integration Test toggleContractWhiteList', () => {
+describe.skip('Integration Test toggleContractWhiteList', () => {
it('Enable white list contract mode', async () => {
await usingApi(async api => {
@@ -121,7 +121,7 @@
});
-describe('Negative Integration Test toggleContractWhiteList', () => {
+describe.skip('Negative Integration Test toggleContractWhiteList', () => {
it('Enable white list for a non-contract', async () => {
await usingApi(async api => {
tests/src/transfer.test.tsdiffbeforeafterboth--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -16,7 +16,7 @@
findUnusedAddress,
getCreateCollectionResult,
getCreateItemResult,
- transferExpectFail,
+ transferExpectFailure,
transferExpectSuccess,
} from './util/helpers';
@@ -103,13 +103,13 @@
await usingApi(async (api) => {
// nft
const nftCollectionCount = await api.query.nft.createdCollectionCount() as unknown as number;
- await transferExpectFail(nftCollectionCount + 1, 1, Alice, Bob, 1);
+ await transferExpectFailure(nftCollectionCount + 1, 1, Alice, Bob, 1);
// fungible
const fungibleCollectionCount = await api.query.nft.createdCollectionCount() as unknown as number;
- await transferExpectFail(fungibleCollectionCount + 1, 1, Alice, Bob, 1);
+ await transferExpectFailure(fungibleCollectionCount + 1, 1, Alice, Bob, 1);
// reFungible
const reFungibleCollectionCount = await api.query.nft.createdCollectionCount() as unknown as number;
- await transferExpectFail(reFungibleCollectionCount + 1, 1, Alice, Bob, 1);
+ await transferExpectFailure(reFungibleCollectionCount + 1, 1, Alice, Bob, 1);
});
});
it('Transfer with deleted collection_id', async () => {
@@ -117,43 +117,41 @@
const nftCollectionId = await createCollectionExpectSuccess();
const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
await destroyCollectionExpectSuccess(nftCollectionId);
- await transferExpectFail(nftCollectionId, newNftTokenId, Alice, Bob, 1, 'NFT');
+ await transferExpectFailure(nftCollectionId, newNftTokenId, Alice, Bob, 1);
// fungible
const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');
await destroyCollectionExpectSuccess(fungibleCollectionId);
- await transferExpectFail(fungibleCollectionId, newFungibleTokenId, Alice, Bob, 1, 'Fungible');
+ await transferExpectFailure(fungibleCollectionId, newFungibleTokenId, Alice, Bob, 1);
// reFungible
const reFungibleCollectionId = await
createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
await destroyCollectionExpectSuccess(reFungibleCollectionId);
- await transferExpectFail(
+ await transferExpectFailure(
reFungibleCollectionId,
newReFungibleTokenId,
Alice,
Bob,
1,
- 'ReFungible',
);
});
it('Transfer with not existed item_id', async () => {
// nft
const nftCollectionId = await createCollectionExpectSuccess();
- await transferExpectFail(nftCollectionId, 2, Alice, Bob, 1, 'NFT');
+ await transferExpectFailure(nftCollectionId, 2, Alice, Bob, 1);
// fungible
const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- await transferExpectFail(fungibleCollectionId, 2, Alice, Bob, 1, 'Fungible');
+ await transferExpectFailure(fungibleCollectionId, 2, Alice, Bob, 1);
// reFungible
const reFungibleCollectionId = await
createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- await transferExpectFail(
+ await transferExpectFailure(
reFungibleCollectionId,
2,
Alice,
Bob,
1,
- 'ReFungible',
);
});
it('Transfer with deleted item_id', async () => {
@@ -161,46 +159,44 @@
const nftCollectionId = await createCollectionExpectSuccess();
const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
await burnItemExpectSuccess(Alice, nftCollectionId, newNftTokenId, 1);
- await transferExpectFail(nftCollectionId, newNftTokenId, Alice, Bob, 1, 'NFT');
+ await transferExpectFailure(nftCollectionId, newNftTokenId, Alice, Bob, 1);
// fungible
const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');
await burnItemExpectSuccess(Alice, fungibleCollectionId, newFungibleTokenId, 10);
- await transferExpectFail(fungibleCollectionId, newFungibleTokenId, Alice, Bob, 1, 'Fungible');
+ await transferExpectFailure(fungibleCollectionId, newFungibleTokenId, Alice, Bob, 1);
// reFungible
const reFungibleCollectionId = await
createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 1);
- await transferExpectFail(
+ await transferExpectFailure(
reFungibleCollectionId,
newReFungibleTokenId,
Alice,
Bob,
1,
- 'ReFungible',
);
});
it('Transfer with recipient that is not owner', async () => {
// nft
const nftCollectionId = await createCollectionExpectSuccess();
const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
- await transferExpectFail(nftCollectionId, newNftTokenId, Charlie, Bob, 1, 'NFT');
+ await transferExpectFailure(nftCollectionId, newNftTokenId, Charlie, Bob, 1);
// fungible
const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');
- await transferExpectFail(fungibleCollectionId, newFungibleTokenId, Charlie, Bob, 1, 'Fungible');
+ await transferExpectFailure(fungibleCollectionId, newFungibleTokenId, Charlie, Bob, 1);
// reFungible
const reFungibleCollectionId = await
createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');
- await transferExpectFail(
+ await transferExpectFailure(
reFungibleCollectionId,
newReFungibleTokenId,
Charlie,
Bob,
1,
- 'ReFungible',
);
});
});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -84,7 +84,7 @@
}
interface ITokenDataType {
- Owner: number[];
+ Owner: IKeyringPair;
ConstData: number[];
VariableData: number[];
}
@@ -523,6 +523,30 @@
});
}
+export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {
+
+ await usingApi(async (api) => {
+
+ const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);
+ const events = await submitTransactionAsync(sender, tx);
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.true;
+ });
+}
+
+export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {
+
+ await usingApi(async (api) => {
+
+ const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);
+ const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
+ const result = getGenericResult(events);
+
+ expect(result.success).to.be.false;
+ });
+}
+
export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {
await usingApi(async (api) => {
const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);
@@ -543,9 +567,9 @@
});
}
-export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string) {
+export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {
await usingApi(async (api) => {
- const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);
+ const tx = api.tx.nft.toggleContractWhiteList(contractAddress, value);
const events = await submitTransactionAsync(sender, tx);
const result = getGenericResult(events);
@@ -748,29 +772,31 @@
sender: IKeyringPair,
recipient: IKeyringPair,
value: number | bigint = 1,
+ blockTimeMs: number,
+ blockSchedule: number,
) {
await usingApi(async (api: ApiPromise) => {
const blockNumber: number | undefined = await getBlockNumber(api);
- const expectedBlockNumber = blockNumber + 2;
+ const expectedBlockNumber = blockNumber + blockSchedule;
expect(blockNumber).to.be.greaterThan(0);
- const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);
+ const transferTx = await api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);
await submitTransactionAsync(sender, scheduleTx);
const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());
- const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;
- expect(nftItemDataBefore.Owner.toString()).to.be.equal(sender.address);
+ const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as any as ITokenDataType;
+ expect(toSubstrateAddress(nftItemDataBefore.Owner)).to.be.equal(sender.address);
- // sleep for 2 blocks
- await new Promise(resolve => setTimeout(resolve, 6000 * 2));
+ // sleep for 4 blocks
+ await new Promise(resolve => setTimeout(resolve, blockTimeMs * (blockSchedule + 1)));
const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());
const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;
- expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);
+ expect(toSubstrateAddress(nftItemData.Owner)).to.be.equal(recipient.address);
expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());
});
}
@@ -820,7 +846,7 @@
}
export async function
-transferExpectFail(
+transferExpectFailure(
collectionId: number,
tokenId: number,
sender: IKeyringPair,
@@ -895,7 +921,8 @@
const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };
tx = api.tx.nft.createItem(collectionId, to, createData);
} else {
- tx = api.tx.nft.createItem(collectionId, to, createMode);
+ const createData = { nft: { const_data: [], variable_data: [] } };
+ tx = api.tx.nft.createItem(collectionId, to, createData);
}
const events = await submitTransactionAsync(sender, tx);
tests/yarn.lockdiffbeforeafterboth--- a/tests/yarn.lock
+++ b/tests/yarn.lock
@@ -42,7 +42,7 @@
resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.14.7.tgz#7b047d7a3a89a67d2258dc61f604f098f1bc7e08"
integrity sha512-nS6dZaISCXJ3+518CWiBfEr//gHyMO02uDxBkXTKZDN5POruCnOZ1N4YBRZDCabwF8nZMWBpRxIicmXtBs+fvw==
-"@babel/core@^7.1.0", "@babel/core@^7.14.5", "@babel/core@^7.14.6", "@babel/core@^7.7.2", "@babel/core@^7.7.5":
+"@babel/core@^7.1.0", "@babel/core@^7.14.6", "@babel/core@^7.7.2", "@babel/core@^7.7.5":
version "7.14.6"
resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.14.6.tgz#e0814ec1a950032ff16c13a2721de39a8416fcab"
integrity sha512-gJnOEWSqTk96qG5BoIrl5bVtc23DCycmIePPYnamY9RboYdI4nFy5vAQMSl81O5K/W0sLDWfGysnOECC+KUUCA==
@@ -971,7 +971,7 @@
pirates "^4.0.0"
source-map-support "^0.5.16"
-"@babel/runtime@^7.13.9", "@babel/runtime@^7.14.5", "@babel/runtime@^7.14.6", "@babel/runtime@^7.8.4":
+"@babel/runtime@^7.14.6", "@babel/runtime@^7.8.4":
version "7.14.6"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.14.6.tgz#535203bc0892efc7dec60bdc27b2ecf6e409062d"
integrity sha512-/PCB2uJ7oM44tz8YhC4Z/6PeOKXp4K588f+5M3clr1M4zbqztlo0XEfJ2LEzj/FgwfgGcIdl8n7YYjTCI0BYwg==
@@ -1019,21 +1019,6 @@
version "0.4.2"
resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-0.4.2.tgz#f63d0ef06f5c0c57d76c4ab5f63d3835c51b0179"
integrity sha512-8nmGq/4ycLpIwzvhI4tNDmQztZ8sp+hI7cyG8i1nQDhkAbRzHpXPidRAHlNvCZQpJTKw5ItIpMw9RSToGF00mg==
- dependencies:
- ajv "^6.12.4"
- debug "^4.1.1"
- espree "^7.3.0"
- globals "^13.9.0"
- ignore "^4.0.6"
- import-fresh "^3.2.1"
- js-yaml "^3.13.1"
- minimatch "^3.0.4"
- strip-json-comments "^3.1.1"
-
-"@eslint/eslintrc@^0.4.3":
- version "0.4.3"
- resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-0.4.3.tgz#9e42981ef035beb3dd49add17acb96e8ff6f394c"
- integrity sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==
dependencies:
ajv "^6.12.4"
debug "^4.1.1"
@@ -1559,47 +1544,46 @@
dependencies:
"@octokit/openapi-types" "^7.3.2"
-"@polkadot/api-contract@4.15.1":
- version "4.15.1"
- resolved "https://registry.yarnpkg.com/@polkadot/api-contract/-/api-contract-4.15.1.tgz#bfa5aa67b2cdc3c203ed09cfd14c396469eeafa2"
- integrity sha512-TyKc6fyBMJnrHhnicM2hTCQMZMfd5Baarz4L75QMxkWFLTpxQ68BnYFcdupfH6fNXHZeHdRpSW/KPBj47UYgeA==
+"@polkadot/api-contract@5.0.1":
+ version "5.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/api-contract/-/api-contract-5.0.1.tgz#520a7b3cd990a76374b79e12eca5bf629cc565a1"
+ integrity sha512-qZ2wnXHDyU2c1/V9GKpbcZKBfVua4YFsU/LHKevZLkJfnGFBgNRdwAuKgVe5h2FCt2W2/pt618WgxG0UDWwjcw==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/api" "4.15.1"
- "@polkadot/types" "4.15.1"
- "@polkadot/util" "^6.9.1"
- "@polkadot/x-rxjs" "^6.9.1"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/api" "5.0.1"
+ "@polkadot/types" "5.0.1"
+ "@polkadot/util" "^7.0.1"
+ rxjs "^7.2.0"
-"@polkadot/api-derive@4.15.1":
- version "4.15.1"
- resolved "https://registry.yarnpkg.com/@polkadot/api-derive/-/api-derive-4.15.1.tgz#841ae233142f4b509d4db1fbcf76db15a77bed0f"
- integrity sha512-gAkKg4w09PThemRz0VI4YDzTy3RfCJrjpR0ZnYT93lZWsspSDiQIzMOTPbOn7MvC7FujeRIT0zqpzDeqKc4wFQ==
+"@polkadot/api-derive@5.0.1":
+ version "5.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/api-derive/-/api-derive-5.0.1.tgz#08064c10ed159826ffd07013dcdde1d8b63186a0"
+ integrity sha512-JZpH1JVLu3PvX4+A71iDLtNr6LL103dAFou61DxyJF4obyTmS2lzigG3xXqUFShiPDb19ywxQpsE4gAOP6emuQ==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/api" "4.15.1"
- "@polkadot/rpc-core" "4.15.1"
- "@polkadot/types" "4.15.1"
- "@polkadot/util" "^6.9.1"
- "@polkadot/util-crypto" "^6.9.1"
- "@polkadot/x-rxjs" "^6.9.1"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/api" "5.0.1"
+ "@polkadot/rpc-core" "5.0.1"
+ "@polkadot/types" "5.0.1"
+ "@polkadot/util" "^7.0.1"
+ "@polkadot/util-crypto" "^7.0.1"
+ rxjs "^7.2.0"
-"@polkadot/api@4.15.1":
- version "4.15.1"
- resolved "https://registry.yarnpkg.com/@polkadot/api/-/api-4.15.1.tgz#c9a041b855639a98d6df0706c7546e076a8d5727"
- integrity sha512-MsGKpTAmnkxIN+Zu21NPKWot4xLsDGn/cdranf+P2OjqB80E6m8zkQOE7ug3912WIi5byZp55TSOE9UUzAAW3Q==
+"@polkadot/api@5.0.1":
+ version "5.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/api/-/api-5.0.1.tgz#9607b53009322f9264f7dcc8705c466bd33aa516"
+ integrity sha512-5JDpM2Fjc80gHBju1B/rMBGDfAvY8UiU4XVlivJRk+mTVD3OTwbtTro4nmwJOub05xQCJvD/bnCuxG8eFSoq+Q==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/api-derive" "4.15.1"
- "@polkadot/keyring" "^6.9.1"
- "@polkadot/metadata" "4.15.1"
- "@polkadot/rpc-core" "4.15.1"
- "@polkadot/rpc-provider" "4.15.1"
- "@polkadot/types" "4.15.1"
- "@polkadot/types-known" "4.15.1"
- "@polkadot/util" "^6.9.1"
- "@polkadot/util-crypto" "^6.9.1"
- "@polkadot/x-rxjs" "^6.9.1"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/api-derive" "5.0.1"
+ "@polkadot/keyring" "^7.0.1"
+ "@polkadot/rpc-core" "5.0.1"
+ "@polkadot/rpc-provider" "5.0.1"
+ "@polkadot/types" "5.0.1"
+ "@polkadot/types-known" "5.0.1"
+ "@polkadot/util" "^7.0.1"
+ "@polkadot/util-crypto" "^7.0.1"
eventemitter3 "^4.0.7"
+ rxjs "^7.2.0"
"@polkadot/dev@0.62.43":
version "0.62.43"
@@ -1665,57 +1649,45 @@
typescript "^4.3.4"
yargs "^17.0.1"
-"@polkadot/keyring@^6.9.1":
- version "6.9.1"
- resolved "https://registry.yarnpkg.com/@polkadot/keyring/-/keyring-6.9.1.tgz#a92dd2d4ef8ccb999bc7d443ef4a13e6ef9b2ce2"
- integrity sha512-UF+9psVwVlar7LRJYWJB/xETYBPu1OcyVrxDe88w17Y+ZIsIeNfcR9quVS4M7AdAhplmscsz/wgEMjmggXH9/Q==
- dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/util" "6.9.1"
- "@polkadot/util-crypto" "6.9.1"
-
-"@polkadot/metadata@4.15.1":
- version "4.15.1"
- resolved "https://registry.yarnpkg.com/@polkadot/metadata/-/metadata-4.15.1.tgz#3cd2392b956577edf96090793fd8b9b392a67502"
- integrity sha512-pnOgJSFCVgQpZtp7ghS0AS7xWCp6POKrb5LhY1CK7XTy6iQ6VHcGnr1N4wfia1c3o5ZOPj8Xic29Da61tkjp2Q==
+"@polkadot/keyring@^7.0.1":
+ version "7.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/keyring/-/keyring-7.0.1.tgz#666e903661b98279dc16d512be69f5ace4b58d8d"
+ integrity sha512-eSvG8Q4gUTRDFWj2lqTY/9NekGP8dtp+W6WmouKh0DDwHRawaVeDaq6UJYQv6XoBG1i+ZGPvErRQeGMPOn/mUQ==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/types" "4.15.1"
- "@polkadot/types-known" "4.15.1"
- "@polkadot/util" "^6.9.1"
- "@polkadot/util-crypto" "^6.9.1"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/util" "7.0.1"
+ "@polkadot/util-crypto" "7.0.1"
-"@polkadot/networks@6.9.1", "@polkadot/networks@^6.9.1":
- version "6.9.1"
- resolved "https://registry.yarnpkg.com/@polkadot/networks/-/networks-6.9.1.tgz#8d66338569c9891a00cc6737e18c1dbffd7153f5"
- integrity sha512-imBPIrLN0W+7zuosD4WBtOkMzXc/271NhWn6dQmyA0xEoJx+6coJHQH/04fqO/gfZd4M1R70f3Gt5hlsfzCwlA==
+"@polkadot/networks@7.0.1", "@polkadot/networks@^7.0.1":
+ version "7.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/networks/-/networks-7.0.1.tgz#e07c4b88e25711433e76d24fce4c7273c25dd38b"
+ integrity sha512-bJSvI7UgEpxmBKS8TMh+I1mfmCMwhClGdSs29kwU+K61IjBTKTt3yQJ/SflYIQV7QftGbz3oMfSkGbQbRHZqvQ==
dependencies:
- "@babel/runtime" "^7.14.5"
+ "@babel/runtime" "^7.14.6"
-"@polkadot/rpc-core@4.15.1":
- version "4.15.1"
- resolved "https://registry.yarnpkg.com/@polkadot/rpc-core/-/rpc-core-4.15.1.tgz#2e14edcdf8cd4e6f9658ecbd90540a9d39c3e929"
- integrity sha512-g9NxsHgOBzqLBWGV+hbXd8tmDWBdIZSxr3b107xY090wbQQ0R9I6D6wi+d7mJtcH1tazuhQgWQqyvvsbr2xPZg==
+"@polkadot/rpc-core@5.0.1":
+ version "5.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/rpc-core/-/rpc-core-5.0.1.tgz#8460287532fe61c31505564df53e92ef6feba875"
+ integrity sha512-JMNOVQijjyJZNu9B8CJwIrQzGYzAp03uCBSbqYfzWBFnYVLKh7JmvOlkLnODM8uUYq0gVN4BaDUSPc39GpELAQ==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/metadata" "4.15.1"
- "@polkadot/rpc-provider" "4.15.1"
- "@polkadot/types" "4.15.1"
- "@polkadot/util" "^6.9.1"
- "@polkadot/x-rxjs" "^6.9.1"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/rpc-provider" "5.0.1"
+ "@polkadot/types" "5.0.1"
+ "@polkadot/util" "^7.0.1"
+ rxjs "^7.2.0"
-"@polkadot/rpc-provider@4.15.1":
- version "4.15.1"
- resolved "https://registry.yarnpkg.com/@polkadot/rpc-provider/-/rpc-provider-4.15.1.tgz#18a61b5353388da73f722f30905f23927b2c5e31"
- integrity sha512-NfgdBsLP56XAIrSu29iKmqLb4ZAbK50VINGv3Qi99s5V2FiFOAvZq22arkoCmFo1q4zFpQeQqul3ZyZv8QX/Kg==
+"@polkadot/rpc-provider@5.0.1":
+ version "5.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/rpc-provider/-/rpc-provider-5.0.1.tgz#ef022a123eb9073634b59c6e0f6e1705e96066a5"
+ integrity sha512-t+VKhMtQfQVgkZDqYnP/44KlBDmcCVo1/MvJ+DoNd7RUWUIBJt3v71G5gDSNeGMTyvxn0KK0qL4j+Nqr6c4FUQ==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/types" "4.15.1"
- "@polkadot/util" "^6.9.1"
- "@polkadot/util-crypto" "^6.9.1"
- "@polkadot/x-fetch" "^6.9.1"
- "@polkadot/x-global" "^6.9.1"
- "@polkadot/x-ws" "^6.9.1"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/types" "5.0.1"
+ "@polkadot/util" "^7.0.1"
+ "@polkadot/util-crypto" "^7.0.1"
+ "@polkadot/x-fetch" "^7.0.1"
+ "@polkadot/x-global" "^7.0.1"
+ "@polkadot/x-ws" "^7.0.1"
eventemitter3 "^4.0.7"
"@polkadot/ts@0.3.89":
@@ -1725,57 +1697,55 @@
dependencies:
"@types/chrome" "^0.0.144"
-"@polkadot/typegen@4.15.1":
- version "4.15.1"
- resolved "https://registry.yarnpkg.com/@polkadot/typegen/-/typegen-4.15.1.tgz#e04d5ef70712bfc91707723a1ae0198e5309ed75"
- integrity sha512-gIk3GdgNuRp0GnbrljUVUgrsT7GLbGcNmI/Jbnt64Zyw20beMrvPQyDkoRBWrN4aN14B1SW1xIXQz4axVy7Tug==
+"@polkadot/typegen@5.0.1":
+ version "5.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/typegen/-/typegen-5.0.1.tgz#718b517f4f1578441911096603577bd0a2a968e0"
+ integrity sha512-iFLJoWgIkn+J6MDw3AUWveP9qxVn1C+VeLJbpZ21St5WyeE148Tml0BmYnKLSXlaPMhZEwB+/IV3jpQ35dH4bw==
dependencies:
- "@babel/core" "^7.14.5"
+ "@babel/core" "^7.14.6"
"@babel/register" "^7.14.5"
- "@babel/runtime" "^7.14.5"
- "@polkadot/api" "4.15.1"
- "@polkadot/metadata" "4.15.1"
- "@polkadot/rpc-provider" "4.15.1"
- "@polkadot/types" "4.15.1"
- "@polkadot/util" "^6.9.1"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/api" "5.0.1"
+ "@polkadot/rpc-provider" "5.0.1"
+ "@polkadot/types" "5.0.1"
+ "@polkadot/util" "^7.0.1"
handlebars "^4.7.7"
websocket "^1.0.34"
yargs "^17.0.1"
-"@polkadot/types-known@4.15.1":
- version "4.15.1"
- resolved "https://registry.yarnpkg.com/@polkadot/types-known/-/types-known-4.15.1.tgz#d60cfb1e4ed315f2c82646795243a34df6b21fd3"
- integrity sha512-yj2fVwEyYrc6eBoW6W3JQ5h1FZjcyyhDzfrtxronSLdT7H6zUtlLqn1A5uzkxPD0eSXkesh960GHeYzAi+p4cw==
+"@polkadot/types-known@5.0.1":
+ version "5.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/types-known/-/types-known-5.0.1.tgz#21feb327fc4323733bf027c8d874a2aa3014b21f"
+ integrity sha512-AIhPlN4r14ZW4wdwHZD2nIe1DE61ZO9PsyrCyAU3ysl6Cw6TI+txDCN3aS/8XYuC7wDLEgLB9vJv2sVWdCzqJg==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/networks" "^6.9.1"
- "@polkadot/types" "4.15.1"
- "@polkadot/util" "^6.9.1"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/networks" "^7.0.1"
+ "@polkadot/types" "5.0.1"
+ "@polkadot/util" "^7.0.1"
-"@polkadot/types@4.15.1":
- version "4.15.1"
- resolved "https://registry.yarnpkg.com/@polkadot/types/-/types-4.15.1.tgz#03f32fd4ce81d69c43368d3e476c0421cedb8607"
- integrity sha512-daCblGDkiNHyDNkVDOQ0x/hblK7zkGAFQy+ykMt6euGGllUiKaAbCKlQN803aKmsB/5m8zQU63MHQC65tkpWXg==
+"@polkadot/types@5.0.1":
+ version "5.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/types/-/types-5.0.1.tgz#2a4e23e452f999eeae175b595470df0e426a930d"
+ integrity sha512-aN6JKeF7ZYi5irYAaUoDqth6qlOlB15C5vhlDOojEorYLfRs/R+GCrO+lPSs+bKmSxh7BSRh500ikI/xD4nx5A==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/metadata" "4.15.1"
- "@polkadot/util" "^6.9.1"
- "@polkadot/util-crypto" "^6.9.1"
- "@polkadot/x-rxjs" "^6.9.1"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/util" "^7.0.1"
+ "@polkadot/util-crypto" "^7.0.1"
+ rxjs "^7.2.0"
-"@polkadot/util-crypto@6.9.1", "@polkadot/util-crypto@^6.9.1":
- version "6.9.1"
- resolved "https://registry.yarnpkg.com/@polkadot/util-crypto/-/util-crypto-6.9.1.tgz#175a2bbc040785599730baee35f0235226b8343e"
- integrity sha512-lniY8bhRoayA8PD3NHyvpAL2N9YETDll6HbxaOIkGS9nnVmlOjIvslcd343b30rj7/qSV72w+8qkReHj650aQw==
+"@polkadot/util-crypto@7.0.1", "@polkadot/util-crypto@^7.0.1":
+ version "7.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/util-crypto/-/util-crypto-7.0.1.tgz#03109dc11323dad174fb2214d395855495def16a"
+ integrity sha512-dbvdsICoyOVw/K45RmHOP7wXE/7vj+NzEKGcKbiDt39nglHm6g2BTJ947PwwyNusTTAx82Q2iJ9vIZ1Kl0xG+g==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/networks" "6.9.1"
- "@polkadot/util" "6.9.1"
- "@polkadot/wasm-crypto" "^4.0.2"
- "@polkadot/x-randomvalues" "6.9.1"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/networks" "7.0.1"
+ "@polkadot/util" "7.0.1"
+ "@polkadot/wasm-crypto" "^4.1.2"
+ "@polkadot/x-randomvalues" "7.0.1"
base-x "^3.0.8"
base64-js "^1.5.1"
- blakejs "^1.1.0"
+ blakejs "^1.1.1"
bn.js "^4.11.9"
create-hash "^1.2.0"
elliptic "^6.5.4"
@@ -1785,101 +1755,91 @@
tweetnacl "^1.0.3"
xxhashjs "^0.2.2"
-"@polkadot/util@6.9.1", "@polkadot/util@^6.9.1":
- version "6.9.1"
- resolved "https://registry.yarnpkg.com/@polkadot/util/-/util-6.9.1.tgz#009a9e0771523398517dbf3a978285b071f6081c"
- integrity sha512-RTIn8+Xdgywj8Bl7D12557zi8iIoUvDpAJztp/CwIq4O3jEw6Y/7lqNX/K6OXhZm/gZf7tFgFnvGlsIuNbtYcQ==
+"@polkadot/util@7.0.1", "@polkadot/util@^7.0.1":
+ version "7.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/util/-/util-7.0.1.tgz#79afd40473016876f51d65ebb9900a20108fe0a4"
+ integrity sha512-EtQlZL6ok0Ep+zRz2QHMUoJo/b3kFHVN2qqyD2+9sdqg0FGLmkzNFM+K6dasCMLXieJ1l0HoFsQppSo/leUeaA==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/x-textdecoder" "6.9.1"
- "@polkadot/x-textencoder" "6.9.1"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/x-textdecoder" "7.0.1"
+ "@polkadot/x-textencoder" "7.0.1"
"@types/bn.js" "^4.11.6"
bn.js "^4.11.9"
camelcase "^5.3.1"
ip-regex "^4.3.0"
-"@polkadot/wasm-crypto-asmjs@^4.0.2":
- version "4.0.2"
- resolved "https://registry.yarnpkg.com/@polkadot/wasm-crypto-asmjs/-/wasm-crypto-asmjs-4.0.2.tgz#f42c353a64e1243841daf90e4bd54eff01a4e3cf"
- integrity sha512-hlebqtGvfjg2ZNm4scwBGVHwOwfUhy2yw5RBHmPwkccUif3sIy4SAzstpcVBIVMdAEvo746bPWEInA8zJRcgJA==
+"@polkadot/wasm-crypto-asmjs@^4.1.2":
+ version "4.1.2"
+ resolved "https://registry.yarnpkg.com/@polkadot/wasm-crypto-asmjs/-/wasm-crypto-asmjs-4.1.2.tgz#094b3eeeb5fd39a93db177583b48454511874cfc"
+ integrity sha512-3Q+vVUxDAC2tXgKMM3lKzx2JW+tarDpTjkvdxIKATyi8Ek69KkUqvMyJD0VL/iFZOFZED0YDX9UU4XOJ/astlg==
dependencies:
- "@babel/runtime" "^7.13.9"
+ "@babel/runtime" "^7.14.6"
-"@polkadot/wasm-crypto-wasm@^4.0.2":
- version "4.0.2"
- resolved "https://registry.yarnpkg.com/@polkadot/wasm-crypto-wasm/-/wasm-crypto-wasm-4.0.2.tgz#89f9e0a1e4d076784d4a42bea37fc8b06bdd8bb6"
- integrity sha512-de/AfNPZ0uDKFWzOZ1rJCtaUbakGN29ks6IRYu6HZTRg7+RtqvE1rIkxabBvYgQVHIesmNwvEA9DlIkS6hYRFQ==
+"@polkadot/wasm-crypto-wasm@^4.1.2":
+ version "4.1.2"
+ resolved "https://registry.yarnpkg.com/@polkadot/wasm-crypto-wasm/-/wasm-crypto-wasm-4.1.2.tgz#773c78c1d65886671d3ba1d66c31afd86c93d02f"
+ integrity sha512-/l4IBEdQ41szHdHkuF//z1qr+XmWuLHlpBA7s9Eb221m1Fir6AKoCHoh1hp1r3v0ecZYLKvak1B225w6JAU3Fg==
dependencies:
- "@babel/runtime" "^7.13.9"
+ "@babel/runtime" "^7.14.6"
-"@polkadot/wasm-crypto@^4.0.2":
- version "4.0.2"
- resolved "https://registry.yarnpkg.com/@polkadot/wasm-crypto/-/wasm-crypto-4.0.2.tgz#9649057adee8383cc86433d107ba526b718c5a3b"
- integrity sha512-2h9FuQFkBc+B3TwSapt6LtyPvgtd0Hq9QsHW8g8FrmKBFRiiFKYRpfJKHCk0aCZzuRf9h95bQl/X6IXAIWF2ng==
+"@polkadot/wasm-crypto@^4.1.2":
+ version "4.1.2"
+ resolved "https://registry.yarnpkg.com/@polkadot/wasm-crypto/-/wasm-crypto-4.1.2.tgz#dead71ae5d2f7722d23aed5be2112e1732d315e9"
+ integrity sha512-2EKdOjIrD2xHP2rC+0G/3Qo6926nL/18vCFkd34lBd9zP9YNF2GDEtDY+zAeDIRFKe1sQHTpsKgNdYSWoV2eBg==
dependencies:
- "@babel/runtime" "^7.13.9"
- "@polkadot/wasm-crypto-asmjs" "^4.0.2"
- "@polkadot/wasm-crypto-wasm" "^4.0.2"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/wasm-crypto-asmjs" "^4.1.2"
+ "@polkadot/wasm-crypto-wasm" "^4.1.2"
-"@polkadot/x-fetch@^6.9.1":
- version "6.9.1"
- resolved "https://registry.yarnpkg.com/@polkadot/x-fetch/-/x-fetch-6.9.1.tgz#89ff2741b35f2bb9fdc30a22cdb0debf72248597"
- integrity sha512-CckiiRiGM+7WGOw1WijDeN9NJcTBEjZ96LRMaUng+BNvNhUQplsmX6CUt86Qn6T1O8TQaAg93wtqb+deykkn2g==
+"@polkadot/x-fetch@^7.0.1":
+ version "7.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/x-fetch/-/x-fetch-7.0.1.tgz#2db6fa19f4f4d9b2f4cf50ba78bf3aa947d7b982"
+ integrity sha512-9R38FjtlJcvdpEA7tVGmTmH4aiBCTABuLJdVSn3cYkgWfxDHeFMqjdFzTJ6Asa5cY0Ds3ZKsh9uccTQBQzV/HQ==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/x-global" "6.9.1"
- "@types/node-fetch" "^2.5.10"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/x-global" "7.0.1"
+ "@types/node-fetch" "^2.5.11"
node-fetch "^2.6.1"
-"@polkadot/x-global@6.9.1", "@polkadot/x-global@^6.9.1":
- version "6.9.1"
- resolved "https://registry.yarnpkg.com/@polkadot/x-global/-/x-global-6.9.1.tgz#c3d7482e2ac62c306379592550d476fc60ce7dfe"
- integrity sha512-/pVzvQUObccuk/f2BGcs0WMjveLQPr1Qf+uiSF/7ae9BZHIG4ydLz0/Lnzbt4YQkIEaRNvVFD1Vph5hyjo4VCA==
+"@polkadot/x-global@7.0.1", "@polkadot/x-global@^7.0.1":
+ version "7.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/x-global/-/x-global-7.0.1.tgz#44fb248d3aaea557753318327149772969e96bff"
+ integrity sha512-gVVACSdRhHYRJejLEAL0mM9BZfY8N50VT2+15A7ALD1tVqwS4tz3P9vRW3Go7ZjfyAc83aEmh0PiQ8Nm1R+2Cg==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@types/node-fetch" "^2.5.10"
- node-fetch "^2.6.1"
+ "@babel/runtime" "^7.14.6"
-"@polkadot/x-randomvalues@6.9.1":
- version "6.9.1"
- resolved "https://registry.yarnpkg.com/@polkadot/x-randomvalues/-/x-randomvalues-6.9.1.tgz#e289e79849e332777fb96e8544b1193a4e793e59"
- integrity sha512-L1c5ddjzyPAvzRkbnrbVgQTUskM4vRtfxblOV/tmM1BP6mB1U3rWo0FeHNWN/uiUoibVFIDNUKqUnZ5vhYs1qg==
+"@polkadot/x-randomvalues@7.0.1":
+ version "7.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/x-randomvalues/-/x-randomvalues-7.0.1.tgz#32036ae5d48645a062f6a1c3ebbf227236c806b8"
+ integrity sha512-UNoIFaz1xJPozruT+lo8BTeT8A3NM3PgWuru7Vs8OsIz0Phkg7lUWlpHu9PZHyQCyKlUryvkOA692IlVlNYy2Q==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/x-global" "6.9.1"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/x-global" "7.0.1"
-"@polkadot/x-rxjs@^6.9.1":
- version "6.9.1"
- resolved "https://registry.yarnpkg.com/@polkadot/x-rxjs/-/x-rxjs-6.9.1.tgz#713a399568922aff10fe47c3875dba44a139d6c6"
- integrity sha512-sfQNA7so5KoeFEIIx7OGZL5D+0Hn0SRZJMbZSuGRFMKjyovpyzWi+Mjs3l6T6OXbKm972XAseNGDUWSVG4EpLQ==
+"@polkadot/x-textdecoder@7.0.1":
+ version "7.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/x-textdecoder/-/x-textdecoder-7.0.1.tgz#bb9bba94b2eb1612dd35c299f43ab74515db74d9"
+ integrity sha512-CFRnpI0cp1h2N1+ec551BLVLwV6OHG6Gj62EYcIOXR+o/SX/6MXm3Qcehm2YvfTKqktyIUSWmTwbWjGjuqPrpA==
dependencies:
- "@babel/runtime" "^7.14.5"
- rxjs "^6.6.7"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/x-global" "7.0.1"
-"@polkadot/x-textdecoder@6.9.1":
- version "6.9.1"
- resolved "https://registry.yarnpkg.com/@polkadot/x-textdecoder/-/x-textdecoder-6.9.1.tgz#dab6e95b35c9386550c4907fd1efb195ab605ec9"
- integrity sha512-U7Cu7PbY5CG5kjbKqAQ/e07FfvPYZwHZZbC+343vDHUnJlyONKxp+jhod+A1pepu15fsYH/iZC0Os6RwfKoEAA==
+"@polkadot/x-textencoder@7.0.1":
+ version "7.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/x-textencoder/-/x-textencoder-7.0.1.tgz#181d403c5dc1d94fd1e2147fd1c5c528d30d8805"
+ integrity sha512-m+QL1HNiu5GMz6cfr/udSA6fUTv3RyIybJb7v43EQCxqlj/L0J3cUHapFd6tqH9PElD6jPkH1pXcgYN8e7dWTQ==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/x-global" "6.9.1"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/x-global" "7.0.1"
-"@polkadot/x-textencoder@6.9.1":
- version "6.9.1"
- resolved "https://registry.yarnpkg.com/@polkadot/x-textencoder/-/x-textencoder-6.9.1.tgz#cf98a3f248ad9a4cdb2559f950ff6559d009b619"
- integrity sha512-M9VNm7IpbBwQnCZhEBAXSQ+/g2psEv4zjJYdX4/HTcWNpnYEUHeayIVTw91Wkgo3dN8wBL245vVp/8apfKfMkQ==
- dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/x-global" "6.9.1"
-
-"@polkadot/x-ws@^6.9.1":
- version "6.9.1"
- resolved "https://registry.yarnpkg.com/@polkadot/x-ws/-/x-ws-6.9.1.tgz#ac4d0cf22c333359a426f4104581c9e394d7f6e5"
- integrity sha512-BeoVqFFLatrt3k8Leyi6LsOMz5rkdXbQ5oE2Db0V+ezfh5aEV/JjoLsaPkX+i6xsCYibB43rY64FBhpJ2O0iYg==
+"@polkadot/x-ws@^7.0.1":
+ version "7.0.1"
+ resolved "https://registry.yarnpkg.com/@polkadot/x-ws/-/x-ws-7.0.1.tgz#8c22a61c0dd9b82865c7631e22ac147c2b73b118"
+ integrity sha512-VUn/6sCJUpvW9WhUK+DKo1uDrw4yO84twRcy5JSzvSiBTaSplhU9Q4qGFl2Atr3WIzAYYx1jQSm/j6AhPRji1w==
dependencies:
- "@babel/runtime" "^7.14.5"
- "@polkadot/x-global" "6.9.1"
- "@types/websocket" "^1.0.2"
+ "@babel/runtime" "^7.14.6"
+ "@polkadot/x-global" "7.0.1"
+ "@types/websocket" "^1.0.3"
websocket "^1.0.34"
"@rushstack/eslint-patch@^1.0.6":
@@ -2046,10 +2006,10 @@
resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-8.2.2.tgz#91daa226eb8c2ff261e6a8cbf8c7304641e095e0"
integrity sha512-Lwh0lzzqT5Pqh6z61P3c3P5nm6fzQK/MMHl9UKeneAeInVflBSz1O2EkX6gM6xfJd7FBXBY5purtLx7fUiZ7Hw==
-"@types/node-fetch@^2.5.10":
- version "2.5.10"
- resolved "https://registry.yarnpkg.com/@types/node-fetch/-/node-fetch-2.5.10.tgz#9b4d4a0425562f9fcea70b12cb3fcdd946ca8132"
- integrity sha512-IpkX0AasN44hgEad0gEF/V6EgR5n69VEqPEgnmoM8GsIGro3PowbWs4tR6IhxUTyPLpOn+fiGG6nrQhcmoCuIQ==
+"@types/node-fetch@^2.5.11":
+ version "2.5.11"
+ resolved "https://registry.yarnpkg.com/@types/node-fetch/-/node-fetch-2.5.11.tgz#ce22a2e65fc8999f4dbdb7ddbbcf187d755169e4"
+ integrity sha512-2upCKaqVZETDRb8A2VTaRymqFBEgH8u6yr96b/u3+1uQEPDRo3mJLEiPk7vdXBHRtjwkjqzFYMJXrt0Z9QsYjQ==
dependencies:
"@types/node" "*"
form-data "^3.0.0"
@@ -2093,10 +2053,10 @@
resolved "https://registry.yarnpkg.com/@types/stack-utils/-/stack-utils-2.0.0.tgz#7036640b4e21cc2f259ae826ce843d277dad8cff"
integrity sha512-RJJrrySY7A8havqpGObOB4W92QXKJo63/jFLLgpvOtsGUqbQZ9Sbgl35KMm1DjC6j7AvmmU2bIno+3IyEaemaw==
-"@types/websocket@^1.0.2":
- version "1.0.2"
- resolved "https://registry.yarnpkg.com/@types/websocket/-/websocket-1.0.2.tgz#d2855c6a312b7da73ed16ba6781815bf30c6187a"
- integrity sha512-B5m9aq7cbbD/5/jThEr33nUY8WEfVi6A2YKCTOvw5Ldy7mtsOkqRvGjnzy6g7iMMDsgu7xREuCzqATLDLQVKcQ==
+"@types/websocket@^1.0.3":
+ version "1.0.3"
+ resolved "https://registry.yarnpkg.com/@types/websocket/-/websocket-1.0.3.tgz#49e09f939afd0ccdee4f7108d4712ec9feb0f153"
+ integrity sha512-ZdoTSwmDsKR7l1I8fpfQtmTI/hUwlOvE3q0iyJsp4tXU0MkdrYowimDzwxjhQvxU4qjhHLd3a6ig0OXRbLgIdw==
dependencies:
"@types/node" "*"
@@ -2826,6 +2786,11 @@
resolved "https://registry.yarnpkg.com/blakejs/-/blakejs-1.1.0.tgz#69df92ef953aa88ca51a32df6ab1c54a155fc7a5"
integrity sha1-ad+S75U6qIylGjLfarHFShVfx6U=
+blakejs@^1.1.1:
+ version "1.1.1"
+ resolved "https://registry.yarnpkg.com/blakejs/-/blakejs-1.1.1.tgz#bf313053978b2cd4c444a48795710be05c785702"
+ integrity sha512-bLG6PHOCZJKNshTjGRBvET0vTciwQE6zFKOKKXPDJfwFBd4Ac0yBfPZqcGvGJap50l7ktvlpFqc2jGVaUgbJgg==
+
bluebird@^3.1.1, bluebird@^3.5.0:
version "3.7.2"
resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.7.2.tgz#9f229c15be272454ffa973ace0dbee79a1b0c36f"
@@ -4307,12 +4272,12 @@
integrity sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==
eslint@^7.28.0:
- version "7.31.0"
- resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.31.0.tgz#f972b539424bf2604907a970860732c5d99d3aca"
- integrity sha512-vafgJpSh2ia8tnTkNUkwxGmnumgckLh5aAbLa1xRmIn9+owi8qBNGKL+B881kNKNTy7FFqTEkpNkUvmw0n6PkA==
+ version "7.30.0"
+ resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.30.0.tgz#6d34ab51aaa56112fd97166226c9a97f505474f8"
+ integrity sha512-VLqz80i3as3NdloY44BQSJpFw534L9Oh+6zJOUaViV4JPd+DaHwutqP7tcpkW3YiXbK6s05RZl7yl7cQn+lijg==
dependencies:
"@babel/code-frame" "7.12.11"
- "@eslint/eslintrc" "^0.4.3"
+ "@eslint/eslintrc" "^0.4.2"
"@humanwhocodes/config-array" "^0.5.0"
ajv "^6.10.0"
chalk "^4.0.0"
@@ -8557,13 +8522,20 @@
dependencies:
queue-microtask "^1.2.2"
-rxjs@^6.6.6, rxjs@^6.6.7:
+rxjs@^6.6.6:
version "6.6.7"
resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-6.6.7.tgz#90ac018acabf491bf65044235d5863c4dab804c9"
integrity sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==
dependencies:
tslib "^1.9.0"
+rxjs@^7.2.0:
+ version "7.2.0"
+ resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-7.2.0.tgz#5cd12409639e9514a71c9f5f9192b2c4ae94de31"
+ integrity sha512-aX8w9OpKrQmiPKfT1bqETtUr9JygIz6GZ+gql8v7CijClsP0laoFUdKzxFAoWuRdSlOdU2+crss+cMf+cqMTnw==
+ dependencies:
+ tslib "~2.1.0"
+
safe-buffer@5.1.2, safe-buffer@~5.1.0, safe-buffer@~5.1.1:
version "5.1.2"
resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d"
@@ -9422,6 +9394,11 @@
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00"
integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==
+tslib@~2.1.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.1.0.tgz#da60860f1c2ecaa5703ab7d39bc05b6bf988b97a"
+ integrity sha512-hcVC3wYEziELGGmEEXue7D75zbwIIVUMWAVbHItGPx0ziyXxrOMQx4rQEVEV45Ut/1IotuEvwqPopzIOkDMf0A==
+
tslint@^6.1.3:
version "6.1.3"
resolved "https://registry.yarnpkg.com/tslint/-/tslint-6.1.3.tgz#5c23b2eccc32487d5523bd3a470e9aa31789d904"