Skip to content

Commit

Permalink
feat: Add post handler for cosmos transact (#89)
Browse files Browse the repository at this point in the history
* feat: Add post handler for cosmos transact

* refactor: Refactor simulate cosmos tx api

* fix: Add default config for PostHandler
  • Loading branch information
code0xff authored Oct 28, 2024
1 parent 6ca529e commit 271620b
Show file tree
Hide file tree
Showing 7 changed files with 85 additions and 17 deletions.
1 change: 1 addition & 0 deletions frame/cosmos/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ cosmos-runtime-api = { workspace = true, features = ["std"] }
futures = "0.3"
hex = "0.4.3"
jsonrpsee = { version = "0.24", features = ["client", "server", "macros"] }
pallet-cosmos-types = { workspace = true, features = ["std"] }
sc-transaction-pool-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409" }
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409" }
sp-blockchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2409" }
Expand Down
3 changes: 2 additions & 1 deletion frame/cosmos/rpc/src/cosmos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@
// limitations under the License.

use crate::{internal_error, request_error};
use cosmos_runtime_api::{ChainInfo, CosmosRuntimeApi, SimulateError, SimulateResponse};
use cosmos_runtime_api::{ChainInfo, CosmosRuntimeApi, SimulateError};
use futures::future::TryFutureExt;
use jsonrpsee::{
core::{async_trait, RpcResult},
proc_macros::rpc,
};
use pallet_cosmos_types::tx::SimulateResponse;
use sc_transaction_pool_api::TransactionPool;
use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend;
Expand Down
14 changes: 1 addition & 13 deletions frame/cosmos/runtime-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,25 +20,13 @@
extern crate alloc;

use alloc::{string::String, vec::Vec};
use pallet_cosmos_types::{events::CosmosEvent, gas::Gas};
use pallet_cosmos_types::tx::SimulateResponse;
use parity_scale_codec::{Decode, Encode};
use scale_info::TypeInfo;
use serde::{Deserialize, Serialize};
use sp_api::decl_runtime_apis;
use sp_runtime::traits::Block as BlockT;

#[derive(Clone, Decode, Encode, Debug, TypeInfo, Serialize, Deserialize)]
pub struct GasInfo {
pub gas_wanted: Gas,
pub gas_used: Gas,
}

#[derive(Clone, Decode, Encode, Debug, TypeInfo, Serialize, Deserialize)]
pub struct SimulateResponse {
pub gas_info: GasInfo,
pub events: Vec<CosmosEvent>,
}

#[derive(Clone, Decode, Encode, Debug, Eq, PartialEq, TypeInfo)]
pub enum SimulateError {
InvalidTx,
Expand Down
30 changes: 28 additions & 2 deletions frame/cosmos/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ use pallet_cosmos_types::{
errors::{CosmosError, RootError},
events::traits::EventManager,
gas::traits::GasMeter,
handler::AnteDecorator,
handler::{AnteDecorator, PostDecorator},
msgservice::traits::MsgServiceRouter,
tx::{GasInfo, SimulateResponse},
tx_msgs::FeeTx,
};
use pallet_cosmos_x_auth_signing::sign_verifiable_tx::traits::SigVerifiableTx;
Expand Down Expand Up @@ -150,6 +151,7 @@ pub mod pallet {
use np_cosmos::traits::ChainInfo;
use pallet_cosmos_types::{
context::traits::MinGasPrices, errors::CosmosError, events::CosmosEvent, gas::Gas,
handler::PostDecorator,
};
use pallet_cosmos_x_auth_signing::sign_mode_handler::traits::SignModeHandler;
use sp_runtime::traits::{Convert, TryConvert};
Expand All @@ -165,6 +167,7 @@ pub mod pallet {
pub enum Event {
AnteHandled(Vec<CosmosEvent>),
Executed { gas_wanted: u64, gas_used: u64, events: Vec<CosmosEvent> },
PostHandled(Vec<CosmosEvent>),
}

#[pallet::error]
Expand Down Expand Up @@ -224,6 +227,9 @@ pub mod pallet {
/// Ante handler for fee and auth.
type AnteHandler: AnteDecorator;

/// Post handler to perform custom post-processing.
type PostHandler: PostDecorator<Self::Context>;

/// Message filter for allowed messages.
type MsgFilter: Contains<Any>;

Expand Down Expand Up @@ -295,6 +301,7 @@ pub mod pallet {
type WeightToGas = WeightToGas;
type Context = Context;
type AnteHandler = ();
type PostHandler = ();
type MaxMemoCharacters = MaxMemoCharacters;
type TxSigLimit = TxSigLimit;
type MaxDenomLimit = MaxDenomLimit;
Expand Down Expand Up @@ -379,7 +386,10 @@ impl<T: Config> Pallet<T> {
.with_weight(T::WeightToGas::convert(ctx.gas_meter().consumed_gas()))
})?;

// TODO: Implement PostHandlers for refund functionality
T::PostHandler::post_handle(&mut ctx, &tx, false).map_err(|e| {
Error::<T>::CosmosError(e)
.with_weight(T::WeightToGas::convert(ctx.gas_meter().consumed_gas()))
})?;

Self::deposit_event(Event::Executed {
gas_wanted: gas_limit,
Expand Down Expand Up @@ -408,4 +418,20 @@ impl<T: Config> Pallet<T> {

Ok(())
}

pub fn simulate(tx_bytes: Vec<u8>) -> Result<SimulateResponse, CosmosError> {
let tx = Tx::decode(&mut &*tx_bytes).map_err(|_| RootError::TxDecodeError)?;

T::AnteHandler::ante_handle(&tx, true)?;

let mut ctx = T::Context::new(T::SimulationGasLimit::get());
Self::run_tx(&mut ctx, &tx)?;

T::PostHandler::post_handle(&mut ctx, &tx, true)?;

Ok(SimulateResponse {
gas_info: GasInfo { gas_wanted: 0, gas_used: ctx.gas_meter().consumed_gas() },
events: ctx.event_manager().events(),
})
}
}
20 changes: 19 additions & 1 deletion frame/cosmos/types/src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::errors::CosmosError;
use crate::{context::traits::Context, errors::CosmosError};
use cosmos_sdk_proto::cosmos::tx::v1beta1::Tx;

pub trait AnteDecorator {
Expand All @@ -35,3 +35,21 @@ impl AnteDecorator for Tuple {
Ok(())
}
}

pub trait PostDecorator<C: Context> {
fn post_handle(ctx: &mut C, tx: &Tx, simulate: bool) -> Result<(), CosmosError>;
}

impl<C: Context> PostDecorator<C> for () {
fn post_handle(_ctx: &mut C, _tx: &Tx, _simulate: bool) -> Result<(), CosmosError> {
Ok(())
}
}

#[impl_trait_for_tuples::impl_for_tuples(1, 12)]
impl<C: Context> PostDecorator<C> for Tuple {
fn post_handle(ctx: &mut C, tx: &Tx, simulate: bool) -> Result<(), CosmosError> {
for_tuples!( #( Tuple::post_handle(ctx, tx, simulate)?; )* );
Ok(())
}
}
1 change: 1 addition & 0 deletions frame/cosmos/types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,5 @@ pub mod gas;
pub mod handler;
pub mod macros;
pub mod msgservice;
pub mod tx;
pub mod tx_msgs;
33 changes: 33 additions & 0 deletions frame/cosmos/types/src/tx.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// This file is part of Noir.

// Copyright (c) Haderech Pte. Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::{events::CosmosEvent, gas::Gas};
use parity_scale_codec::{Decode, Encode};
use scale_info::TypeInfo;
use serde::{Deserialize, Serialize};

#[derive(Clone, Decode, Encode, Debug, TypeInfo, Serialize, Deserialize)]
pub struct GasInfo {
pub gas_wanted: Gas,
pub gas_used: Gas,
}

#[derive(Clone, Decode, Encode, Debug, TypeInfo, Serialize, Deserialize)]
pub struct SimulateResponse {
pub gas_info: GasInfo,
pub events: Vec<CosmosEvent>,
}

0 comments on commit 271620b

Please sign in to comment.