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

refactor: remove duplicate chain extensions #161

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
21 changes: 21 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 13 additions & 9 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,19 @@ members = [
"primitives",
"scripts/fund-dev-accounts",
]
exclude = [
"pop-api",
"tests/contracts"
]
exclude = ["pop-api", "tests/contracts"]

resolver = "2"

[workspace.dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [
"derive",
] }
hex-literal = "0.4.1"
log = { version = "0.4.20", default-features = false }
scale-info = { version = "2.10.0", default-features = false, features = ["derive"] }
scale-info = { version = "2.10.0", default-features = false, features = [
"derive",
] }
smallvec = "1.11.0"
serde = "1.0.195"
clap = { version = "4.4.18", features = ["derive"] }
Expand All @@ -53,9 +54,10 @@ substrate-build-script-utils = "11.0.0"

# Local
pallet-api = { path = "pallets/api", default-features = false }
pop-runtime-devnet = { path = "runtime/devnet", default-features = true } # default-features=true required for `-p pop-node` builds
pop-runtime-testnet = { path = "runtime/testnet", default-features = true } # default-features=true required for `-p pop-node` builds
pop-runtime-devnet = { path = "runtime/devnet", default-features = true } # default-features=true required for `-p pop-node` builds
pop-runtime-testnet = { path = "runtime/testnet", default-features = true } # default-features=true required for `-p pop-node` builds
pop-runtime-common = { path = "runtime/common", default-features = false }
pop-runtime-extensions = { path = "runtime/extensions", default-features = false }
pop-primitives = { path = "./primitives", default-features = false }

# Substrate
Expand Down Expand Up @@ -143,7 +145,9 @@ xcm-executor = { version = "8.0.2", package = "staging-xcm-executor", default-fe
asset-hub-rococo-runtime = { version = "0.12.3", default-features = false }
asset-test-utils = { version = "8.0.1", default-features = false }
cumulus-pallet-aura-ext = { version = "0.8.0", default-features = false }
cumulus-pallet-parachain-system = { version = "0.8.1", default-features = false, features = ["parameterized-consensus-hook"] }
cumulus-pallet-parachain-system = { version = "0.8.1", default-features = false, features = [
"parameterized-consensus-hook",
] }
cumulus-pallet-session-benchmarking = { version = "10.0.0", default-features = false }
cumulus-pallet-xcm = { version = "0.8.0", default-features = false }
cumulus-pallet-xcmp-queue = { version = "0.8.0", default-features = false }
Expand Down
3 changes: 3 additions & 0 deletions runtime/devnet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ smallvec.workspace = true
# Local
pop-primitives.workspace = true
pop-runtime-common.workspace = true
pop-runtime-extensions.workspace = true
pallet-api.workspace = true

# Substrate
Expand Down Expand Up @@ -140,6 +141,8 @@ std = [
"polkadot-parachain-primitives/std",
"polkadot-runtime-common/std",
"pop-primitives/std",
"pop-runtime-extensions/std",
"pop-runtime-extensions/pop-devnet",
"scale-info/std",
"sp-api/std",
"sp-io/std",
Expand Down
56 changes: 5 additions & 51 deletions runtime/devnet/src/config/api.rs
Original file line number Diff line number Diff line change
@@ -1,54 +1,8 @@
use crate::{config::assets::TrustBackedAssetsInstance, fungibles, Runtime, RuntimeCall};
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::traits::Contains;

/// A query of runtime state.
#[derive(Encode, Decode, Debug, MaxEncodedLen)]
#[repr(u8)]
pub enum RuntimeRead<T: fungibles::Config> {
/// Fungible token queries.
#[codec(index = 150)]
Fungibles(fungibles::Read<T>),
}

/// A type to identify allowed calls to the Runtime from the API.
pub struct AllowedApiCalls;

impl Contains<RuntimeCall> for AllowedApiCalls {
/// Allowed runtime calls from the API.
fn contains(c: &RuntimeCall) -> bool {
use fungibles::Call::*;
matches!(
c,
RuntimeCall::Fungibles(
transfer { .. }
| transfer_from { .. }
| approve { .. } | increase_allowance { .. }
| decrease_allowance { .. }
| create { .. } | set_metadata { .. }
| start_destroy { .. }
| clear_metadata { .. }
| mint { .. } | burn { .. }
)
)
}
}

impl<T: fungibles::Config> Contains<RuntimeRead<T>> for AllowedApiCalls {
/// Allowed state queries from the API.
fn contains(c: &RuntimeRead<T>) -> bool {
use fungibles::Read::*;
matches!(
c,
RuntimeRead::Fungibles(
TotalSupply(..)
| BalanceOf { .. } | Allowance { .. }
| TokenName(..) | TokenSymbol(..)
| TokenDecimals(..) | AssetExists(..)
)
)
}
}
use crate::{
config::assets::TrustBackedAssetsInstance,
fungibles::{self},
Runtime,
};

impl fungibles::Config for Runtime {
type AssetsInstance = TrustBackedAssetsInstance;
Expand Down
6 changes: 3 additions & 3 deletions runtime/devnet/src/config/contracts.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
deposit, extensions, Balance, Balances, BalancesCall, Perbill, Runtime, RuntimeCall,
RuntimeEvent, RuntimeHoldReason, Timestamp,
deposit, Balance, Balances, BalancesCall, Perbill, Runtime, RuntimeCall, RuntimeEvent,
RuntimeHoldReason, Timestamp,
};
use frame_support::{
parameter_types,
Expand Down Expand Up @@ -63,7 +63,7 @@ impl pallet_contracts::Config for Runtime {
type CallStack = [pallet_contracts::Frame<Self>; 23];
type WeightPrice = pallet_transaction_payment::Pallet<Self>;
type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
type ChainExtension = extensions::PopApiExtension;
type ChainExtension = pop_runtime_extensions::PopApiExtension;
type Schedule = Schedule;
type AddressGenerator = pallet_contracts::DefaultAddressGenerator;
// This node is geared towards development and testing of contracts.
Expand Down
142 changes: 142 additions & 0 deletions runtime/devnet/src/config/extension.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
use crate::{
config::assets::TrustBackedAssetsInstance,
fungibles::{self},
Runtime, RuntimeCall,
};
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::traits::OriginTrait;
use frame_support::{ensure, traits::Contains};
use frame_system::RawOrigin;
use pallet_contracts::chain_extension::{BufInBufOutState, Environment, Ext};
use pop_runtime_extensions::{
constants::{DECODING_FAILED_ERROR, LOG_TARGET, UNKNOWN_CALL_ERROR},
dispatch_call, DispatchCallParamsHandler, PopApiExtensionConfig, ReadStateParamsHandler,
};
use sp_core::Get;
use sp_runtime::DispatchError;

/// A query of runtime state.
#[derive(Encode, Decode, Debug, MaxEncodedLen)]
#[repr(u8)]
pub enum RuntimeRead<T: fungibles::Config> {
/// Fungible token queries.
#[codec(index = 150)]
Fungibles(fungibles::Read<T>),
}

/// A type to identify allowed calls to the Runtime from the API.
pub struct AllowedApiCalls;

impl Contains<RuntimeCall> for AllowedApiCalls {
/// Allowed runtime calls from the API.
fn contains(c: &RuntimeCall) -> bool {
use fungibles::Call::*;
matches!(
c,
RuntimeCall::Fungibles(
transfer { .. }
| transfer_from { .. }
| approve { .. } | increase_allowance { .. }
| decrease_allowance { .. }
)
)
}
}

impl<T: fungibles::Config> Contains<RuntimeRead<T>> for AllowedApiCalls {
/// Allowed state queries from the API.
fn contains(c: &RuntimeRead<T>) -> bool {
use fungibles::Read::*;
matches!(
c,
RuntimeRead::Fungibles(
TotalSupply(..)
| BalanceOf { .. } | Allowance { .. }
| TokenName(..) | TokenSymbol(..)
| TokenDecimals(..)
)
)
}
}

/// Wrapper to enable versioning of runtime state reads.
#[derive(Decode, Debug)]
enum VersionedStateRead<T: fungibles::Config> {
/// Version zero of state reads.
#[codec(index = 0)]
V0(RuntimeRead<T>),
}

/// Wrapper to enable versioning of runtime calls.
#[derive(Decode, Debug)]
enum VersionedDispatch<T: PopApiExtensionConfig> {
/// Version zero of dispatch calls.
#[codec(index = 0)]
V0(T::RuntimeCall),
}

pub struct ChainExtensionEnvironment;

impl DispatchCallParamsHandler for ChainExtensionEnvironment {
fn handle_params<T, E>(
env: &mut Environment<E, BufInBufOutState>,
params: Vec<u8>,
) -> Result<(), DispatchError>
where
E: Ext<T = T>,
T: PopApiExtensionConfig,
{
const LOG_PREFIX: &str = " dispatch |";

let call =
<VersionedDispatch<T>>::decode(&mut &params[..]).map_err(|_| DECODING_FAILED_ERROR)?;

// Contract is the origin by default.
let mut origin: T::RuntimeOrigin = RawOrigin::Signed(env.ext().address().clone()).into();
match call {
VersionedDispatch::V0(call) => {
origin.add_filter(T::AllowedDispatchCalls::contains);
dispatch_call::<T, E>(env, call, origin, LOG_PREFIX)
},
}
}
}

impl ReadStateParamsHandler for ChainExtensionEnvironment {
fn handle_params<T, E>(
env: &mut Environment<E, BufInBufOutState>,
params: Vec<u8>,
) -> Result<(), DispatchError>
where
E: Ext<T = T>,
T: PopApiExtensionConfig,
{
const LOG_PREFIX: &str = " read_state |";

let read =
<VersionedStateRead<T>>::decode(&mut &params[..]).map_err(|_| DECODING_FAILED_ERROR)?;

// Charge weight for doing one storage read.
env.charge_weight(T::DbWeight::get().reads(1_u64))?;
let result = match read {
VersionedStateRead::V0(read) => {
ensure!(AllowedApiCalls::contains(&read), UNKNOWN_CALL_ERROR);
match read {
RuntimeRead::Fungibles(key) => fungibles::Pallet::<T>::read_state(key),
}
},
};
log::trace!(
target:LOG_TARGET,
"{} result: {:?}.", LOG_PREFIX, result
);
env.write(&result, false, None)
}
}

impl PopApiExtensionConfig for Runtime {
type AssetInstance = TrustBackedAssetsInstance;
type ReadStateParamsHandler = ChainExtensionEnvironment;
type DispatchCallParamsHandler = ChainExtensionEnvironment;
type AllowedDispatchCalls = AllowedApiCalls;
}
1 change: 1 addition & 0 deletions runtime/devnet/src/config/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
pub(crate) mod api;
pub mod assets;
mod contracts;
pub(crate) mod extension;
mod proxy;
// Public due to integration tests crate.
pub mod xcm;
1 change: 0 additions & 1 deletion runtime/devnet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

mod extensions;
mod weights;
// Public due to integration tests crate.
pub mod config;
Expand Down
Loading
Loading