git.delta.rocks / unique-network / refs/commits / 256d0671ae81

difftreelog

Merge branch 'dev' of https://github.com/usetech-llc/nft_parachain

str-mv2020-08-03parents: #675d1d0 #10c381b.patch.diff
in: master

5 files changed

modifiedCargo.lockdiffbeforeafterboth
3085dependencies = [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]
30943096
3095[[package]]3097[[package]]
modifieddoc/application_development.mddiffbeforeafterboth
1616
17![](serverless_architecture.png)17![](serverless_architecture.png)
1818
19## Custom Types for JS API
20
21```
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```
66
19## NFT Palette Methods67## NFT Palette Methods
2068
21### Collection Management69### Collection Management
modifiedpallets/nft/Cargo.tomldiffbeforeafterboth
37# third-party dependencies37# third-party dependencies
38serde = { version = "1.0.102", features = ["derive"] }38serde = { version = "1.0.102", features = ["derive"] }
39
40[dependencies.sp-std]
41default-features = false
42git = 'https://github.com/usetech-llc/substrate.git'
43branch = 'rc4_ext_dispatch_reenabled'
44version = '2.0.0-rc4'
45
46[dependencies.transaction-payment]
47default-features = false
48git = 'https://github.com/usetech-llc/substrate.git'
49package = 'pallet-transaction-payment'
50branch = 'rc4_ext_dispatch_reenabled'
51version = '2.0.0-rc4'
3952
40[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]
6175
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs
55
6use 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 ensure
19};
20
8use 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, TransactionValidity
28 },
29 traits::{
30 Saturating, Dispatchable, DispatchInfoOf, PostDispatchInfoOf, SignedExtension, Zero, SaturatedConversion,
31 },
32};
1033
11#[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 char
64 pub token_prefix: Vec<u8>, // 16 include null escape char87 pub token_prefix: Vec<u8>, // 16 include null escape char
65 pub custom_data_size: u32,88 pub custom_data_size: u32,
89<<<<<<< HEAD
66 pub offchain_schema: Vec<u8>,90 pub offchain_schema: Vec<u8>,
91=======
92>>>>>>> 10c381b426801d64ec3dcf8623de6b7e279067a2
67 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 sender
68 pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship94 pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship
69}95}
100126
101pub 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>;
129
103}130}
104131
105decl_storage! {132decl_storage! {
275 }302 }
276303
277 #[weight = 0]304 #[weight = 0]
305 pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {
306
307 let sender = ensure_signed(origin)?;
308 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");
309
310 let mut target_collection = <Collection<T>>::get(collection_id);
311 ensure!(sender == target_collection.owner, "You do not own this collection");
312
313 target_collection.unconfirmed_sponsor = new_sponsor;
314 <Collection<T>>::insert(collection_id, target_collection);
315
316 Ok(())
317 }
318
319 #[weight = 0]
320 pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {
321
322 let sender = ensure_signed(origin)?;
323 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");
324
325 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");
327
328 target_collection.sponsor = target_collection.unconfirmed_sponsor;
329 target_collection.unconfirmed_sponsor = T::AccountId::default();
330 <Collection<T>>::insert(collection_id, target_collection);
331
332 Ok(())
333 }
334
335 #[weight = 0]
336 pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {
337
338 let sender = ensure_signed(origin)?;
339 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");
340
341 let mut target_collection = <Collection<T>>::get(collection_id);
342 ensure!(sender == target_collection.owner, "You do not own this collection");
343
344 target_collection.sponsor = T::AccountId::default();
345 <Collection<T>>::insert(collection_id, target_collection);
346
347 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 {
279352
280 let sender = ensure_signed(origin)?;353 let sender = ensure_signed(origin)?;
593666
594 Ok(())667 Ok(())
595 }668 }
669}
670
671
672////////////////////////////////////////////////////////////////////////////////////////////////////
673// Economic models
674
675/// Fee multiplier.
676pub type Multiplier = FixedU128;
677
678type 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;
682
683
684
685/// Require the transactor pay for themselves and maybe include a tip to gain additional priority
686/// in the queue.
687#[derive(Encode, Decode, Clone, Eq, PartialEq)]
688pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);
689
690impl<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}
700
701impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where
702 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 }
709
710 pub fn traditional_fee(
711 len: usize,
712 info: &DispatchInfoOf<T::Call>,
713 tip: BalanceOf<T>,
714 ) -> BalanceOf<T> where
715 T::Call: Dispatchable<Info=DispatchInfo>,
716 {
717 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)
718 }
719
720 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;
728
729 // Set fee based on call type. Creating collection costs 1 Unique.
730 // All other transactions have traditional fees so far
731 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)
734
735 // Flat fee model, use only for testing purposes
736 // _ => <BalanceOf<T>>::from(100)
737 };
738
739 // Determine who is paying transaction fee based on ecnomic model
740 // Parse call to extract collection ID and access collection sponsor
741 let sponsor: T::AccountId = match call.is_sub_type() {
742 Some(Call::create_item(collection_id, _properties, _owner)) => {
743 <Collection<T>>::get(collection_id).sponsor
744 },
745 Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {
746 <Collection<T>>::get(collection_id).sponsor
747 },
748
749 _ => T::AccountId::default()
750 };
751
752 let mut who_pays_fee: T::AccountId = sponsor.clone();
753 if sponsor == T::AccountId::default() {
754 who_pays_fee = who.clone();
755 }
756
757 // Only mess with balances if fee is not zero.
758 if fee.is_zero() {
759 return Ok((fee, None));
760 }
761
762 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::Tip
769 },
770 ExistenceRequirement::KeepAlive,
771 ) {
772 Ok(imbalance) => Ok((fee, Some(imbalance))),
773 Err(_) => Err(InvalidTransaction::Payment.into()),
774 }
775 }
776}
777
778impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where
779 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(()) }
788
789 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)?;
797
798 let mut r = ValidTransaction::default();
799 // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which
800 // 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 }
804
805 fn pre_dispatch(
806 self,
807 who: &Self::AccountId,
808 call: &Self::Call,
809 info: &DispatchInfoOf<Self::Call>,
810 len: usize
811 ) -> Result<Self::Pre, TransactionValidityError> {
812 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;
813 Ok((self.0, who.clone(), imbalance, fee))
814 }
815
816 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 payment
842 // 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}
597852
modifiedruntime/src/lib.rsdiffbeforeafterboth
14use 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};
49
228}234}
229235
230parameter_types! {236parameter_types! {
237 // pub const ExistentialDeposit: u128 = 500;
231 pub const ExistentialDeposit: u128 = 500;238 pub const ExistentialDeposit: u128 = 0;
232}239}
233240
234impl 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>;