From aa518d79b69f2d912d21b9f239a760c9b79fff15 Mon Sep 17 00:00:00 2001 From: code0xff Date: Wed, 11 Sep 2024 14:22:22 +0900 Subject: [PATCH] refactor: Refactor pallet-cosmos-types --- frame/cosmos/src/lib.rs | 81 ++++--------------- frame/cosmos/types/src/context/mod.rs | 45 +++++++++++ .../src/{context.rs => context/traits.rs} | 4 +- .../types/src/{events.rs => events/mod.rs} | 28 +++++-- frame/cosmos/types/src/events/traits.rs | 25 ++++++ frame/cosmos/types/src/{gas.rs => gas/mod.rs} | 12 +-- frame/cosmos/types/src/gas/traits.rs | 26 ++++++ frame/cosmos/x/bank/src/msgs.rs | 5 +- frame/cosmos/x/wasm/src/msgs.rs | 14 ++-- template/runtime/src/lib.rs | 9 ++- template/runtime/src/msgs.rs | 2 +- 11 files changed, 155 insertions(+), 96 deletions(-) create mode 100644 frame/cosmos/types/src/context/mod.rs rename frame/cosmos/types/src/{context.rs => context/traits.rs} (93%) rename frame/cosmos/types/src/{events.rs => events/mod.rs} (78%) create mode 100644 frame/cosmos/types/src/events/traits.rs rename frame/cosmos/types/src/{gas.rs => gas/mod.rs} (84%) create mode 100644 frame/cosmos/types/src/gas/traits.rs diff --git a/frame/cosmos/src/lib.rs b/frame/cosmos/src/lib.rs index 0c0bc8e..052deeb 100644 --- a/frame/cosmos/src/lib.rs +++ b/frame/cosmos/src/lib.rs @@ -50,13 +50,14 @@ use frame_support::{ weights::Weight, }; use frame_system::{pallet_prelude::OriginFor, CheckWeight}; +use pallet_cosmos_types::events::traits::EventManager; use pallet_cosmos_types::{ address::acc_address_from_bech32, - context::{self, Context as _}, + context, + context::traits::Context, errors::{CosmosError, RootError}, - events, - events::{CosmosEvent, CosmosEvents, EventManager as _}, - gas::{BasicGasMeter, Gas, GasMeter}, + events::CosmosEvent, + gas::{traits::GasMeter, Gas}, handler::AnteDecorator, msgservice::MsgServiceRouter, }; @@ -102,21 +103,18 @@ where pub fn check_self_contained(&self) -> Option> { if let Call::transact { tx_bytes } = self { let check = || { - let tx = Tx::decode(&mut &tx_bytes[..]) + let (_hrp, address) = Tx::decode(&mut &tx_bytes[..]) + .map(|tx| T::SigVerifiableTx::fee_payer(&tx)) + .map_err(|_| TransactionValidityError::Invalid(InvalidTransaction::Call))? + .map(|fee_payer| acc_address_from_bech32(&fee_payer)) + .map_err(|_| TransactionValidityError::Invalid(InvalidTransaction::Call))? .map_err(|_| TransactionValidityError::Invalid(InvalidTransaction::Call))?; - let fee_payer = T::SigVerifiableTx::fee_payer(&tx).map_err(|_| { - TransactionValidityError::Invalid(InvalidTransaction::BadSigner) - })?; - let (_hrp, address_raw) = acc_address_from_bech32(&fee_payer).map_err(|_| { - TransactionValidityError::Invalid(InvalidTransaction::BadSigner) - })?; - - if address_raw.len() != 20 { - return Err(TransactionValidityError::Invalid(InvalidTransaction::BadSigner)); + if address.len() != 20 { + return Err(TransactionValidityError::Invalid(InvalidTransaction::Call)); } - Ok(H160::from_slice(&address_raw)) + Ok(H160::from_slice(&address)) }; Some(check()) @@ -168,6 +166,7 @@ pub trait AddressMapping { #[frame_support::pallet] pub mod pallet { use super::*; + use crate::context::traits::Context; use frame_support::{ pallet_prelude::*, traits::{fungibles::metadata::Inspect as _, Contains}, @@ -229,54 +228,6 @@ pub mod pallet { pub const AddressPrefix: &'static str = "cosmos"; } - #[derive(Clone, Debug, Default)] - pub struct EventManager { - events: CosmosEvents, - } - - impl events::EventManager for EventManager { - fn new() -> Self { - Self::default() - } - - fn events(&self) -> CosmosEvents { - self.events.clone() - } - - fn emit_event(&mut self, event: events::CosmosEvent) { - self.events.push(event); - } - - fn emit_events(&mut self, events: CosmosEvents) { - self.events.extend(events); - } - } - - pub struct Context { - pub gas_meter: BasicGasMeter, - pub event_manager: EventManager, - } - - impl context::Context for Context { - type GasMeter = BasicGasMeter; - type EventManager = EventManager; - - fn new(limit: Gas) -> Self { - Self { - gas_meter: Self::GasMeter::new(limit), - event_manager: Self::EventManager::new(), - } - } - - fn gas_meter(&mut self) -> &mut Self::GasMeter { - &mut self.gas_meter - } - - fn event_manager(&mut self) -> &mut Self::EventManager { - &mut self.event_manager - } - } - #[frame_support::register_default_impl(TestDefaultConfig)] impl DefaultConfig for TestDefaultConfig { #[inject_runtime_type] @@ -292,7 +243,7 @@ pub mod pallet { type TxSigLimit = TxSigLimit; type MaxDenomLimit = MaxDenomLimit; type AddressPrefix = AddressPrefix; - type Context = Context; + type Context = pallet_cosmos_types::context::Context; } } @@ -372,7 +323,7 @@ pub mod pallet { #[pallet::constant] type AddressPrefix: Get<&'static str>; - type Context: context::Context; + type Context: Context; } #[pallet::genesis_config] diff --git a/frame/cosmos/types/src/context/mod.rs b/frame/cosmos/types/src/context/mod.rs new file mode 100644 index 0000000..0eb139d --- /dev/null +++ b/frame/cosmos/types/src/context/mod.rs @@ -0,0 +1,45 @@ +// This file is part of Horizon. + +// Copyright (C) 2023 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. + +pub mod traits; + +use crate::{ + events::{traits::EventManager as _, EventManager}, + gas::{traits::GasMeter, BasicGasMeter, Gas}, +}; + +pub struct Context { + pub gas_meter: BasicGasMeter, + pub event_manager: EventManager, +} + +impl traits::Context for Context { + type GasMeter = BasicGasMeter; + type EventManager = EventManager; + + fn new(limit: Gas) -> Self { + Self { gas_meter: Self::GasMeter::new(limit), event_manager: Self::EventManager::new() } + } + + fn gas_meter(&mut self) -> &mut Self::GasMeter { + &mut self.gas_meter + } + + fn event_manager(&mut self) -> &mut Self::EventManager { + &mut self.event_manager + } +} diff --git a/frame/cosmos/types/src/context.rs b/frame/cosmos/types/src/context/traits.rs similarity index 93% rename from frame/cosmos/types/src/context.rs rename to frame/cosmos/types/src/context/traits.rs index 4855fe4..462c6e8 100644 --- a/frame/cosmos/types/src/context.rs +++ b/frame/cosmos/types/src/context/traits.rs @@ -16,8 +16,8 @@ // limitations under the License. use crate::{ - events::EventManager, - gas::{Gas, GasMeter}, + events::traits::EventManager, + gas::{traits::GasMeter, Gas}, }; pub trait Context { diff --git a/frame/cosmos/types/src/events.rs b/frame/cosmos/types/src/events/mod.rs similarity index 78% rename from frame/cosmos/types/src/events.rs rename to frame/cosmos/types/src/events/mod.rs index a09e328..eefa3fc 100644 --- a/frame/cosmos/types/src/events.rs +++ b/frame/cosmos/types/src/events/mod.rs @@ -15,6 +15,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +pub mod traits; + use alloc::vec::Vec; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; @@ -45,9 +47,25 @@ pub struct EventAttribute { pub type CosmosEvents = Vec; -pub trait EventManager { - fn new() -> Self; - fn events(&self) -> CosmosEvents; - fn emit_event(&mut self, event: CosmosEvent); - fn emit_events(&mut self, events: CosmosEvents); +#[derive(Clone, Debug, Default)] +pub struct EventManager { + events: CosmosEvents, +} + +impl traits::EventManager for EventManager { + fn new() -> Self { + Self::default() + } + + fn events(&self) -> CosmosEvents { + self.events.clone() + } + + fn emit_event(&mut self, event: CosmosEvent) { + self.events.push(event); + } + + fn emit_events(&mut self, events: CosmosEvents) { + self.events.extend(events); + } } diff --git a/frame/cosmos/types/src/events/traits.rs b/frame/cosmos/types/src/events/traits.rs new file mode 100644 index 0000000..f3de04b --- /dev/null +++ b/frame/cosmos/types/src/events/traits.rs @@ -0,0 +1,25 @@ +// This file is part of Horizon. + +// Copyright (C) 2023 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 super::{CosmosEvent, CosmosEvents}; + +pub trait EventManager { + fn new() -> Self; + fn events(&self) -> CosmosEvents; + fn emit_event(&mut self, event: CosmosEvent); + fn emit_events(&mut self, events: CosmosEvents); +} diff --git a/frame/cosmos/types/src/gas.rs b/frame/cosmos/types/src/gas/mod.rs similarity index 84% rename from frame/cosmos/types/src/gas.rs rename to frame/cosmos/types/src/gas/mod.rs index 123799f..5b45a3d 100644 --- a/frame/cosmos/types/src/gas.rs +++ b/frame/cosmos/types/src/gas/mod.rs @@ -15,6 +15,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +pub mod traits; + pub type Gas = u64; #[derive(Clone, Debug, Eq, PartialEq)] @@ -23,21 +25,13 @@ pub enum Error { OutOfGas, } -pub trait GasMeter { - fn new(limit: Gas) -> Self; - fn consumed_gas(&self) -> Gas; - fn gas_remaining(&self) -> Gas; - fn limit(&self) -> Gas; - fn consume_gas(&mut self, amount: Gas, descriptor: &str) -> Result; -} - #[derive(Clone, Debug)] pub struct BasicGasMeter { pub limit: Gas, pub consumed: Gas, } -impl GasMeter for BasicGasMeter { +impl traits::GasMeter for BasicGasMeter { fn new(limit: Gas) -> Self { Self { limit, consumed: 0 } } diff --git a/frame/cosmos/types/src/gas/traits.rs b/frame/cosmos/types/src/gas/traits.rs new file mode 100644 index 0000000..c6aa662 --- /dev/null +++ b/frame/cosmos/types/src/gas/traits.rs @@ -0,0 +1,26 @@ +// This file is part of Horizon. + +// Copyright (C) 2023 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 super::{Error, Gas}; + +pub trait GasMeter { + fn new(limit: Gas) -> Self; + fn consumed_gas(&self) -> Gas; + fn gas_remaining(&self) -> Gas; + fn limit(&self) -> Gas; + fn consume_gas(&mut self, amount: Gas, descriptor: &str) -> Result; +} diff --git a/frame/cosmos/x/bank/src/msgs.rs b/frame/cosmos/x/bank/src/msgs.rs index 8a8f721..922789d 100644 --- a/frame/cosmos/x/bank/src/msgs.rs +++ b/frame/cosmos/x/bank/src/msgs.rs @@ -29,8 +29,7 @@ use pallet_cosmos_types::{ coin::amount_to_string, context, errors::{CosmosError, RootError}, - events::{EventAttribute, EventManager, ATTRIBUTE_KEY_AMOUNT, ATTRIBUTE_KEY_SENDER}, - gas::GasMeter, + events::{traits::EventManager, EventAttribute, ATTRIBUTE_KEY_AMOUNT, ATTRIBUTE_KEY_SENDER}, gas::traits::GasMeter, }; use pallet_cosmos_x_bank_types::events::{ATTRIBUTE_KEY_RECIPIENT, EVENT_TYPE_TRANSFER}; use sp_runtime::{traits::Convert, SaturatedConversion}; @@ -46,7 +45,7 @@ impl Default for MsgSendHandler { impl pallet_cosmos_types::msgservice::MsgHandler for MsgSendHandler where T: pallet_cosmos::Config, - Context: context::Context, + Context: context::traits::Context, { fn handle(&self, msg: &Any, ctx: &mut Context) -> Result<(), CosmosError> { let MsgSend { from_address, to_address, amount } = diff --git a/frame/cosmos/x/wasm/src/msgs.rs b/frame/cosmos/x/wasm/src/msgs.rs index 8a9814d..56b020a 100644 --- a/frame/cosmos/x/wasm/src/msgs.rs +++ b/frame/cosmos/x/wasm/src/msgs.rs @@ -34,8 +34,8 @@ use pallet_cosmos::AddressMapping; use pallet_cosmos_types::{ context, errors::{CosmosError, RootError}, - events::{CosmosEvent, EventAttribute, EventManager}, - gas::GasMeter, + events::{traits::EventManager, CosmosEvent, EventAttribute}, + gas::traits::GasMeter, msgservice::MsgHandler, }; use pallet_cosmos_x_wasm_types::{ @@ -65,7 +65,7 @@ impl Default for MsgStoreCodeHandler { impl MsgHandler for MsgStoreCodeHandler where T: pallet_cosmos::Config + pallet_cosmwasm::Config, - Context: context::Context, + Context: context::traits::Context, { fn handle(&self, msg: &Any, ctx: &mut Context) -> Result<(), CosmosError> { // TODO: Apply actual weights @@ -116,7 +116,7 @@ impl MsgHandler for MsgInstantiateContract2Handler where T: pallet_cosmos::Config + pallet_cosmwasm::Config, T::AccountId: EcdsaExt, - Context: context::Context, + Context: context::traits::Context, { // TODO: Consume gas fn handle(&self, msg: &Any, ctx: &mut Context) -> Result<(), CosmosError> { @@ -193,7 +193,7 @@ impl MsgHandler for MsgExecuteContractHandler where T: pallet_cosmos::Config + pallet_cosmwasm::Config, T::AccountId: EcdsaExt, - Context: context::Context, + Context: context::traits::Context, { // TODO: Consume gas fn handle(&self, msg: &Any, ctx: &mut Context) -> Result<(), CosmosError> { @@ -250,7 +250,7 @@ impl Default for MsgMigrateContractHandler { impl MsgHandler for MsgMigrateContractHandler where T: pallet_cosmos::Config + pallet_cosmwasm::Config, - Context: context::Context, + Context: context::traits::Context, { fn handle(&self, msg: &Any, ctx: &mut Context) -> Result<(), CosmosError> { let MsgMigrateContract { sender, contract, code_id, msg } = @@ -309,7 +309,7 @@ impl Default for MsgUpdateAdminHandler { impl MsgHandler for MsgUpdateAdminHandler where T: pallet_cosmos::Config + pallet_cosmwasm::Config, - Context: context::Context, + Context: context::traits::Context, { fn handle(&self, msg: &Any, ctx: &mut Context) -> Result<(), CosmosError> { let MsgUpdateAdmin { sender, new_admin, contract } = diff --git a/template/runtime/src/lib.rs b/template/runtime/src/lib.rs index 58ee192..0ffb68e 100644 --- a/template/runtime/src/lib.rs +++ b/template/runtime/src/lib.rs @@ -58,12 +58,12 @@ use hp_account::CosmosSigner; use hp_crypto::EcdsaExt; use pallet_cosmos::{ config_preludes::{ - AddressPrefix, ChainId, Context, MaxDenomLimit, MaxMemoCharacters, MsgFilter, NativeDenom, + AddressPrefix, ChainId, MaxDenomLimit, MaxMemoCharacters, MsgFilter, NativeDenom, TxSigLimit, WeightToGas, }, AddressMapping, }; -use pallet_cosmos_types::any_match; +use pallet_cosmos_types::{any_match, context::Context}; use pallet_cosmos_x_auth_signing::{ sign_mode_handler::SignModeHandler, sign_verifiable_tx::SigVerifiableTx, }; @@ -577,10 +577,11 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Cosmos(pallet_cosmos::Call::transact { .. }) => + call @ RuntimeCall::Cosmos(pallet_cosmos::Call::transact { .. }) => { Some(call.dispatch(RuntimeOrigin::from( pallet_cosmos::RawOrigin::CosmosTransaction(info.to_cosmos_address().unwrap()), - ))), + ))) + }, _ => None, } } diff --git a/template/runtime/src/msgs.rs b/template/runtime/src/msgs.rs index c7ae0e8..dbee0d1 100644 --- a/template/runtime/src/msgs.rs +++ b/template/runtime/src/msgs.rs @@ -39,7 +39,7 @@ impl pallet_cosmos_types::msgservice::MsgServiceRouter for where T: frame_system::Config + pallet_cosmos::Config + pallet_cosmwasm::Config, T::AccountId: EcdsaExt, - Context: context::Context, + Context: context::traits::Context, { fn route(msg: &Any) -> Option>> { any_match!(