123#![cfg_attr(not(feature = "std"), no_std)]45#![recursion_limit = "256"]678#[cfg(feature = "std")]9include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1011use pallet_contracts_rpc_runtime_api::ContractExecResult;12use pallet_grandpa::fg_primitives;13use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};14use sp_api::impl_runtime_apis;15use sp_consensus_aura::sr25519::AuthorityId as AuraId;16use sp_core::{ crypto::KeyTypeId, crypto::Public, OpaqueMetadata };17use sp_runtime::{18 create_runtime_str, generic, impl_opaque_keys,19 traits::{20 Convert, BlakeTwo256, Block as BlockT, IdentifyAccount, 21 IdentityLookup, NumberFor, Saturating, Verify,22 },23 transaction_validity::{TransactionSource, TransactionValidity},24 ApplyExtrinsicResult, MultiSignature,25};26use sp_std::prelude::*;27#[cfg(feature = "std")]28use sp_version::NativeVersion;29use sp_version::RuntimeVersion;303132pub use pallet_balances::Call as BalancesCall;33pub use pallet_contracts::Schedule as ContractsSchedule;34pub use frame_support::{35 construct_runtime,36 dispatch::DispatchResult,37 parameter_types,38 traits::{39 Currency, ExistenceRequirement, Get, KeyOwnerProofSystem, OnUnbalanced, Randomness,40 WithdrawReason, LockIdentifier,41 },42 weights::{43 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},44 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,45 WeightToFeePolynomial,46 },47 StorageValue,48};49#[cfg(any(feature = "std", test))]50pub use sp_runtime::BuildStorage;51use sp_runtime:: { Perbill, Permill, Percent, ModuleId };52use frame_system::{self as system, EnsureRoot };53use sp_std::{marker::PhantomData};5455pub use pallet_timestamp::Call as TimestampCall;56575859pub struct CurrencyToVoteHandler;6061impl CurrencyToVoteHandler {62 fn factor() -> Balance {63 (Balances::total_issuance() / u64::max_value() as Balance).max(1)64 }65}6667impl Convert<Balance, u64> for CurrencyToVoteHandler {68 fn convert(x: Balance) -> u64 {69 (x / Self::factor()) as u6470 }71}7273impl Convert<u128, Balance> for CurrencyToVoteHandler {74 fn convert(x: u128) -> Balance {75 x * Self::factor()76 }77}78798081extern crate pallet_nft;82pub use pallet_nft::*;838485pub type BlockNumber = u32;868788pub type Signature = MultiSignature;89909192pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;93949596pub type AccountIndex = u32;979899pub type Balance = u128;100101102pub type Index = u32;103104105pub type Hash = sp_core::H256;106107108pub type DigestItem = generic::DigestItem<Hash>;109110mod nft_weights;111112113114115116pub mod opaque {117 use super::*;118119 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;120121 122 pub type Header = generic::Header<BlockNumber, BlakeTwo256>;123 124 pub type Block = generic::Block<Header, UncheckedExtrinsic>;125 126 pub type BlockId = generic::BlockId<Block>;127128 impl_opaque_keys! {129 pub struct SessionKeys {130 pub aura: Aura,131 pub grandpa: Grandpa,132 }133 }134}135136137pub const VERSION: RuntimeVersion = RuntimeVersion {138 spec_name: create_runtime_str!("nft"),139 impl_name: create_runtime_str!("nft"),140 authoring_version: 1,141 spec_version: 2,142 impl_version: 1,143 apis: RUNTIME_API_VERSIONS,144 transaction_version: 1,145};146147pub const MILLISECS_PER_BLOCK: u64 = 6000;148149pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;150151152pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);153pub const HOURS: BlockNumber = MINUTES * 60;154pub const DAYS: BlockNumber = HOURS * 24;155156157#[cfg(feature = "std")]158pub fn native_version() -> NativeVersion {159 NativeVersion {160 runtime_version: VERSION,161 can_author_with: Default::default(),162 }163}164165166pub struct ValiudatorsOnly<Runtime: pallet_aura::Trait>(PhantomData<Runtime>);167impl frame_support::traits::Contains<AccountId> for ValiudatorsOnly<Runtime> {168 fn contains(t: &AccountId) -> bool {169 let arr: [u8; 32] = *t.as_ref();170 let raw_key: Vec<u8> = Vec::from(arr);171172 match pallet_aura::Module::<Runtime>::authorities().iter().find(|auth| auth.to_raw_vec() == raw_key) {173 Some(_) => true,174 None => false,175 } 176 }177 fn sorted_members() -> Vec<AccountId> {178 let mut members: Vec<AccountId> = Vec::new();179 for auth in pallet_aura::Module::<Runtime>::authorities() {180 let mut arr: [u8; 32] = Default::default(); 181 let bor_arr = auth.clone().to_raw_vec();182 let slice = bor_arr.as_slice();183 arr.copy_from_slice(slice);184 members.push(AccountId::from(arr));185 }186 members 187 }188 fn count() -> usize {189 pallet_aura::Module::<Runtime>::authorities().len()190 }191}192193impl frame_support::traits::ContainsLengthBound for ValiudatorsOnly<Runtime> {194 fn min_len() -> usize {195 1196 }197 fn max_len() -> usize {198 100199 }200}201202parameter_types! {203 pub const BlockHashCount: BlockNumber = 2400;204 205 pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND;206 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);207 208 pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get()209 .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get();210 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;211 pub const Version: RuntimeVersion = VERSION;212}213214impl system::Trait for Runtime {215 216 type BaseCallFilter = ();217 218 type AccountId = AccountId;219 220 type Call = Call;221 222 type Lookup = IdentityLookup<AccountId>;223 224 type Index = Index;225 226 type BlockNumber = BlockNumber;227 228 type Hash = Hash;229 230 type Hashing = BlakeTwo256;231 232 type Header = generic::Header<BlockNumber, BlakeTwo256>;233 234 type Event = Event;235 236 type Origin = Origin;237 238 type BlockHashCount = BlockHashCount;239 240 type MaximumBlockWeight = MaximumBlockWeight;241 242 type DbWeight = RocksDbWeight;243 244 245 type BlockExecutionWeight = BlockExecutionWeight;246 247 248 type ExtrinsicBaseWeight = ExtrinsicBaseWeight;249 250 251 252 type MaximumExtrinsicWeight = MaximumExtrinsicWeight;253 254 type MaximumBlockLength = MaximumBlockLength;255 256 type AvailableBlockRatio = AvailableBlockRatio;257 258 type Version = Version;259 260 type PalletInfo = PalletInfo;261 262 type OnNewAccount = ();263 264 type OnKilledAccount = ();265 266 type AccountData = pallet_balances::AccountData<Balance>;267 268 type SystemWeightInfo = ();269}270271impl pallet_aura::Trait for Runtime {272 type AuthorityId = AuraId;273}274275impl pallet_grandpa::Trait for Runtime {276 type Event = Event;277 type Call = Call;278279 type KeyOwnerProofSystem = ();280281 type KeyOwnerProof =282 <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;283284 type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(285 KeyTypeId,286 GrandpaId,287 )>>::IdentificationTuple;288289 type HandleEquivocation = ();290291 type WeightInfo = ();292}293294parameter_types! {295 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;296}297298impl pallet_timestamp::Trait for Runtime {299 300 type Moment = u64;301 type OnTimestampSet = Aura;302 type MinimumPeriod = MinimumPeriod;303 type WeightInfo = ();304}305306parameter_types! {307 308 pub const ExistentialDeposit: u128 = 0;309 pub const MaxLocks: u32 = 50;310}311312impl pallet_balances::Trait for Runtime {313 type MaxLocks = MaxLocks;314 315 type Balance = Balance;316 317 type Event = Event;318 type DustRemoval = ();319 type ExistentialDeposit = ExistentialDeposit;320 type AccountStore = System;321 type WeightInfo = ();322}323324pub const MILLICENTS: Balance = 1_000_000_000;325pub const CENTS: Balance = 1_000 * MILLICENTS;326pub const DOLLARS: Balance = 100 * CENTS;327328parameter_types! {329 pub const TombstoneDeposit: Balance = 0;330 pub const RentByteFee: Balance = 4 * MILLICENTS;331 pub const RentDepositOffset: Balance = 1000 * MILLICENTS;332 pub const SurchargeReward: Balance = 150 * MILLICENTS;333}334335impl pallet_contracts::Trait for Runtime {336 type Time = Timestamp;337 type Randomness = RandomnessCollectiveFlip;338 type Currency = Balances;339 type Event = Event;340 type DetermineContractAddress = pallet_contracts::SimpleAddressDeterminer<Runtime>;341 type TrieIdGenerator = pallet_contracts::TrieIdFromParentCounter<Runtime>;342 type RentPayment = ();343 type SignedClaimHandicap = pallet_contracts::DefaultSignedClaimHandicap;344 type TombstoneDeposit = TombstoneDeposit;345 type StorageSizeOffset = pallet_contracts::DefaultStorageSizeOffset;346 type RentByteFee = RentByteFee;347 type RentDepositOffset = RentDepositOffset;348 type SurchargeReward = SurchargeReward;349 type MaxDepth = pallet_contracts::DefaultMaxDepth;350 type MaxValueSize = pallet_contracts::DefaultMaxValueSize;351 type WeightPrice = pallet_transaction_payment::Module<Self>;352}353354parameter_types! {355 pub const TransactionByteFee: Balance = 10 * MILLICENTS;356}357358impl pallet_transaction_payment::Trait for Runtime {359 type Currency = pallet_balances::Module<Runtime>;360 type OnTransactionPayment = ();361 type TransactionByteFee = TransactionByteFee;362 type WeightToFee = IdentityFee<Balance>;363 type FeeMultiplierUpdate = ();364}365366parameter_types! {367 pub const ProposalBond: Permill = Permill::from_percent(5);368 pub const ProposalBondMinimum: Balance = 1 * DOLLARS;369 pub const SpendPeriod: BlockNumber = 5 * MINUTES;370 pub const Burn: Permill = Permill::from_percent(0);371 pub const TipCountdown: BlockNumber = 1 * DAYS;372 pub const TipFindersFee: Percent = Percent::from_percent(20);373 pub const TipReportDepositBase: Balance = 1 * DOLLARS;374 pub const DataDepositPerByte: Balance = 1 * CENTS;375 pub const BountyDepositBase: Balance = 1 * DOLLARS;376 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;377 pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry");378 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;379 pub const MaximumReasonLength: u32 = 16384;380 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);381 pub const BountyValueMinimum: Balance = 5 * DOLLARS;382}383384impl pallet_treasury::Trait for Runtime {385 type ModuleId = TreasuryModuleId;386 type Currency = Balances;387 type ApproveOrigin = EnsureRoot<AccountId>;388 type RejectOrigin = EnsureRoot<AccountId>;389 type Tippers = ValiudatorsOnly<Self>;390 type TipCountdown = TipCountdown;391 type TipFindersFee = TipFindersFee;392 type TipReportDepositBase = TipReportDepositBase;393 type DataDepositPerByte = DataDepositPerByte;394 type Event = Event;395 type OnSlash = ();396 type ProposalBond = ProposalBond;397 type ProposalBondMinimum = ProposalBondMinimum;398 type SpendPeriod = SpendPeriod;399 type Burn = Burn;400 type BountyDepositBase = BountyDepositBase;401 type BountyDepositPayoutDelay = BountyDepositPayoutDelay;402 type BountyUpdatePeriod = BountyUpdatePeriod;403 type BountyCuratorDeposit = BountyCuratorDeposit;404 type BountyValueMinimum = BountyValueMinimum;405 type MaximumReasonLength = MaximumReasonLength;406 type BurnDestination = ();407 type WeightInfo = ();408}409410impl pallet_sudo::Trait for Runtime {411 type Event = Event;412 type Call = Call;413}414415416impl pallet_nft::Trait for Runtime {417 type Event = Event;418 type WeightInfo = nft_weights::WeightInfo;419}420421construct_runtime!(422 pub enum Runtime where423 Block = Block,424 NodeBlock = opaque::Block,425 UncheckedExtrinsic = UncheckedExtrinsic426 {427 System: system::{Module, Call, Config, Storage, Event<T>},428 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},429 Contracts: pallet_contracts::{Module, Call, Config, Storage, Event<T>},430 Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},431 Aura: pallet_aura::{Module, Config<T>, Inherent},432 Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},433 Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},434 TransactionPayment: pallet_transaction_payment::{Module, Storage},435 Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>},436 Nft: pallet_nft::{Module, Call, Config<T>, Storage, Event<T>},437 Treasury: pallet_treasury::{Module, Call, Storage, Config, Event<T>},438 }439);440441442pub type Address = AccountId;443444pub type Header = generic::Header<BlockNumber, BlakeTwo256>;445446pub type Block = generic::Block<Header, UncheckedExtrinsic>;447448pub type SignedBlock = generic::SignedBlock<Block>;449450pub type BlockId = generic::BlockId<Block>;451452pub type SignedExtra = (453 system::CheckSpecVersion<Runtime>,454 system::CheckTxVersion<Runtime>,455 system::CheckGenesis<Runtime>,456 system::CheckEra<Runtime>,457 system::CheckNonce<Runtime>,458 system::CheckWeight<Runtime>,459 pallet_nft::ChargeTransactionPayment<Runtime>,460);461462pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;463464pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;465466pub type Executive =467 frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;468469impl_runtime_apis! {470471 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>472 for Runtime473 {474 fn call(475 origin: AccountId,476 dest: AccountId,477 value: Balance,478 gas_limit: u64,479 input_data: Vec<u8>,480 ) -> ContractExecResult {481 let (exec_result, gas_consumed) =482 Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);483 match exec_result {484 Ok(v) => ContractExecResult::Success {485 flags: v.flags.bits(),486 data: v.data,487 gas_consumed: gas_consumed,488 },489 Err(_) => ContractExecResult::Error,490 }491 }492493 fn get_storage(494 address: AccountId,495 key: [u8; 32],496 ) -> pallet_contracts_primitives::GetStorageResult {497 Contracts::get_storage(address, key)498 }499500 fn rent_projection(501 address: AccountId,502 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {503 Contracts::rent_projection(address)504 }505 }506507 impl sp_api::Core<Block> for Runtime {508 fn version() -> RuntimeVersion {509 VERSION510 }511512 fn execute_block(block: Block) {513 Executive::execute_block(block)514 }515516 fn initialize_block(header: &<Block as BlockT>::Header) {517 Executive::initialize_block(header)518 }519 }520521 impl sp_api::Metadata<Block> for Runtime {522 fn metadata() -> OpaqueMetadata {523 Runtime::metadata().into()524 }525 }526527 impl sp_block_builder::BlockBuilder<Block> for Runtime {528 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {529 Executive::apply_extrinsic(extrinsic)530 }531532 fn finalize_block() -> <Block as BlockT>::Header {533 Executive::finalize_block()534 }535536 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {537 data.create_extrinsics()538 }539540 fn check_inherents(541 block: Block,542 data: sp_inherents::InherentData,543 ) -> sp_inherents::CheckInherentsResult {544 data.check_extrinsics(&block)545 }546547 fn random_seed() -> <Block as BlockT>::Hash {548 RandomnessCollectiveFlip::random_seed()549 }550 }551552 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {553 fn validate_transaction(554 source: TransactionSource,555 tx: <Block as BlockT>::Extrinsic,556 ) -> TransactionValidity {557 Executive::validate_transaction(source, tx)558 }559 }560561 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {562 fn offchain_worker(header: &<Block as BlockT>::Header) {563 Executive::offchain_worker(header)564 }565 }566567 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {568 fn slot_duration() -> u64 {569 Aura::slot_duration()570 }571572 fn authorities() -> Vec<AuraId> {573 Aura::authorities()574 }575 }576577 impl sp_session::SessionKeys<Block> for Runtime {578 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {579 opaque::SessionKeys::generate(seed)580 }581582 fn decode_session_keys(583 encoded: Vec<u8>,584 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {585 opaque::SessionKeys::decode_into_raw_public_keys(&encoded)586 }587 }588589 impl fg_primitives::GrandpaApi<Block> for Runtime {590 fn grandpa_authorities() -> GrandpaAuthorityList {591 Grandpa::grandpa_authorities()592 }593594 fn submit_report_equivocation_unsigned_extrinsic(595 _equivocation_proof: fg_primitives::EquivocationProof<596 <Block as BlockT>::Hash,597 NumberFor<Block>,598 >,599 _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,600 ) -> Option<()> {601 None602 }603604 fn generate_key_ownership_proof(605 _set_id: fg_primitives::SetId,606 _authority_id: GrandpaId,607 ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {608 609 610 611 None612 }613 }614 615 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {616 fn account_nonce(account: AccountId) -> Index {617 System::account_nonce(account)618 }619 }620621 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {622 fn query_info(623 uxt: <Block as BlockT>::Extrinsic,624 len: u32,625 ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {626 TransactionPayment::query_info(uxt, len)627 }628 }629630 #[cfg(feature = "runtime-benchmarks")]631 impl frame_benchmarking::Benchmark<Block> for Runtime {632 fn dispatch_benchmark(633 config: frame_benchmarking::BenchmarkConfig634 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {635 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};636637 let whitelist: Vec<TrackedStorageKey> = vec![638 639 hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),640 641 642 643 644 645 646 647 648 ];649650 let mut batches = Vec::<BenchmarkBatch>::new();651 let params = (&config, &whitelist);652653 add_benchmark!(params, batches, pallet_nft, Nft);654655 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }656 Ok(batches)657 }658 }659}