difftreelog
Merge branch 'dev' of https://github.com/usetech-llc/nft_parachain
in: master
5 files changed
Cargo.lockdiffbeforeafterboth3085dependencies = [3085dependencies = [3086 "frame-support",3086 "frame-support",3087 "frame-system",3087 "frame-system",3088 "pallet-transaction-payment",3088 "parity-scale-codec",3089 "parity-scale-codec",3089 "serde",3090 "serde",3090 "sp-core",3091 "sp-core",3091 "sp-io",3092 "sp-io",3092 "sp-runtime",3093 "sp-runtime",3094 "sp-std",3093]3095]309430963095[[package]]3097[[package]]doc/application_development.mddiffbeforeafterboth16161717181819## Custom Types for JS API2021```22{23 "Schedule": {24 "version": "u32",25 "put_code_per_byte_cost": "Gas",26 "grow_mem_cost": "Gas",27 "regular_op_cost": "Gas",28 "return_data_per_byte_cost": "Gas",29 "event_data_per_byte_cost": "Gas",30 "event_per_topic_cost": "Gas",31 "event_base_cost": "Gas",32 "call_base_cost": "Gas",33 "instantiate_base_cost": "Gas",34 "dispatch_base_cost": "Gas",35 "sandbox_data_read_cost": "Gas",36 "sandbox_data_write_cost": "Gas",37 "transfer_cost": "Gas",38 "instantiate_cost": "Gas",39 "max_event_topics": "u32",40 "max_stack_height": "u32",41 "max_memory_pages": "u32",42 "max_table_size": "u32",43 "enable_println": "bool",44 "max_subject_len": "u32"45 },46 "NftItemType": {47 "Collection": "u64",48 "Owner": "AccountId",49 "Data": "Vec<u8>"50 },51 "CollectionType": {52 "Owner": "AccountId",53 "NextItemId": "u64",54 "Name": "Vec<u16>",55 "Description": "Vec<u16>",56 "TokenPrefix": "Vec<u8>",57 "CustomDataSize": "u32",58 "Sponsor": "AccountId",59 "UnconfirmedSponsor": "AccountId"60 },61 "Address": "AccountId",62 "LookupSource": "AccountId",63 "Weight": "u64"64}65```6619## NFT Palette Methods67## NFT Palette Methods206821### Collection Management69### Collection Managementpallets/nft/Cargo.tomldiffbeforeafterboth37# third-party dependencies37# third-party dependencies38serde = { version = "1.0.102", features = ["derive"] }38serde = { version = "1.0.102", features = ["derive"] }3940[dependencies.sp-std]41default-features = false42git = 'https://github.com/usetech-llc/substrate.git'43branch = 'rc4_ext_dispatch_reenabled'44version = '2.0.0-rc4'4546[dependencies.transaction-payment]47default-features = false48git = 'https://github.com/usetech-llc/substrate.git'49package = 'pallet-transaction-payment'50branch = 'rc4_ext_dispatch_reenabled'51version = '2.0.0-rc4'395240[package]53[package]41authors = ['Substrate DevHub <https://github.com/substrate-developer-hub>']54authors = ['Substrate DevHub <https://github.com/substrate-developer-hub>']57 'frame-support/std',70 'frame-support/std',58 'frame-system/std',71 'frame-system/std',59 'sp-runtime/std',72 'sp-runtime/std',73 'sp-std/std',60]74]6175pallets/nft/src/lib.rsdiffbeforeafterboth4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs556use codec::{Decode, Encode};6use codec::{Decode, Encode};7use frame_support::{decl_event, decl_module, decl_storage, dispatch::DispatchResult, ensure};7pub use frame_support::{8 decl_event, decl_module, decl_storage,9 construct_runtime, parameter_types,10 traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason, Imbalance},11 weights::{12 DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},13 IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,14 },15 StorageValue,16 dispatch::DispatchResult, 17 IsSubType,18 ensure19};208use frame_system::{self as system, ensure_signed};21use frame_system::{self as system, ensure_signed};9use sp_runtime::sp_std::prelude::Vec;22use sp_runtime::sp_std::prelude::Vec;23use sp_std::prelude::*;24use sp_runtime::{25 FixedU128, FixedPointOperand, 26 transaction_validity::{27 TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError, TransactionValidity28 },29 traits::{30 Saturating, Dispatchable, DispatchInfoOf, PostDispatchInfoOf, SignedExtension, Zero, SaturatedConversion,31 },32};103311#[cfg(test)]34#[cfg(test)]12mod mock;35mod mock;63 pub description: Vec<u16>, // 256 include null escape char86 pub description: Vec<u16>, // 256 include null escape char64 pub token_prefix: Vec<u8>, // 16 include null escape char87 pub token_prefix: Vec<u8>, // 16 include null escape char65 pub custom_data_size: u32,88 pub custom_data_size: u32,89<<<<<<< HEAD66 pub offchain_schema: Vec<u8>,90 pub offchain_schema: Vec<u8>,91=======92>>>>>>> 10c381b426801d64ec3dcf8623de6b7e279067a267 pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender93 pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender68 pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship94 pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship69}95}100126101pub trait Trait: system::Trait {127pub trait Trait: system::Trait {102 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;128 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;129103}130}104131105decl_storage! {132decl_storage! {275 }302 }276303277 #[weight = 0]304 #[weight = 0]305 pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {306307 let sender = ensure_signed(origin)?;308 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");309310 let mut target_collection = <Collection<T>>::get(collection_id);311 ensure!(sender == target_collection.owner, "You do not own this collection");312313 target_collection.unconfirmed_sponsor = new_sponsor;314 <Collection<T>>::insert(collection_id, target_collection);315316 Ok(())317 }318319 #[weight = 0]320 pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {321322 let sender = ensure_signed(origin)?;323 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");324325 let mut target_collection = <Collection<T>>::get(collection_id);326 ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");327328 target_collection.sponsor = target_collection.unconfirmed_sponsor;329 target_collection.unconfirmed_sponsor = T::AccountId::default();330 <Collection<T>>::insert(collection_id, target_collection);331332 Ok(())333 }334335 #[weight = 0]336 pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {337338 let sender = ensure_signed(origin)?;339 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");340341 let mut target_collection = <Collection<T>>::get(collection_id);342 ensure!(sender == target_collection.owner, "You do not own this collection");343344 target_collection.sponsor = T::AccountId::default();345 <Collection<T>>::insert(collection_id, target_collection);346347 Ok(())348 }349 350 #[weight = 0]278 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {351 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {279352280 let sender = ensure_signed(origin)?;353 let sender = ensure_signed(origin)?;593666594 Ok(())667 Ok(())595 }668 }669}670671672////////////////////////////////////////////////////////////////////////////////////////////////////673// Economic models674675/// Fee multiplier.676pub type Multiplier = FixedU128;677678type BalanceOf<T> =679 <<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;680type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<681 <T as system::Trait>::AccountId,>>::NegativeImbalance;682683684685/// Require the transactor pay for themselves and maybe include a tip to gain additional priority686/// in the queue.687#[derive(Encode, Decode, Clone, Eq, PartialEq)]688pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);689690impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {691 #[cfg(feature = "std")]692 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {693 write!(f, "ChargeTransactionPayment<{:?}>", self.0)694 }695 #[cfg(not(feature = "std"))]696 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {697 Ok(())698 }699}700701impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where702 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,703 BalanceOf<T>: Send + Sync + FixedPointOperand,704{705 /// utility constructor. Used only in client/factory code.706 pub fn from(fee: BalanceOf<T>) -> Self {707 Self(fee)708 }709710 pub fn traditional_fee(711 len: usize,712 info: &DispatchInfoOf<T::Call>,713 tip: BalanceOf<T>,714 ) -> BalanceOf<T> where715 T::Call: Dispatchable<Info=DispatchInfo>,716 {717 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)718 }719720 fn withdraw_fee(721 &self,722 who: &T::AccountId,723 call: &T::Call,724 info: &DispatchInfoOf<T::Call>,725 len: usize,726 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {727 let tip = self.0;728729 // Set fee based on call type. Creating collection costs 1 Unique.730 // All other transactions have traditional fees so far731 let fee = match call.is_sub_type() {732 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),733 _ => Self::traditional_fee(len, info, tip)734735 // Flat fee model, use only for testing purposes736 // _ => <BalanceOf<T>>::from(100)737 };738739 // Determine who is paying transaction fee based on ecnomic model740 // Parse call to extract collection ID and access collection sponsor741 let sponsor: T::AccountId = match call.is_sub_type() {742 Some(Call::create_item(collection_id, _properties, _owner)) => {743 <Collection<T>>::get(collection_id).sponsor744 },745 Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {746 <Collection<T>>::get(collection_id).sponsor747 },748749 _ => T::AccountId::default()750 };751752 let mut who_pays_fee: T::AccountId = sponsor.clone();753 if sponsor == T::AccountId::default() {754 who_pays_fee = who.clone();755 }756757 // Only mess with balances if fee is not zero.758 if fee.is_zero() {759 return Ok((fee, None));760 }761762 match <T as transaction_payment::Trait>::Currency::withdraw(763 &who_pays_fee,764 fee,765 if tip.is_zero() {766 WithdrawReason::TransactionPayment.into()767 } else {768 WithdrawReason::TransactionPayment | WithdrawReason::Tip769 },770 ExistenceRequirement::KeepAlive,771 ) {772 Ok(imbalance) => Ok((fee, Some(imbalance))),773 Err(_) => Err(InvalidTransaction::Payment.into()),774 }775 }776}777778impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where779 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,780 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,781{782 const IDENTIFIER: &'static str = "ChargeTransactionPayment";783 type AccountId = T::AccountId;784 type Call = T::Call;785 type AdditionalSigned = ();786 type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);787 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }788789 fn validate(790 &self,791 who: &Self::AccountId,792 call: &Self::Call,793 info: &DispatchInfoOf<Self::Call>,794 len: usize,795 ) -> TransactionValidity {796 let (fee, _) = self.withdraw_fee(who, call, info, len)?;797798 let mut r = ValidTransaction::default();799 // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which800 // will be a bit more than setting the priority to tip. For now, this is enough.801 r.priority = fee.saturated_into::<TransactionPriority>();802 Ok(r)803 }804805 fn pre_dispatch(806 self,807 who: &Self::AccountId,808 call: &Self::Call,809 info: &DispatchInfoOf<Self::Call>,810 len: usize811 ) -> Result<Self::Pre, TransactionValidityError> {812 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;813 Ok((self.0, who.clone(), imbalance, fee))814 }815816 fn post_dispatch(817 pre: Self::Pre,818 info: &DispatchInfoOf<Self::Call>,819 post_info: &PostDispatchInfoOf<Self::Call>,820 len: usize,821 _result: &DispatchResult,822 ) -> Result<(), TransactionValidityError> {823 let (tip, who, imbalance, fee) = pre;824 if let Some(payed) = imbalance {825 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(826 len as u32,827 info,828 post_info,829 tip,830 );831 let refund = fee.saturating_sub(actual_fee);832 let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {833 Ok(refund_imbalance) => {834 // The refund cannot be larger than the up front payed max weight.835 // `PostDispatchInfo::calc_unspent` guards against such a case.836 match payed.offset(refund_imbalance) {837 Ok(actual_payment) => actual_payment,838 Err(_) => return Err(InvalidTransaction::Payment.into()),839 }840 }841 // We do not recreate the account using the refund. The up front payment842 // is gone in that case.843 Err(_) => payed,844 };845 let imbalances = actual_payment.split(tip);846 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()847 .chain(Some(imbalances.1)));848 }849 Ok(())850 }596}851}597852runtime/src/lib.rsdiffbeforeafterboth14use sp_api::impl_runtime_apis;14use sp_api::impl_runtime_apis;15use sp_consensus_aura::sr25519::AuthorityId as AuraId;15use sp_consensus_aura::sr25519::AuthorityId as AuraId;16use sp_core::{crypto::KeyTypeId, OpaqueMetadata};16use sp_core::{crypto::KeyTypeId, OpaqueMetadata};17use sp_runtime::traits::{17use sp_runtime::{18 create_runtime_str, generic, impl_opaque_keys,19 transaction_validity::{TransactionSource, TransactionValidity},20 ApplyExtrinsicResult, MultiSignature,21 traits::{18 BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating, Verify,22 BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating, Verify,19};23 },20use sp_runtime::{24};21 create_runtime_str, generic, impl_opaque_keys,22 transaction_validity::{TransactionSource, TransactionValidity},23 ApplyExtrinsicResult, MultiSignature,24};25use sp_std::prelude::*;25use sp_std::prelude::*;26#[cfg(feature = "std")]26#[cfg(feature = "std")]27use sp_version::NativeVersion;27use sp_version::NativeVersion;32pub use contracts::Schedule as ContractsSchedule;32pub use contracts::Schedule as ContractsSchedule;33pub use frame_support::{33pub use frame_support::{34 construct_runtime, parameter_types,34 construct_runtime, parameter_types,35 traits::{KeyOwnerProofSystem, Randomness},35 traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason},36 weights::{36 weights::{37 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},37 DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},38 IdentityFee, Weight,38 IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,39 },39 },40 StorageValue,40 StorageValue,41 dispatch::DispatchResult,41};42};43use system::{self as system};42#[cfg(any(feature = "std", test))]44#[cfg(any(feature = "std", test))]43pub use sp_runtime::BuildStorage;45pub use sp_runtime::BuildStorage;44pub use sp_runtime::{Perbill, Permill};46use sp_runtime::{47 Perbill,48};49228}234}229235230parameter_types! {236parameter_types! {237 // pub const ExistentialDeposit: u128 = 500;231 pub const ExistentialDeposit: u128 = 500;238 pub const ExistentialDeposit: u128 = 0;232}239}233240234impl balances::Trait for Runtime {241impl balances::Trait for Runtime {331 system::CheckEra<Runtime>,338 system::CheckEra<Runtime>,332 system::CheckNonce<Runtime>,339 system::CheckNonce<Runtime>,333 system::CheckWeight<Runtime>,340 system::CheckWeight<Runtime>,334 transaction_payment::ChargeTransactionPayment<Runtime>,341 nft::ChargeTransactionPayment<Runtime>,335);342);336/// Unchecked extrinsic type as expected by this runtime.343/// Unchecked extrinsic type as expected by this runtime.337pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;344pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;