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
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3085,11 +3085,13 @@
 dependencies = [
  "frame-support",
  "frame-system",
+ "pallet-transaction-payment",
  "parity-scale-codec",
  "serde",
  "sp-core",
  "sp-io",
  "sp-runtime",
+ "sp-std",
 ]
 
 [[package]]
modifieddoc/application_development.mddiffbeforeafterboth
--- a/doc/application_development.md
+++ b/doc/application_development.md
@@ -16,6 +16,54 @@
 
 ![](serverless_architecture.png)
 
+## Custom Types for JS API
+
+```
+{
+  "Schedule": {
+    "version": "u32",
+    "put_code_per_byte_cost": "Gas",
+    "grow_mem_cost": "Gas",
+    "regular_op_cost": "Gas",
+    "return_data_per_byte_cost": "Gas",
+    "event_data_per_byte_cost": "Gas",
+    "event_per_topic_cost": "Gas",
+    "event_base_cost": "Gas",
+    "call_base_cost": "Gas",
+    "instantiate_base_cost": "Gas",
+    "dispatch_base_cost": "Gas",
+    "sandbox_data_read_cost": "Gas",
+    "sandbox_data_write_cost": "Gas",
+    "transfer_cost": "Gas",
+    "instantiate_cost": "Gas",
+    "max_event_topics": "u32",
+    "max_stack_height": "u32",
+    "max_memory_pages": "u32",
+    "max_table_size": "u32",
+    "enable_println": "bool",
+    "max_subject_len": "u32"
+  },
+  "NftItemType": {
+    "Collection": "u64",
+    "Owner": "AccountId",
+    "Data": "Vec<u8>"
+  },
+  "CollectionType": {
+    "Owner": "AccountId",
+    "NextItemId": "u64",
+    "Name": "Vec<u16>",
+    "Description": "Vec<u16>",
+    "TokenPrefix": "Vec<u8>",
+    "CustomDataSize": "u32",
+    "Sponsor": "AccountId",
+    "UnconfirmedSponsor": "AccountId"
+  },
+  "Address": "AccountId",
+  "LookupSource": "AccountId",
+  "Weight": "u64"
+}
+```
+
 ## NFT Palette Methods
 
 ### Collection Management
modifiedpallets/nft/Cargo.tomldiffbeforeafterboth
--- a/pallets/nft/Cargo.toml
+++ b/pallets/nft/Cargo.toml
@@ -37,6 +37,19 @@
 # third-party dependencies
 serde = { version = "1.0.102", features = ["derive"] }
 
+[dependencies.sp-std]
+default-features = false
+git = 'https://github.com/usetech-llc/substrate.git'
+branch = 'rc4_ext_dispatch_reenabled'
+version = '2.0.0-rc4'
+
+[dependencies.transaction-payment]
+default-features = false
+git = 'https://github.com/usetech-llc/substrate.git'
+package = 'pallet-transaction-payment'
+branch = 'rc4_ext_dispatch_reenabled'
+version = '2.0.0-rc4'
+
 [package]
 authors = ['Substrate DevHub <https://github.com/substrate-developer-hub>']
 description = 'FRAME pallet nft'
@@ -57,4 +70,5 @@
     'frame-support/std',
     'frame-system/std',
     'sp-runtime/std',
+    'sp-std/std',
 ]
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
--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -14,13 +14,13 @@
 use sp_api::impl_runtime_apis;
 use sp_consensus_aura::sr25519::AuthorityId as AuraId;
 use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
-use sp_runtime::traits::{
-    BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating, Verify,
-};
 use sp_runtime::{
     create_runtime_str, generic, impl_opaque_keys,
     transaction_validity::{TransactionSource, TransactionValidity},
     ApplyExtrinsicResult, MultiSignature,
+	traits::{
+        BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating, Verify,
+	},
 };
 use sp_std::prelude::*;
 #[cfg(feature = "std")]
@@ -32,16 +32,22 @@
 pub use contracts::Schedule as ContractsSchedule;
 pub use frame_support::{
     construct_runtime, parameter_types,
-    traits::{KeyOwnerProofSystem, Randomness},
+    traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason},
     weights::{
-        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
-        IdentityFee, Weight,
+        DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
+        IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,
     },
     StorageValue,
+	dispatch::DispatchResult,
 };
+use system::{self as system};
 #[cfg(any(feature = "std", test))]
 pub use sp_runtime::BuildStorage;
-pub use sp_runtime::{Perbill, Permill};
+use sp_runtime::{
+	Perbill,
+};
+
+
 pub use timestamp::Call as TimestampCall;
 
 /// Importing a nft pallet
@@ -228,7 +234,8 @@
 }
 
 parameter_types! {
-    pub const ExistentialDeposit: u128 = 500;
+    // pub const ExistentialDeposit: u128 = 500;
+    pub const ExistentialDeposit: u128 = 0;
 }
 
 impl balances::Trait for Runtime {
@@ -331,7 +338,7 @@
     system::CheckEra<Runtime>,
     system::CheckNonce<Runtime>,
     system::CheckWeight<Runtime>,
-    transaction_payment::ChargeTransactionPayment<Runtime>,
+    nft::ChargeTransactionPayment<Runtime>,
 );
 /// Unchecked extrinsic type as expected by this runtime.
 pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
@@ -486,3 +493,4 @@
         }
     }
 }
+