difftreelog
Merge branch 'develop' into feature/NFTPAR-142
in: master
# Conflicts: # pallets/nft/src/default_weights.rs # pallets/nft/src/lib.rs
6 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3737,6 +3737,7 @@
"frame-support",
"frame-system",
"log",
+ "pallet-contracts",
"pallet-transaction-payment",
"parity-scale-codec",
"serde",
pallets/nft/Cargo.tomldiffbeforeafterboth--- a/pallets/nft/Cargo.toml
+++ b/pallets/nft/Cargo.toml
@@ -73,6 +73,34 @@
branch = 'v2.0.0_release'
optional = true
+[dependencies.pallet-contracts]
+default-features = false
+git = 'https://github.com/usetech-llc/substrate.git'
+package = 'pallet-contracts'
+branch = 'v2.0.0_release'
+version = '2.0.0'
+
+[dependencies.pallet-balances]
+default-features = false
+git = 'https://github.com/usetech-llc/substrate.git'
+package = 'pallet-balances'
+branch = 'v2.0.0_release'
+version = '2.0.0'
+
+[dependencies.pallet-timestamp]
+default-features = false
+git = 'https://github.com/usetech-llc/substrate.git'
+package = 'pallet-timestamp'
+branch = 'v2.0.0_release'
+version = '2.0.0'
+
+[dependencies.pallet-randomness-collective-flip]
+default-features = false
+git = 'https://github.com/usetech-llc/substrate.git'
+package = 'pallet-randomness-collective-flip'
+branch = 'v2.0.0_release'
+version = '2.0.0'
+
[features]
default = ['std']
std = [
@@ -80,6 +108,9 @@
"serde/std",
'frame-support/std',
'frame-system/std',
+ 'pallet-balances/std',
+ 'pallet-timestamp/std',
+ 'pallet-randomness-collective-flip/std',
'sp-std/std',
'sp-runtime/std',
'frame-benchmarking/std',
pallets/nft/src/default_weights.rsdiffbeforeafterboth--- a/pallets/nft/src/default_weights.rs
+++ b/pallets/nft/src/default_weights.rs
@@ -107,4 +107,9 @@
.saturating_add(DbWeight::get().reads(2 as Weight))
.saturating_add(DbWeight::get().writes(1 as Weight))
}
+ // fn enable_contract_sponsoring() -> Weight {
+ // (0 as Weight)
+ // .saturating_add(DbWeight::get().reads(1 as Weight))
+ // .saturating_add(DbWeight::get().writes(1 as Weight))
+ // }
}
pallets/nft/src/lib.rsdiffbeforeafterboth28use sp_runtime::sp_std::prelude::Vec;28use sp_runtime::sp_std::prelude::Vec;29use sp_runtime::{29use sp_runtime::{30 traits::{30 traits::{31 DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SaturatedConversion, Saturating,31 DispatchInfoOf, Dispatchable, PostDispatchInfoOf, Saturating, SignedExtension, Zero,32 SignedExtension, Zero,33 },32 },34 transaction_validity::{33 transaction_validity::{35 InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError,34 InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction,36 ValidTransaction,37 },35 },38 FixedPointOperand, FixedU128,36 FixedPointOperand, FixedU128,39};37};38use pallet_contracts::ContractAddressFor;39use sp_runtime::traits::StaticLookup;404041#[cfg(test)]41#[cfg(test)]42mod mock;42mod mock;208 fn set_const_on_chain_schema() -> Weight;208 fn set_const_on_chain_schema() -> Weight;209 fn set_variable_on_chain_schema() -> Weight;209 fn set_variable_on_chain_schema() -> Weight;210 fn set_variable_meta_data() -> Weight;210 fn set_variable_meta_data() -> Weight;211 // fn enable_contract_sponsoring() -> Weight;211}212}212213213#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]214#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]249 }250 }250}251}251252252pub trait Trait: system::Trait + Sized {253pub trait Trait: system::Trait + Sized + transaction_payment::Trait + pallet_contracts::Trait {253 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;254 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;254255255 /// Weight information for extrinsics in this pallet.256 /// Weight information for extrinsics in this pallet.301 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => Vec<BasketItem<T::AccountId, T::BlockNumber>>;302 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => Vec<BasketItem<T::AccountId, T::BlockNumber>>;302 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => T::BlockNumber;303 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => T::BlockNumber;303304304 // Sponsorship305 // Contract Sponsorship and Ownership305 pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;306 pub ContractOwner get(fn contract_owner): map hasher(identity) T::AccountId => T::AccountId;306 pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;307 pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(identity) T::AccountId => bool;307 }308 }308 add_extra_genesis {309 add_extra_genesis {309 build(|config: &GenesisConfig<T>| {310 build(|config: &GenesisConfig<T>| {1253 Ok(())1254 Ok(())1254 } 1255 }12561257 /// Enable smart contract self-sponsoring.1258 /// 1259 /// # Permissions1260 /// 1261 /// * Contract Owner1262 /// 1263 /// # Arguments1264 /// 1265 /// * contract address1266 /// * enable flag1267 /// 1268 #[weight = 0]1269 pub fn enable_contract_sponsoring(1270 origin,1271 contract_address: T::AccountId,1272 enable: bool1273 ) -> DispatchResult {1274 let sender = ensure_signed(origin)?;1275 let mut is_owner = false;1276 if <ContractOwner<T>>::contains_key(contract_address.clone()) {1277 let owner = <ContractOwner<T>>::get(&contract_address);1278 is_owner = sender == owner;1279 }1280 ensure!(is_owner, "Only contract owner may call this method");12811282 <ContractSelfSponsoring<T>>::insert(contract_address, enable);1283 Ok(())1284 }12851255 }1286 }1256}1287}1919/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1950/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1920/// in the queue.1951/// in the queue.1921#[derive(Encode, Decode, Clone, Eq, PartialEq)]1952#[derive(Encode, Decode, Clone, Eq, PartialEq)]1922pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1953pub struct ChargeTransactionPayment<T: Trait + Send + Sync>(1923 #[codec(compact)] BalanceOf<T>,1954 #[codec(compact)] BalanceOf<T>1924);1955);192519561926impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1957impl<T: Trait + Send + Sync> sp_std::fmt::Debug1927 for ChargeTransactionPayment<T>1958 for ChargeTransactionPayment<T>1928{1959{1929 #[cfg(feature = "std")]1960 #[cfg(feature = "std")]1936 }1967 }1937}1968}193819691939impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1970impl<T: Trait + Send + Sync> ChargeTransactionPayment<T>1940where1971where1941 T::Call:1972 T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Call<T>> + IsSubType<pallet_contracts::Call<T>>,1942 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Call<T>>,1943 BalanceOf<T>: Send + Sync + FixedPointOperand,1973 BalanceOf<T>: Send + Sync + FixedPointOperand,1944{1974{196919991970 // Set fee based on call type. Creating collection costs 1 Unique.2000 // Set fee based on call type. Creating collection costs 1 Unique.1971 // All other transactions have traditional fees so far2001 // All other transactions have traditional fees so far2002 // let fee = match call.is_sub_type() {2003 // Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),2004 // _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes2005 // // _ => <BalanceOf<T>>::from(100)2006 // };1972 let fee = match call.is_sub_type() {2007 let fee = Self::traditional_fee(len, info, tip);1973 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1974 _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes1975 // _ => <BalanceOf<T>>::from(100)1976 };197720081978 // Determine who is paying transaction fee based on ecnomic model2009 // Determine who is paying transaction fee based on ecnomic model1979 // Parse call to extract collection ID and access collection sponsor2010 // Parse call to extract collection ID and access collection sponsor1980 let sponsor: T::AccountId = match call.is_sub_type() {2011 let mut sponsor: T::AccountId = match IsSubType::<Call<T>>::is_sub_type(call) {1981 Some(Call::create_item(collection_id, _properties, _owner)) => {2012 Some(Call::create_item(collection_id, _properties, _owner)) => {1982 <Collection<T>>::get(collection_id).sponsor2013 <Collection<T>>::get(collection_id).sponsor1983 }2014 }2046 _ => T::AccountId::default(),2077 _ => T::AccountId::default(),2047 };2078 };20792080 // Sponsor smart contracts2081 sponsor = match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {20822083 // On instantiation: set the contract owner2084 Some(pallet_contracts::Call::instantiate(_endowment, _gas_limit, code_hash, data)) => {20852086 let new_contract_address = <T as pallet_contracts::Trait>::DetermineContractAddress::contract_address_for(2087 code_hash,2088 &data,2089 &who,2090 );2091 <ContractOwner<T>>::insert(new_contract_address.clone(), who.clone());20922093 T::AccountId::default()2094 },20952096 // When the contract is called, check if the sponsoring is enabled and pay fees from contract endowment if it is2097 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {20982099 let mut sp = T::AccountId::default();2100 let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());2101 if <ContractSelfSponsoring<T>>::contains_key(called_contract.clone()) {2102 if <ContractSelfSponsoring<T>>::get(called_contract.clone()) {2103 sp = called_contract;2104 }2105 }21062107 sp2108 },21092110 _ => sponsor,2111 };204821122049 let mut who_pays_fee: T::AccountId = sponsor.clone();2113 let mut who_pays_fee: T::AccountId = sponsor.clone();2050 if sponsor == T::AccountId::default() {2114 if sponsor == T::AccountId::default() {2073}2137}2138207421392075impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension2140impl<T: Trait + Send + Sync> SignedExtension2076 for ChargeTransactionPayment<T>2141 for ChargeTransactionPayment<T>2077where2142where2078 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,2143 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,2079 T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Call<T>>,2144 T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Call<T>> + IsSubType<pallet_contracts::Call<T>>,2080{2145{2081 const IDENTIFIER: &'static str = "ChargeTransactionPayment";2146 const IDENTIFIER: &'static str = "ChargeTransactionPayment";2082 type AccountId = T::AccountId;2147 type AccountId = T::AccountId;209421592095 fn validate(2160 fn validate(2096 &self,2161 &self,2097 who: &Self::AccountId,2162 _who: &Self::AccountId,2098 call: &Self::Call,2163 _call: &Self::Call,2099 info: &DispatchInfoOf<Self::Call>,2164 _info: &DispatchInfoOf<Self::Call>,2100 len: usize,2165 _len: usize,2101 ) -> TransactionValidity {2166 ) -> TransactionValidity {2102 let (fee, _) = self.withdraw_fee(who, call, info, len)?;21032104 let mut r = ValidTransaction::default();2167 Ok(ValidTransaction::default())2105 // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which2106 // will be a bit more than setting the priority to tip. For now, this is enough.2107 r.priority = fee.saturated_into::<TransactionPriority>();2108 Ok(r)2109 }2168 }211021692111 fn pre_dispatch(2170 fn pre_dispatch(pallets/nft/src/mock.rsdiffbeforeafterboth--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -1,20 +1,27 @@
// Creating mock runtime here
use crate::{Module, Trait};
+
+use pallet_contracts::{
+ ContractAddressFor, TrieId, TrieIdGenerator,
+};
+
use frame_support::{
impl_outer_origin, parameter_types,
weights::{
- constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight},
- Weight,
+ // constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight},
+ Weight, IdentityFee,
},
};
use frame_system as system;
+use transaction_payment;
use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup, Saturating},
Perbill,
};
+pub use pallet_balances;
impl_outer_origin! {
pub enum Origin for Test {}
@@ -56,13 +63,101 @@
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
type PalletInfo = ();
- type AccountData = ();
+ type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
}
-impl Trait for Test {
+
+parameter_types! {
+ pub const ExistentialDeposit: u64 = 1;
+ pub const MaxLocks: u32 = 50;
+}
+
+type System = frame_system::Module<Test>;
+impl pallet_balances::Trait for Test {
+ type AccountStore = System;
+ type Balance = u64;
+ type DustRemoval = ();
type Event = ();
+ type ExistentialDeposit = ExistentialDeposit;
+ type WeightInfo = ();
+ type MaxLocks = MaxLocks;
+}
+
+parameter_types! {
+ pub const TransactionByteFee: u64 = 1;
+}
+impl transaction_payment::Trait for Test {
+ type Currency = pallet_balances::Module<Test>;
+ type OnTransactionPayment = ();
+ type TransactionByteFee = TransactionByteFee;
+ type WeightToFee = IdentityFee<u64>;
+ type FeeMultiplierUpdate = ();
+}
+
+
+parameter_types! {
+ pub const MinimumPeriod: u64 = 1;
+}
+impl pallet_timestamp::Trait for Test {
+ type Moment = u64;
+ type OnTimestampSet = ();
+ type MinimumPeriod = MinimumPeriod;
+ type WeightInfo = ();
+}
+
+type Timestamp = pallet_timestamp::Module<Test>;
+type Randomness = pallet_randomness_collective_flip::Module<Test>;
+
+parameter_types! {
+ pub const TombstoneDeposit: u64 = 1;
+ pub const RentByteFee: u64 = 1;
+ pub const RentDepositOffset: u64 = 1;
+ pub const SurchargeReward: u64 = 1;
+}
+
+pub struct DummyTrieIdGenerator;
+impl TrieIdGenerator<u64> for DummyTrieIdGenerator {
+ fn trie_id(account_id: &u64) -> TrieId {
+ let new_seed = *account_id + 1;
+ let mut res = vec![];
+ res.extend_from_slice(&new_seed.to_le_bytes());
+ res.extend_from_slice(&account_id.to_le_bytes());
+ res
+ }
+}
+
+pub struct DummyContractAddressFor;
+impl ContractAddressFor<H256, u64> for DummyContractAddressFor {
+ fn contract_address_for(_code_hash: &H256, _data: &[u8], origin: &u64) -> u64 {
+ *origin + 1
+ }
+}
+
+impl pallet_contracts::Trait for Test {
+ type Time = Timestamp;
+ type Randomness = Randomness;
+ type Currency = pallet_balances::Module<Test>;
+ type Event = ();
+ type DetermineContractAddress = DummyContractAddressFor;
+ type TrieIdGenerator = DummyTrieIdGenerator;
+ type RentPayment = ();
+ type SignedClaimHandicap = pallet_contracts::DefaultSignedClaimHandicap;
+ type TombstoneDeposit = TombstoneDeposit;
+ type StorageSizeOffset = pallet_contracts::DefaultStorageSizeOffset;
+ type RentByteFee = RentByteFee;
+ type RentDepositOffset = RentDepositOffset;
+ type SurchargeReward = SurchargeReward;
+ type MaxDepth = pallet_contracts::DefaultMaxDepth;
+ type MaxValueSize = pallet_contracts::DefaultMaxValueSize;
+ type WeightPrice = ();
+}
+
+impl Trait for Test {
+ type Event = ();
+ type WeightInfo = ();
+
}
pub type TemplateModule = Module<Test>;
pallets/nft/src/tests.rsdiffbeforeafterboth--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -292,6 +292,77 @@
assert_eq!(TemplateModule::balance_count(1, 1), 1);
assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+ // neg transfer
+ assert_noop!(TemplateModule::transfer_from(
+ origin2.clone(),
+ 1,
+ 2,
+ 1,
+ 1,
+ 1), "Only item owner, collection owner and admins can modify items");
+
+ // do approve
+ assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
+ assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
+ assert_eq!(
+ TemplateModule::approved(1, (1, 1))[0],
+ ApprovePermissions {
+ approved: 2,
+ amount: 100000000
+ }
+ );
+
+ assert_ok!(TemplateModule::transfer_from(
+ origin2.clone(),
+ 1,
+ 2,
+ 1,
+ 1,
+ 1
+ ));
+ assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 0);
+ });
+}
+
+#[test]
+fn nft_approve_and_transfer_from_white_list() {
+ new_test_ext().execute_with(|| {
+ let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+ let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+ let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+ let mode: CollectionMode = CollectionMode::NFT(2000);
+
+ assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {
+ collection_numbers_limit: 10,
+ account_token_ownership_limit: 10,
+ collections_admins_limit: 5,
+ custom_data_limit: 2048,
+ nft_sponsor_transfer_timeout: 15,
+ fungible_sponsor_transfer_timeout: 15,
+ refungible_sponsor_transfer_timeout: 15,
+ }));
+
+ let origin1 = Origin::signed(1);
+ let origin2 = Origin::signed(2);
+ assert_ok!(TemplateModule::create_collection(
+ origin1.clone(),
+ col_name1.clone(),
+ col_desc1.clone(),
+ token_prefix1.clone(),
+ mode
+ ));
+ assert_eq!(TemplateModule::collection(1).owner, 1);
+
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 2, 3].to_vec(),
+ 1
+ ));
+ assert_eq!(TemplateModule::nft_item_id(1, 1).data, [1, 2, 3].to_vec());
+ assert_eq!(TemplateModule::balance_count(1, 1), 1);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+
assert_ok!(TemplateModule::set_mint_permission(
origin1.clone(),
1,