git.delta.rocks / unique-network / refs/commits / 0c99fe85a93b

difftreelog

source

runtime/src/lib.rs14.6 KiBsourcehistory
1//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.23#![cfg_attr(not(feature = "std"), no_std)]4// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.5#![recursion_limit = "256"]67// Make the WASM binary available.8#[cfg(feature = "std")]9include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1011use grandpa::fg_primitives;12use grandpa::AuthorityList as GrandpaAuthorityList;13use sp_api::impl_runtime_apis;14use sp_consensus_aura::sr25519::AuthorityId as AuraId;15use sp_core::OpaqueMetadata;16use sp_runtime::traits::{17    BlakeTwo256, Block as BlockT, ConvertInto, IdentifyAccount, IdentityLookup, Verify,18};19use sp_runtime::{20    create_runtime_str, generic, impl_opaque_keys,21    transaction_validity::{TransactionSource, TransactionValidity},22    ApplyExtrinsicResult, MultiSignature,23};24use sp_std::prelude::*;25#[cfg(feature = "std")]26use sp_version::NativeVersion;27use sp_version::RuntimeVersion;2829// A few exports that help ease life for downstream crates.30pub use balances::Call as BalancesCall;31pub use frame_support::{32    construct_runtime, parameter_types, traits::Randomness, weights::Weight, StorageValue,33};34#[cfg(any(feature = "std", test))]35pub use sp_runtime::BuildStorage;36pub use sp_runtime::{Perbill, Permill};37pub use timestamp::Call as TimestampCall;38pub use contracts::Schedule as ContractsSchedule;39pub use contracts_rpc_runtime_api::{40	self as runtime_api, ContractExecResult41};4243/// Importing a template pallet44pub use nft;4546/// An index to a block.47pub type BlockNumber = u32;4849/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.50pub type Signature = MultiSignature;5152/// Some way of identifying an account on the chain. We intentionally make it equivalent53/// to the public key of our transaction signing scheme.54pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;5556/// The type for looking up accounts. We don't expect more than 4 billion of them, but you57/// never know...58pub type AccountIndex = u32;5960/// Balance of an account.61pub type Balance = u128;6263/// Index of a transaction in the chain.64pub type Index = u32;6566/// A hash of some data used by the chain.67pub type Hash = sp_core::H256;6869/// Digest item type.70pub type DigestItem = generic::DigestItem<Hash>;7172/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know73/// the specifics of the runtime. They can then be made to be agnostic over specific formats74/// of data like extrinsics, allowing for them to continue syncing the network through upgrades75/// to even the core data structures.76pub mod opaque {77    use super::*;7879    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;8081    /// Opaque block header type.82    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;83    /// Opaque block type.84    pub type Block = generic::Block<Header, UncheckedExtrinsic>;85    /// Opaque block identifier type.86    pub type BlockId = generic::BlockId<Block>;8788    impl_opaque_keys! {89        pub struct SessionKeys {90            pub aura: Aura,91            pub grandpa: Grandpa,92        }93    }94}9596/// This runtime version.97pub const VERSION: RuntimeVersion = RuntimeVersion {98    spec_name: create_runtime_str!("nft"),99    impl_name: create_runtime_str!("nft"),100    authoring_version: 1,101    spec_version: 1,102    impl_version: 1,103    apis: RUNTIME_API_VERSIONS,104};105106pub const MILLISECS_PER_BLOCK: u64 = 6000;107108pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;109110// These time units are defined in number of blocks.111pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);112pub const HOURS: BlockNumber = MINUTES * 60;113pub const DAYS: BlockNumber = HOURS * 24;114115/// The version information used to identify this runtime when compiled natively.116#[cfg(feature = "std")]117pub fn native_version() -> NativeVersion {118    NativeVersion {119        runtime_version: VERSION,120        can_author_with: Default::default(),121    }122}123124parameter_types! {125    pub const BlockHashCount: BlockNumber = 250;126    pub const MaximumBlockWeight: Weight = 1_000_000_000;127    pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);128    pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;129    pub const Version: RuntimeVersion = VERSION;130}131132impl system::Trait for Runtime {133    /// The identifier used to distinguish between accounts.134    type AccountId = AccountId;135    /// The aggregated dispatch type that is available for extrinsics.136    type Call = Call;137    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.138    type Lookup = IdentityLookup<AccountId>;139    /// The index type for storing how many extrinsics an account has signed.140    type Index = Index;141    /// The index type for blocks.142    type BlockNumber = BlockNumber;143    /// The type for hashing blocks and tries.144    type Hash = Hash;145    /// The hashing algorithm used.146    type Hashing = BlakeTwo256;147    /// The header type.148    type Header = generic::Header<BlockNumber, BlakeTwo256>;149    /// The ubiquitous event type.150    type Event = Event;151    /// The ubiquitous origin type.152    type Origin = Origin;153    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).154    type BlockHashCount = BlockHashCount;155    /// Maximum weight of each block.156    type MaximumBlockWeight = MaximumBlockWeight;157    /// Maximum size of all encoded transactions (in bytes) that are allowed in one block.158    type MaximumBlockLength = MaximumBlockLength;159    /// Portion of the block weight that is available to all normal transactions.160    type AvailableBlockRatio = AvailableBlockRatio;161    /// Version of the runtime.162    type Version = Version;163    /// Converts a module to the index of the module in `construct_runtime!`.164    ///165    /// This type is being generated by `construct_runtime!`.166    type ModuleToIndex = ModuleToIndex;167    /// What to do if a new account is created.168    type OnNewAccount = ();169    /// What to do if an account is fully reaped from the system.170    type OnKilledAccount = ();171    /// The data to be stored in an account.172    type AccountData = balances::AccountData<Balance>;173}174175impl aura::Trait for Runtime {176    type AuthorityId = AuraId;177}178179impl grandpa::Trait for Runtime {180    type Event = Event;181}182183parameter_types! {184    pub const MinimumPeriod: u64 = SLOT_DURATION / 2;185}186187impl timestamp::Trait for Runtime {188    /// A timestamp: milliseconds since the unix epoch.189    type Moment = u64;190    type OnTimestampSet = Aura;191    type MinimumPeriod = MinimumPeriod;192}193194parameter_types! {195    pub const ExistentialDeposit: u128 = 500;196}197198impl balances::Trait for Runtime {199    /// The type for recording an account's balance.200    type Balance = Balance;201    /// The ubiquitous event type.202    type Event = Event;203    type DustRemoval = ();204    type ExistentialDeposit = ExistentialDeposit;205    type AccountStore = System;206}207208// Contracts price units.209pub const MILLICENTS: Balance = 1_000_000_000;210pub const CENTS: Balance = 1_000 * MILLICENTS;211pub const DOLLARS: Balance = 100 * CENTS;212213parameter_types! {214    pub const TombstoneDeposit: Balance = 16 * MILLICENTS;215    pub const RentByteFee: Balance = 4 * MILLICENTS;216    pub const RentDepositOffset: Balance = 1000 * MILLICENTS;217	pub const SurchargeReward: Balance = 150 * MILLICENTS;218	pub const ContractTransactionBaseFee: Balance = 1 * CENTS;219	pub const ContractTransactionByteFee: Balance = 10 * MILLICENTS;220	pub const ContractFee: Balance = 1 * CENTS;221}222223impl contracts::Trait for Runtime {224	type Currency = Balances;225	type Time = Timestamp;226	type Randomness = RandomnessCollectiveFlip;227	type Call = Call;228	type Event = Event;229	type DetermineContractAddress = contracts::SimpleAddressDeterminer<Runtime>;230	type ComputeDispatchFee = contracts::DefaultDispatchFeeComputor<Runtime>;231	type TrieIdGenerator = contracts::TrieIdFromParentCounter<Runtime>;232	type GasPayment = ();233	type RentPayment = ();234	type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap;235	type TombstoneDeposit = TombstoneDeposit;236	type StorageSizeOffset = contracts::DefaultStorageSizeOffset;237	type RentByteFee = RentByteFee;238	type RentDepositOffset = RentDepositOffset;239	type SurchargeReward = SurchargeReward;240	type TransactionBaseFee = ContractTransactionBaseFee;241	type TransactionByteFee = ContractTransactionByteFee;242	type ContractFee = ContractFee;243	type CallBaseFee = contracts::DefaultCallBaseFee;244	type InstantiateBaseFee = contracts::DefaultInstantiateBaseFee;245	type MaxDepth = contracts::DefaultMaxDepth;246	type MaxValueSize = contracts::DefaultMaxValueSize;247	type BlockGasLimit = contracts::DefaultBlockGasLimit;248}249250parameter_types! {251    pub const TransactionBaseFee: Balance = 0;252    pub const TransactionByteFee: Balance = 1;253}254255impl transaction_payment::Trait for Runtime {256    type Currency = balances::Module<Runtime>;257    type OnTransactionPayment = ();258    type TransactionBaseFee = TransactionBaseFee;259    type TransactionByteFee = TransactionByteFee;260    type WeightToFee = ConvertInto;261    type FeeMultiplierUpdate = ();262}263264impl sudo::Trait for Runtime {265    type Event = Event;266    type Call = Call;267}268269/// Used for the module template in `./template.rs`270impl nft::Trait for Runtime {271    type Event = Event;272}273274construct_runtime!(275    pub enum Runtime where276        Block = Block,277        NodeBlock = opaque::Block,278        UncheckedExtrinsic = UncheckedExtrinsic,279    {280        System: system::{Module, Call, Config, Storage, Event<T>},281        RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},282        Timestamp: timestamp::{Module, Call, Storage, Inherent},283        Aura: aura::{Module, Config<T>, Inherent(Timestamp)},284        Grandpa: grandpa::{Module, Call, Storage, Config, Event},285        Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},286        TransactionPayment: transaction_payment::{Module, Storage},287		Sudo: sudo::{Module, Call, Config<T>, Storage, Event<T>},288		Contracts: contracts::{Module, Call, Config<T>, Storage, Event<T>},289        // Used for the module template in `./template.rs`290        Nft: nft::{Module, Call, Storage, Event<T>},291    }292);293294/// The address format for describing accounts.295pub type Address = AccountId;296/// Block header type as expected by this runtime.297pub type Header = generic::Header<BlockNumber, BlakeTwo256>;298/// Block type as expected by this runtime.299pub type Block = generic::Block<Header, UncheckedExtrinsic>;300/// A Block signed with a Justification301pub type SignedBlock = generic::SignedBlock<Block>;302/// BlockId type as expected by this runtime.303pub type BlockId = generic::BlockId<Block>;304/// The SignedExtension to the basic transaction logic.305pub type SignedExtra = (306    system::CheckVersion<Runtime>,307    system::CheckGenesis<Runtime>,308    system::CheckEra<Runtime>,309    system::CheckNonce<Runtime>,310    system::CheckWeight<Runtime>,311    transaction_payment::ChargeTransactionPayment<Runtime>,312);313/// Unchecked extrinsic type as expected by this runtime.314pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;315/// Extrinsic type that has already been checked.316pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;317/// Executive: handles dispatch to the various modules.318pub type Executive =319    frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;320321impl_runtime_apis! {322    impl sp_api::Core<Block> for Runtime {323        fn version() -> RuntimeVersion {324            VERSION325        }326327        fn execute_block(block: Block) {328            Executive::execute_block(block)329        }330331        fn initialize_block(header: &<Block as BlockT>::Header) {332            Executive::initialize_block(header)333        }334    }335336    impl sp_api::Metadata<Block> for Runtime {337        fn metadata() -> OpaqueMetadata {338            Runtime::metadata().into()339        }340    }341342    impl sp_block_builder::BlockBuilder<Block> for Runtime {343        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {344            Executive::apply_extrinsic(extrinsic)345        }346347        fn finalize_block() -> <Block as BlockT>::Header {348            Executive::finalize_block()349        }350351        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {352            data.create_extrinsics()353        }354355        fn check_inherents(356            block: Block,357            data: sp_inherents::InherentData,358        ) -> sp_inherents::CheckInherentsResult {359            data.check_extrinsics(&block)360        }361362        fn random_seed() -> <Block as BlockT>::Hash {363            RandomnessCollectiveFlip::random_seed()364        }365    }366367    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {368        fn validate_transaction(369            source: TransactionSource,370            tx: <Block as BlockT>::Extrinsic,371        ) -> TransactionValidity {372            Executive::validate_transaction(source, tx)373        }374    }375376    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {377        fn offchain_worker(header: &<Block as BlockT>::Header) {378            Executive::offchain_worker(header)379        }380    }381382    impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {383        fn slot_duration() -> u64 {384            Aura::slot_duration()385        }386387        fn authorities() -> Vec<AuraId> {388            Aura::authorities()389        }390    }391392    impl sp_session::SessionKeys<Block> for Runtime {393        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {394            opaque::SessionKeys::generate(seed)395        }396397        fn decode_session_keys(398            encoded: Vec<u8>,399        ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {400            opaque::SessionKeys::decode_into_raw_public_keys(&encoded)401        }402    }403404    impl fg_primitives::GrandpaApi<Block> for Runtime {405        fn grandpa_authorities() -> GrandpaAuthorityList {406            Grandpa::grandpa_authorities()407        }408    }409410    impl contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>411        for Runtime412	{413		fn call(414			origin: AccountId,415			dest: AccountId,416			value: Balance,417			gas_limit: u64,418			input_data: Vec<u8>,419		) -> ContractExecResult {420			let exec_result =421				Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);422			match exec_result {423                Ok(v) => ContractExecResult::Success {424                    status: v.status,425                    data: v.data,426                },427				Err(_) => ContractExecResult::Error,428			}429		}430431		fn get_storage(432			address: AccountId,433			key: [u8; 32],434		) -> contracts_primitives::GetStorageResult {435			Contracts::get_storage(address, key)436		}437438		fn rent_projection(439			address: AccountId,440		) -> contracts_primitives::RentProjectionResult<BlockNumber> {441			Contracts::rent_projection(address)442		}443	}444}