Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: pallet api fungibles #278

Merged
merged 26 commits into from
Sep 13, 2024
Merged
Changes from 1 commit
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
e8a3045
refactor: encoding scheme
Daanvdplas Sep 10, 2024
b16430b
tests: pallet api extension
Daanvdplas Sep 10, 2024
2179645
docs: tests
Daanvdplas Sep 10, 2024
dad4beb
refactor: remove unnecessary
Daanvdplas Sep 10, 2024
1c6f03a
test: primitives
Daanvdplas Sep 10, 2024
a51d619
style: naming variable
Daanvdplas Sep 10, 2024
9ff9915
test: devnet runtime versioning
Daanvdplas Sep 10, 2024
a2b9e76
test: runtime devnet mod (small tests)
Daanvdplas Sep 10, 2024
dc0f90a
refactor: fallible conversion
evilrobot-01 Sep 10, 2024
6f8205e
refactor: fallible conversion (#275)
evilrobot-01 Sep 11, 2024
1547dca
fix: tests after fallible conversion feat
Daanvdplas Sep 11, 2024
2b07130
rebase
Daanvdplas Sep 11, 2024
36e8735
fix: test after fallible conversion feat
Daanvdplas Sep 11, 2024
438de63
Merge branch 'daan/tests-pallet_api_extension' into daan/test-devnet_…
Daanvdplas Sep 11, 2024
a1ee377
test: config contracts
Daanvdplas Sep 11, 2024
8949e13
test: ensure signed test coverage
Daanvdplas Sep 11, 2024
d2eeb08
test: coverage fungibles pallet
Daanvdplas Sep 11, 2024
538b19e
fix: comment
Daanvdplas Sep 11, 2024
ca1ccca
test: error case test coverage
Daanvdplas Sep 12, 2024
1060a91
test: no state set test
Daanvdplas Sep 12, 2024
98e89dd
refactor: test variables
Daanvdplas Sep 12, 2024
0ad8b36
test: encoding read result
Daanvdplas Sep 12, 2024
682e8f3
refactor: pallet fungibles mod.rs
Daanvdplas Sep 13, 2024
db382a8
refactor: split tests and test badorigin first
Daanvdplas Sep 13, 2024
497b2f7
refactor: assets helper functions
Daanvdplas Sep 13, 2024
4e7fbaa
merge daan/api
Daanvdplas Sep 13, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
test: ensure signed test coverage
Daanvdplas committed Sep 11, 2024

Verified

This commit was signed with the committer’s verified signature.
Daanvdplas Daan van der Plas
commit 8949e134dd1570e48bf76dd2cbfebfb499013e50
12 changes: 4 additions & 8 deletions pallets/api/src/fungibles/mod.rs
Original file line number Diff line number Diff line change
@@ -14,16 +14,12 @@ mod tests;
pub mod weights;

type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
type TokenIdOf<T> = <pallet_assets::Pallet<T, AssetsInstanceOf<T>> as Inspect<
<T as frame_system::Config>::AccountId,
>>::AssetId;
type TokenIdOf<T> = <AssetsOf<T> as Inspect<<T as frame_system::Config>::AccountId>>::AssetId;
type TokenIdParameterOf<T> = <T as pallet_assets::Config<AssetsInstanceOf<T>>>::AssetIdParameter;
type AssetsOf<T> = pallet_assets::Pallet<T, AssetsInstanceOf<T>>;
type AssetsInstanceOf<T> = <T as Config>::AssetsInstance;
type AssetsWeightInfoOf<T> = <T as pallet_assets::Config<AssetsInstanceOf<T>>>::WeightInfo;
type BalanceOf<T> = <pallet_assets::Pallet<T, AssetsInstanceOf<T>> as Inspect<
<T as frame_system::Config>::AccountId,
>>::Balance;
type BalanceOf<T> = <AssetsOf<T> as Inspect<<T as frame_system::Config>::AccountId>>::Balance;

#[frame_support::pallet]
pub mod pallet {
@@ -78,7 +74,7 @@ pub mod pallet {
/// Decimals for the specified token.
#[codec(index = 10)]
TokenDecimals(TokenIdOf<T>),
/// Check if a specified token exists.
/// Whether a specified token exists.
#[codec(index = 18)]
TokenExists(TokenIdOf<T>),
}
@@ -123,7 +119,7 @@ pub mod pallet {
pub trait Config: frame_system::Config + pallet_assets::Config<Self::AssetsInstance> {
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The instance of pallet assets it is tightly coupled to.
/// The instance of pallet-assets.
type AssetsInstance;
/// Weight information for dispatchables in this pallet.
type WeightInfo: WeightInfo;
30 changes: 28 additions & 2 deletions pallets/api/src/fungibles/tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use codec::Encode;
use frame_support::{
assert_ok,
sp_runtime::traits::Zero,
assert_noop, assert_ok,
sp_runtime::{traits::Zero, DispatchError::BadOrigin},
traits::fungibles::{
approvals::Inspect as ApprovalInspect, metadata::Inspect as MetadataInspect, Inspect,
},
@@ -22,6 +22,9 @@ fn transfer_works() {
let to = Some(BOB);

create_token_and_mint_to(ALICE, token, ALICE, value * 2);
for origin in vec![root(), none()] {
assert_noop!(Fungibles::transfer(origin, token, BOB, value), BadOrigin);
}
let balance_before_transfer = Assets::balance(token, &BOB);
assert_ok!(Fungibles::transfer(signed(ALICE), token, BOB, value));
let balance_after_transfer = Assets::balance(token, &BOB);
@@ -40,6 +43,10 @@ fn transfer_from_works() {

// Approve CHARLIE to transfer up to `value` to BOB.
create_token_mint_and_approve(ALICE, token, ALICE, value * 2, CHARLIE, value);
// TODO: weight
for origin in vec![root(), none()] {
assert_noop!(Fungibles::transfer_from(origin, token, ALICE, BOB, value), BadOrigin);
}
// Successfully call transfer from.
let alice_balance_before_transfer = Assets::balance(token, &ALICE);
let bob_balance_before_transfer = Assets::balance(token, &BOB);
@@ -101,6 +108,10 @@ fn increase_allowance_works() {
let spender = BOB;

create_token_and_mint_to(ALICE, token, ALICE, value);
// TODO: weight
for origin in vec![root(), none()] {
assert_noop!(Fungibles::increase_allowance(origin, token, BOB, value), BadOrigin);
}
assert_eq!(0, Assets::allowance(token, &ALICE, &BOB));
assert_ok!(Fungibles::increase_allowance(signed(ALICE), token, BOB, value));
assert_eq!(Assets::allowance(token, &ALICE, &BOB), value);
@@ -123,6 +134,10 @@ fn decrease_allowance_works() {
let spender = BOB;

create_token_mint_and_approve(ALICE, token, ALICE, value, BOB, value);
// TODO: weight
for origin in vec![root(), none()] {
assert_noop!(Fungibles::decrease_allowance(origin, token, BOB, 0), BadOrigin);
}
assert_eq!(Assets::allowance(token, &ALICE, &BOB), value);
// Owner balance is not changed if decreased by zero.
assert_ok!(Fungibles::decrease_allowance(signed(ALICE), token, BOB, 0));
@@ -147,6 +162,9 @@ fn create_works() {
let creator = ALICE;
let admin = ALICE;

for origin in vec![root(), none()] {
assert_noop!(Fungibles::create(origin, id, admin, 100), BadOrigin);
}
assert!(!Assets::asset_exists(id));
assert_ok!(Fungibles::create(signed(creator), id, admin, 100));
assert!(Assets::asset_exists(id));
@@ -297,6 +315,14 @@ fn signed(account: AccountId) -> RuntimeOrigin {
RuntimeOrigin::signed(account)
}

fn root() -> RuntimeOrigin {
RuntimeOrigin::root()
}

fn none() -> RuntimeOrigin {
RuntimeOrigin::none()
}

fn create_token(owner: AccountId, token: TokenId) {
assert_ok!(Assets::create(signed(owner), token, owner, 1));
}
15 changes: 8 additions & 7 deletions pallets/api/src/mock.rs
Original file line number Diff line number Diff line change
@@ -9,6 +9,12 @@ use sp_runtime::{
BuildStorage,
};

pub(crate) const ALICE: AccountId = 1;
pub(crate) const BOB: AccountId = 2;
pub(crate) const CHARLIE: AccountId = 3;
pub(crate) const INIT_AMOUNT: Balance = 100_000_000 * UNIT;
pub(crate) const UNIT: Balance = 10_000_000_000;

type Block = frame_system::mocking::MockBlock<Test>;
pub(crate) type AccountId = u64;
pub(crate) type Balance = u128;
@@ -80,7 +86,7 @@ impl pallet_assets::Config<AssetsInstance> for Test {
type AssetAccountDeposit = ConstU128<10>;
type AssetDeposit = ConstU128<1>;
type AssetId = TokenId;
type AssetIdParameter = u32;
type AssetIdParameter = TokenId;
type Balance = Balance;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
@@ -97,18 +103,13 @@ impl pallet_assets::Config<AssetsInstance> for Test {
type StringLimit = ConstU32<50>;
type WeightInfo = ();
}

impl crate::fungibles::Config for Test {
type AssetsInstance = AssetsInstance;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = ();
}

pub(crate) const ALICE: AccountId = 1;
pub(crate) const BOB: AccountId = 2;
pub(crate) const CHARLIE: AccountId = 3;
pub(crate) const INIT_AMOUNT: Balance = 100_000_000 * UNIT;
pub(crate) const UNIT: Balance = 10_000_000_000;

pub(crate) fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<Test>::default()
.build_storage()

Unchanged files with check annotations Beta

/// Sub-commands supported by the collator.
#[derive(Debug, clap::Subcommand)]
pub enum Subcommand {
/// Build a chain specification.
BuildSpec(sc_cli::BuildSpecCmd),
/// Validate blocks.
CheckBlock(sc_cli::CheckBlockCmd),
/// Export blocks.
ExportBlocks(sc_cli::ExportBlocksCmd),
/// Export the state of a given block into a chain spec.
ExportState(sc_cli::ExportStateCmd),
/// Import blocks.
ImportBlocks(sc_cli::ImportBlocksCmd),
/// Revert the chain to a previous state.
Revert(sc_cli::RevertCmd),
/// Remove the whole chain.
PurgeChain(cumulus_client_cli::PurgeChainCmd),
/// Export the genesis head data of the parachain.
///
/// Head data is the encoded block header.
#[command(alias = "export-genesis-state")]
ExportGenesisHead(cumulus_client_cli::ExportGenesisHeadCommand),
/// Export the genesis wasm of the parachain.
ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand),
/// Sub-commands concerned with benchmarking.
/// The pallet benchmarking moved to the `pallet` sub-command.
#[command(subcommand)]
Benchmark(frame_benchmarking_cli::BenchmarkCmd),
/// Key management CLI utilities
#[command(subcommand)]
Key(sc_cli::KeySubcommand),
}

Check warning on line 44 in node/src/cli.rs

GitHub Actions / clippy

large size difference between variants

warning: large size difference between variants --> node/src/cli.rs:5:1 | 5 | / pub enum Subcommand { 6 | | /// Build a chain specification. 7 | | BuildSpec(sc_cli::BuildSpecCmd), ... | 19 | | ImportBlocks(sc_cli::ImportBlocksCmd), | | ------------------------------------- the second-largest variant contains at least 240 bytes ... | 39 | | Benchmark(frame_benchmarking_cli::BenchmarkCmd), | | ----------------------------------------------- the largest variant contains at least 544 bytes ... | 43 | | Key(sc_cli::KeySubcommand), 44 | | } | |_^ the entire enum is at least 544 bytes | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#large_enum_variant = note: `#[warn(clippy::large_enum_variant)]` on by default help: consider boxing the large fields to reduce the total size of the enum | 39 | Benchmark(Box<frame_benchmarking_cli::BenchmarkCmd>), | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const AFTER_HELP_EXAMPLE: &str = color_print::cstr!(
r#"<bold><underline>Examples:</></>
}
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {

Check warning on line 179 in runtime/testnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/testnet/src/lib.rs:179:1 | 179 | pub const VERSION: RuntimeVersion = RuntimeVersion { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
spec_name: create_runtime_str!("pop"),
impl_name: create_runtime_str!("pop"),
authoring_version: 1,
type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
}
#[frame_support::runtime]

Check warning on line 554 in runtime/testnet/src/lib.rs

GitHub Actions / clippy

missing documentation for an associated function

warning: missing documentation for an associated function --> runtime/testnet/src/lib.rs:554:1 | 554 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 554 in runtime/testnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a type alias

warning: missing documentation for a type alias --> runtime/testnet/src/lib.rs:554:1 | 554 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 554 in runtime/testnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a struct field

warning: missing documentation for a struct field --> runtime/testnet/src/lib.rs:554:1 | 554 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 554 in runtime/testnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a variant

warning: missing documentation for a variant --> runtime/testnet/src/lib.rs:554:1 | 554 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 554 in runtime/testnet/src/lib.rs

GitHub Actions / clippy

missing documentation for an enum

warning: missing documentation for an enum --> runtime/testnet/src/lib.rs:554:1 | 554 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 554 in runtime/testnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a struct

warning: missing documentation for a struct --> runtime/testnet/src/lib.rs:554:1 | 554 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)
mod runtime {
// Create the runtime by composing the FRAME pallets that were previously configured.
#[runtime::runtime]
);
}
impl_runtime_apis! {
impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
fn slot_duration() -> sp_consensus_aura::SlotDuration {
sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
}
fn authorities() -> Vec<AuraId> {
pallet_aura::Authorities::<Runtime>::get().into_inner()
}
}
impl sp_api::Core<Block> for Runtime {
fn version() -> RuntimeVersion {
VERSION
}
fn execute_block(block: Block) {
Executive::execute_block(block)
}
fn initialize_block(header: &<Block as BlockT>::Header) -> ExtrinsicInclusionMode{
Executive::initialize_block(header)
}
}
impl sp_api::Metadata<Block> for Runtime {
fn metadata() -> OpaqueMetadata {
OpaqueMetadata::new(Runtime::metadata().into())
}
fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
Runtime::metadata_at_version(version)
}
fn metadata_versions() -> sp_std::vec::Vec<u32> {
Runtime::metadata_versions()
}
}
impl sp_block_builder::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
Executive::apply_extrinsic(extrinsic)
}
fn finalize_block() -> <Block as BlockT>::Header {
Executive::finalize_block()
}
fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
data.create_extrinsics()
}
fn check_inherents(
block: Block,
data: sp_inherents::InherentData,
) -> sp_inherents::CheckInherentsResult {
data.check_extrinsics(&block)
}
}
impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
fn validate_transaction(
source: TransactionSource,
tx: <Block as BlockT>::Extrinsic,
block_hash: <Block as BlockT>::Hash,
) -> TransactionValidity {
Executive::validate_transaction(source, tx, block_hash)
}
}
impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
fn offchain_worker(header: &<Block as BlockT>::Header) {
Executive::offchain_worker(header)
}
}
impl sp_session::SessionKeys<Block> for Runtime {
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
SessionKeys::generate(seed)
}
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
SessionKeys::decode_into_raw_public_keys(&encoded)
}
}
impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
fn account_nonce(account: AccountId) -> Nonce {
System::account_nonce(account)
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
fn query_info(
uxt: <Block as BlockT>::Extrinsic,
len: u32,
) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
TransactionPayment::query_info(uxt, len)
}
fn query_fee_details(
uxt: <Block as BlockT>::Extrinsic,
len: u32,
) -> pallet_transaction_payment::FeeDetails<Balance> {
TransactionPayment::query_fee_details(uxt, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
for Runtime
{
fn query_call_info(
call: RuntimeCall,
len: u32,
) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
TransactionPayment::query_call_info(call, len)
}
fn query_call_fee_details(
call: RuntimeCall,
len: u32,
) -> pallet_transaction_payment::FeeDetails<Balance> {
TransactionPayment::query_call_fee_details(call, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
}
impl pallet_contracts::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash, EventRecord>
for Runtime
{
fn call(
origin: AccountId,
dest: AccountId,
value: Balance,
gas_limit: Option<Weight>,
storage_deposit_limit: Option<Balance>,
input_data: Vec<u8>,
) -> pallet_contracts::ContractExecResult<Balance, EventRecord> {
let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block);
Contracts::bare_call(
origin,
dest,
value,
gas_limit,
storage_deposit_limit,
input_data,
CONTRACTS_DEBUG_OUTPUT,
CONTRACTS_EVENTS,
pallet_contracts::Determinism::Enforced,
)
}
fn instantiate(
origin: AccountId,
value: Balance,
gas_limit: Option<Weight>,
storage_deposit_limit: Option<Balance>,
code: pallet_contracts::Code<Hash>,
data: Vec<u8>,
salt: Vec<u8>,
) -> pallet_contracts::ContractInstantiateResult<AccountId, Balance, EventRecord>
{
let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block);
Contracts::bare_instantiate(
origin,
value,
gas_limit,
storage_deposit_limit,
code,
data,
salt,
CONTRACTS_DEBUG_OUTPUT,
CONTRACTS_EVENTS,
)
}
fn upload_code(
origin: AccountId,
code: Vec<u8>,
storage_deposit_limit: Option<Balance>,
determinism: pallet_contracts::Determinism,
) -> pallet_contracts::CodeUploadResult<Hash, Balance>
{
Contracts::bare_upload_code(origin, code, storage_deposit_limit, determinism)
}
fn get_storage(
address: AccountId,
key: Vec<u8>,
) -> pallet_contracts::GetStorageResult {
Contracts::get_storage(address, key)
}
}
impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
fn can_build_upon(
included_hash: <Block as BlockT>::Hash,
slot: cumulus_primitives_aura::Slot,
) -> bool {
ConsensusHook::can_build_upon(included_hash, slot)
}
}
impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
ParachainSystem::collect_collation_info(header)
}
}
impl pallet_nfts_runtime_api::NftsApi<Block, AccountId, u32, u32> for Runtime {
fn owner(collection: u32, item: u32) -> Option<AccountId> {
<Nfts as Inspect<AccountId>>::owner(&collection, &item)
}
fn collection_owner(collection: u32) -> Option<AccountId> {
<Nfts as Inspect<AccountId>>::collection_owner(&collection)
}
fn attribute(
collection: u32,
item: u32,
key: Vec<u8>,
) -> Option<Vec<u8>> {
<Nfts as Inspect<AccountId>>::attribute(&collection, &item, &key)
}
fn custom_attribute(
account: AccountId,
collection: u32,
item: u32,
key: Vec<u8>,
) -> Option<Vec<u8>> {
<Nfts as Inspect<AccountId>>::custom_attribute(
&account,
&collection,
&item,
&key,
)
}
fn system_attribute(
collection: u32,
item: Option<u32>,
key: Vec<u8>,
) -> Option<Vec<u8>> {
<Nfts as Inspect<AccountId>>::system_attribute(&collection, item.as_ref(), &key)
}
fn collection_attribute(collection: u32, key: Vec<u8>) -> Option<Vec<u8>> {
<Nfts as Inspect<AccountId>>::collection_attribute(&collection, &key)
}
}
#[cfg(feature = "try-runtime")]
impl frame_try_runtime::TryRuntime<Block> for Runtime {
fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
let weight = Executive::try_runtime_upgrade(checks).unwrap();
(weight, RuntimeBlockWeights::get().max_block)
}
fn execute_block(
block: Block,
state_root_check: bool,
signature_check: bool,
select: frame_try_runtime::TryStateSelect,
) -> Weight {
// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
// have a backtrace here.
Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
}
}
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
Vec<frame_benchmarking::BenchmarkList>,
Vec<frame_support::traits::StorageInfo>,
) {
use frame_benchmarking::{Benchmarking, BenchmarkList};
use frame_support::traits::StorageInfoTrait;
use frame_system_benchmarking::Pallet as SystemBench;
use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
let mut list = Vec::<BenchmarkList>::new();
list_benchmarks!(list, extra);
let storage_info = AllPalletsWithSystem::storage_info();
(list, storage_info)
}
fn dispatch_benchmark(
config: frame_benchmarking::BenchmarkConfig
) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
use frame_benchmarking::{BenchmarkError, Benchmarking, BenchmarkBatch};
use frame_system_benchmarking::Pallet as SystemBench;
impl frame_system_benchmarking::Config for Runtime {
fn setup_set_code_requirements(code: &sp_std::vec::Vec<u8>) -> Result<(), BenchmarkError> {
ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
Ok(())
}
fn verify_set_code() {
System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
}
}
use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
impl cumulus_pallet_session_benchmarking::Config for Runtime {}
use frame_support::traits::WhitelistedStorageKeys;
let whitelist = AllPalletsWithSystem::whitelisted_storage_keys();
let mut batches = Vec::<BenchmarkBatch>::new();
let params = (&config, &whitelist);
add_benchmarks!(params, batches);
if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
Ok(batches)
}
}
impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
build_state::<RuntimeGenesisConfig>(config)
}
fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
get_preset::<RuntimeGenesisConfig>(id, |_| None)
}
fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
Default::default()
}
}
}

Check warning on line 1006 in runtime/testnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a function

warning: missing documentation for a function --> runtime/testnet/src/lib.rs:659:1 | 659 | / impl_runtime_apis! { 660 | | 661 | | impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { 662 | | fn slot_duration() -> sp_consensus_aura::SlotDuration { ... | 1005 | | } 1006 | | } | |_^ | = note: this warning originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 1006 in runtime/testnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a module

warning: missing documentation for a module --> runtime/testnet/src/lib.rs:659:1 | 659 | / impl_runtime_apis! { 660 | | 661 | | impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { 662 | | fn slot_duration() -> sp_consensus_aura::SlotDuration { ... | 1005 | | } 1006 | | } | |_^ | = note: this warning originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 1006 in runtime/testnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/testnet/src/lib.rs:659:1 | 659 | / impl_runtime_apis! { 660 | | 661 | | impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { 662 | | fn slot_duration() -> sp_consensus_aura::SlotDuration { ... | 1005 | | } 1006 | | } | |_^ | = note: this warning originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 1006 in runtime/testnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a struct

warning: missing documentation for a struct --> runtime/testnet/src/lib.rs:659:1 | 659 | / impl_runtime_apis! { 660 | | 661 | | impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { 662 | | fn slot_duration() -> sp_consensus_aura::SlotDuration { ... | 1005 | | } 1006 | | } | |_^ | = note: this warning originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)
cumulus_pallet_parachain_system::register_validate_block! {
Runtime = Runtime,
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
pub mod config;

Check warning on line 9 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a module

warning: missing documentation for a module --> runtime/mainnet/src/lib.rs:9:1 | 9 | pub mod config; | ^^^^^^^^^^^^^^
mod weights;
use config::xcm::{RelayLocation, XcmOriginToTransactDispatchOrigin};
Migrations,
>;
pub const fn deposit(items: u32, bytes: u32) -> Balance {

Check warning on line 116 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a function

warning: missing documentation for a function --> runtime/mainnet/src/lib.rs:116:1 | 116 | pub const fn deposit(items: u32, bytes: u32) -> Balance { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// src: https://github.com/polkadot-fellows/runtimes/blob/main/system-parachains/constants/src/polkadot.rs#L70
(items as Balance * 20 * UNIT + (bytes as Balance) * 100 * fee::MILLICENTS) / 100
}
use smallvec::smallvec;
pub use sp_runtime::Perbill;
pub const CENTS: Balance = MILLIUNIT * 10; // 100_000_000

Check warning on line 135 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/mainnet/src/lib.rs:135:2 | 135 | pub const CENTS: Balance = MILLIUNIT * 10; // 100_000_000 | ^^^^^^^^^^^^^^^^^^^^^^^^
pub const MILLICENTS: Balance = CENTS / 1_000; // 100_000

Check warning on line 136 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/mainnet/src/lib.rs:136:2 | 136 | pub const MILLICENTS: Balance = CENTS / 1_000; // 100_000 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/// Cost of every transaction byte at Polkadot system parachains.
///
}
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {

Check warning on line 235 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/mainnet/src/lib.rs:235:1 | 235 | pub const VERSION: RuntimeVersion = RuntimeVersion { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
spec_name: create_runtime_str!("pop"),
impl_name: create_runtime_str!("pop"),
authoring_version: 1,
type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
}
#[frame_support::runtime]

Check warning on line 587 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for an associated function

warning: missing documentation for an associated function --> runtime/mainnet/src/lib.rs:587:1 | 587 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 587 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a type alias

warning: missing documentation for a type alias --> runtime/mainnet/src/lib.rs:587:1 | 587 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 587 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a struct field

warning: missing documentation for a struct field --> runtime/mainnet/src/lib.rs:587:1 | 587 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 587 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a variant

warning: missing documentation for a variant --> runtime/mainnet/src/lib.rs:587:1 | 587 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 587 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for an enum

warning: missing documentation for an enum --> runtime/mainnet/src/lib.rs:587:1 | 587 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 587 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a struct

warning: missing documentation for a struct --> runtime/mainnet/src/lib.rs:587:1 | 587 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)
mod runtime {
// Create the runtime by composing the FRAME pallets that were previously configured.
#[runtime::runtime]
);
}
impl_runtime_apis! {
impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
fn slot_duration() -> sp_consensus_aura::SlotDuration {
sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
}
fn authorities() -> Vec<AuraId> {
pallet_aura::Authorities::<Runtime>::get().into_inner()
}
}
impl sp_api::Core<Block> for Runtime {
fn version() -> RuntimeVersion {
VERSION
}
fn execute_block(block: Block) {
Executive::execute_block(block)
}
fn initialize_block(header: &<Block as BlockT>::Header) -> ExtrinsicInclusionMode{
Executive::initialize_block(header)
}
}
impl sp_api::Metadata<Block> for Runtime {
fn metadata() -> OpaqueMetadata {
OpaqueMetadata::new(Runtime::metadata().into())
}
fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
Runtime::metadata_at_version(version)
}
fn metadata_versions() -> sp_std::vec::Vec<u32> {
Runtime::metadata_versions()
}
}
impl sp_block_builder::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
Executive::apply_extrinsic(extrinsic)
}
fn finalize_block() -> <Block as BlockT>::Header {
Executive::finalize_block()
}
fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
data.create_extrinsics()
}
fn check_inherents(
block: Block,
data: sp_inherents::InherentData,
) -> sp_inherents::CheckInherentsResult {
data.check_extrinsics(&block)
}
}
impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
fn validate_transaction(
source: TransactionSource,
tx: <Block as BlockT>::Extrinsic,
block_hash: <Block as BlockT>::Hash,
) -> TransactionValidity {
Executive::validate_transaction(source, tx, block_hash)
}
}
impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
fn offchain_worker(header: &<Block as BlockT>::Header) {
Executive::offchain_worker(header)
}
}
impl sp_session::SessionKeys<Block> for Runtime {
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
SessionKeys::generate(seed)
}
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
SessionKeys::decode_into_raw_public_keys(&encoded)
}
}
impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
fn account_nonce(account: AccountId) -> Nonce {
System::account_nonce(account)
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
fn query_info(
uxt: <Block as BlockT>::Extrinsic,
len: u32,
) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
TransactionPayment::query_info(uxt, len)
}
fn query_fee_details(
uxt: <Block as BlockT>::Extrinsic,
len: u32,
) -> pallet_transaction_payment::FeeDetails<Balance> {
TransactionPayment::query_fee_details(uxt, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
for Runtime
{
fn query_call_info(
call: RuntimeCall,
len: u32,
) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
TransactionPayment::query_call_info(call, len)
}
fn query_call_fee_details(
call: RuntimeCall,
len: u32,
) -> pallet_transaction_payment::FeeDetails<Balance> {
TransactionPayment::query_call_fee_details(call, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
}
impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
fn can_build_upon(
included_hash: <Block as BlockT>::Hash,
slot: cumulus_primitives_aura::Slot,
) -> bool {
ConsensusHook::can_build_upon(included_hash, slot)
}
}
impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
ParachainSystem::collect_collation_info(header)
}
}
#[cfg(feature = "try-runtime")]
impl frame_try_runtime::TryRuntime<Block> for Runtime {
fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
let weight = Executive::try_runtime_upgrade(checks).unwrap();
(weight, RuntimeBlockWeights::get().max_block)
}
fn execute_block(
block: Block,
state_root_check: bool,
signature_check: bool,
select: frame_try_runtime::TryStateSelect,
) -> Weight {
// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
// have a backtrace here.
Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
}
}
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
Vec<frame_benchmarking::BenchmarkList>,
Vec<frame_support::traits::StorageInfo>,
) {
use frame_benchmarking::{Benchmarking, BenchmarkList};
use frame_support::traits::StorageInfoTrait;
use frame_system_benchmarking::Pallet as SystemBench;
use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
let mut list = Vec::<BenchmarkList>::new();
list_benchmarks!(list, extra);
let storage_info = AllPalletsWithSystem::storage_info();
(list, storage_info)
}
fn dispatch_benchmark(
config: frame_benchmarking::BenchmarkConfig
) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
use frame_benchmarking::{BenchmarkError, Benchmarking, BenchmarkBatch};
use frame_system_benchmarking::Pallet as SystemBench;
impl frame_system_benchmarking::Config for Runtime {
fn setup_set_code_requirements(code: &sp_std::vec::Vec<u8>) -> Result<(), BenchmarkError> {
ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
Ok(())
}
fn verify_set_code() {
System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
}
}
use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
impl cumulus_pallet_session_benchmarking::Config for Runtime {}
use frame_support::traits::WhitelistedStorageKeys;
let whitelist = AllPalletsWithSystem::whitelisted_storage_keys();
let mut batches = Vec::<BenchmarkBatch>::new();
let params = (&config, &whitelist);
add_benchmarks!(params, batches);
if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
Ok(batches)
}
}
impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
build_state::<RuntimeGenesisConfig>(config)
}
fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
get_preset::<RuntimeGenesisConfig>(id, |_| None)
}
fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
Default::default()
}
}
}

Check warning on line 916 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a function

warning: missing documentation for a function --> runtime/mainnet/src/lib.rs:680:1 | 680 | / impl_runtime_apis! { 681 | | 682 | | impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { 683 | | fn slot_duration() -> sp_consensus_aura::SlotDuration { ... | 915 | | } 916 | | } | |_^ | = note: this warning originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 916 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a module

warning: missing documentation for a module --> runtime/mainnet/src/lib.rs:680:1 | 680 | / impl_runtime_apis! { 681 | | 682 | | impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { 683 | | fn slot_duration() -> sp_consensus_aura::SlotDuration { ... | 915 | | } 916 | | } | |_^ | = note: this warning originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 916 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/mainnet/src/lib.rs:680:1 | 680 | / impl_runtime_apis! { 681 | | 682 | | impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { 683 | | fn slot_duration() -> sp_consensus_aura::SlotDuration { ... | 915 | | } 916 | | } | |_^ | = note: this warning originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 916 in runtime/mainnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a struct

warning: missing documentation for a struct --> runtime/mainnet/src/lib.rs:680:1 | 680 | / impl_runtime_apis! { 681 | | 682 | | impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { 683 | | fn slot_duration() -> sp_consensus_aura::SlotDuration { ... | 915 | | } 916 | | } | |_^ | = note: this warning originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)
cumulus_pallet_parachain_system::register_validate_block! {
Runtime = Runtime,
pub const MaxAssetsIntoHolding: u32 = 64;
}
pub type Barrier = TrailingSetTopicAsId<(

Check warning on line 93 in runtime/mainnet/src/config/xcm.rs

GitHub Actions / clippy

missing documentation for a type alias

warning: missing documentation for a type alias --> runtime/mainnet/src/config/xcm.rs:93:1 | 93 | pub type Barrier = TrailingSetTopicAsId<( | ^^^^^^^^^^^^^^^^
TakeWeightCredit,
AllowKnownQueryResponses<PolkadotXcm>,
WithComputedOrigin<
if *asset_loc == Location::from(Parent))
}
}
pub type TrustedReserves = (NativeAsset, NativeAssetFrom<AssetHub>);

Check warning on line 117 in runtime/mainnet/src/config/xcm.rs

GitHub Actions / clippy

missing documentation for a type alias

warning: missing documentation for a type alias --> runtime/mainnet/src/config/xcm.rs:117:1 | 117 | pub type TrustedReserves = (NativeAsset, NativeAssetFrom<AssetHub>); | ^^^^^^^^^^^^^^^^^^^^^^^^
/// Locations that will not be charged fees in the executor,
/// either execution or delivery.
/// We only waive fees for system functions, which these locations represent.
pub type WaivedLocations = (RelayOrOtherSystemParachains<AllSiblingSystemParachains, Runtime>,);
pub struct XcmConfig;

Check warning on line 124 in runtime/mainnet/src/config/xcm.rs

GitHub Actions / clippy

missing documentation for a struct

warning: missing documentation for a struct --> runtime/mainnet/src/config/xcm.rs:124:1 | 124 | pub struct XcmConfig; | ^^^^^^^^^^^^^^^^^^^^
impl xcm_executor::Config for XcmConfig {
type Aliasers = Nothing;
type AssetClaims = PolkadotXcm;
mod proxy;
pub mod xcm;

Check warning on line 2 in runtime/mainnet/src/config/mod.rs

GitHub Actions / clippy

missing documentation for a module

warning: missing documentation for a module --> runtime/mainnet/src/config/mod.rs:2:1 | 2 | pub mod xcm; | ^^^^^^^^^^^
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
// Public due to integration tests crate.
pub mod config;

Check warning on line 10 in runtime/devnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a module

warning: missing documentation for a module --> runtime/devnet/src/lib.rs:10:1 | 10 | pub mod config; | ^^^^^^^^^^^^^^
mod weights;
use config::xcm::{RelayLocation, XcmOriginToTransactDispatchOrigin};
}
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {

Check warning on line 172 in runtime/devnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/devnet/src/lib.rs:172:1 | 172 | pub const VERSION: RuntimeVersion = RuntimeVersion { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
spec_name: create_runtime_str!("pop"),
impl_name: create_runtime_str!("pop"),
authoring_version: 1,
type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
}
#[frame_support::runtime]

Check warning on line 534 in runtime/devnet/src/lib.rs

GitHub Actions / clippy

missing documentation for an associated function

warning: missing documentation for an associated function --> runtime/devnet/src/lib.rs:534:1 | 534 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 534 in runtime/devnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a type alias

warning: missing documentation for a type alias --> runtime/devnet/src/lib.rs:534:1 | 534 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 534 in runtime/devnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a struct field

warning: missing documentation for a struct field --> runtime/devnet/src/lib.rs:534:1 | 534 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 534 in runtime/devnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a variant

warning: missing documentation for a variant --> runtime/devnet/src/lib.rs:534:1 | 534 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 534 in runtime/devnet/src/lib.rs

GitHub Actions / clippy

missing documentation for an enum

warning: missing documentation for an enum --> runtime/devnet/src/lib.rs:534:1 | 534 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 534 in runtime/devnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a struct

warning: missing documentation for a struct --> runtime/devnet/src/lib.rs:534:1 | 534 | #[frame_support::runtime] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this warning originates in the attribute macro `frame_support::runtime` (in Nightly builds, run with -Z macro-backtrace for more info)
mod runtime {
// Create the runtime by composing the FRAME pallets that were previously configured.
#[runtime::runtime]
);
}
impl_runtime_apis! {
impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
fn slot_duration() -> sp_consensus_aura::SlotDuration {
sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)
}
fn authorities() -> Vec<AuraId> {
pallet_aura::Authorities::<Runtime>::get().into_inner()
}
}
impl sp_api::Core<Block> for Runtime {
fn version() -> RuntimeVersion {
VERSION
}
fn execute_block(block: Block) {
Executive::execute_block(block)
}
fn initialize_block(header: &<Block as BlockT>::Header) -> ExtrinsicInclusionMode {
Executive::initialize_block(header)
}
}
impl sp_api::Metadata<Block> for Runtime {
fn metadata() -> OpaqueMetadata {
OpaqueMetadata::new(Runtime::metadata().into())
}
fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
Runtime::metadata_at_version(version)
}
fn metadata_versions() -> Vec<u32> {
Runtime::metadata_versions()
}
}
impl sp_block_builder::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
Executive::apply_extrinsic(extrinsic)
}
fn finalize_block() -> <Block as BlockT>::Header {
Executive::finalize_block()
}
fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
data.create_extrinsics()
}
fn check_inherents(
block: Block,
data: sp_inherents::InherentData,
) -> sp_inherents::CheckInherentsResult {
data.check_extrinsics(&block)
}
}
impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
fn validate_transaction(
source: TransactionSource,
tx: <Block as BlockT>::Extrinsic,
block_hash: <Block as BlockT>::Hash,
) -> TransactionValidity {
Executive::validate_transaction(source, tx, block_hash)
}
}
impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
fn offchain_worker(header: &<Block as BlockT>::Header) {
Executive::offchain_worker(header)
}
}
impl sp_session::SessionKeys<Block> for Runtime {
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
SessionKeys::generate(seed)
}
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
SessionKeys::decode_into_raw_public_keys(&encoded)
}
}
impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
fn account_nonce(account: AccountId) -> Nonce {
System::account_nonce(account)
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
fn query_info(
uxt: <Block as BlockT>::Extrinsic,
len: u32,
) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
TransactionPayment::query_info(uxt, len)
}
fn query_fee_details(
uxt: <Block as BlockT>::Extrinsic,
len: u32,
) -> pallet_transaction_payment::FeeDetails<Balance> {
TransactionPayment::query_fee_details(uxt, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
for Runtime
{
fn query_call_info(
call: RuntimeCall,
len: u32,
) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
TransactionPayment::query_call_info(call, len)
}
fn query_call_fee_details(
call: RuntimeCall,
len: u32,
) -> pallet_transaction_payment::FeeDetails<Balance> {
TransactionPayment::query_call_fee_details(call, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
}
impl pallet_contracts::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash, EventRecord>
for Runtime
{
fn call(
origin: AccountId,
dest: AccountId,
value: Balance,
gas_limit: Option<Weight>,
storage_deposit_limit: Option<Balance>,
input_data: Vec<u8>,
) -> pallet_contracts::ContractExecResult<Balance, EventRecord> {
let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block);
Contracts::bare_call(
origin,
dest,
value,
gas_limit,
storage_deposit_limit,
input_data,
CONTRACTS_DEBUG_OUTPUT,
CONTRACTS_EVENTS,
pallet_contracts::Determinism::Enforced,
)
}
fn instantiate(
origin: AccountId,
value: Balance,
gas_limit: Option<Weight>,
storage_deposit_limit: Option<Balance>,
code: pallet_contracts::Code<Hash>,
data: Vec<u8>,
salt: Vec<u8>,
) -> pallet_contracts::ContractInstantiateResult<AccountId, Balance, EventRecord>
{
let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block);
Contracts::bare_instantiate(
origin,
value,
gas_limit,
storage_deposit_limit,
code,
data,
salt,
CONTRACTS_DEBUG_OUTPUT,
CONTRACTS_EVENTS,
)
}
fn upload_code(
origin: AccountId,
code: Vec<u8>,
storage_deposit_limit: Option<Balance>,
determinism: pallet_contracts::Determinism,
) -> pallet_contracts::CodeUploadResult<Hash, Balance>
{
Contracts::bare_upload_code(origin, code, storage_deposit_limit, determinism)
}
fn get_storage(
address: AccountId,
key: Vec<u8>,
) -> pallet_contracts::GetStorageResult {
Contracts::get_storage(address, key)
}
}
impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
fn can_build_upon(
included_hash: <Block as BlockT>::Hash,
slot: cumulus_primitives_aura::Slot,
) -> bool {
ConsensusHook::can_build_upon(included_hash, slot)
}
}
impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
ParachainSystem::collect_collation_info(header)
}
}
impl pallet_nfts_runtime_api::NftsApi<Block, AccountId, u32, u32> for Runtime {
fn owner(collection: u32, item: u32) -> Option<AccountId> {
<Nfts as Inspect<AccountId>>::owner(&collection, &item)
}
fn collection_owner(collection: u32) -> Option<AccountId> {
<Nfts as Inspect<AccountId>>::collection_owner(&collection)
}
fn attribute(
collection: u32,
item: u32,
key: Vec<u8>,
) -> Option<Vec<u8>> {
<Nfts as Inspect<AccountId>>::attribute(&collection, &item, &key)
}
fn custom_attribute(
account: AccountId,
collection: u32,
item: u32,
key: Vec<u8>,
) -> Option<Vec<u8>> {
<Nfts as Inspect<AccountId>>::custom_attribute(
&account,
&collection,
&item,
&key,
)
}
fn system_attribute(
collection: u32,
item: Option<u32>,
key: Vec<u8>,
) -> Option<Vec<u8>> {
<Nfts as Inspect<AccountId>>::system_attribute(&collection, item.as_ref(), &key)
}
fn collection_attribute(collection: u32, key: Vec<u8>) -> Option<Vec<u8>> {
<Nfts as Inspect<AccountId>>::collection_attribute(&collection, &key)
}
}
#[cfg(feature = "try-runtime")]
impl frame_try_runtime::TryRuntime<Block> for Runtime {
fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
let weight = Executive::try_runtime_upgrade(checks).unwrap();
(weight, RuntimeBlockWeights::get().max_block)
}
fn execute_block(
block: Block,
state_root_check: bool,
signature_check: bool,
select: frame_try_runtime::TryStateSelect,
) -> Weight {
// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
// have a backtrace here.
Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
}
}
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
Vec<frame_benchmarking::BenchmarkList>,
Vec<frame_support::traits::StorageInfo>,
) {
use frame_benchmarking::{Benchmarking, BenchmarkList};
use frame_support::traits::StorageInfoTrait;
use frame_system_benchmarking::Pallet as SystemBench;
use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
let mut list = Vec::<BenchmarkList>::new();
list_benchmarks!(list, extra);
let storage_info = AllPalletsWithSystem::storage_info();
(list, storage_info)
}
fn dispatch_benchmark(
config: frame_benchmarking::BenchmarkConfig
) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
use frame_benchmarking::{BenchmarkError, Benchmarking, BenchmarkBatch};
use frame_system_benchmarking::Pallet as SystemBench;
impl frame_system_benchmarking::Config for Runtime {
fn setup_set_code_requirements(code: &Vec<u8>) -> Result<(), BenchmarkError> {
ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
Ok(())
}
fn verify_set_code() {
System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
}
}
use cumulus_pallet_session_benchmarking::Pallet as SessionBench;
impl cumulus_pallet_session_benchmarking::Config for Runtime {}
use frame_support::traits::WhitelistedStorageKeys;
let whitelist = AllPalletsWithSystem::whitelisted_storage_keys();
let mut batches = Vec::<BenchmarkBatch>::new();
let params = (&config, &whitelist);
add_benchmarks!(params, batches);
if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
Ok(batches)
}
}
impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
build_state::<RuntimeGenesisConfig>(config)
}
fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
get_preset::<RuntimeGenesisConfig>(id, |_| None)
}
fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
Default::default()
}
}
}

Check warning on line 991 in runtime/devnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a function

warning: missing documentation for a function --> runtime/devnet/src/lib.rs:644:1 | 644 | / impl_runtime_apis! { 645 | | 646 | | impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { 647 | | fn slot_duration() -> sp_consensus_aura::SlotDuration { ... | 990 | | } 991 | | } | |_^ | = note: this warning originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 991 in runtime/devnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a module

warning: missing documentation for a module --> runtime/devnet/src/lib.rs:644:1 | 644 | / impl_runtime_apis! { 645 | | 646 | | impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { 647 | | fn slot_duration() -> sp_consensus_aura::SlotDuration { ... | 990 | | } 991 | | } | |_^ | = note: this warning originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 991 in runtime/devnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/devnet/src/lib.rs:644:1 | 644 | / impl_runtime_apis! { 645 | | 646 | | impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { 647 | | fn slot_duration() -> sp_consensus_aura::SlotDuration { ... | 990 | | } 991 | | } | |_^ | = note: this warning originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)

Check warning on line 991 in runtime/devnet/src/lib.rs

GitHub Actions / clippy

missing documentation for a struct

warning: missing documentation for a struct --> runtime/devnet/src/lib.rs:644:1 | 644 | / impl_runtime_apis! { 645 | | 646 | | impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { 647 | | fn slot_duration() -> sp_consensus_aura::SlotDuration { ... | 990 | | } 991 | | } | |_^ | = note: this warning originates in the macro `impl_runtime_apis` (in Nightly builds, run with -Z macro-backtrace for more info)
cumulus_pallet_parachain_system::register_validate_block! {
Runtime = Runtime,
pub const MaxAssetsIntoHolding: u32 = 64;
}
pub struct ParentOrParentsExecutivePlurality;

Check warning on line 94 in runtime/devnet/src/config/xcm.rs

GitHub Actions / clippy

missing documentation for a struct

warning: missing documentation for a struct --> runtime/devnet/src/config/xcm.rs:94:1 | 94 | pub struct ParentOrParentsExecutivePlurality; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
impl Contains<Location> for ParentOrParentsExecutivePlurality {
fn contains(location: &Location) -> bool {
matches!(location.unpack(), (1, []) | (1, [Plurality { id: BodyId::Executive, .. }]))
}
}
pub type Barrier = TrailingSetTopicAsId<(

Check warning on line 101 in runtime/devnet/src/config/xcm.rs

GitHub Actions / clippy

missing documentation for a type alias

warning: missing documentation for a type alias --> runtime/devnet/src/config/xcm.rs:101:1 | 101 | pub type Barrier = TrailingSetTopicAsId<( | ^^^^^^^^^^^^^^^^
TakeWeightCredit,
AllowKnownQueryResponses<PolkadotXcm>,
WithComputedOrigin<
if *asset_loc == Location::from(Parent))
}
}
pub type TrustedReserves = (NativeAsset, NativeAssetFrom<AssetHub>);

Check warning on line 126 in runtime/devnet/src/config/xcm.rs

GitHub Actions / clippy

missing documentation for a type alias

warning: missing documentation for a type alias --> runtime/devnet/src/config/xcm.rs:126:1 | 126 | pub type TrustedReserves = (NativeAsset, NativeAssetFrom<AssetHub>); | ^^^^^^^^^^^^^^^^^^^^^^^^
pub struct XcmConfig;

Check warning on line 128 in runtime/devnet/src/config/xcm.rs

GitHub Actions / clippy

missing documentation for a struct

warning: missing documentation for a struct --> runtime/devnet/src/config/xcm.rs:128:1 | 128 | pub struct XcmConfig; | ^^^^^^^^^^^^^^^^^^^^
impl xcm_executor::Config for XcmConfig {
type Aliasers = Nothing;
type AssetClaims = PolkadotXcm;
type WeightInfo = pallet_nft_fractionalization::weights::SubstrateWeight<Self>;
}
pub type TrustBackedAssetsInstance = pallet_assets::Instance1;

Check warning on line 99 in runtime/devnet/src/config/assets.rs

GitHub Actions / clippy

missing documentation for a type alias

warning: missing documentation for a type alias --> runtime/devnet/src/config/assets.rs:99:1 | 99 | pub type TrustBackedAssetsInstance = pallet_assets::Instance1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pub type TrustBackedAssetsCall = pallet_assets::Call<Runtime, TrustBackedAssetsInstance>;

Check warning on line 100 in runtime/devnet/src/config/assets.rs

GitHub Actions / clippy

missing documentation for a type alias

warning: missing documentation for a type alias --> runtime/devnet/src/config/assets.rs:100:1 | 100 | pub type TrustBackedAssetsCall = pallet_assets::Call<Runtime, TrustBackedAssetsInstance>; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
impl pallet_assets::Config<TrustBackedAssetsInstance> for Runtime {
type ApprovalDeposit = ApprovalDeposit;
type AssetAccountDeposit = AssetAccountDeposit;
mod api;
// Public due to pop api integration tests crate.
pub mod assets;

Check warning on line 3 in runtime/devnet/src/config/mod.rs

GitHub Actions / clippy

missing documentation for a module

warning: missing documentation for a module --> runtime/devnet/src/config/mod.rs:3:1 | 3 | pub mod assets; | ^^^^^^^^^^^^^^
mod contracts;
mod proxy;
// Public due to integration tests crate.
pub mod xcm;

Check warning on line 7 in runtime/devnet/src/config/mod.rs

GitHub Actions / clippy

missing documentation for a module

warning: missing documentation for a module --> runtime/devnet/src/config/mod.rs:7:1 | 7 | pub mod xcm; | ^^^^^^^^^^^
#[cfg(all(feature = "std", feature = "metadata-hash"))]
fn main() {
substrate_wasm_builder::WasmBuilder::init_with_defaults()
.enable_metadata_hash("PAS", 10)
.build()
}
#[cfg(all(feature = "std", not(feature = "metadata-hash")))]
fn main() {
substrate_wasm_builder::WasmBuilder::build_using_defaults()
}
/// The wasm builder is deactivated when compiling
/// this crate for wasm to speed up the compilation.
#[cfg(not(feature = "std"))]
fn main() {}

Check warning on line 16 in runtime/devnet/build.rs

GitHub Actions / clippy

missing documentation for the crate

warning: missing documentation for the crate --> runtime/devnet/build.rs:1:1 | 1 | / #[cfg(all(feature = "std", feature = "metadata-hash"))] 2 | | fn main() { 3 | | substrate_wasm_builder::WasmBuilder::init_with_defaults() 4 | | .enable_metadata_hash("PAS", 10) ... | 15 | | #[cfg(not(feature = "std"))] 16 | | fn main() {} | |____________^ | = note: requested on the command line with `-W missing-docs`
#[cfg(all(feature = "std", feature = "metadata-hash"))]
fn main() {
substrate_wasm_builder::WasmBuilder::init_with_defaults()
.enable_metadata_hash("DOT", 10)
.build()
}
#[cfg(all(feature = "std", not(feature = "metadata-hash")))]
fn main() {
substrate_wasm_builder::WasmBuilder::build_using_defaults()
}
/// The wasm builder is deactivated when compiling
/// this crate for wasm to speed up the compilation.
#[cfg(not(feature = "std"))]
fn main() {}

Check warning on line 16 in runtime/mainnet/build.rs

GitHub Actions / clippy

missing documentation for the crate

warning: missing documentation for the crate --> runtime/mainnet/build.rs:1:1 | 1 | / #[cfg(all(feature = "std", feature = "metadata-hash"))] 2 | | fn main() { 3 | | substrate_wasm_builder::WasmBuilder::init_with_defaults() 4 | | .enable_metadata_hash("DOT", 10) ... | 15 | | #[cfg(not(feature = "std"))] 16 | | fn main() {} | |____________^ | = note: requested on the command line with `-W missing-docs`
#[cfg(all(feature = "std", feature = "metadata-hash"))]
fn main() {
substrate_wasm_builder::WasmBuilder::init_with_defaults()
.enable_metadata_hash("PAS", 10)
.build()
}
#[cfg(all(feature = "std", not(feature = "metadata-hash")))]
fn main() {
substrate_wasm_builder::WasmBuilder::build_using_defaults()
}
/// The wasm builder is deactivated when compiling
/// this crate for wasm to speed up the compilation.
#[cfg(not(feature = "std"))]
fn main() {}

Check warning on line 16 in runtime/devnet/build.rs

GitHub Actions / clippy

missing documentation for the crate

warning: missing documentation for the crate --> runtime/devnet/build.rs:1:1 | 1 | / #[cfg(all(feature = "std", feature = "metadata-hash"))] 2 | | fn main() { 3 | | substrate_wasm_builder::WasmBuilder::init_with_defaults() 4 | | .enable_metadata_hash("PAS", 10) ... | 15 | | #[cfg(not(feature = "std"))] 16 | | fn main() {} | |____________^ | = note: requested on the command line with `-W missing-docs`
#![cfg(test)]
use asset_hub_paseo_runtime::xcm_config::XcmConfig as AssetHubPaseoXcmConfig;
use asset_test_utils::xcm_helpers;
use chains::{asset_hub_paseo::AssetHubPaseo, paseo::Paseo, pop_network::PopNetwork};
use emulated_integration_tests_common::{
accounts::{ALICE, BOB},
xcm_emulator::{
assert_expected_events, bx, decl_test_networks,
decl_test_sender_receiver_accounts_parameter_types, Chain, Parachain as Para,
RelayChain as Relay, Test, TestArgs, TestContext, TestExt,
},
};
use frame_support::{pallet_prelude::Weight, sp_runtime::DispatchResult};
use paseo_runtime::xcm_config::XcmConfig as PaseoXcmConfig;
use pop_runtime_common::Balance;
use pop_runtime_devnet::config::xcm::XcmConfig as PopNetworkXcmConfig;
use xcm::prelude::*;
use crate::chains::{
asset_hub_paseo::{genesis::ED as ASSET_HUB_PASEO_ED, AssetHubPaseoParaPallet},
paseo::{genesis::ED as PASEO_ED, PaseoRelayPallet},
pop_network::PopNetworkParaPallet,
};
mod chains;
decl_test_networks! {
// `pub` mandatory for the macro
pub struct PaseoMockNet {
relay_chain = Paseo,
parachains = vec![
AssetHubPaseo,
PopNetwork,
],
bridge = ()
},
}
decl_test_sender_receiver_accounts_parameter_types! {
PaseoRelay { sender: ALICE, receiver: BOB },
AssetHubPaseoPara { sender: ALICE, receiver: BOB },
PopNetworkPara { sender: ALICE, receiver: BOB}
}
type RelayToParaTest = Test<PaseoRelay, PopNetworkPara>;
type SystemParaToParaTest = Test<AssetHubPaseoPara, PopNetworkPara>;
type ParaToSystemParaTest = Test<PopNetworkPara, AssetHubPaseoPara>;
type ParaToRelayTest = Test<PopNetworkPara, PaseoRelay>;
fn relay_to_para_sender_assertions(t: RelayToParaTest) {
type RuntimeEvent = <PaseoRelay as Chain>::RuntimeEvent;
PaseoRelay::assert_xcm_pallet_attempted_complete(Some(Weight::from_parts(864_610_000, 8_799)));
assert_expected_events!(
PaseoRelay,
vec![
// Amount to reserve transfer is transferred to Parachain's Sovereign account
RuntimeEvent::Balances(
pallet_balances::Event::Transfer { from, to, amount }
) => {
from: *from == t.sender.account_id,
to: *to == PaseoRelay::sovereign_account_id_of(
t.args.dest.clone()
),
amount: *amount == t.args.amount,
},
]
);
}
fn system_para_to_para_sender_assertions(t: SystemParaToParaTest) {
type RuntimeEvent = <AssetHubPaseoPara as Chain>::RuntimeEvent;
AssetHubPaseoPara::assert_xcm_pallet_attempted_complete(Some(Weight::from_parts(
864_610_000,
8_799,
)));
assert_expected_events!(
AssetHubPaseoPara,
vec![
// Amount to reserve transfer is transferred to Parachain's Sovereign account
RuntimeEvent::Balances(
pallet_balances::Event::Transfer { from, to, amount }
) => {
from: *from == t.sender.account_id,
to: *to == AssetHubPaseoPara::sovereign_account_id_of(
t.args.dest.clone()
),
amount: *amount == t.args.amount,
},
]
);
}
fn para_receiver_assertions<Test>(_: Test) {
type RuntimeEvent = <PopNetworkPara as Chain>::RuntimeEvent;
assert_expected_events!(
PopNetworkPara,
vec![
RuntimeEvent::Balances(pallet_balances::Event::Minted { .. }) => {},
RuntimeEvent::MessageQueue(
pallet_message_queue::Event::Processed { success: true, .. }
) => {},
]
);
}
fn para_to_system_para_sender_assertions(t: ParaToSystemParaTest) {
type RuntimeEvent = <PopNetworkPara as Chain>::RuntimeEvent;
PopNetworkPara::assert_xcm_pallet_attempted_complete(Some(Weight::from_parts(
864_610_000,
8_799,
)));
assert_expected_events!(
PopNetworkPara,
vec![
// Amount to reserve transfer is transferred to Parachain's Sovereign account
RuntimeEvent::Balances(pallet_balances::Event::Burned { who, amount }) => {
who: *who == t.sender.account_id,
amount: *amount == t.args.amount,
},
]
);
}
fn para_to_relay_sender_assertions(t: ParaToRelayTest) {
type RuntimeEvent = <PopNetworkPara as Chain>::RuntimeEvent;
PopNetworkPara::assert_xcm_pallet_attempted_complete(Some(Weight::from_parts(
864_610_000,
8_799,
)));
assert_expected_events!(
PopNetworkPara,
vec![
// Amount to reserve transfer is transferred to Parachain's Sovereign account
RuntimeEvent::Balances(pallet_balances::Event::Burned { who, amount }) => {
who: *who == t.sender.account_id,
amount: *amount == t.args.amount,
},
]
);
}
fn para_to_system_para_receiver_assertions(t: ParaToSystemParaTest) {
type RuntimeEvent = <AssetHubPaseoPara as Chain>::RuntimeEvent;
let sov_pop_net_on_ahr = AssetHubPaseoPara::sovereign_account_id_of(
AssetHubPaseoPara::sibling_location_of(PopNetworkPara::para_id()),
);
assert_expected_events!(
AssetHubPaseoPara,
vec![
// Amount to reserve transfer is withdrawn from Parachain's Sovereign account
RuntimeEvent::Balances(
pallet_balances::Event::Burned { who, amount }
) => {
who: *who == sov_pop_net_on_ahr.clone().into(),
amount: *amount == t.args.amount,
},
RuntimeEvent::Balances(pallet_balances::Event::Minted { .. }) => {},
RuntimeEvent::MessageQueue(
pallet_message_queue::Event::Processed { success: true, .. }
) => {},
]
);
}
fn para_to_relay_receiver_assertions(t: ParaToRelayTest) {
type RuntimeEvent = <PaseoRelay as Chain>::RuntimeEvent;
let sov_pop_net_on_relay = PaseoRelay::sovereign_account_id_of(PaseoRelay::child_location_of(
PopNetworkPara::para_id(),
));
assert_expected_events!(
PaseoRelay,
vec![
// Amount to reserve transfer is withdrawn from Parachain's Sovereign account
RuntimeEvent::Balances(
pallet_balances::Event::Burned { who, amount }
) => {
who: *who == sov_pop_net_on_relay.clone().into(),
amount: *amount == t.args.amount,
},
RuntimeEvent::Balances(pallet_balances::Event::Minted { .. }) => {},
RuntimeEvent::MessageQueue(
pallet_message_queue::Event::Processed { success: true, .. }
) => {},
]
);
}
fn relay_to_para_reserve_transfer_assets(t: RelayToParaTest) -> DispatchResult {
<PaseoRelay as PaseoRelayPallet>::XcmPallet::limited_reserve_transfer_assets(
t.signed_origin,
bx!(t.args.dest.into()),
bx!(t.args.beneficiary.into()),
bx!(t.args.assets.into()),
t.args.fee_asset_item,
t.args.weight_limit,
)
}
fn system_para_to_para_reserve_transfer_assets(t: SystemParaToParaTest) -> DispatchResult {
<AssetHubPaseoPara as AssetHubPaseoParaPallet>::PolkadotXcm::limited_reserve_transfer_assets(
t.signed_origin,
bx!(t.args.dest.into()),
bx!(t.args.beneficiary.into()),
bx!(t.args.assets.into()),
t.args.fee_asset_item,
t.args.weight_limit,
)
}
fn para_to_system_para_reserve_transfer_assets(t: ParaToSystemParaTest) -> DispatchResult {
<PopNetworkPara as PopNetworkParaPallet>::PolkadotXcm::limited_reserve_transfer_assets(
t.signed_origin,
bx!(t.args.dest.into()),
bx!(t.args.beneficiary.into()),
bx!(t.args.assets.into()),
t.args.fee_asset_item,
t.args.weight_limit,
)
}
fn para_to_relay_reserve_transfer_assets(t: ParaToRelayTest) -> DispatchResult {
<PopNetworkPara as PopNetworkParaPallet>::PolkadotXcm::limited_reserve_transfer_assets(
t.signed_origin,
bx!(t.args.dest.into()),
bx!(t.args.beneficiary.into()),
bx!(t.args.assets.into()),
t.args.fee_asset_item,
t.args.weight_limit,
)
}
// Funds Pop with relay tokens
fn fund_pop_from_relay(
sender: sp_runtime::AccountId32,
amount_to_send: Balance,
beneficiary: sp_runtime::AccountId32,
) {
let destination = PaseoRelay::child_location_of(PopNetworkPara::para_id());
let test_args = TestContext {
sender,
receiver: beneficiary.clone(),
args: TestArgs::new_relay(destination, beneficiary, amount_to_send),
};
let mut test = RelayToParaTest::new(test_args);
test.set_dispatchable::<PaseoRelay>(relay_to_para_reserve_transfer_assets);
test.assert();
}
// Funds Pop with relay tokens from system para
fn fund_pop_from_system_para(
sender: sp_runtime::AccountId32,
amount_to_send: Balance,
beneficiary: sp_runtime::AccountId32,
assets: Assets,
) {
let destination = AssetHubPaseoPara::sibling_location_of(PopNetworkPara::para_id());
let test_args = TestContext {
sender,
receiver: beneficiary.clone(),
args: TestArgs::new_para(destination, beneficiary, amount_to_send, assets, None, 0),
};
let mut test = SystemParaToParaTest::new(test_args);
test.set_dispatchable::<AssetHubPaseoPara>(system_para_to_para_reserve_transfer_assets);
test.assert();
}
/// Reserve Transfers of native asset from Relay to Parachain should work
#[test]
fn reserve_transfer_native_asset_from_relay_to_para() {
init_tracing();
// Init values for Relay
let destination = PaseoRelay::child_location_of(PopNetworkPara::para_id());
let beneficiary_id = PopNetworkParaReceiver::get();
let amount_to_send: Balance = PASEO_ED * 1000;
let test_args = TestContext {
sender: PaseoRelaySender::get(),
receiver: PopNetworkParaReceiver::get(),
args: TestArgs::new_relay(destination, beneficiary_id, amount_to_send),
};
let mut test = RelayToParaTest::new(test_args);
let sender_balance_before = test.sender.balance;
let receiver_balance_before = test.receiver.balance;
test.set_assertion::<PaseoRelay>(relay_to_para_sender_assertions);
test.set_assertion::<PopNetworkPara>(para_receiver_assertions);
test.set_dispatchable::<PaseoRelay>(relay_to_para_reserve_transfer_assets);
test.assert();
let delivery_fees = PaseoRelay::execute_with(|| {
xcm_helpers::teleport_assets_delivery_fees::<
<PaseoXcmConfig as xcm_executor::Config>::XcmSender,
>(
test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest
)
});
let sender_balance_after = test.sender.balance;
let receiver_balance_after = test.receiver.balance;
// Sender's balance is reduced
assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after);
// Receiver's balance is increased
assert!(receiver_balance_after > receiver_balance_before);
// Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`;
// `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown
// but should be non-zero
assert!(receiver_balance_after < receiver_balance_before + amount_to_send);
}
/// Reserve Transfers of native asset from Parachain to Relay should work
#[test]
fn reserve_transfer_native_asset_from_para_to_relay() {
init_tracing();
// Setup: reserve transfer from relay to Pop, so that sovereign account accurate for return
// transfer
let amount_to_send: Balance = PASEO_ED * 1_000;
fund_pop_from_relay(PaseoRelaySender::get(), amount_to_send, PopNetworkParaReceiver::get()); // alice on relay > bob on pop
// Init values for Pop Network Parachain
let destination = PopNetworkPara::parent_location(); // relay
let beneficiary_id = PaseoRelayReceiver::get(); // bob on relay
let amount_to_send = PopNetworkPara::account_data_of(PopNetworkParaReceiver::get()).free; // bob on pop balance
let assets = (Parent, amount_to_send).into();
let test_args = TestContext {
sender: PopNetworkParaReceiver::get(), // bob on pop
receiver: PaseoRelayReceiver::get(), // bob on relay
args: TestArgs::new_para(destination, beneficiary_id, amount_to_send, assets, None, 0),
};
let mut test = ParaToRelayTest::new(test_args);
let sender_balance_before = test.sender.balance;
let receiver_balance_before = test.receiver.balance;
test.set_assertion::<PopNetworkPara>(para_to_relay_sender_assertions);
test.set_assertion::<PaseoRelay>(para_to_relay_receiver_assertions);
test.set_dispatchable::<PopNetworkPara>(para_to_relay_reserve_transfer_assets);
test.assert();
let sender_balance_after = test.sender.balance;
let receiver_balance_after = test.receiver.balance;
let delivery_fees = PopNetworkPara::execute_with(|| {
xcm_helpers::teleport_assets_delivery_fees::<
<PopNetworkXcmConfig as xcm_executor::Config>::XcmSender,
>(
test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest
)
});
// Sender's balance is reduced
assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after);
// Receiver's balance is increased
assert!(receiver_balance_after > receiver_balance_before);
// Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`;
// `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown
// but should be non-zero
assert!(receiver_balance_after < receiver_balance_before + amount_to_send);
}
/// Reserve Transfers of native asset from System Parachain to Parachain should work
#[test]
fn reserve_transfer_native_asset_from_system_para_to_para() {
init_tracing();
// Init values for System Parachain
let destination = AssetHubPaseoPara::sibling_location_of(PopNetworkPara::para_id());
let beneficiary_id = PopNetworkParaReceiver::get();
let amount_to_send: Balance = ASSET_HUB_PASEO_ED * 1000;
let assets = (Parent, amount_to_send).into();
let test_args = TestContext {
sender: AssetHubPaseoParaSender::get(),
receiver: PopNetworkParaReceiver::get(),
args: TestArgs::new_para(destination, beneficiary_id, amount_to_send, assets, None, 0),
};
let mut test = SystemParaToParaTest::new(test_args);
let sender_balance_before = test.sender.balance;
let receiver_balance_before = test.receiver.balance;
test.set_assertion::<AssetHubPaseoPara>(system_para_to_para_sender_assertions);
test.set_assertion::<PopNetworkPara>(para_receiver_assertions);
test.set_dispatchable::<AssetHubPaseoPara>(system_para_to_para_reserve_transfer_assets);
test.assert();
let sender_balance_after = test.sender.balance;
let receiver_balance_after = test.receiver.balance;
let delivery_fees = AssetHubPaseoPara::execute_with(|| {
xcm_helpers::teleport_assets_delivery_fees::<
<AssetHubPaseoXcmConfig as xcm_executor::Config>::XcmSender,
>(
test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest
)
});
// Sender's balance is reduced
assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after);
// Receiver's balance is increased
assert!(receiver_balance_after > receiver_balance_before);
// Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`;
// `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown
// but should be non-zero
assert!(receiver_balance_after < receiver_balance_before + amount_to_send);
}
/// Reserve Transfers of native asset from Parachain to System Parachain should work
#[test]
fn reserve_transfer_native_asset_from_para_to_system_para() {
init_tracing();
// Setup: reserve transfer from AH to Pop, so that sovereign account accurate for return
// transfer
let amount_to_send: Balance = ASSET_HUB_PASEO_ED * 1000;
fund_pop_from_system_para(
AssetHubPaseoParaSender::get(),
amount_to_send,
PopNetworkParaReceiver::get(),
(Parent, amount_to_send).into(),
); // alice on asset hub > bob on pop
// Init values for Pop Network Parachain
let destination = PopNetworkPara::sibling_location_of(AssetHubPaseoPara::para_id());
let beneficiary_id = AssetHubPaseoParaReceiver::get(); // bob on asset hub
let amount_to_send = PopNetworkPara::account_data_of(PopNetworkParaReceiver::get()).free; // bob on pop balance
let assets = (Parent, amount_to_send).into();
let test_args = TestContext {
sender: PopNetworkParaReceiver::get(), // bob on pop
receiver: AssetHubPaseoParaReceiver::get(), // bob on asset hub
args: TestArgs::new_para(destination, beneficiary_id, amount_to_send, assets, None, 0),
};
let mut test = ParaToSystemParaTest::new(test_args);
let sender_balance_before = test.sender.balance;
let receiver_balance_before = test.receiver.balance;
let pop_net_location_as_seen_by_ahr =
AssetHubPaseoPara::sibling_location_of(PopNetworkPara::para_id());
let sov_pop_net_on_ahr =
AssetHubPaseoPara::sovereign_account_id_of(pop_net_location_as_seen_by_ahr);
// fund Pop Network's SA on AHR with the native tokens held in reserve
AssetHubPaseoPara::fund_accounts(vec![(sov_pop_net_on_ahr.into(), amount_to_send * 2)]);
test.set_assertion::<PopNetworkPara>(para_to_system_para_sender_assertions);
test.set_assertion::<AssetHubPaseoPara>(para_to_system_para_receiver_assertions);
test.set_dispatchable::<PopNetworkPara>(para_to_system_para_reserve_transfer_assets);
test.assert();
let sender_balance_after = test.sender.balance;
let receiver_balance_after = test.receiver.balance;
let delivery_fees = PopNetworkPara::execute_with(|| {
xcm_helpers::teleport_assets_delivery_fees::<
<PopNetworkXcmConfig as xcm_executor::Config>::XcmSender,
>(
test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest
)
});
// Sender's balance is reduced
assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after);
// Receiver's balance is increased
assert!(receiver_balance_after > receiver_balance_before);
// Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`;
// `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown
// but should be non-zero
assert!(receiver_balance_after < receiver_balance_before + amount_to_send);
}
// Note: commented out until coretime added to Paseo
// #[test]
// fn place_coretime_spot_order_from_para_to_relay() {
// init_tracing();
//
// let beneficiary: sp_runtime::AccountId32 = [1u8; 32].into();
//
// // Setup: reserve transfer from relay to Pop, so that sovereign account accurate for return
// transfer let amount_to_send: Balance = pop_runtime::UNIT * 1000;
// fund_pop_from_relay(PaseoRelaySender::get(), amount_to_send, beneficiary.clone());
//
// let message = {
// let assets: Asset = (Here, 10 * pop_runtime::UNIT).into();
// let beneficiary = AccountId32 { id: beneficiary.clone().into(), network: None }.into();
// let spot_order = <PaseoRelay as Chain>::RuntimeCall::OnDemandAssignmentProvider(
// assigner_on_demand::Call::<<PaseoRelay as Chain>::Runtime>::place_order_keep_alive {
// max_amount: 1 * pop_runtime::UNIT,
// para_id: AssetHubPaseoPara::para_id().into(),
// },
// );
//
// // Set up transact status response handler
// let query_id = PopNetworkPara::execute_with(|| {
// <PopNetwork<PaseoMockNet> as PopNetworkParaPallet>::PolkadotXcm::new_query(
// PopNetworkPara::parent_location(),
// // timeout in blocks
// 10u32.into(),
// Location::here(),
// )
// });
//
// let message = Xcm::builder()
// .withdraw_asset(assets.clone().into())
// .buy_execution(assets.clone().into(), Unlimited)
// .transact(
// OriginKind::SovereignAccount,
// Weight::from_parts(220_000_000, 15_000),
// spot_order.encode().into(),
// )
// .report_transact_status(QueryResponseInfo {
// destination: PaseoRelay::child_location_of(PopNetworkPara::para_id()),
// query_id,
// max_weight: Weight::from_parts(250_000_000, 10_000),
// })
// .refund_surplus()
// .deposit_asset(assets.into(), beneficiary)
// .build();
// message
// };
//
// let destination = PopNetworkPara::parent_location().into_versioned();
// PopNetworkPara::execute_with(|| {
// let res = <PopNetworkPara as Chain>::RuntimeCall::PolkadotXcm(pallet_xcm::Call::<
// <PopNetworkPara as Chain>::Runtime,
// >::send {
// dest: bx!(destination),
// message: bx!(VersionedXcm::V4(message)),
// })
// // TODO: replace root with signed, currently prohibited by HashedDescription<AccountId, DescribeFamily<DescribeBodyTerminal>> (https://github.com/paritytech/polkadot-sdk/blob/a6713c55fd5082d333518c3ca13f2a4294726fcc/polkadot/runtime/rococo/src/xcm_config.rs#L67) rather than HashedDescription<AccountId, DescribeFamily<DescribeAllTerminal>> (https://github.com/polkadot-fellows/runtimes/blob/e42821da8d85f721d0dd1670dfb23f4dd91bd3e8/relay/kusama/src/xcm_config.rs#L76)
// //.dispatch(RawOrigin::Signed(beneficiary).into());
// .dispatch(RawOrigin::Root.into());
//
// assert!(res.is_ok());
// type RuntimeEvent = <PopNetworkPara as Chain>::RuntimeEvent;
// // Check that the message was sent
// assert_expected_events!(
// PopNetworkPara,
// vec![
// RuntimeEvent::PolkadotXcm(pallet_xcm::Event::Sent { .. }) => {},
// ]
// );
// });
//
// PaseoRelay::execute_with(|| {
// type RuntimeEvent = <PaseoRelay as Chain>::RuntimeEvent;
// assert_expected_events!(
// PaseoRelay,
// vec![
// // We currently only check that the message was processed successfully
// RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { success: true, .. }) =>
// {}, // TODO: check order placed once we can have on-demand para id registered (probably via
// setting raw storage as a workaround) //
// RuntimeEvent::OnDemandAssignmentProvider(assigner_on_demand::Event::OnDemandOrderPlaced { //
// .. // }) => {},
// ]
// );
// });
//
// PopNetworkPara::execute_with(|| {
// type RuntimeEvent = <PopNetworkPara as Chain>::RuntimeEvent;
// // Check that the reporting of the transact status message was sent
// assert_expected_events!(
// PopNetworkPara,
// vec![
// RuntimeEvent::PolkadotXcm(pallet_xcm::Event::ResponseReady { query_id: 0, .. }) => {},
// RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { success: true, .. }) =>
// {}, ]
// );
// });
// }
#[allow(dead_code)]
static INIT: std::sync::Once = std::sync::Once::new();
// Used during debugging by calling this function as first statement in test
#[allow(dead_code)]
fn init_tracing() {
INIT.call_once(|| {
// Add test tracing (from sp_tracing::init_for_tests()) but filtering for xcm logs only
let _ = tracing_subscriber::fmt()
.with_max_level(tracing_subscriber::filter::LevelFilter::TRACE)
.with_env_filter("xcm=trace,system::events=trace,evm=trace") // Comment out this line to see all traces
.with_test_writer()
.init();
});
}

Check warning on line 598 in integration-tests/src/lib.rs

GitHub Actions / clippy

missing documentation for the crate

warning: missing documentation for the crate --> integration-tests/src/lib.rs:1:1 | 1 | / #![cfg(test)] 2 | | 3 | | use asset_hub_paseo_runtime::xcm_config::XcmConfig as AssetHubPaseoXcmConfig; 4 | | use asset_test_utils::xcm_helpers; ... | 597 | | }); 598 | | } | |_^ | = note: requested on the command line with `-W missing-docs`
use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
fn main() {
generate_cargo_keys();
rerun_if_git_head_changed();
}

Check warning on line 7 in node/build.rs

GitHub Actions / clippy

missing documentation for the crate

warning: missing documentation for the crate --> node/build.rs:1:1 | 1 | / use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; 2 | | 3 | | fn main() { 4 | | generate_cargo_keys(); 5 | | 6 | | rerun_if_git_head_changed(); 7 | | } | |_^ | = note: requested on the command line with `-W missing-docs`
#![cfg_attr(not(feature = "std"), no_std)]
pub use extension::Extension;
use frame_support::pallet_prelude::Weight;
pub mod extension;

Check warning on line 6 in pallets/api/src/lib.rs

GitHub Actions / clippy

missing documentation for a module

warning: missing documentation for a module --> pallets/api/src/lib.rs:6:1 | 6 | pub mod extension; | ^^^^^^^^^^^^^^^^^
pub mod fungibles;
#[cfg(test)]
mod mock;
/// Trait for performing reads of runtime state.
pub trait Read {
/// The type of read requested.
type Read;
/// The type or result returned.
type Result;
/// Determines the weight of the requested read, used to charge the appropriate weight before
/// the read is performed.
///
/// # Parameters
/// - `request` - The read request.
fn weight(read: &Self::Read) -> Weight;
/// Performs the requested read and returns the result.
///
/// # Parameters
/// - `request` - The read request.
fn read(request: Self::Read) -> Self::Result;
}

Check warning on line 30 in pallets/api/src/lib.rs

GitHub Actions / clippy

missing documentation for the crate

warning: missing documentation for the crate --> pallets/api/src/lib.rs:1:1 | 1 | / #![cfg_attr(not(feature = "std"), no_std)] 2 | | 3 | | pub use extension::Extension; 4 | | use frame_support::pallet_prelude::Weight; ... | 29 | | fn read(request: Self::Read) -> Self::Result; 30 | | } | |_^ | = note: requested on the command line with `-W missing-docs`
#![cfg_attr(not(feature = "std"), no_std)]
use core::marker::PhantomData;
pub use decoding::{Decode, Decodes, DecodingFailed, Identity, Processor};
pub use environment::{BufIn, BufOut, Environment, Ext};
use frame_support::{
dispatch::{GetDispatchInfo, PostDispatchInfo, RawOrigin},
ensure,
traits::{Contains, OriginTrait},
weights::Weight,
};
pub use functions::{
Converter, DefaultConverter, DispatchCall, ErrorConverter, Function, ReadState, Readable,
};
pub use matching::{Equals, FunctionId, Matches};
pub use pallet_contracts::chain_extension::{Result, RetVal, State};
use pallet_contracts::{
chain_extension::{ChainExtension, InitState, RetVal::Converging},
WeightInfo,
};
use sp_core::Get;
use sp_runtime::{traits::Dispatchable, DispatchError};
use sp_std::vec::Vec;
mod decoding;
mod environment;
mod functions;
mod matching;
// Mock runtime/environment for unit/integration testing.
#[cfg(test)]
mod mock;
// Integration tests using proxy contract and mock runtime.
#[cfg(test)]
mod tests;
type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
pub type ContractWeightsOf<T> = <T as pallet_contracts::Config>::WeightInfo;

Check warning on line 38 in extension/src/lib.rs

GitHub Actions / clippy

missing documentation for a type alias

warning: missing documentation for a type alias --> extension/src/lib.rs:38:1 | 38 | pub type ContractWeightsOf<T> = <T as pallet_contracts::Config>::WeightInfo; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
type RuntimeCallOf<T> = <T as frame_system::Config>::RuntimeCall;
/// A configurable chain extension.
#[derive(Default)]
pub struct Extension<C: Config>(PhantomData<C>);
impl<Runtime, Config> ChainExtension<Runtime> for Extension<Config>
where
Runtime: pallet_contracts::Config
+ frame_system::Config<
RuntimeCall: GetDispatchInfo + Dispatchable<PostInfo = PostDispatchInfo>,
>,
Config: self::Config<Functions: Function<Config = Runtime>> + 'static,
{
/// Call the chain extension logic.
///
/// # Parameters
/// - `env`: Access to the remaining arguments and the execution environment.
fn call<E: pallet_contracts::chain_extension::Ext<T = Runtime>>(
&mut self,
env: pallet_contracts::chain_extension::Environment<E, InitState>,
) -> Result<RetVal> {
let mut env = environment::Env(env.buf_in_buf_out());
self.call(&mut env)
}
}
impl<
Runtime: pallet_contracts::Config,
Config: self::Config<Functions: Function<Config = Runtime>>,
> Extension<Config>
{
fn call(
&mut self,
env: &mut (impl Environment<AccountId = Runtime::AccountId> + BufIn + BufOut),
) -> Result<RetVal> {
log::trace!(target: Config::LOG_TARGET, "extension called");
// Charge weight for making a call from a contract to the runtime.
// `debug_message` weight is a good approximation of the additional overhead of going from
// contract layer to substrate layer. reference: https://github.com/paritytech/polkadot-sdk/pull/4233/files#:~:text=DebugMessage(len)%20%3D%3E%20T%3A%3AWeightInfo%3A%3Aseal_debug_message(len)%2C
let len = env.in_len();
let overhead = ContractWeightsOf::<Runtime>::seal_debug_message(len);
let charged = env.charge_weight(overhead)?;
log::debug!(target: Config::LOG_TARGET, "extension call weight charged: len={len}, weight={overhead}, charged={charged:?}");
// Execute the function
Config::Functions::execute(env)
}
}
/// Trait for configuration of the chain extension.
pub trait Config {
/// The function(s) available with the chain extension.
type Functions: Function;
/// The log target.
const LOG_TARGET: &'static str;
}
/// Trait to enable specification of a log target.
pub trait LogTarget {
/// The log target.
const LOG_TARGET: &'static str;
}
impl LogTarget for () {
const LOG_TARGET: &'static str = "pop-chain-extension";
}
#[test]
fn default_log_target_works() {
assert!(matches!(<() as LogTarget>::LOG_TARGET, "pop-chain-extension"));
}
#[cfg(test)]
mod extension {
use codec::Encode;
use frame_system::Call;
use super::*;
use crate::mock::{
new_test_ext, DispatchExtFuncId, MockEnvironment, NoopFuncId, ReadExtFuncId, RuntimeCall,
RuntimeRead, Test, INVALID_FUNC_ID,
};
#[test]
fn call_works() {
let input = vec![2, 2];
let mut env = MockEnvironment::new(NoopFuncId::get(), input.clone());
let mut extension = Extension::<mock::Config>::default();
assert!(matches!(extension.call(&mut env), Ok(Converging(0))));
// Charges weight.
assert_eq!(env.charged(), overhead_weight(input.len() as u32))
}
#[test]
fn calling_unknown_function_fails() {
let input = vec![2, 2];
// No function registered for id 0.
let mut env = MockEnvironment::new(INVALID_FUNC_ID, input.clone());
let mut extension = Extension::<mock::Config>::default();
assert!(matches!(
extension.call(&mut env),
Err(error) if error == pallet_contracts::Error::<Test>::DecodingFailed.into()
));
// Charges weight.
assert_eq!(env.charged(), overhead_weight(input.len() as u32))
}
#[test]
fn dispatch_call_works() {
new_test_ext().execute_with(|| {
let call =
RuntimeCall::System(Call::remark_with_event { remark: "pop".as_bytes().to_vec() });
let encoded_call = call.encode();
let mut env = MockEnvironment::new(DispatchExtFuncId::get(), encoded_call.clone());
let mut extension = Extension::<mock::Config>::default();
assert!(matches!(extension.call(&mut env), Ok(Converging(0))));
// Charges weight.
assert_eq!(
env.charged(),
overhead_weight(encoded_call.len() as u32) +
read_from_buffer_weight(encoded_call.len() as u32) +
call.get_dispatch_info().weight
);
});
}
#[test]
fn dispatch_call_with_invalid_input_returns_error() {
// Invalid encoded runtime call.
let input = vec![0u8, 99];
let mut env = MockEnvironment::new(DispatchExtFuncId::get(), input.clone());
let mut extension = Extension::<mock::Config>::default();
assert!(extension.call(&mut env).is_err());
// Charges weight.
assert_eq!(
env.charged(),
overhead_weight(input.len() as u32) + read_from_buffer_weight(input.len() as u32)
);
}
#[test]
fn read_state_works() {
let read = RuntimeRead::Ping;
let encoded_read = read.encode();
let expected = "pop".as_bytes().encode();
let mut env = MockEnvironment::new(ReadExtFuncId::get(), encoded_read.clone());
let mut extension = Extension::<mock::Config>::default();
assert!(matches!(extension.call(&mut env), Ok(Converging(0))));
// Charges weight.
assert_eq!(
env.charged(),
overhead_weight(encoded_read.len() as u32) +
read_from_buffer_weight(encoded_read.len() as u32) +
read.weight() +
write_to_contract_weight(expected.len() as u32)
);
// Check if the contract environment buffer is written correctly.
assert_eq!(env.buffer, expected);
}
#[test]
fn read_state_with_invalid_input_returns_error() {
let input = vec![0u8, 99];
let mut env = MockEnvironment::new(
ReadExtFuncId::get(),
// Invalid runtime state read.
input.clone(),
);
let mut extension = Extension::<mock::Config>::default();
assert!(extension.call(&mut env).is_err());
// Charges weight.
assert_eq!(
env.charged(),
overhead_weight(input.len() as u32) + read_from_buffer_weight(input.len() as u32)
);
}
// Weight charged for calling into the runtime from a contract.
fn overhead_weight(input_len: u32) -> Weight {
ContractWeightsOf::<Test>::seal_debug_message(input_len)
}
// Weight charged for reading function call input from buffer.
pub(crate) fn read_from_buffer_weight(input_len: u32) -> Weight {
ContractWeightsOf::<Test>::seal_return(input_len)
}
// Weight charged for writing to contract memory.
pub(crate) fn write_to_contract_weight(len: u32) -> Weight {
ContractWeightsOf::<Test>::seal_input(len)
}
}

Check warning on line 230 in extension/src/lib.rs

GitHub Actions / clippy

missing documentation for the crate

warning: missing documentation for the crate --> extension/src/lib.rs:1:1 | 1 | / #![cfg_attr(not(feature = "std"), no_std)] 2 | | 3 | | use core::marker::PhantomData; ... | 229 | | } 230 | | } | |_^ | = note: requested on the command line with `-W missing-docs`
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight};
// Cumulus types re-export
// These types are shared between the devnet and testnet runtimes
pub use parachains_common::{AccountId, AuraId, Balance, Block, BlockNumber, Hash, Signature};
pub use polkadot_primitives::MAX_POV_SIZE;
use sp_runtime::Perbill;
/// Nonce for an account
pub type Nonce = u32;
/// This determines the average expected block time that we are targeting.
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
/// up by `pallet_aura` to implement `fn slot_duration()`.
///
/// Change this to adjust the block time.
pub const MILLISECS_PER_BLOCK: u64 = 6000;
// NOTE: Currently it is not possible to change the slot duration after the chain has started.
// Attempting to do so will brick block production.
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;

Check warning on line 22 in runtime/common/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/common/src/lib.rs:22:1 | 22 | pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/// Relay chain slot duration, in milliseconds.
// Value is 6000 millisecs. If `MILLISECS_PER_BLOCK` changes this needs addressing.
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
// Time is measured by number of blocks.
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);

Check warning on line 29 in runtime/common/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/common/src/lib.rs:29:1 | 29 | pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pub const HOURS: BlockNumber = MINUTES * 60;

Check warning on line 30 in runtime/common/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/common/src/lib.rs:30:1 | 30 | pub const HOURS: BlockNumber = MINUTES * 60; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pub const DAYS: BlockNumber = HOURS * 24;

Check warning on line 31 in runtime/common/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/common/src/lib.rs:31:1 | 31 | pub const DAYS: BlockNumber = HOURS * 24; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
/// We assume that ~5% of the block weight is consumed by `on_initialize` handlers. This is
/// used to limit the maximal weight of a single extrinsic.
pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5);
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
/// `Operational` extrinsics.
pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
/// We allow for 2 seconds of compute with a 6-second average block.
pub const MAXIMUM_BLOCK_WEIGHT: Weight =
Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), MAX_POV_SIZE as u64);
// Unit = the base number of indivisible units for balances
pub const UNIT: Balance = 10_000_000_000; // 10 decimals

Check warning on line 46 in runtime/common/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/common/src/lib.rs:46:1 | 46 | pub const UNIT: Balance = 10_000_000_000; // 10 decimals | ^^^^^^^^^^^^^^^^^^^^^^^
pub const MILLIUNIT: Balance = UNIT / 1_000; // 10_000_000

Check warning on line 48 in runtime/common/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/common/src/lib.rs:48:1 | 48 | pub const MILLIUNIT: Balance = UNIT / 1_000; // 10_000_000 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pub const MICROUNIT: Balance = UNIT / 1_000_000; // 10_000

Check warning on line 49 in runtime/common/src/lib.rs

GitHub Actions / clippy

missing documentation for a constant

warning: missing documentation for a constant --> runtime/common/src/lib.rs:49:1 | 49 | pub const MICROUNIT: Balance = UNIT / 1_000_000; // 10_000 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Deposits
pub const fn deposit(items: u32, bytes: u32) -> Balance {

Check warning on line 52 in runtime/common/src/lib.rs

GitHub Actions / clippy

missing documentation for a function

warning: missing documentation for a function --> runtime/common/src/lib.rs:52:1 | 52 | pub const fn deposit(items: u32, bytes: u32) -> Balance { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(items as Balance * UNIT + (bytes as Balance) * (5 * MILLIUNIT / 100)) / 10
}
/// The existential deposit. Set to 1/1_000 of the Connected Relay Chain.
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
// Async backing
/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
/// into the relay chain.
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
/// How many parachain blocks are processed by the relay chain per parent. Limits the
/// number of blocks authored per slot.
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
/// Proxy commons for Pop runtimes
pub mod proxy {
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::parameter_types;
use sp_runtime::RuntimeDebug;
use super::{deposit, Balance};
parameter_types! {
// One storage item; key size 32, value size 8; .
pub const ProxyDepositBase: Balance = deposit(1, 40);
// Additional storage item size of 33 bytes.
pub const ProxyDepositFactor: Balance = deposit(0, 33);
pub const MaxProxies: u16 = 32;
// One storage item; key size 32, value size 16
pub const AnnouncementDepositBase: Balance = deposit(1, 48);
pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
pub const MaxPending: u16 = 32;
}
/// The type used to represent the kinds of proxying allowed.
#[derive(
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Encode,
Decode,
RuntimeDebug,
MaxEncodedLen,
scale_info::TypeInfo,
)]
pub enum ProxyType {
/// Fully permissioned proxy. Can execute any call on behalf of _proxied_.
Any,
/// Can execute any call that does not transfer funds or assets.
NonTransfer,
/// Proxy with the ability to reject time-delay proxy announcements.
CancelProxy,
/// Assets proxy. Can execute any call from `assets`, **including asset transfers**.
Assets,
/// Owner proxy. Can execute calls related to asset ownership.
AssetOwner,
/// Asset manager. Can execute calls related to asset management.
AssetManager,
/// Collator selection proxy. Can execute calls related to collator selection mechanism.
Collator,
}
impl Default for ProxyType {
fn default() -> Self {
Self::Any
}
}
impl ProxyType {
pub fn is_superset(s: &ProxyType, o: &ProxyType) -> bool {

Check warning on line 125 in runtime/common/src/lib.rs

GitHub Actions / clippy

missing documentation for an associated function

warning: missing documentation for an associated function --> runtime/common/src/lib.rs:125:3 | 125 | pub fn is_superset(s: &ProxyType, o: &ProxyType) -> bool { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
match (s, o) {
(x, y) if x == y => true,
(ProxyType::Any, _) => true,
(_, ProxyType::Any) => false,
(ProxyType::Assets, ProxyType::AssetOwner) => true,
(ProxyType::Assets, ProxyType::AssetManager) => true,
(ProxyType::NonTransfer, ProxyType::Collator) => true,
_ => false,
}
}
}
}

Check warning on line 137 in runtime/common/src/lib.rs

GitHub Actions / clippy

missing documentation for the crate

warning: missing documentation for the crate --> runtime/common/src/lib.rs:1:1 | 1 | / #![cfg_attr(not(feature = "std"), no_std)] 2 | | use frame_support::weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}; 3 | | // Cumulus types re-export 4 | | // These types are shared between the devnet and testnet runtimes ... | 136 | | } 137 | | } | |_^ | = note: requested on the command line with `-W missing-docs`