git.delta.rocks / unique-network / refs/commits / e9291bd41a30

difftreelog

Add economic model POC

Greg Zaitsev2020-07-27parent: #31df977.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 "sp-core",3090 "sp-core",
3090 "sp-io",3091 "sp-io",
3091 "sp-runtime",3092 "sp-runtime",
3093 "sp-std",
3092]3094]
30933095
3094[[package]]3096[[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
33branch = 'rc4_ext_dispatch_reenabled'33branch = 'rc4_ext_dispatch_reenabled'
34version = '2.0.0-rc4'34version = '2.0.0-rc4'
35
36[dependencies.sp-std]
37default-features = false
38git = 'https://github.com/usetech-llc/substrate.git'
39branch = 'rc4_ext_dispatch_reenabled'
40version = '2.0.0-rc4'
41
42[dependencies.transaction-payment]
43default-features = false
44git = 'https://github.com/usetech-llc/substrate.git'
45package = 'pallet-transaction-payment'
46branch = 'rc4_ext_dispatch_reenabled'
47version = '2.0.0-rc4'
3548
36[package]49[package]
37authors = ['Substrate DevHub <https://github.com/substrate-developer-hub>']50authors = ['Substrate DevHub <https://github.com/substrate-developer-hub>']
52 'frame-support/std',65 'frame-support/std',
53 'frame-system/std',66 'frame-system/std',
54 'sp-runtime/std',67 'sp-runtime/std',
68 'sp-std/std',
55]69]
5670
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
99
10/// For more guidance on Substrate FRAME, see the example pallet10/// For more guidance on Substrate FRAME, see the example pallet
11/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs11/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs
12use frame_support::{decl_event, decl_module, decl_storage, dispatch::DispatchResult, ensure};12pub use frame_support::{
13 decl_event, decl_module, decl_storage,
14 construct_runtime, parameter_types,
15 traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason, Imbalance},
16 weights::{
17 DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
18 IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,
19 },
20 StorageValue,
21 dispatch::DispatchResult,
22 IsSubType,
23 ensure
24};
25
13use frame_system::{self as system, ensure_signed};26use frame_system::{self as system, ensure_signed};
14use sp_runtime::sp_std::prelude::Vec;27use sp_runtime::sp_std::prelude::Vec;
28use sp_std::prelude::*;
29use sp_runtime::{
30 FixedU128, FixedPointOperand,
31 transaction_validity::{
32 TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError, TransactionValidity
33 },
34 traits::{
35 Saturating, Dispatchable, DispatchInfoOf, PostDispatchInfoOf, SignedExtension, Zero, SaturatedConversion,
36 },
37};
1538
16#[cfg(test)]39#[cfg(test)]
17mod mock;40mod mock;
28 pub description: Vec<u16>, // 256 include null escape char51 pub description: Vec<u16>, // 256 include null escape char
29 pub token_prefix: Vec<u8>, // 16 include null escape char52 pub token_prefix: Vec<u8>, // 16 include null escape char
30 pub custom_data_size: u32,53 pub custom_data_size: u32,
54 pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender
55 pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship
31}56}
3257
33#[derive(Encode, Decode, Default, Clone, PartialEq)]58#[derive(Encode, Decode, Default, Clone, PartialEq)]
138 token_prefix: prefix,164 token_prefix: prefix,
139 next_item_id: next_id,165 next_item_id: next_id,
140 custom_data_size: custom_data_sz,166 custom_data_size: custom_data_sz,
167 sponsor: T::AccountId::default(),
168 unconfirmed_sponsor: T::AccountId::default(),
141 };169 };
142170
143 // Add new collection to map171 // Add new collection to map
237 }265 }
238266
239 #[weight = 0]267 #[weight = 0]
268 pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {
269
270 let sender = ensure_signed(origin)?;
271 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");
272
273 let mut target_collection = <Collection<T>>::get(collection_id);
274 ensure!(sender == target_collection.owner, "You do not own this collection");
275
276 target_collection.unconfirmed_sponsor = new_sponsor;
277 <Collection<T>>::insert(collection_id, target_collection);
278
279 Ok(())
280 }
281
282 #[weight = 0]
283 pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {
284
285 let sender = ensure_signed(origin)?;
286 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");
287
288 let mut target_collection = <Collection<T>>::get(collection_id);
289 ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");
290
291 target_collection.sponsor = target_collection.unconfirmed_sponsor;
292 target_collection.unconfirmed_sponsor = T::AccountId::default();
293 <Collection<T>>::insert(collection_id, target_collection);
294
295 Ok(())
296 }
297
298 #[weight = 0]
299 pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {
300
301 let sender = ensure_signed(origin)?;
302 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");
303
304 let mut target_collection = <Collection<T>>::get(collection_id);
305 ensure!(sender == target_collection.owner, "You do not own this collection");
306
307 target_collection.sponsor = T::AccountId::default();
308 <Collection<T>>::insert(collection_id, target_collection);
309
310 Ok(())
311 }
312
313
314
315 #[weight = 0]
240 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>) -> DispatchResult {316 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>) -> DispatchResult {
241317
242 let sender = ensure_signed(origin)?;318 let sender = ensure_signed(origin)?;
492}568}
569
570
571////////////////////////////////////////////////////////////////////////////////////////////////////
572// Economic models
573
574/// Fee multiplier.
575pub type Multiplier = FixedU128;
576
577type BalanceOf<T> =
578 <<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;
579type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<
580 <T as system::Trait>::AccountId,>>::NegativeImbalance;
581
582
583
584/// Require the transactor pay for themselves and maybe include a tip to gain additional priority
585/// in the queue.
586#[derive(Encode, Decode, Clone, Eq, PartialEq)]
587pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);
588
589impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {
590 #[cfg(feature = "std")]
591 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
592 write!(f, "ChargeTransactionPayment<{:?}>", self.0)
593 }
594 #[cfg(not(feature = "std"))]
595 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
596 Ok(())
597 }
598}
599
600impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where
601 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,
602 BalanceOf<T>: Send + Sync + FixedPointOperand,
603{
604 /// utility constructor. Used only in client/factory code.
605 pub fn from(fee: BalanceOf<T>) -> Self {
606 Self(fee)
607 }
608
609 pub fn traditional_fee(
610 len: usize,
611 info: &DispatchInfoOf<T::Call>,
612 tip: BalanceOf<T>,
613 ) -> BalanceOf<T> where
614 T::Call: Dispatchable<Info=DispatchInfo>,
615 {
616 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)
617 }
618
619 fn withdraw_fee(
620 &self,
621 who: &T::AccountId,
622 call: &T::Call,
623 info: &DispatchInfoOf<T::Call>,
624 len: usize,
625 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {
626 let tip = self.0;
627
628 // Set fee based on call type. Creating collection costs 1 Unique.
629 // All other transactions have traditional fees so far
630 let fee = match call.is_sub_type() {
631 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),
632 _ => Self::traditional_fee(len, info, tip)
633
634 // Flat fee model, use only for testing purposes
635 // _ => <BalanceOf<T>>::from(100)
636 };
637
638 // Determine who is paying transaction fee based on ecnomic model
639 // Parse call to extract collection ID and access collection sponsor
640 let sponsor: T::AccountId = match call.is_sub_type() {
641 Some(Call::create_item(collection_id, _properties)) => {
642 <Collection<T>>::get(collection_id).sponsor
643 },
644 Some(Call::transfer(collection_id, _item_id, _new_owner)) => {
645 <Collection<T>>::get(collection_id).sponsor
646 },
647
648 _ => T::AccountId::default()
649 };
650
651 let mut who_pays_fee: T::AccountId = sponsor.clone();
652 if sponsor == T::AccountId::default() {
653 who_pays_fee = who.clone();
654 }
655
656 // Only mess with balances if fee is not zero.
657 if fee.is_zero() {
658 return Ok((fee, None));
659 }
660
661 match <T as transaction_payment::Trait>::Currency::withdraw(
662 &who_pays_fee,
663 fee,
664 if tip.is_zero() {
665 WithdrawReason::TransactionPayment.into()
666 } else {
667 WithdrawReason::TransactionPayment | WithdrawReason::Tip
668 },
669 ExistenceRequirement::KeepAlive,
670 ) {
671 Ok(imbalance) => Ok((fee, Some(imbalance))),
672 Err(_) => Err(InvalidTransaction::Payment.into()),
673 }
674 }
675}
676
677impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where
678 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,
679 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,
680{
681 const IDENTIFIER: &'static str = "ChargeTransactionPayment";
682 type AccountId = T::AccountId;
683 type Call = T::Call;
684 type AdditionalSigned = ();
685 type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);
686 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }
687
688 fn validate(
689 &self,
690 who: &Self::AccountId,
691 call: &Self::Call,
692 info: &DispatchInfoOf<Self::Call>,
693 len: usize,
694 ) -> TransactionValidity {
695 let (fee, _) = self.withdraw_fee(who, call, info, len)?;
696
697 let mut r = ValidTransaction::default();
698 // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which
699 // will be a bit more than setting the priority to tip. For now, this is enough.
700 r.priority = fee.saturated_into::<TransactionPriority>();
701 Ok(r)
702 }
703
704 fn pre_dispatch(
705 self,
706 who: &Self::AccountId,
707 call: &Self::Call,
708 info: &DispatchInfoOf<Self::Call>,
709 len: usize
710 ) -> Result<Self::Pre, TransactionValidityError> {
711 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;
712 Ok((self.0, who.clone(), imbalance, fee))
713 }
714
715 fn post_dispatch(
716 pre: Self::Pre,
717 info: &DispatchInfoOf<Self::Call>,
718 post_info: &PostDispatchInfoOf<Self::Call>,
719 len: usize,
720 _result: &DispatchResult,
721 ) -> Result<(), TransactionValidityError> {
722 let (tip, who, imbalance, fee) = pre;
723 if let Some(payed) = imbalance {
724 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(
725 len as u32,
726 info,
727 post_info,
728 tip,
729 );
730 let refund = fee.saturating_sub(actual_fee);
731 let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {
732 Ok(refund_imbalance) => {
733 // The refund cannot be larger than the up front payed max weight.
734 // `PostDispatchInfo::calc_unspent` guards against such a case.
735 match payed.offset(refund_imbalance) {
736 Ok(actual_payment) => actual_payment,
737 Err(_) => return Err(InvalidTransaction::Payment.into()),
738 }
739 }
740 // We do not recreate the account using the refund. The up front payment
741 // is gone in that case.
742 Err(_) => payed,
743 };
744 let imbalances = actual_payment.split(tip);
745 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()
746 .chain(Some(imbalances.1)));
747 }
748 Ok(())
749 }
750}
493751
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>;