difftreelog
Merge branch 'develop' into feature/NFTPAR-196_sponsor_setVariableMetadata
in: master
10 files changed
.github/workflows/notify.ymldiffbeforeafterboth--- a/.github/workflows/notify.yml
+++ b/.github/workflows/notify.yml
@@ -6,8 +6,8 @@
build:
runs-on: ubuntu-latest
steps:
- - uses: avkviring/telegram-github-action@v0.0.8
+ - uses: avkviring/telegram-github-action@v0.0.13
env:
telegram_to: ${{ secrets.TELEGRAM_TO }}
telegram_token: ${{ secrets.TELEGRAM_TOKEN }}
- event: ${{ toJson(github.event) }}
\ No newline at end of file
+ event: ${{ toJson(github.event) }}
node/src/chain_spec.rsdiffbeforeafterboth--- a/node/src/chain_spec.rs
+++ b/node/src/chain_spec.rs
@@ -193,8 +193,7 @@
mint_mode: false,
offchain_schema: vec![],
schema_version: SchemaVersion::default(),
- sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),
- sponsor_confirmed: true,
+ sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<sr25519::Public>("Alice")),
const_on_chain_schema: vec![],
variable_on_chain_schema: vec![],
limits: CollectionLimits::default()
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -21,7 +21,7 @@
ensure, fail, parameter_types,
traits::{
Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,
- Randomness, IsSubType,
+ Randomness, IsSubType, WithdrawReasons,
},
weights::{
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -29,6 +29,7 @@
WeightToFeePolynomial, DispatchClass,
},
StorageValue,
+ transactional,
};
use frame_system::{self as system, ensure_signed, ensure_root};
@@ -124,6 +125,42 @@
pub fraction: u128,
}
+#[derive(Encode, Decode, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub enum SponsorshipState<AccountId> {
+ /// The fees are applied to the transaction sender
+ Disabled,
+ Unconfirmed(AccountId),
+ /// Transactions are sponsored by specified account
+ Confirmed(AccountId),
+}
+
+impl<AccountId> SponsorshipState<AccountId> {
+ fn sponsor(&self) -> Option<&AccountId> {
+ match self {
+ Self::Confirmed(sponsor) => Some(sponsor),
+ _ => None,
+ }
+ }
+
+ fn pending_sponsor(&self) -> Option<&AccountId> {
+ match self {
+ Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),
+ _ => None,
+ }
+ }
+
+ fn confirmed(&self) -> bool {
+ matches!(self, Self::Confirmed(_))
+ }
+}
+
+impl<T> Default for SponsorshipState<T> {
+ fn default() -> Self {
+ Self::Disabled
+ }
+}
+
#[derive(Encode, Decode, Clone, PartialEq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct Collection<T: Config> {
@@ -137,8 +174,7 @@
pub mint_mode: bool,
pub offchain_schema: Vec<u8>,
pub schema_version: SchemaVersion,
- pub sponsor: T::AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender
- pub sponsor_confirmed: bool, // False if sponsor address has not yet confirmed sponsorship. True otherwise.
+ pub sponsorship: SponsorshipState<AccountId>,
pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions
pub variable_on_chain_schema: Vec<u8>, //
pub const_on_chain_schema: Vec<u8>, //
@@ -413,7 +449,9 @@
/// Schema data size limit bound exceeded
SchemaDataLimitExceeded,
/// Maximum refungibility exceeded
- WrongRefungiblePieces
+ WrongRefungiblePieces,
+ /// createRefungible should be called with one owner
+ BadCreateRefungibleCall,
}
}
@@ -422,6 +460,10 @@
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
+
+ type Currency: Currency<Self::AccountId>;
+ type CollectionCreationPrice: Get<<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance>;
+ type TreasuryAccountId: Get<Self::AccountId>;
}
#[cfg(feature = "runtime-benchmarks")]
@@ -429,57 +471,117 @@
// #endregion
+// # Used definitions
+//
+// ## User control levels
+//
+// chain-controlled - key is uncontrolled by user
+// i.e autoincrementing index
+// can use non-cryptographic hash
+// real - key is controlled by user
+// but it is hard to generate enough colliding values, i.e owner of signed txs
+// can use non-cryptographic hash
+// controlled - key is completly controlled by users
+// i.e maps with mutable keys
+// should use cryptographic hash
+//
+// ## User control level downgrade reasons
+//
+// ?1 - chain-controlled -> controlled
+// collections/tokens can be destroyed, resulting in massive holes
+// ?2 - chain-controlled -> controlled
+// same as ?1, but can be only added, resulting in easier exploitation
+// ?3 - real -> controlled
+// no confirmation required, so addresses can be easily generated
decl_storage! {
trait Store for Module<T: Config> as Nft {
- // Private members
- NextCollectionID: CollectionId;
+ //#region Private members
+ /// Id of next collection
CreatedCollectionCount: u32;
+ /// Used for migrations
ChainVersion: u64;
- ItemListIndex: map hasher(identity) CollectionId => TokenId;
+ /// Id of last collection token
+ /// Collection id (controlled?1)
+ ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;
+ //#endregion
- // Chain limits struct
+ //#region Chain limits struct
pub ChainLimit get(fn chain_limit) config(): ChainLimits;
+ //#endregion
- // Bound counters
- CollectionCount: u32;
+ //#region Bound counters
+ /// Amount of collections destroyed, used for total amount tracking with
+ /// CreatedCollectionCount
+ DestroyedCollectionCount: u32;
+ /// Total amount of account owned tokens (NFTs + RFTs + unique fungibles)
+ /// Account id (real)
pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;
+ //#endregion
- // Basic collections
- pub CollectionById get(fn collection_id) config(): map hasher(identity) CollectionId => Option<Collection<T>> = None;
- pub AdminList get(fn admin_list_collection): map hasher(identity) CollectionId => Vec<T::AccountId>;
- pub WhiteList get(fn white_list): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => bool;
+ //#region Basic collections
+ /// Collection info
+ /// Collection id (controlled?1)
+ pub CollectionById get(fn collection_id) config(): map hasher(blake2_128_concat) CollectionId => Option<Collection<T>> = None;
+ /// List of collection admins
+ /// Collection id (controlled?2)
+ pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::AccountId>;
+ /// Whitelisted collection users
+ /// Collection id (controlled?2), user id (controlled?3)
+ pub WhiteList get(fn white_list): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => bool;
+ //#endregion
- /// Balance owner per collection map
- pub Balance get(fn balance_count): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => u128;
+ /// How many of collection items user have
+ /// Collection id (controlled?2), account id (real)
+ pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => u128;
- /// second parameter: item id + owner account id + spender account id
- pub Allowances get(fn approved): double_map hasher(identity) CollectionId, hasher(twox_64_concat) (TokenId, T::AccountId, T::AccountId) => u128;
+ /// Amount of items which spender can transfer out of owners account (via transferFrom)
+ /// Collection id (controlled?2), (token id (controlled ?2) + owner account id (real) + spender account id (controlled?3))
+ pub Allowances get(fn approved): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) (TokenId, T::AccountId, T::AccountId) => u128;
- /// Item collections
- pub NftItemList get(fn nft_item_id) config(): double_map hasher(identity) CollectionId, hasher(identity) TokenId => NftItemType<T::AccountId>;
- pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => FungibleItemType;
- pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(identity) CollectionId, hasher(identity) TokenId => ReFungibleItemType<T::AccountId>;
+ //#region Item collections
+ /// Collection id (controlled?2), token id (controlled?1)
+ pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => NftItemType<T::AccountId>;
+ /// Collection id (controlled?2), owner (controlled?2)
+ pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;
+ /// Collection id (controlled?2), token id (controlled?1)
+ pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => ReFungibleItemType<T::AccountId>;
+ //#endregion
- /// Index list
- pub AddressTokens get(fn address_tokens): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => Vec<TokenId>;
+ //#region Index list
+ /// Collection id (controlled?2), tokens owner (controlled?2)
+ pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => Vec<TokenId>;
+ //#endregion
- /// Tokens transfer baskets
- pub CreateItemBasket get(fn create_item_basket): map hasher(twox_64_concat) (CollectionId, T::AccountId) => T::BlockNumber;
- pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => T::BlockNumber;
- pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;
- pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => T::BlockNumber;
+ //#region Tokens transfer rate limit baskets
+ /// (Collection id (controlled?2), who created (real))
+ pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => T::BlockNumber;
+ /// Collection id (controlled?2), token id (controlled?2)
+ pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;
+ /// Collection id (controlled?2), owning user (real)
+ pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;
+ /// Collection id (controlled?2), token id (controlled?2)
+ pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;
+ //#endregion
/// Variable metadata sponsoring
- pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => Option<T::BlockNumber> = None;
-
- // Contract Sponsorship and Ownership
+ /// Collection id (controlled?2), token id (controlled?2)
+ pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;
+
+ //#region Contract Sponsorship and Ownership
+ /// Contract address (real)
pub ContractOwner get(fn contract_owner): map hasher(twox_64_concat) T::AccountId => T::AccountId;
+ /// Contract address (real)
pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;
+ /// (Contract address(real), caller (real))
pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;
+ /// Contract address (real)
pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;
+ /// Contract address (real)
pub ContractWhiteListEnabled get(fn contract_white_list_enabled): map hasher(twox_64_concat) T::AccountId => bool;
- pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(twox_64_concat) T::AccountId => bool;
+ /// Contract address (real) => Whitelisted user (controlled?3)
+ pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(blake2_128_concat) T::AccountId => bool;
+ //#endregion
}
add_extra_genesis {
build(|config: &GenesisConfig<T>| {
@@ -563,14 +665,6 @@
type Error = Error<T>;
fn on_initialize(now: T::BlockNumber) -> Weight {
-
- if ChainVersion::get() < 2
- {
- let value = NextCollectionID::get();
- CreatedCollectionCount::put(value);
- ChainVersion::put(2);
- }
-
0
}
@@ -591,6 +685,7 @@
/// * mode: [CollectionMode] collection type and type dependent data.
// returns collection ID
#[weight = <T as Config>::WeightInfo::create_collection()]
+ #[transactional]
pub fn create_collection(origin,
collection_name: Vec<u16>,
collection_description: Vec<u16>,
@@ -600,6 +695,19 @@
// Anyone can create a collection
let who = ensure_signed(origin)?;
+ // Take a (non-refundable) deposit of collection creation
+ let mut imbalance = <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();
+ imbalance.subsume(<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(
+ &T::TreasuryAccountId::get(),
+ T::CollectionCreationPrice::get(),
+ ));
+ <T as Config>::Currency::settle(
+ &who,
+ imbalance,
+ WithdrawReasons::TRANSFER,
+ ExistenceRequirement::KeepAlive,
+ ).map_err(|_| Error::<T>::NoPermission)?;
+
let decimal_points = match mode {
CollectionMode::Fungible(points) => points,
_ => 0
@@ -607,8 +715,11 @@
let chain_limit = ChainLimit::get();
+ let created_count = CreatedCollectionCount::get();
+ let destroyed_count = DestroyedCollectionCount::get();
+
// bound Total number of collections
- ensure!(CollectionCount::get() < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);
+ ensure!(created_count - destroyed_count < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);
// check params
ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
@@ -617,17 +728,11 @@
ensure!(token_prefix.len() <= 16, Error::<T>::CollectionTokenPrefixLimitExceeded);
// Generate next collection ID
- let next_id = CreatedCollectionCount::get()
- .checked_add(1)
- .ok_or(Error::<T>::NumOverflow)?;
-
- // bound counter
- let total = CollectionCount::get()
+ let next_id = created_count
.checked_add(1)
.ok_or(Error::<T>::NumOverflow)?;
CreatedCollectionCount::put(next_id);
- CollectionCount::put(total);
let limits = CollectionLimits {
sponsored_data_size: chain_limit.custom_data_limit,
@@ -646,8 +751,7 @@
token_prefix: token_prefix,
offchain_schema: Vec::new(),
schema_version: SchemaVersion::ImageURL,
- sponsor: T::AccountId::default(),
- sponsor_confirmed: false,
+ sponsorship: SponsorshipState::Disabled,
variable_on_chain_schema: Vec::new(),
const_on_chain_schema: Vec::new(),
limits,
@@ -672,6 +776,7 @@
///
/// * collection_id: collection to destroy.
#[weight = <T as Config>::WeightInfo::destroy_collection()]
+ #[transactional]
pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -699,16 +804,10 @@
<VariableMetaDataBasket<T>>::remove_prefix(collection_id);
- if CollectionCount::get() > 0
- {
- // bound couter
- let total = CollectionCount::get()
- .checked_sub(1)
- .ok_or(Error::<T>::NumOverflow)?;
+ DestroyedCollectionCount::put(DestroyedCollectionCount::get()
+ .checked_add(1)
+ .ok_or(Error::<T>::NumOverflow)?);
- CollectionCount::put(total);
- }
-
Ok(())
}
@@ -725,6 +824,7 @@
///
/// * address.
#[weight = <T as Config>::WeightInfo::add_to_white_list()]
+ #[transactional]
pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{
let sender = ensure_signed(origin)?;
@@ -749,6 +849,7 @@
///
/// * address.
#[weight = <T as Config>::WeightInfo::remove_from_white_list()]
+ #[transactional]
pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{
let sender = ensure_signed(origin)?;
@@ -772,6 +873,7 @@
///
/// * mode: [AccessMode]
#[weight = <T as Config>::WeightInfo::set_public_access_mode()]
+ #[transactional]
pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult
{
let sender = ensure_signed(origin)?;
@@ -798,6 +900,7 @@
///
/// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.
#[weight = <T as Config>::WeightInfo::set_mint_permission()]
+ #[transactional]
pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult
{
let sender = ensure_signed(origin)?;
@@ -822,6 +925,7 @@
///
/// * new_owner.
#[weight = <T as Config>::WeightInfo::change_collection_owner()]
+ #[transactional]
pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -847,6 +951,7 @@
///
/// * new_admin_id: Address of new admin to add.
#[weight = <T as Config>::WeightInfo::add_collection_admin()]
+ #[transactional]
pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::AccountId) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -882,6 +987,7 @@
///
/// * account_id: Address of admin to remove.
#[weight = <T as Config>::WeightInfo::remove_collection_admin()]
+ #[transactional]
pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::AccountId) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -906,14 +1012,14 @@
///
/// * new_sponsor.
#[weight = <T as Config>::WeightInfo::set_collection_sponsor()]
+ #[transactional]
pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {
let sender = ensure_signed(origin)?;
let mut target_collection = Self::get_collection(collection_id)?;
Self::check_owner_permissions(&target_collection, sender)?;
- target_collection.sponsor = new_sponsor;
- target_collection.sponsor_confirmed = false;
+ target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);
Self::save_collection(target_collection);
Ok(())
@@ -927,14 +1033,18 @@
///
/// * collection_id.
#[weight = <T as Config>::WeightInfo::confirm_sponsorship()]
+ #[transactional]
pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {
let sender = ensure_signed(origin)?;
let mut target_collection = Self::get_collection(collection_id)?;
- ensure!(sender == target_collection.sponsor, Error::<T>::ConfirmUnsetSponsorFail);
+ ensure!(
+ target_collection.sponsorship.pending_sponsor() == Some(&sender),
+ Error::<T>::ConfirmUnsetSponsorFail
+ );
- target_collection.sponsor_confirmed = true;
+ target_collection.sponsorship = SponsorshipState::Confirmed(sender);
Self::save_collection(target_collection);
Ok(())
@@ -950,6 +1060,7 @@
///
/// * collection_id.
#[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]
+ #[transactional]
pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -957,8 +1068,7 @@
let mut target_collection = Self::get_collection(collection_id)?;
Self::check_owner_permissions(&target_collection, sender)?;
- target_collection.sponsor = T::AccountId::default();
- target_collection.sponsor_confirmed = false;
+ target_collection.sponsorship = SponsorshipState::Disabled;
Self::save_collection(target_collection);
Ok(())
@@ -989,6 +1099,7 @@
// .saturating_add(RocksDbWeight::get().writes(8 as Weight))]
#[weight = <T as Config>::WeightInfo::create_item(data.len())]
+ #[transactional]
pub fn create_item(origin, collection_id: CollectionId, owner: T::AccountId, data: CreateItemData) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -1002,7 +1113,7 @@
Ok(())
}
- /// This method creates multiple instances of NFT Collection created with CreateCollection method.
+ /// This method creates multiple items in a collection created with CreateCollection method.
///
/// # Permissions
///
@@ -1023,6 +1134,7 @@
#[weight = <T as Config>::WeightInfo::create_item(items_data.into_iter()
.map(|data| { data.len() })
.sum())]
+ #[transactional]
pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::AccountId, items_data: Vec<CreateItemData>) -> DispatchResult {
ensure!(items_data.len() > 0, Error::<T>::EmptyArgument);
@@ -1056,6 +1168,7 @@
///
/// * item_id: ID of NFT to burn.
#[weight = <T as Config>::WeightInfo::burn_item()]
+ #[transactional]
pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -1113,6 +1226,7 @@
/// * Fungible Mode: Must specify transferred amount
/// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)
#[weight = <T as Config>::WeightInfo::transfer()]
+ #[transactional]
pub fn transfer(origin, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {
let sender = ensure_signed(origin)?;
let collection = Self::get_collection(collection_id)?;
@@ -1136,6 +1250,7 @@
///
/// * item_id: ID of the item.
#[weight = <T as Config>::WeightInfo::approve()]
+ #[transactional]
pub fn approve(origin, spender: T::AccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -1200,6 +1315,7 @@
///
/// * value: Amount to transfer.
#[weight = <T as Config>::WeightInfo::transfer_from()]
+ #[transactional]
pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -1234,7 +1350,7 @@
}
// Reduce approval by transferred amount or remove if remaining approval drops to 0
- if approval.checked_sub(value).unwrap_or(0) > 0 {
+ if approval.saturating_sub(value) > 0 {
<Allowances<T>>::insert(collection_id, (item_id, &from, &sender), approval - value);
}
else {
@@ -1280,6 +1396,7 @@
///
/// * schema: String representing the offchain data schema.
#[weight = <T as Config>::WeightInfo::set_variable_meta_data()]
+ #[transactional]
pub fn set_variable_meta_data (
origin,
collection_id: CollectionId,
@@ -1324,6 +1441,7 @@
///
/// * schema: SchemaVersion: enum
#[weight = <T as Config>::WeightInfo::set_schema_version()]
+ #[transactional]
pub fn set_schema_version(
origin,
collection_id: CollectionId,
@@ -1351,6 +1469,7 @@
///
/// * schema: String representing the offchain data schema.
#[weight = <T as Config>::WeightInfo::set_offchain_schema()]
+ #[transactional]
pub fn set_offchain_schema(
origin,
collection_id: CollectionId,
@@ -1382,6 +1501,7 @@
///
/// * schema: String representing the const on-chain data schema.
#[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]
+ #[transactional]
pub fn set_const_on_chain_schema (
origin,
collection_id: CollectionId,
@@ -1413,6 +1533,7 @@
///
/// * schema: String representing the variable on-chain data schema.
#[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]
+ #[transactional]
pub fn set_variable_on_chain_schema (
origin,
collection_id: CollectionId,
@@ -1433,6 +1554,7 @@
// Sudo permissions function
#[weight = <T as Config>::WeightInfo::set_chain_limits()]
+ #[transactional]
pub fn set_chain_limits(
origin,
limits: ChainLimits
@@ -1457,6 +1579,7 @@
/// * enable flag
///
#[weight = <T as Config>::WeightInfo::enable_contract_sponsoring()]
+ #[transactional]
pub fn enable_contract_sponsoring(
origin,
contract_address: T::AccountId,
@@ -1492,6 +1615,7 @@
/// -`rate_limit`: Number of blocks to wait until the next sponsored transaction is allowed
///
#[weight = <T as Config>::WeightInfo::set_contract_sponsoring_rate_limit()]
+ #[transactional]
pub fn set_contract_sponsoring_rate_limit(
origin,
contract_address: T::AccountId,
@@ -1519,6 +1643,7 @@
///
/// - `enable`: .
#[weight = <T as Config>::WeightInfo::toggle_contract_white_list()]
+ #[transactional]
pub fn toggle_contract_white_list(
origin,
contract_address: T::AccountId,
@@ -1546,6 +1671,7 @@
///
/// -`account_address`: Address to add.
#[weight = <T as Config>::WeightInfo::add_to_contract_white_list()]
+ #[transactional]
pub fn add_to_contract_white_list(
origin,
contract_address: T::AccountId,
@@ -1573,6 +1699,7 @@
///
/// -`account_address`: Address to remove.
#[weight = <T as Config>::WeightInfo::remove_from_contract_white_list()]
+ #[transactional]
pub fn remove_from_contract_white_list(
origin,
contract_address: T::AccountId,
@@ -1589,6 +1716,7 @@
}
#[weight = <T as Config>::WeightInfo::set_collection_limits()]
+ #[transactional]
pub fn set_collection_limits(
origin,
collection_id: u32,
@@ -1754,9 +1882,6 @@
Self::add_refungible_item(collection, item)?;
}
};
-
- // call event
- Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id), owner));
Ok(())
}
@@ -1782,6 +1907,7 @@
.ok_or(Error::<T>::NumOverflow)?;
<Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);
+ Self::deposit_event(RawEvent::ItemCreated(collection_id, 0, owner.clone()));
Ok(())
}
@@ -1793,8 +1919,14 @@
.ok_or(Error::<T>::NumOverflow)?;
let itemcopy = item.clone();
- let value = item.owner.first().unwrap().fraction;
- let owner = item.owner.first().unwrap().owner.clone();
+ ensure!(
+ item.owner.len() == 1,
+ Error::<T>::BadCreateRefungibleCall,
+ );
+ let item_owner = item.owner.first().expect("only one owner is defined");
+
+ let value = item_owner.fraction;
+ let owner = item_owner.owner.clone();
Self::add_token_index(collection_id, current_index, &owner)?;
@@ -1807,6 +1939,7 @@
.ok_or(Error::<T>::NumOverflow)?;
<Balance<T>>::insert(collection_id, owner.clone(), new_balance);
+ Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, owner));
Ok(())
}
@@ -1829,6 +1962,7 @@
.ok_or(Error::<T>::NumOverflow)?;
<Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);
+ Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, item_owner));
Ok(())
}
@@ -1847,9 +1981,8 @@
let rft_balance = token
.owner
.iter()
- .filter(|&i| i.owner == *owner)
- .next()
- .unwrap();
+ .find(|&i| i.owner == *owner)
+ .ok_or(Error::<T>::TokenNotFound)?;
Self::remove_token_index(collection_id, item_id, owner)?;
// update balance
@@ -1863,7 +1996,7 @@
.owner
.iter()
.position(|i| i.owner == *owner)
- .unwrap();
+ .expect("owned item is exists");
token.owner.remove(index);
let owner_count = token.owner.len();
@@ -2100,7 +2233,7 @@
.iter()
.filter(|i| i.owner == owner)
.next()
- .ok_or(Error::<T>::NumOverflow)?;
+ .ok_or(Error::<T>::TokenNotFound)?;
let amount = item.fraction;
ensure!(amount >= value, Error::<T>::TokenValueTooLow);
@@ -2111,10 +2244,10 @@
.ok_or(Error::<T>::NumOverflow)?;
<Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);
- let balancenew_owner = <Balance<T>>::get(collection_id, new_owner.clone())
+ let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())
.checked_add(value)
.ok_or(Error::<T>::NumOverflow)?;
- <Balance<T>>::insert(collection_id, new_owner.clone(), balancenew_owner);
+ <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);
let old_owner = item.owner.clone();
let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);
@@ -2128,7 +2261,7 @@
.owner
.iter_mut()
.find(|i| i.owner == owner)
- .unwrap()
+ .expect("old owner does present in refungible")
.owner = new_owner.clone();
<ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);
@@ -2140,7 +2273,7 @@
.owner
.iter_mut()
.find(|i| i.owner == owner)
- .unwrap()
+ .expect("old owner does present in refungible")
.fraction -= value;
// separate amount
@@ -2150,7 +2283,7 @@
.owner
.iter_mut()
.find(|i| i.owner == new_owner)
- .unwrap()
+ .expect("new owner has account")
.fraction += value;
} else {
// new owner do not have account
@@ -2472,13 +2605,6 @@
> {
let tip = self.0;
- // Set fee based on call type. Creating collection costs 1 Unique.
- // All other transactions have traditional fees so far
- // let fee = match call.is_sub_type() {
- // Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),
- // _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes
- // // _ => <BalanceOf<T>>::from(100)
- // };
let fee = Self::traditional_fee(len, info, tip);
// Only mess with balances if fee is not zero.
@@ -2496,7 +2622,10 @@
// sponsor timeout
let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
+ let collection = <Collection<T>>::get(collection_id);
+
let limit = collection.limits.sponsor_transfer_timeout;
+ let mut sponsored = true;
if <CreateItemBasket<T>>::contains_key((collection_id, &who)) {
let last_tx_block = <CreateItemBasket<T>>::get((collection_id, &who));
let limit_time = last_tx_block + limit.into();
@@ -2508,9 +2637,10 @@
// check free create limit
if (collection.limits.sponsored_data_size >= (_properties.len() as u32)) &&
- (collection.sponsor_confirmed)
+ (sponsored)
{
- Some(collection.sponsor)
+ collection.sponsorship.sponsor()
+ .cloned()
} else {
None
}
@@ -2519,7 +2649,7 @@
let collection = <CollectionById<T>>::get(collection_id)?;
let mut sponsor_transfer = false;
- if collection.sponsor_confirmed {
+ if collection.sponsorship.confirmed() {
let collection_limits = collection.limits;
let collection_mode = collection.mode;
@@ -2606,7 +2736,8 @@
if !sponsor_transfer {
None
} else {
- Some(collection.sponsor)
+ collection.sponsorship.sponsor()
+ .cloned()
}
}
pallets/nft/src/mock.rsdiffbeforeafterboth--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -133,9 +133,14 @@
type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
}
+parameter_types! {
+ pub const CollectionCreationPrice: u64 = 1_000_000_000_000;
+}
+
impl pallet_template::Config for Test {
type Event = ();
type WeightInfo = ();
+ type CollectionCreationPrice = CollectionCreationPrice;
}
// Build genesis storage according to the mock runtime.
runtime/src/lib.rsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "256"]1112// Make the WASM binary available.13#[cfg(feature = "std")]14include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1516use pallet_grandpa::fg_primitives;17use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};18use sp_api::impl_runtime_apis;19use sp_consensus_aura::sr25519::AuthorityId as AuraId;20use sp_core::{ crypto::KeyTypeId, crypto::Public, OpaqueMetadata };21use sp_runtime::{22 Permill, Perbill, Percent,23 ModuleId,24 create_runtime_str, generic, impl_opaque_keys,25 traits::{26 Convert, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, 27 IdentityLookup, NumberFor, Verify,28 },29 transaction_validity::{TransactionSource, TransactionValidity},30 ApplyExtrinsicResult, MultiSignature,31};32#[cfg(feature = "std")]33use sp_version::NativeVersion;34use sp_version::RuntimeVersion;35pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment, CurrencyAdapter, FeeDetails, RuntimeDispatchInfo};36// A few exports that help ease life for downstream crates.37pub use pallet_balances::Call as BalancesCall;38pub use pallet_contracts::{Schedule as ContractsSchedule };39pub use frame_support::{40 construct_runtime,41 dispatch::DispatchResult,42 parameter_types,43 StorageValue,44 traits::{45 Currency, ExistenceRequirement, Get, KeyOwnerProofSystem, OnUnbalanced, Randomness,46 LockIdentifier,47 },48 weights::{49 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},50 DispatchClass, DispatchInfo, GetDispatchInfo, Pays, PostDispatchInfo, Weight,51 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients52 },53};54use pallet_contracts::weights::WeightInfo;55// #[cfg(any(feature = "std", test))]56use frame_system::{57 self as system,58 EnsureRoot, 59 limits::{BlockWeights, BlockLength},60};61use sp_std::{prelude::*, marker::PhantomData};62use sp_arithmetic::{traits::{BaseArithmetic, Unsigned}};63use smallvec::smallvec;6465pub use pallet_timestamp::Call as TimestampCall;6667mod chain_extension;68use crate::chain_extension::{ NFTExtension, Imbalance };6970/// Struct that handles the conversion of Balance -> `u64`. This is used for71/// staking's election calculation.72pub struct CurrencyToVoteHandler;7374impl CurrencyToVoteHandler {75 fn factor() -> Balance {76 (Balances::total_issuance() / u64::max_value() as Balance).max(1)77 }78}7980impl Convert<Balance, u64> for CurrencyToVoteHandler {81 fn convert(x: Balance) -> u64 {82 (x / Self::factor()) as u6483 }84}8586impl Convert<u128, Balance> for CurrencyToVoteHandler {87 fn convert(x: u128) -> Balance {88 x * Self::factor()89 }90}9192/// Re-export a nft pallet93/// TODO: Check this re-export. Is this safe and good style?94extern crate pallet_nft;95pub use pallet_nft::*;9697/// An index to a block.98pub type BlockNumber = u32;99100/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.101pub type Signature = MultiSignature;102103/// Some way of identifying an account on the chain. We intentionally make it equivalent104/// to the public key of our transaction signing scheme.105pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;106107/// The type for looking up accounts. We don't expect more than 4 billion of them, but you108/// never know...109pub type AccountIndex = u32;110111/// Balance of an account.112pub type Balance = u128;113114/// Index of a transaction in the chain.115pub type Index = u32;116117/// A hash of some data used by the chain.118pub type Hash = sp_core::H256;119120/// Digest item type.121pub type DigestItem = generic::DigestItem<Hash>;122123mod nft_weights;124125/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know126/// the specifics of the runtime. They can then be made to be agnostic over specific formats127/// of data like extrinsics, allowing for them to continue syncing the network through upgrades128/// to even the core data structures.129pub mod opaque {130 use super::*;131132 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;133134 /// Opaque block header type.135 pub type Header = generic::Header<BlockNumber, BlakeTwo256>;136 /// Opaque block type.137 pub type Block = generic::Block<Header, UncheckedExtrinsic>;138 /// Opaque block identifier type.139 pub type BlockId = generic::BlockId<Block>;140141 impl_opaque_keys! {142 pub struct SessionKeys {143 pub aura: Aura,144 pub grandpa: Grandpa,145 }146 }147}148149/// This runtime version.150pub const VERSION: RuntimeVersion = RuntimeVersion {151 spec_name: create_runtime_str!("nft"),152 impl_name: create_runtime_str!("nft"),153 authoring_version: 1,154 spec_version: 3,155 impl_version: 1,156 apis: RUNTIME_API_VERSIONS,157 transaction_version: 1,158};159160pub const MILLISECS_PER_BLOCK: u64 = 6000;161162pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;163164// These time units are defined in number of blocks.165pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);166pub const HOURS: BlockNumber = MINUTES * 60;167pub const DAYS: BlockNumber = HOURS * 24;168169/// The version information used to identify this runtime when compiled natively.170#[cfg(feature = "std")]171pub fn native_version() -> NativeVersion {172 NativeVersion {173 runtime_version: VERSION,174 can_author_with: Default::default(),175 }176}177178/// Provides a membership set with only the configured aura users179pub struct ValiudatorsOnly<Runtime: pallet_aura::Config>(PhantomData<Runtime>);180impl frame_support::traits::Contains<AccountId> for ValiudatorsOnly<Runtime> {181 fn contains(t: &AccountId) -> bool {182 let arr: [u8; 32] = *t.as_ref();183 let raw_key: Vec<u8> = Vec::from(arr);184185 match pallet_aura::Module::<Runtime>::authorities().iter().find(|auth| auth.to_raw_vec() == raw_key) {186 Some(_) => true,187 None => false,188 } 189 }190 fn sorted_members() -> Vec<AccountId> {191 let mut members: Vec<AccountId> = Vec::new();192 for auth in pallet_aura::Module::<Runtime>::authorities() {193 let mut arr: [u8; 32] = Default::default(); 194 let bor_arr = auth.clone().to_raw_vec();195 let slice = bor_arr.as_slice();196 arr.copy_from_slice(slice);197 members.push(AccountId::from(arr));198 }199 members 200 }201 fn count() -> usize {202 pallet_aura::Module::<Runtime>::authorities().len()203 }204}205206impl frame_support::traits::ContainsLengthBound for ValiudatorsOnly<Runtime> {207 fn min_len() -> usize {208 1209 }210 fn max_len() -> usize {211 100212 }213}214215type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;216217pub struct DealWithFees;218impl OnUnbalanced<NegativeImbalance> for DealWithFees {219 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {220 if let Some(fees) = fees_then_tips.next() {221 // for fees, 100% to treasury222 let mut split = fees.ration(100, 0);223 if let Some(tips) = fees_then_tips.next() {224 // for tips, if any, 100% to treasury225 tips.ration_merge_into(100, 0, &mut split);226 }227 Treasury::on_unbalanced(split.0);228 // Author::on_unbalanced(split.1);229 }230 }231}232233// impl OnUnbalanced<NegativeImbalance> for DealWithFees {234// fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {235// if let Some(fees) = fees_then_tips.next() {236// // for fees, 100% to treasury237// let mut split = fees.ration(100, 0);238// if let Some(tips) = fees_then_tips.next() {239// // for tips, if any, 100% to treasury240// tips.ration_merge_into(100, 0, &mut split);241// }242// Treasury::on_unbalanced(split.0);243// // Author::on_unbalanced(split.1);244// }245// }246// }247248/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.249/// This is used to limit the maximal weight of a single extrinsic.250const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);251/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used252/// by Operational extrinsics.253const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);254/// We allow for 2 seconds of compute with a 6 second average block time.255const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND;256257parameter_types! {258 pub const BlockHashCount: BlockNumber = 2400;259 pub RuntimeBlockLength: BlockLength =260 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);261 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);262 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;263 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()264 .base_block(BlockExecutionWeight::get())265 .for_class(DispatchClass::all(), |weights| {266 weights.base_extrinsic = ExtrinsicBaseWeight::get();267 })268 .for_class(DispatchClass::Normal, |weights| {269 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);270 })271 .for_class(DispatchClass::Operational, |weights| {272 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);273 // Operational transactions have some extra reserved space, so that they274 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.275 weights.reserved = Some(276 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT277 );278 })279 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)280 .build_or_panic();281 pub const Version: RuntimeVersion = VERSION;282 pub const SS58Prefix: u8 = 42;283}284285impl system::Config for Runtime {286 /// The basic call filter to use in dispatchable.287 type BaseCallFilter = ();288 /// The identifier used to distinguish between accounts.289 type AccountId = AccountId;290 /// The aggregated dispatch type that is available for extrinsics.291 type Call = Call;292 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.293 type Lookup = IdentityLookup<AccountId>;294 /// The index type for storing how many extrinsics an account has signed.295 type Index = Index;296 /// The index type for blocks.297 type BlockNumber = BlockNumber;298 /// The type for hashing blocks and tries.299 type Hash = Hash;300 /// The hashing algorithm used.301 type Hashing = BlakeTwo256;302 /// The header type.303 type Header = generic::Header<BlockNumber, BlakeTwo256>;304 /// The ubiquitous event type.305 type Event = Event;306 /// The ubiquitous origin type.307 type Origin = Origin;308 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).309 type BlockHashCount = BlockHashCount;310 /// The weight of database operations that the runtime can invoke.311 type DbWeight = RocksDbWeight;312 /// The weight of the overhead invoked on the block import process, independent of the313 /// extrinsics included in that block.314 type BlockWeights = RuntimeBlockWeights;315 /// Version of the runtime.316 type Version = Version;317 /// This type is being generated by `construct_runtime!`.318 type PalletInfo = PalletInfo;319 /// What to do if a new account is created.320 type OnNewAccount = ();321 /// What to do if an account is fully reaped from the system.322 type OnKilledAccount = ();323 /// The data to be stored in an account.324 type AccountData = pallet_balances::AccountData<Balance>;325 /// Weight information for the extrinsics of this pallet.326 type SystemWeightInfo = system::weights::SubstrateWeight<Runtime>;327 328 type BlockLength = RuntimeBlockLength;329 type SS58Prefix = SS58Prefix;330}331332impl pallet_aura::Config for Runtime {333 type AuthorityId = AuraId;334}335336impl pallet_grandpa::Config for Runtime {337 type Event = Event;338 type Call = Call;339340 type KeyOwnerProofSystem = ();341342 type KeyOwnerProof =343 <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;344345 type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(346 KeyTypeId,347 GrandpaId,348 )>>::IdentificationTuple;349350 type HandleEquivocation = ();351352 type WeightInfo = ();353}354355parameter_types! {356 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;357}358359impl pallet_timestamp::Config for Runtime {360 /// A timestamp: milliseconds since the unix epoch.361 type Moment = u64;362 type OnTimestampSet = Aura;363 type MinimumPeriod = MinimumPeriod;364 type WeightInfo = ();365}366367parameter_types! {368 // pub const ExistentialDeposit: u128 = 500;369 pub const ExistentialDeposit: u128 = 0;370 pub const MaxLocks: u32 = 50;371}372373impl pallet_balances::Config for Runtime {374 type MaxLocks = MaxLocks;375 /// The type for recording an account's balance.376 type Balance = Balance;377 /// The ubiquitous event type.378 type Event = Event;379 type DustRemoval = Treasury;380 type ExistentialDeposit = ExistentialDeposit;381 type AccountStore = System;382 type WeightInfo = ();383}384385pub const MICROUNIQUE: Balance = 1_000_000_000;386pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;387pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;388pub const UNIQUE: Balance = 100 * CENTIUNIQUE;389390pub const fn deposit(items: u32, bytes: u32) -> Balance {391 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE392}393394parameter_types! {395 pub const TombstoneDeposit: Balance = deposit(396 0,397 sp_std::mem::size_of::<pallet_contracts::ContractInfo<Runtime>>() as u32398 );399 pub const DepositPerContract: Balance = TombstoneDeposit::get();400 pub const DepositPerStorageByte: Balance = deposit(0, 1);401 pub const DepositPerStorageItem: Balance = deposit(1, 0);402 pub RentFraction: Perbill = Perbill::from_rational_approximation(1u32, 30 * DAYS);403 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;404 pub const SignedClaimHandicap: u32 = 2;405 pub const MaxDepth: u32 = 32;406 pub const MaxValueSize: u32 = 16 * 1024;407 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb 408 // The lazy deletion runs inside on_initialize.409 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *410 RuntimeBlockWeights::get().max_block;411 // The weight needed for decoding the queue should be less or equal than a fifth412 // of the overall weight dedicated to the lazy deletion.413 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (414 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -415 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)416 )) / 5) as u32;417}418419420impl pallet_contracts::Config for Runtime {421 type Time = Timestamp;422 type Randomness = RandomnessCollectiveFlip;423 type Currency = Balances;424 type Event = Event;425 type RentPayment = ();426 type SignedClaimHandicap = SignedClaimHandicap;427 type TombstoneDeposit = TombstoneDeposit;428 type DepositPerContract = DepositPerContract;429 type DepositPerStorageByte = DepositPerStorageByte;430 type DepositPerStorageItem = DepositPerStorageItem;431 type RentFraction = RentFraction;432 type SurchargeReward = SurchargeReward;433 type MaxDepth = MaxDepth;434 type MaxValueSize = MaxValueSize;435 type WeightPrice = pallet_transaction_payment::Module<Self>;436 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;437 type ChainExtension = NFTExtension;438 type DeletionQueueDepth = DeletionQueueDepth;439 type DeletionWeightLimit = DeletionWeightLimit;440 type MaxCodeSize = MaxCodeSize;441}442443parameter_types! {444 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer 445}446447/// Linear implementor of `WeightToFeePolynomial` 448pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);449450impl<T> WeightToFeePolynomial for LinearFee<T> where451 T: BaseArithmetic + From<u32> + Copy + Unsigned452{453 type Balance = T;454455 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {456 smallvec!(WeightToFeeCoefficient {457 coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer458 coeff_frac: Perbill::zero(),459 negative: false,460 degree: 1,461 })462 }463}464465impl pallet_transaction_payment::Config for Runtime {466 type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees>;467 type TransactionByteFee = TransactionByteFee;468 type WeightToFee = LinearFee<Balance>;469 type FeeMultiplierUpdate = ();470}471472parameter_types! {473 pub const ProposalBond: Permill = Permill::from_percent(5);474 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;475 pub const SpendPeriod: BlockNumber = 5 * MINUTES;476 pub const Burn: Permill = Permill::from_percent(0);477 pub const TipCountdown: BlockNumber = 1 * DAYS;478 pub const TipFindersFee: Percent = Percent::from_percent(20);479 pub const TipReportDepositBase: Balance = 1 * UNIQUE;480 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;481 pub const BountyDepositBase: Balance = 1 * UNIQUE;482 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;483 pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry");484 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;485 pub const MaximumReasonLength: u32 = 16384;486 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);487 pub const BountyValueMinimum: Balance = 5 * UNIQUE;488}489490impl pallet_treasury::Config for Runtime {491 type ModuleId = TreasuryModuleId;492 type Currency = Balances;493 type ApproveOrigin = EnsureRoot<AccountId>;494 type RejectOrigin = EnsureRoot<AccountId>;495 type Event = Event;496 type OnSlash = ();497 type ProposalBond = ProposalBond;498 type ProposalBondMinimum = ProposalBondMinimum;499 type SpendPeriod = SpendPeriod;500 type Burn = Burn;501 type BurnDestination = ();502 type SpendFunds = ();503 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;504}505506impl pallet_sudo::Config for Runtime {507 type Event = Event;508 type Call = Call;509}510511parameter_types! {512 pub const MinVestedTransfer: Balance = 10 * UNIQUE;513}514515impl pallet_vesting::Config for Runtime {516 type Event = Event;517 type Currency = Balances;518 type BlockNumberToBalance = ConvertInto;519 type MinVestedTransfer = MinVestedTransfer;520 type WeightInfo = ();521}522523/// Used for the module nft in `./nft.rs`524impl pallet_nft::Config for Runtime {525 type Event = Event;526 type WeightInfo = nft_weights::WeightInfo;527}528529construct_runtime!(530 pub enum Runtime where531 Block = Block,532 NodeBlock = opaque::Block,533 UncheckedExtrinsic = UncheckedExtrinsic534 {535 System: system::{Module, Call, Config, Storage, Event<T>},536 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},537 Contracts: pallet_contracts::{Module, Call, Config<T>, Storage, Event<T>},538 Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},539 Aura: pallet_aura::{Module, Config<T> },540 Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},541 Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},542 TransactionPayment: pallet_transaction_payment::{Module, Storage},543 Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>},544 Nft: pallet_nft::{Module, Call, Config<T>, Storage, Event<T>},545 Treasury: pallet_treasury::{Module, Call, Storage, Config, Event<T>},546 Vesting: pallet_vesting::{Module, Call, Config<T>, Storage, Event<T>},547 }548);549550/// The address format for describing accounts.551pub type Address = AccountId;552/// Block header type as expected by this runtime.553pub type Header = generic::Header<BlockNumber, BlakeTwo256>;554/// Block type as expected by this runtime.555pub type Block = generic::Block<Header, UncheckedExtrinsic>;556/// A Block signed with a Justification557pub type SignedBlock = generic::SignedBlock<Block>;558/// BlockId type as expected by this runtime.559pub type BlockId = generic::BlockId<Block>;560/// The SignedExtension to the basic transaction logic.561pub type SignedExtra = (562 system::CheckSpecVersion<Runtime>,563 system::CheckTxVersion<Runtime>,564 system::CheckGenesis<Runtime>,565 system::CheckEra<Runtime>,566 system::CheckNonce<Runtime>,567 system::CheckWeight<Runtime>,568 pallet_nft::ChargeTransactionPayment<Runtime>,569);570/// Unchecked extrinsic type as expected by this runtime.571pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;572/// Extrinsic type that has already been checked.573pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;574/// Executive: handles dispatch to the various modules.575pub type Executive =576 frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;577578impl_runtime_apis! {579580 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>581 for Runtime582 {583 fn call(584 origin: AccountId,585 dest: AccountId,586 value: Balance,587 gas_limit: u64,588 input_data: Vec<u8>,589 ) -> pallet_contracts_primitives::ContractExecResult {590 Contracts::bare_call(origin, dest, value, gas_limit, input_data)591 }592593 fn get_storage(594 address: AccountId,595 key: [u8; 32],596 ) -> pallet_contracts_primitives::GetStorageResult {597 Contracts::get_storage(address, key)598 }599600 fn rent_projection(601 address: AccountId,602 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {603 Contracts::rent_projection(address)604 }605 }606607 impl sp_api::Core<Block> for Runtime {608 fn version() -> RuntimeVersion {609 VERSION610 }611612 fn execute_block(block: Block) {613 Executive::execute_block(block)614 }615616 fn initialize_block(header: &<Block as BlockT>::Header) {617 Executive::initialize_block(header)618 }619 }620621 impl sp_api::Metadata<Block> for Runtime {622 fn metadata() -> OpaqueMetadata {623 Runtime::metadata().into()624 }625 }626627 impl sp_block_builder::BlockBuilder<Block> for Runtime {628 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {629 Executive::apply_extrinsic(extrinsic)630 }631632 fn finalize_block() -> <Block as BlockT>::Header {633 Executive::finalize_block()634 }635636 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {637 data.create_extrinsics()638 }639640 fn check_inherents(641 block: Block,642 data: sp_inherents::InherentData,643 ) -> sp_inherents::CheckInherentsResult {644 data.check_extrinsics(&block)645 }646647 fn random_seed() -> <Block as BlockT>::Hash {648 RandomnessCollectiveFlip::random_seed()649 }650 }651652 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {653 fn validate_transaction(654 source: TransactionSource,655 tx: <Block as BlockT>::Extrinsic,656 ) -> TransactionValidity {657 Executive::validate_transaction(source, tx)658 }659 }660661 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {662 fn offchain_worker(header: &<Block as BlockT>::Header) {663 Executive::offchain_worker(header)664 }665 }666667 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {668 fn slot_duration() -> u64 {669 Aura::slot_duration()670 }671672 fn authorities() -> Vec<AuraId> {673 Aura::authorities()674 }675 }676677 impl sp_session::SessionKeys<Block> for Runtime {678 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {679 opaque::SessionKeys::generate(seed)680 }681682 fn decode_session_keys(683 encoded: Vec<u8>,684 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {685 opaque::SessionKeys::decode_into_raw_public_keys(&encoded)686 }687 }688689 impl fg_primitives::GrandpaApi<Block> for Runtime {690 fn grandpa_authorities() -> GrandpaAuthorityList {691 Grandpa::grandpa_authorities()692 }693694 fn submit_report_equivocation_unsigned_extrinsic(695 _equivocation_proof: fg_primitives::EquivocationProof<696 <Block as BlockT>::Hash,697 NumberFor<Block>,698 >,699 _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,700 ) -> Option<()> {701 None702 }703704 fn generate_key_ownership_proof(705 _set_id: fg_primitives::SetId,706 _authority_id: GrandpaId,707 ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {708 // NOTE: this is the only implementation possible since we've709 // defined our key owner proof type as a bottom type (i.e. a type710 // with no values).711 None712 }713 }714 715 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {716 fn account_nonce(account: AccountId) -> Index {717 System::account_nonce(account)718 }719 }720721 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {722 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {723 TransactionPayment::query_info(uxt, len)724 }725 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {726 TransactionPayment::query_fee_details(uxt, len)727 }728 }729730 #[cfg(feature = "runtime-benchmarks")]731 impl frame_benchmarking::Benchmark<Block> for Runtime {732 fn dispatch_benchmark(733 config: frame_benchmarking::BenchmarkConfig734 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {735 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};736737 let whitelist: Vec<TrackedStorageKey> = vec![738 // Alice account739 hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),740 // // Total Issuance741 // hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),742 // // Execution Phase743 // hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),744 // // Event Count745 // hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),746 // // System Events747 // hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),748 ];749750 let mut batches = Vec::<BenchmarkBatch>::new();751 let params = (&config, &whitelist);752753 add_benchmark!(params, batches, pallet_nft, Nft);754755 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }756 Ok(batches)757 }758 }759}1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "256"]1112// Make the WASM binary available.13#[cfg(feature = "std")]14include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1516use pallet_grandpa::fg_primitives;17use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};18use sp_api::impl_runtime_apis;19use sp_consensus_aura::sr25519::AuthorityId as AuraId;20use sp_core::{ crypto::KeyTypeId, crypto::Public, OpaqueMetadata };21use sp_runtime::{22 Permill, Perbill, Percent,23 ModuleId,24 create_runtime_str, generic, impl_opaque_keys,25 traits::{26 Convert, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, 27 IdentityLookup, NumberFor, Verify, AccountIdConversion,28 },29 transaction_validity::{TransactionSource, TransactionValidity},30 ApplyExtrinsicResult, MultiSignature,31};32#[cfg(feature = "std")]33use sp_version::NativeVersion;34use sp_version::RuntimeVersion;35pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment, CurrencyAdapter, FeeDetails, RuntimeDispatchInfo};36// A few exports that help ease life for downstream crates.37pub use pallet_balances::Call as BalancesCall;38pub use pallet_contracts::{Schedule as ContractsSchedule };39pub use frame_support::{40 construct_runtime,41 dispatch::DispatchResult,42 parameter_types,43 StorageValue,44 traits::{45 Currency, ExistenceRequirement, Get, KeyOwnerProofSystem, OnUnbalanced, Randomness,46 LockIdentifier,47 },48 weights::{49 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},50 DispatchClass, DispatchInfo, GetDispatchInfo, Pays, PostDispatchInfo, Weight,51 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients52 },53};54use pallet_contracts::weights::WeightInfo;55// #[cfg(any(feature = "std", test))]56use frame_system::{57 self as system,58 EnsureRoot, 59 limits::{BlockWeights, BlockLength},60};61use sp_std::{prelude::*, marker::PhantomData};62use sp_arithmetic::{traits::{BaseArithmetic, Unsigned}};63use smallvec::smallvec;6465pub use pallet_timestamp::Call as TimestampCall;6667mod chain_extension;68use crate::chain_extension::{ NFTExtension, Imbalance };6970/// Struct that handles the conversion of Balance -> `u64`. This is used for71/// staking's election calculation.72pub struct CurrencyToVoteHandler;7374impl CurrencyToVoteHandler {75 fn factor() -> Balance {76 (Balances::total_issuance() / u64::max_value() as Balance).max(1)77 }78}7980impl Convert<Balance, u64> for CurrencyToVoteHandler {81 fn convert(x: Balance) -> u64 {82 (x / Self::factor()) as u6483 }84}8586impl Convert<u128, Balance> for CurrencyToVoteHandler {87 fn convert(x: u128) -> Balance {88 x * Self::factor()89 }90}9192/// Re-export a nft pallet93/// TODO: Check this re-export. Is this safe and good style?94extern crate pallet_nft;95pub use pallet_nft::*;9697/// An index to a block.98pub type BlockNumber = u32;99100/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.101pub type Signature = MultiSignature;102103/// Some way of identifying an account on the chain. We intentionally make it equivalent104/// to the public key of our transaction signing scheme.105pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;106107/// The type for looking up accounts. We don't expect more than 4 billion of them, but you108/// never know...109pub type AccountIndex = u32;110111/// Balance of an account.112pub type Balance = u128;113114/// Index of a transaction in the chain.115pub type Index = u32;116117/// A hash of some data used by the chain.118pub type Hash = sp_core::H256;119120/// Digest item type.121pub type DigestItem = generic::DigestItem<Hash>;122123mod nft_weights;124125/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know126/// the specifics of the runtime. They can then be made to be agnostic over specific formats127/// of data like extrinsics, allowing for them to continue syncing the network through upgrades128/// to even the core data structures.129pub mod opaque {130 use super::*;131132 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;133134 /// Opaque block header type.135 pub type Header = generic::Header<BlockNumber, BlakeTwo256>;136 /// Opaque block type.137 pub type Block = generic::Block<Header, UncheckedExtrinsic>;138 /// Opaque block identifier type.139 pub type BlockId = generic::BlockId<Block>;140141 impl_opaque_keys! {142 pub struct SessionKeys {143 pub aura: Aura,144 pub grandpa: Grandpa,145 }146 }147}148149/// This runtime version.150pub const VERSION: RuntimeVersion = RuntimeVersion {151 spec_name: create_runtime_str!("nft"),152 impl_name: create_runtime_str!("nft"),153 authoring_version: 1,154 spec_version: 3,155 impl_version: 1,156 apis: RUNTIME_API_VERSIONS,157 transaction_version: 1,158};159160pub const MILLISECS_PER_BLOCK: u64 = 6000;161162pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;163164// These time units are defined in number of blocks.165pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);166pub const HOURS: BlockNumber = MINUTES * 60;167pub const DAYS: BlockNumber = HOURS * 24;168169/// The version information used to identify this runtime when compiled natively.170#[cfg(feature = "std")]171pub fn native_version() -> NativeVersion {172 NativeVersion {173 runtime_version: VERSION,174 can_author_with: Default::default(),175 }176}177178/// Provides a membership set with only the configured aura users179pub struct ValiudatorsOnly<Runtime: pallet_aura::Config>(PhantomData<Runtime>);180impl frame_support::traits::Contains<AccountId> for ValiudatorsOnly<Runtime> {181 fn contains(t: &AccountId) -> bool {182 let arr: [u8; 32] = *t.as_ref();183 let raw_key: Vec<u8> = Vec::from(arr);184185 match pallet_aura::Module::<Runtime>::authorities().iter().find(|auth| auth.to_raw_vec() == raw_key) {186 Some(_) => true,187 None => false,188 } 189 }190 fn sorted_members() -> Vec<AccountId> {191 let mut members: Vec<AccountId> = Vec::new();192 for auth in pallet_aura::Module::<Runtime>::authorities() {193 let mut arr: [u8; 32] = Default::default(); 194 let bor_arr = auth.clone().to_raw_vec();195 let slice = bor_arr.as_slice();196 arr.copy_from_slice(slice);197 members.push(AccountId::from(arr));198 }199 members 200 }201 fn count() -> usize {202 pallet_aura::Module::<Runtime>::authorities().len()203 }204}205206impl frame_support::traits::ContainsLengthBound for ValiudatorsOnly<Runtime> {207 fn min_len() -> usize {208 1209 }210 fn max_len() -> usize {211 100212 }213}214215type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;216217pub struct DealWithFees;218impl OnUnbalanced<NegativeImbalance> for DealWithFees {219 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {220 if let Some(fees) = fees_then_tips.next() {221 // for fees, 100% to treasury222 let mut split = fees.ration(100, 0);223 if let Some(tips) = fees_then_tips.next() {224 // for tips, if any, 100% to treasury225 tips.ration_merge_into(100, 0, &mut split);226 }227 Treasury::on_unbalanced(split.0);228 // Author::on_unbalanced(split.1);229 }230 }231}232233// impl OnUnbalanced<NegativeImbalance> for DealWithFees {234// fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {235// if let Some(fees) = fees_then_tips.next() {236// // for fees, 100% to treasury237// let mut split = fees.ration(100, 0);238// if let Some(tips) = fees_then_tips.next() {239// // for tips, if any, 100% to treasury240// tips.ration_merge_into(100, 0, &mut split);241// }242// Treasury::on_unbalanced(split.0);243// // Author::on_unbalanced(split.1);244// }245// }246// }247248/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.249/// This is used to limit the maximal weight of a single extrinsic.250const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);251/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used252/// by Operational extrinsics.253const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);254/// We allow for 2 seconds of compute with a 6 second average block time.255const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND;256257parameter_types! {258 pub const BlockHashCount: BlockNumber = 2400;259 pub RuntimeBlockLength: BlockLength =260 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);261 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);262 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;263 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()264 .base_block(BlockExecutionWeight::get())265 .for_class(DispatchClass::all(), |weights| {266 weights.base_extrinsic = ExtrinsicBaseWeight::get();267 })268 .for_class(DispatchClass::Normal, |weights| {269 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);270 })271 .for_class(DispatchClass::Operational, |weights| {272 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);273 // Operational transactions have some extra reserved space, so that they274 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.275 weights.reserved = Some(276 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT277 );278 })279 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)280 .build_or_panic();281 pub const Version: RuntimeVersion = VERSION;282 pub const SS58Prefix: u8 = 42;283}284285impl system::Config for Runtime {286 /// The basic call filter to use in dispatchable.287 type BaseCallFilter = ();288 /// The identifier used to distinguish between accounts.289 type AccountId = AccountId;290 /// The aggregated dispatch type that is available for extrinsics.291 type Call = Call;292 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.293 type Lookup = IdentityLookup<AccountId>;294 /// The index type for storing how many extrinsics an account has signed.295 type Index = Index;296 /// The index type for blocks.297 type BlockNumber = BlockNumber;298 /// The type for hashing blocks and tries.299 type Hash = Hash;300 /// The hashing algorithm used.301 type Hashing = BlakeTwo256;302 /// The header type.303 type Header = generic::Header<BlockNumber, BlakeTwo256>;304 /// The ubiquitous event type.305 type Event = Event;306 /// The ubiquitous origin type.307 type Origin = Origin;308 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).309 type BlockHashCount = BlockHashCount;310 /// The weight of database operations that the runtime can invoke.311 type DbWeight = RocksDbWeight;312 /// The weight of the overhead invoked on the block import process, independent of the313 /// extrinsics included in that block.314 type BlockWeights = RuntimeBlockWeights;315 /// Version of the runtime.316 type Version = Version;317 /// This type is being generated by `construct_runtime!`.318 type PalletInfo = PalletInfo;319 /// What to do if a new account is created.320 type OnNewAccount = ();321 /// What to do if an account is fully reaped from the system.322 type OnKilledAccount = ();323 /// The data to be stored in an account.324 type AccountData = pallet_balances::AccountData<Balance>;325 /// Weight information for the extrinsics of this pallet.326 type SystemWeightInfo = system::weights::SubstrateWeight<Runtime>;327 328 type BlockLength = RuntimeBlockLength;329 type SS58Prefix = SS58Prefix;330}331332impl pallet_aura::Config for Runtime {333 type AuthorityId = AuraId;334}335336impl pallet_grandpa::Config for Runtime {337 type Event = Event;338 type Call = Call;339340 type KeyOwnerProofSystem = ();341342 type KeyOwnerProof =343 <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;344345 type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(346 KeyTypeId,347 GrandpaId,348 )>>::IdentificationTuple;349350 type HandleEquivocation = ();351352 type WeightInfo = ();353}354355parameter_types! {356 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;357}358359impl pallet_timestamp::Config for Runtime {360 /// A timestamp: milliseconds since the unix epoch.361 type Moment = u64;362 type OnTimestampSet = Aura;363 type MinimumPeriod = MinimumPeriod;364 type WeightInfo = ();365}366367parameter_types! {368 // pub const ExistentialDeposit: u128 = 500;369 pub const ExistentialDeposit: u128 = 0;370 pub const MaxLocks: u32 = 50;371}372373impl pallet_balances::Config for Runtime {374 type MaxLocks = MaxLocks;375 /// The type for recording an account's balance.376 type Balance = Balance;377 /// The ubiquitous event type.378 type Event = Event;379 type DustRemoval = Treasury;380 type ExistentialDeposit = ExistentialDeposit;381 type AccountStore = System;382 type WeightInfo = ();383}384385pub const MICROUNIQUE: Balance = 1_000_000_000;386pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;387pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;388pub const UNIQUE: Balance = 100 * CENTIUNIQUE;389390pub const fn deposit(items: u32, bytes: u32) -> Balance {391 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE392}393394parameter_types! {395 pub const TombstoneDeposit: Balance = deposit(396 0,397 sp_std::mem::size_of::<pallet_contracts::ContractInfo<Runtime>>() as u32398 );399 pub const DepositPerContract: Balance = TombstoneDeposit::get();400 pub const DepositPerStorageByte: Balance = deposit(0, 1);401 pub const DepositPerStorageItem: Balance = deposit(1, 0);402 pub RentFraction: Perbill = Perbill::from_rational_approximation(1u32, 30 * DAYS);403 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;404 pub const SignedClaimHandicap: u32 = 2;405 pub const MaxDepth: u32 = 32;406 pub const MaxValueSize: u32 = 16 * 1024;407 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb 408 // The lazy deletion runs inside on_initialize.409 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *410 RuntimeBlockWeights::get().max_block;411 // The weight needed for decoding the queue should be less or equal than a fifth412 // of the overall weight dedicated to the lazy deletion.413 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (414 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -415 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)416 )) / 5) as u32;417}418419420impl pallet_contracts::Config for Runtime {421 type Time = Timestamp;422 type Randomness = RandomnessCollectiveFlip;423 type Currency = Balances;424 type Event = Event;425 type RentPayment = ();426 type SignedClaimHandicap = SignedClaimHandicap;427 type TombstoneDeposit = TombstoneDeposit;428 type DepositPerContract = DepositPerContract;429 type DepositPerStorageByte = DepositPerStorageByte;430 type DepositPerStorageItem = DepositPerStorageItem;431 type RentFraction = RentFraction;432 type SurchargeReward = SurchargeReward;433 type MaxDepth = MaxDepth;434 type MaxValueSize = MaxValueSize;435 type WeightPrice = pallet_transaction_payment::Module<Self>;436 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;437 type ChainExtension = NFTExtension;438 type DeletionQueueDepth = DeletionQueueDepth;439 type DeletionWeightLimit = DeletionWeightLimit;440 type MaxCodeSize = MaxCodeSize;441}442443parameter_types! {444 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer 445}446447/// Linear implementor of `WeightToFeePolynomial` 448pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);449450impl<T> WeightToFeePolynomial for LinearFee<T> where451 T: BaseArithmetic + From<u32> + Copy + Unsigned452{453 type Balance = T;454455 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {456 smallvec!(WeightToFeeCoefficient {457 coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer458 coeff_frac: Perbill::zero(),459 negative: false,460 degree: 1,461 })462 }463}464465impl pallet_transaction_payment::Config for Runtime {466 type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees>;467 type TransactionByteFee = TransactionByteFee;468 type WeightToFee = LinearFee<Balance>;469 type FeeMultiplierUpdate = ();470}471472parameter_types! {473 pub const ProposalBond: Permill = Permill::from_percent(5);474 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;475 pub const SpendPeriod: BlockNumber = 5 * MINUTES;476 pub const Burn: Permill = Permill::from_percent(0);477 pub const TipCountdown: BlockNumber = 1 * DAYS;478 pub const TipFindersFee: Percent = Percent::from_percent(20);479 pub const TipReportDepositBase: Balance = 1 * UNIQUE;480 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;481 pub const BountyDepositBase: Balance = 1 * UNIQUE;482 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;483 pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry");484 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;485 pub const MaximumReasonLength: u32 = 16384;486 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);487 pub const BountyValueMinimum: Balance = 5 * UNIQUE;488}489490impl pallet_treasury::Config for Runtime {491 type ModuleId = TreasuryModuleId;492 type Currency = Balances;493 type ApproveOrigin = EnsureRoot<AccountId>;494 type RejectOrigin = EnsureRoot<AccountId>;495 type Event = Event;496 type OnSlash = ();497 type ProposalBond = ProposalBond;498 type ProposalBondMinimum = ProposalBondMinimum;499 type SpendPeriod = SpendPeriod;500 type Burn = Burn;501 type BurnDestination = ();502 type SpendFunds = ();503 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;504}505506impl pallet_sudo::Config for Runtime {507 type Event = Event;508 type Call = Call;509}510511parameter_types! {512 pub const MinVestedTransfer: Balance = 10 * UNIQUE;513}514515impl pallet_vesting::Config for Runtime {516 type Event = Event;517 type Currency = Balances;518 type BlockNumberToBalance = ConvertInto;519 type MinVestedTransfer = MinVestedTransfer;520 type WeightInfo = ();521}522523parameter_types! {524 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();525 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;526}527528/// Used for the module nft in `./nft.rs`529impl pallet_nft::Config for Runtime {530 type Event = Event;531 type WeightInfo = nft_weights::WeightInfo;532 type Currency = Balances;533 type CollectionCreationPrice = CollectionCreationPrice;534 type TreasuryAccountId = TreasuryAccountId;535}536537construct_runtime!(538 pub enum Runtime where539 Block = Block,540 NodeBlock = opaque::Block,541 UncheckedExtrinsic = UncheckedExtrinsic542 {543 System: system::{Module, Call, Config, Storage, Event<T>},544 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},545 Contracts: pallet_contracts::{Module, Call, Config<T>, Storage, Event<T>},546 Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},547 Aura: pallet_aura::{Module, Config<T> },548 Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},549 Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},550 TransactionPayment: pallet_transaction_payment::{Module, Storage},551 Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>},552 Nft: pallet_nft::{Module, Call, Config<T>, Storage, Event<T>},553 Treasury: pallet_treasury::{Module, Call, Storage, Config, Event<T>},554 Vesting: pallet_vesting::{Module, Call, Config<T>, Storage, Event<T>},555 }556);557558/// The address format for describing accounts.559pub type Address = AccountId;560/// Block header type as expected by this runtime.561pub type Header = generic::Header<BlockNumber, BlakeTwo256>;562/// Block type as expected by this runtime.563pub type Block = generic::Block<Header, UncheckedExtrinsic>;564/// A Block signed with a Justification565pub type SignedBlock = generic::SignedBlock<Block>;566/// BlockId type as expected by this runtime.567pub type BlockId = generic::BlockId<Block>;568/// The SignedExtension to the basic transaction logic.569pub type SignedExtra = (570 system::CheckSpecVersion<Runtime>,571 system::CheckTxVersion<Runtime>,572 system::CheckGenesis<Runtime>,573 system::CheckEra<Runtime>,574 system::CheckNonce<Runtime>,575 system::CheckWeight<Runtime>,576 pallet_nft::ChargeTransactionPayment<Runtime>,577);578/// Unchecked extrinsic type as expected by this runtime.579pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;580/// Extrinsic type that has already been checked.581pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;582/// Executive: handles dispatch to the various modules.583pub type Executive =584 frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;585586impl_runtime_apis! {587588 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>589 for Runtime590 {591 fn call(592 origin: AccountId,593 dest: AccountId,594 value: Balance,595 gas_limit: u64,596 input_data: Vec<u8>,597 ) -> pallet_contracts_primitives::ContractExecResult {598 Contracts::bare_call(origin, dest, value, gas_limit, input_data)599 }600601 fn get_storage(602 address: AccountId,603 key: [u8; 32],604 ) -> pallet_contracts_primitives::GetStorageResult {605 Contracts::get_storage(address, key)606 }607608 fn rent_projection(609 address: AccountId,610 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {611 Contracts::rent_projection(address)612 }613 }614615 impl sp_api::Core<Block> for Runtime {616 fn version() -> RuntimeVersion {617 VERSION618 }619620 fn execute_block(block: Block) {621 Executive::execute_block(block)622 }623624 fn initialize_block(header: &<Block as BlockT>::Header) {625 Executive::initialize_block(header)626 }627 }628629 impl sp_api::Metadata<Block> for Runtime {630 fn metadata() -> OpaqueMetadata {631 Runtime::metadata().into()632 }633 }634635 impl sp_block_builder::BlockBuilder<Block> for Runtime {636 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {637 Executive::apply_extrinsic(extrinsic)638 }639640 fn finalize_block() -> <Block as BlockT>::Header {641 Executive::finalize_block()642 }643644 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {645 data.create_extrinsics()646 }647648 fn check_inherents(649 block: Block,650 data: sp_inherents::InherentData,651 ) -> sp_inherents::CheckInherentsResult {652 data.check_extrinsics(&block)653 }654655 fn random_seed() -> <Block as BlockT>::Hash {656 RandomnessCollectiveFlip::random_seed()657 }658 }659660 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {661 fn validate_transaction(662 source: TransactionSource,663 tx: <Block as BlockT>::Extrinsic,664 ) -> TransactionValidity {665 Executive::validate_transaction(source, tx)666 }667 }668669 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {670 fn offchain_worker(header: &<Block as BlockT>::Header) {671 Executive::offchain_worker(header)672 }673 }674675 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {676 fn slot_duration() -> u64 {677 Aura::slot_duration()678 }679680 fn authorities() -> Vec<AuraId> {681 Aura::authorities()682 }683 }684685 impl sp_session::SessionKeys<Block> for Runtime {686 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {687 opaque::SessionKeys::generate(seed)688 }689690 fn decode_session_keys(691 encoded: Vec<u8>,692 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {693 opaque::SessionKeys::decode_into_raw_public_keys(&encoded)694 }695 }696697 impl fg_primitives::GrandpaApi<Block> for Runtime {698 fn grandpa_authorities() -> GrandpaAuthorityList {699 Grandpa::grandpa_authorities()700 }701702 fn submit_report_equivocation_unsigned_extrinsic(703 _equivocation_proof: fg_primitives::EquivocationProof<704 <Block as BlockT>::Hash,705 NumberFor<Block>,706 >,707 _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,708 ) -> Option<()> {709 None710 }711712 fn generate_key_ownership_proof(713 _set_id: fg_primitives::SetId,714 _authority_id: GrandpaId,715 ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {716 // NOTE: this is the only implementation possible since we've717 // defined our key owner proof type as a bottom type (i.e. a type718 // with no values).719 None720 }721 }722 723 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {724 fn account_nonce(account: AccountId) -> Index {725 System::account_nonce(account)726 }727 }728729 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {730 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {731 TransactionPayment::query_info(uxt, len)732 }733 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {734 TransactionPayment::query_fee_details(uxt, len)735 }736 }737738 #[cfg(feature = "runtime-benchmarks")]739 impl frame_benchmarking::Benchmark<Block> for Runtime {740 fn dispatch_benchmark(741 config: frame_benchmarking::BenchmarkConfig742 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {743 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};744745 let whitelist: Vec<TrackedStorageKey> = vec![746 // Alice account747 hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),748 // // Total Issuance749 // hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),750 // // Execution Phase751 // hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),752 // // Event Count753 // hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),754 // // System Events755 // hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),756 ];757758 let mut batches = Vec::<BenchmarkBatch>::new();759 let params = (&config, &whitelist);760761 add_benchmark!(params, batches, pallet_nft, Nft);762763 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }764 Ok(batches)765 }766 }767}runtime_types.jsondiffbeforeafterboth--- a/runtime_types.json
+++ b/runtime_types.json
@@ -31,6 +31,13 @@
"ConstData": "Vec<u8>",
"VariableData": "Vec<u8>"
},
+ "SponsorshipState": {
+ "_enum": {
+ "Disabled": null,
+ "Unconfirmed": "AccountId",
+ "Confirmed": "AccountId"
+ }
+ },
"Collection": {
"Owner": "AccountId",
"Mode": "CollectionMode",
@@ -42,8 +49,7 @@
"MintMode": "bool",
"OffchainSchema": "Vec<u8>",
"SchemaVersion": "SchemaVersion",
- "Sponsor": "AccountId",
- "SponsorConfirmed": "bool",
+ "Sponsorship": "SponsorshipState",
"Limits": "CollectionLimits",
"VariableOnChainSchema": "Vec<u8>",
"ConstOnChainSchema": "Vec<u8>"
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -25,7 +25,10 @@
"testSetSchemaVersion": "mocha --timeout 9999999 -r ts-node/register ./**/setSchemaVersion.test.ts",
"testSetVariableMetaData": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetaData.test.ts",
"testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",
+ "testSetCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionSponsor.test.ts",
+ "testConfirmSponsorship": "mocha --timeout 9999999 -r ts-node/register ./**/confirmSponsorship.test.ts",
"testRemoveCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionAdmin.test.ts",
+ "testRemoveCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionSponsor.test.ts",
"testRemoveFromWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromWhiteList.test.ts",
"testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",
"testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
tests/src/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -1,59 +1,59 @@
-//
-// This file is subject to the terms and conditions defined in
-// file 'LICENSE', which is part of this source code package.
-//
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import { default as usingApi } from './substrate/substrate-api';
-import { createCollectionExpectFailure, createCollectionExpectSuccess } from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-describe('integration test: ext. createCollection():', () => {
- it('Create new NFT collection', async () => {
- await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
- });
- it('Create new NFT collection whith collection_name of maximum length (64 bytes)', async () => {
- await createCollectionExpectSuccess({name: 'A'.repeat(64)});
- });
- it('Create new NFT collection whith collection_description of maximum length (256 bytes)', async () => {
- await createCollectionExpectSuccess({description: 'A'.repeat(256)});
- });
- it('Create new NFT collection whith token_prefix of maximum length (16 bytes)', async () => {
- await createCollectionExpectSuccess({tokenPrefix: 'A'.repeat(16)});
- });
- it('Create new Fungible collection', async () => {
- await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- });
- it('Create new ReFungible collection', async () => {
- await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- });
-});
-
-describe('(!negative test!) integration test: ext. createCollection():', () => {
- it('(!negative test!) create new NFT collection whith incorrect data (mode)', async () => {
- await usingApi(async (api) => {
- const AcollectionCount = parseInt((await api.query.nft.collectionCount()).toString(), 10);
-
- const badTransaction = async () => {
- await createCollectionExpectSuccess({mode: {type: 'Invalid'}});
- };
- // tslint:disable-next-line:no-unused-expression
- expect(badTransaction()).to.be.rejected;
-
- const BcollectionCount = parseInt((await api.query.nft.collectionCount()).toString(), 10);
- expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Incorrect collection created.');
- });
- });
- it('(!negative test!) create new NFT collection whith incorrect data (collection_name)', async () => {
- await createCollectionExpectFailure({ name: 'A'.repeat(65), mode: {type: 'NFT'}});
- });
- it('(!negative test!) create new NFT collection whith incorrect data (collection_description)', async () => {
- await createCollectionExpectFailure({ description: 'A'.repeat(257), mode: { type: 'NFT' }});
- });
- it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
- await createCollectionExpectFailure({tokenPrefix: 'A'.repeat(17), mode: {type: 'NFT'}});
- });
-});
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import { default as usingApi } from './substrate/substrate-api';
+import { createCollectionExpectFailure, createCollectionExpectSuccess } from './util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('integration test: ext. createCollection():', () => {
+ it('Create new NFT collection', async () => {
+ await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
+ });
+ it('Create new NFT collection whith collection_name of maximum length (64 bytes)', async () => {
+ await createCollectionExpectSuccess({name: 'A'.repeat(64)});
+ });
+ it('Create new NFT collection whith collection_description of maximum length (256 bytes)', async () => {
+ await createCollectionExpectSuccess({description: 'A'.repeat(256)});
+ });
+ it('Create new NFT collection whith token_prefix of maximum length (16 bytes)', async () => {
+ await createCollectionExpectSuccess({tokenPrefix: 'A'.repeat(16)});
+ });
+ it('Create new Fungible collection', async () => {
+ await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+ });
+ it('Create new ReFungible collection', async () => {
+ await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+ });
+});
+
+describe('(!negative test!) integration test: ext. createCollection():', () => {
+ it('(!negative test!) create new NFT collection whith incorrect data (mode)', async () => {
+ await usingApi(async (api) => {
+ const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);
+
+ const badTransaction = async () => {
+ await createCollectionExpectSuccess({mode: {type: 'Invalid'}});
+ };
+ // tslint:disable-next-line:no-unused-expression
+ expect(badTransaction()).to.be.rejected;
+
+ const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);
+ expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Incorrect collection created.');
+ });
+ });
+ it('(!negative test!) create new NFT collection whith incorrect data (collection_name)', async () => {
+ await createCollectionExpectFailure({ name: 'A'.repeat(65), mode: {type: 'NFT'}});
+ });
+ it('(!negative test!) create new NFT collection whith incorrect data (collection_description)', async () => {
+ await createCollectionExpectFailure({ description: 'A'.repeat(257), mode: { type: 'NFT' }});
+ });
+ it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
+ await createCollectionExpectFailure({tokenPrefix: 'A'.repeat(17), mode: {type: 'NFT'}});
+ });
+});
tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -25,6 +25,7 @@
const Treasury = "5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z";
const saneMinimumFee = 0.05;
const saneMaximumFee = 0.5;
+const createCollectionDeposit = 100;
let alice: IKeyringPair;
let bob: IKeyringPair;
@@ -127,8 +128,8 @@
const aliceBalanceAfter = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());
const fee = aliceBalanceBefore.minus(aliceBalanceAfter);
- expect(fee.dividedBy(1e15).toNumber()).to.be.lessThan(saneMaximumFee);
- expect(fee.dividedBy(1e15).toNumber()).to.be.greaterThan(saneMinimumFee);
+ expect(fee.dividedBy(1e15).toNumber()).to.be.lessThan(saneMaximumFee + createCollectionDeposit);
+ expect(fee.dividedBy(1e15).toNumber()).to.be.greaterThan(saneMinimumFee + createCollectionDeposit);
});
});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -376,8 +376,9 @@
// What to expect
expect(result.success).to.be.true;
- expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());
- expect(collection.SponsorConfirmed).to.be.false;
+ expect(collection.Sponsorship).to.deep.equal({
+ Unconfirmed: sponsor.toString(),
+ });
});
}
@@ -395,8 +396,7 @@
// What to expect
expect(result.success).to.be.true;
- expect(collection.Sponsor).to.be.equal(nullPublicKey);
- expect(collection.SponsorConfirmed).to.be.false;
+ expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });
});
}
@@ -434,8 +434,9 @@
// What to expect
expect(result.success).to.be.true;
- expect(collection.Sponsor).to.be.equal(sender.address);
- expect(collection.SponsorConfirmed).to.be.true;
+ expect(collection.Sponsorship).to.be.deep.equal({
+ Confirmed: sender.address,
+ });
});
}