12345678#![cfg_attr(not(feature = "std"), no_std)]910#![recursion_limit = "256"]111213#[cfg(feature = "std")]14include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1516use pallet_grandpa::fg_primitives;17use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};18use sp_api::impl_runtime_apis;19use sp_consensus_aura::sr25519::AuthorityId as AuraId;20use sp_core::{ crypto::KeyTypeId, crypto::Public, OpaqueMetadata };21use sp_runtime::{22 Permill, Perbill, Perquintill, Percent,23 24 ModuleId, FixedPointNumber,25 create_runtime_str, generic, impl_opaque_keys,26 traits::{27 Convert, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, 28 IdentityLookup, NumberFor, Verify,29 },30 transaction_validity::{TransactionSource, TransactionValidity},31 ApplyExtrinsicResult, MultiSignature,32};33use sp_std::prelude::*;34#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment, CurrencyAdapter, FeeDetails, RuntimeDispatchInfo};3839pub use pallet_balances::Call as BalancesCall;40pub use pallet_contracts::Schedule as ContractsSchedule;41use pallet_contracts::WeightInfo;42pub use frame_support::{43 construct_runtime,44 dispatch::DispatchResult,45 parameter_types,46 traits::{47 Currency, ExistenceRequirement, Get, KeyOwnerProofSystem, OnUnbalanced, Randomness,48 LockIdentifier,49 },50 weights::{51 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},52 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,53 WeightToFeePolynomial,54 },55 StorageValue,56};5758use frame_system::{59 self as system,60 EnsureRoot, 61 limits::{BlockWeights, BlockLength}};62use sp_std::{marker::PhantomData};6364pub use pallet_timestamp::Call as TimestampCall;65666768pub struct CurrencyToVoteHandler;6970impl CurrencyToVoteHandler {71 fn factor() -> Balance {72 (Balances::total_issuance() / u64::max_value() as Balance).max(1)73 }74}7576impl Convert<Balance, u64> for CurrencyToVoteHandler {77 fn convert(x: Balance) -> u64 {78 (x / Self::factor()) as u6479 }80}8182impl Convert<u128, Balance> for CurrencyToVoteHandler {83 fn convert(x: u128) -> Balance {84 x * Self::factor()85 }86}87888990extern crate pallet_nft;91pub use pallet_nft::*;929394pub type BlockNumber = u32;959697pub type Signature = MultiSignature;9899100101pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;102103104105pub type AccountIndex = u32;106107108pub type Balance = u128;109110111pub type Index = u32;112113114pub type Hash = sp_core::H256;115116117pub type DigestItem = generic::DigestItem<Hash>;118119mod nft_weights;120121122123124125pub mod opaque {126 use super::*;127128 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;129130 131 pub type Header = generic::Header<BlockNumber, BlakeTwo256>;132 133 pub type Block = generic::Block<Header, UncheckedExtrinsic>;134 135 pub type BlockId = generic::BlockId<Block>;136137 impl_opaque_keys! {138 pub struct SessionKeys {139 pub aura: Aura,140 pub grandpa: Grandpa,141 }142 }143}144145146pub const VERSION: RuntimeVersion = RuntimeVersion {147 spec_name: create_runtime_str!("nft"),148 impl_name: create_runtime_str!("nft"),149 authoring_version: 1,150 spec_version: 3,151 impl_version: 1,152 apis: RUNTIME_API_VERSIONS,153 transaction_version: 1,154};155156pub const MILLISECS_PER_BLOCK: u64 = 6000;157158pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;159160161pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);162pub const HOURS: BlockNumber = MINUTES * 60;163pub const DAYS: BlockNumber = HOURS * 24;164165166#[cfg(feature = "std")]167pub fn native_version() -> NativeVersion {168 NativeVersion {169 runtime_version: VERSION,170 can_author_with: Default::default(),171 }172}173174175pub struct ValiudatorsOnly<Runtime: pallet_aura::Config>(PhantomData<Runtime>);176impl frame_support::traits::Contains<AccountId> for ValiudatorsOnly<Runtime> {177 fn contains(t: &AccountId) -> bool {178 let arr: [u8; 32] = *t.as_ref();179 let raw_key: Vec<u8> = Vec::from(arr);180181 match pallet_aura::Module::<Runtime>::authorities().iter().find(|auth| auth.to_raw_vec() == raw_key) {182 Some(_) => true,183 None => false,184 } 185 }186 fn sorted_members() -> Vec<AccountId> {187 let mut members: Vec<AccountId> = Vec::new();188 for auth in pallet_aura::Module::<Runtime>::authorities() {189 let mut arr: [u8; 32] = Default::default(); 190 let bor_arr = auth.clone().to_raw_vec();191 let slice = bor_arr.as_slice();192 arr.copy_from_slice(slice);193 members.push(AccountId::from(arr));194 }195 members 196 }197 fn count() -> usize {198 pallet_aura::Module::<Runtime>::authorities().len()199 }200}201202impl frame_support::traits::ContainsLengthBound for ValiudatorsOnly<Runtime> {203 fn min_len() -> usize {204 1205 }206 fn max_len() -> usize {207 100208 }209}210211type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;212213pub struct DealWithFees;214impl OnUnbalanced<NegativeImbalance> for DealWithFees {215 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {216 if let Some(fees) = fees_then_tips.next() {217 218 let mut split = fees.ration(80, 20);219 if let Some(tips) = fees_then_tips.next() {220 221 tips.ration_merge_into(80, 20, &mut split);222 }223 Treasury::on_unbalanced(split.0);224 225 }226 }227}228229230231const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);232233234const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);235236const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND;237238parameter_types! {239 pub const BlockHashCount: BlockNumber = 2400;240 pub RuntimeBlockLength: BlockLength =241 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);242 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);243 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;244 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()245 .base_block(BlockExecutionWeight::get())246 .for_class(DispatchClass::all(), |weights| {247 weights.base_extrinsic = ExtrinsicBaseWeight::get();248 })249 .for_class(DispatchClass::Normal, |weights| {250 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);251 })252 .for_class(DispatchClass::Operational, |weights| {253 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);254 255 256 weights.reserved = Some(257 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT258 );259 })260 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)261 .build_or_panic();262 pub const Version: RuntimeVersion = VERSION;263 pub const SS58Prefix: u8 = 42;264}265266impl system::Config for Runtime {267 268 type BaseCallFilter = ();269 270 type AccountId = AccountId;271 272 type Call = Call;273 274 type Lookup = IdentityLookup<AccountId>;275 276 type Index = Index;277 278 type BlockNumber = BlockNumber;279 280 type Hash = Hash;281 282 type Hashing = BlakeTwo256;283 284 type Header = generic::Header<BlockNumber, BlakeTwo256>;285 286 type Event = Event;287 288 type Origin = Origin;289 290 type BlockHashCount = BlockHashCount;291 292 type DbWeight = RocksDbWeight;293 294 295 type BlockWeights = RuntimeBlockWeights;296 297 type Version = Version;298 299 type PalletInfo = PalletInfo;300 301 type OnNewAccount = ();302 303 type OnKilledAccount = ();304 305 type AccountData = pallet_balances::AccountData<Balance>;306 307 type SystemWeightInfo = system::weights::SubstrateWeight<Runtime>;308 309 type BlockLength = RuntimeBlockLength;310 type SS58Prefix = SS58Prefix;311}312313impl pallet_aura::Config for Runtime {314 type AuthorityId = AuraId;315}316317impl pallet_grandpa::Config for Runtime {318 type Event = Event;319 type Call = Call;320321 type KeyOwnerProofSystem = ();322323 type KeyOwnerProof =324 <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;325326 type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(327 KeyTypeId,328 GrandpaId,329 )>>::IdentificationTuple;330331 type HandleEquivocation = ();332333 type WeightInfo = ();334}335336parameter_types! {337 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;338}339340impl pallet_timestamp::Config for Runtime {341 342 type Moment = u64;343 type OnTimestampSet = Aura;344 type MinimumPeriod = MinimumPeriod;345 type WeightInfo = ();346}347348parameter_types! {349 350 pub const ExistentialDeposit: u128 = 0;351 pub const MaxLocks: u32 = 50;352}353354impl pallet_balances::Config for Runtime {355 type MaxLocks = MaxLocks;356 357 type Balance = Balance;358 359 type Event = Event;360 type DustRemoval = Treasury;361 type ExistentialDeposit = ExistentialDeposit;362 type AccountStore = System;363 type WeightInfo = ();364}365366pub const MILLICENTS: Balance = 1_000_000_000;367pub const CENTS: Balance = 1_000 * MILLICENTS;368pub const DOLLARS: Balance = 100 * CENTS;369370pub const fn deposit(items: u32, bytes: u32) -> Balance {371 items as Balance * 15 * CENTS + (bytes as Balance) * 6 * CENTS372}373374parameter_types! {375 pub const TombstoneDeposit: Balance = deposit(376 0,377 sp_std::mem::size_of::<pallet_contracts::ContractInfo<Runtime>>() as u32378 );379 pub const DepositPerContract: Balance = TombstoneDeposit::get();380 pub const DepositPerStorageByte: Balance = deposit(0, 1);381 pub const DepositPerStorageItem: Balance = deposit(1, 0);382 pub RentFraction: Perbill = Perbill::from_rational_approximation(1u32, 30 * DAYS);383 pub const SurchargeReward: Balance = 150 * MILLICENTS;384 pub const SignedClaimHandicap: u32 = 2;385 pub const MaxDepth: u32 = 32;386 pub const MaxValueSize: u32 = 16 * 1024;387 388 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *389 RuntimeBlockWeights::get().max_block;390 391 392 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (393 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -394 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)395 )) / 5) as u32;396}397398399impl pallet_contracts::Config for Runtime {400 type Time = Timestamp;401 type Randomness = RandomnessCollectiveFlip;402 type Currency = Balances;403 type Event = Event;404 type RentPayment = ();405 type SignedClaimHandicap = SignedClaimHandicap;406 type TombstoneDeposit = TombstoneDeposit;407 type DepositPerContract = DepositPerContract;408 type DepositPerStorageByte = DepositPerStorageByte;409 type DepositPerStorageItem = DepositPerStorageItem;410 type RentFraction = RentFraction;411 type SurchargeReward = SurchargeReward;412 type MaxDepth = MaxDepth;413 type MaxValueSize = MaxValueSize;414 type WeightPrice = pallet_transaction_payment::Module<Self>;415 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;416 type ChainExtension = ();417 type DeletionQueueDepth = DeletionQueueDepth;418 type DeletionWeightLimit = DeletionWeightLimit;419}420421parameter_types! {422 pub const TransactionByteFee: Balance = 10 * MILLICENTS;423 pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25);424 pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(1, 100_000);425 pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 1_000_000_000u128);426}427428impl pallet_transaction_payment::Config for Runtime {429 type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees>;430 type TransactionByteFee = TransactionByteFee;431 type WeightToFee = IdentityFee<Balance>;432 type FeeMultiplierUpdate =433 TargetedFeeAdjustment<Self, TargetBlockFullness, AdjustmentVariable, MinimumMultiplier>;434}435436parameter_types! {437 pub const ProposalBond: Permill = Permill::from_percent(5);438 pub const ProposalBondMinimum: Balance = 1 * DOLLARS;439 pub const SpendPeriod: BlockNumber = 5 * MINUTES;440 pub const Burn: Permill = Permill::from_percent(0);441 pub const TipCountdown: BlockNumber = 1 * DAYS;442 pub const TipFindersFee: Percent = Percent::from_percent(20);443 pub const TipReportDepositBase: Balance = 1 * DOLLARS;444 pub const DataDepositPerByte: Balance = 1 * CENTS;445 pub const BountyDepositBase: Balance = 1 * DOLLARS;446 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;447 pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry");448 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;449 pub const MaximumReasonLength: u32 = 16384;450 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);451 pub const BountyValueMinimum: Balance = 5 * DOLLARS;452}453454impl pallet_treasury::Config for Runtime {455 type ModuleId = TreasuryModuleId;456 type Currency = Balances;457 type ApproveOrigin = EnsureRoot<AccountId>;458 type RejectOrigin = EnsureRoot<AccountId>;459 type Event = Event;460 type OnSlash = ();461 type ProposalBond = ProposalBond;462 type ProposalBondMinimum = ProposalBondMinimum;463 type SpendPeriod = SpendPeriod;464 type Burn = Burn;465 type BurnDestination = ();466 type SpendFunds = ();467 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;468}469470impl pallet_sudo::Config for Runtime {471 type Event = Event;472 type Call = Call;473}474475parameter_types! {476 pub const MinVestedTransfer: Balance = 100 * DOLLARS;477}478479impl pallet_vesting::Config for Runtime {480 type Event = Event;481 type Currency = Balances;482 type BlockNumberToBalance = ConvertInto;483 type MinVestedTransfer = MinVestedTransfer;484 type WeightInfo = ();485}486487488impl pallet_nft::Config for Runtime {489 type Event = Event;490 type WeightInfo = nft_weights::WeightInfo;491}492493construct_runtime!(494 pub enum Runtime where495 Block = Block,496 NodeBlock = opaque::Block,497 UncheckedExtrinsic = UncheckedExtrinsic498 {499 System: system::{Module, Call, Config, Storage, Event<T>},500 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},501 Contracts: pallet_contracts::{Module, Call, Config<T>, Storage, Event<T>},502 Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},503 Aura: pallet_aura::{Module, Config<T>, Inherent},504 Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},505 Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},506 TransactionPayment: pallet_transaction_payment::{Module, Storage},507 Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>},508 Nft: pallet_nft::{Module, Call, Config<T>, Storage, Event<T>},509 Treasury: pallet_treasury::{Module, Call, Storage, Config, Event<T>},510 Vesting: pallet_vesting::{Module, Call, Config<T>, Storage, Event<T>},511 }512);513514515pub type Address = AccountId;516517pub type Header = generic::Header<BlockNumber, BlakeTwo256>;518519pub type Block = generic::Block<Header, UncheckedExtrinsic>;520521pub type SignedBlock = generic::SignedBlock<Block>;522523pub type BlockId = generic::BlockId<Block>;524525pub type SignedExtra = (526 system::CheckSpecVersion<Runtime>,527 system::CheckTxVersion<Runtime>,528 system::CheckGenesis<Runtime>,529 system::CheckEra<Runtime>,530 system::CheckNonce<Runtime>,531 system::CheckWeight<Runtime>,532 pallet_nft::ChargeTransactionPayment<Runtime>,533);534535pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;536537pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;538539pub type Executive =540 frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;541542impl_runtime_apis! {543544 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>545 for Runtime546 {547 fn call(548 origin: AccountId,549 dest: AccountId,550 value: Balance,551 gas_limit: u64,552 input_data: Vec<u8>,553 ) -> pallet_contracts_primitives::ContractExecResult {554 Contracts::bare_call(origin, dest, value, gas_limit, input_data)555 }556557 fn get_storage(558 address: AccountId,559 key: [u8; 32],560 ) -> pallet_contracts_primitives::GetStorageResult {561 Contracts::get_storage(address, key)562 }563564 fn rent_projection(565 address: AccountId,566 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {567 Contracts::rent_projection(address)568 }569 }570571 impl sp_api::Core<Block> for Runtime {572 fn version() -> RuntimeVersion {573 VERSION574 }575576 fn execute_block(block: Block) {577 Executive::execute_block(block)578 }579580 fn initialize_block(header: &<Block as BlockT>::Header) {581 Executive::initialize_block(header)582 }583 }584585 impl sp_api::Metadata<Block> for Runtime {586 fn metadata() -> OpaqueMetadata {587 Runtime::metadata().into()588 }589 }590591 impl sp_block_builder::BlockBuilder<Block> for Runtime {592 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {593 Executive::apply_extrinsic(extrinsic)594 }595596 fn finalize_block() -> <Block as BlockT>::Header {597 Executive::finalize_block()598 }599600 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {601 data.create_extrinsics()602 }603604 fn check_inherents(605 block: Block,606 data: sp_inherents::InherentData,607 ) -> sp_inherents::CheckInherentsResult {608 data.check_extrinsics(&block)609 }610611 fn random_seed() -> <Block as BlockT>::Hash {612 RandomnessCollectiveFlip::random_seed()613 }614 }615616 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {617 fn validate_transaction(618 source: TransactionSource,619 tx: <Block as BlockT>::Extrinsic,620 ) -> TransactionValidity {621 Executive::validate_transaction(source, tx)622 }623 }624625 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {626 fn offchain_worker(header: &<Block as BlockT>::Header) {627 Executive::offchain_worker(header)628 }629 }630631 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {632 fn slot_duration() -> u64 {633 Aura::slot_duration()634 }635636 fn authorities() -> Vec<AuraId> {637 Aura::authorities()638 }639 }640641 impl sp_session::SessionKeys<Block> for Runtime {642 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {643 opaque::SessionKeys::generate(seed)644 }645646 fn decode_session_keys(647 encoded: Vec<u8>,648 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {649 opaque::SessionKeys::decode_into_raw_public_keys(&encoded)650 }651 }652653 impl fg_primitives::GrandpaApi<Block> for Runtime {654 fn grandpa_authorities() -> GrandpaAuthorityList {655 Grandpa::grandpa_authorities()656 }657658 fn submit_report_equivocation_unsigned_extrinsic(659 _equivocation_proof: fg_primitives::EquivocationProof<660 <Block as BlockT>::Hash,661 NumberFor<Block>,662 >,663 _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,664 ) -> Option<()> {665 None666 }667668 fn generate_key_ownership_proof(669 _set_id: fg_primitives::SetId,670 _authority_id: GrandpaId,671 ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {672 673 674 675 None676 }677 }678 679 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {680 fn account_nonce(account: AccountId) -> Index {681 System::account_nonce(account)682 }683 }684685 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {686 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {687 TransactionPayment::query_info(uxt, len)688 }689 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {690 TransactionPayment::query_fee_details(uxt, len)691 }692 }693694 #[cfg(feature = "runtime-benchmarks")]695 impl frame_benchmarking::Benchmark<Block> for Runtime {696 fn dispatch_benchmark(697 config: frame_benchmarking::BenchmarkConfig698 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {699 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};700701 let whitelist: Vec<TrackedStorageKey> = vec![702 703 hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),704 705 706 707 708 709 710 711 712 ];713714 let mut batches = Vec::<BenchmarkBatch>::new();715 let params = (&config, &whitelist);716717 add_benchmark!(params, batches, pallet_nft, Nft);718719 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }720 Ok(batches)721 }722 }723}