Skip to content
This repository has been archived by the owner on Nov 20, 2024. It is now read-only.

Commit

Permalink
refactor: Refactor pallet-cosmos-types
Browse files Browse the repository at this point in the history
  • Loading branch information
code0xff committed Sep 11, 2024
1 parent bd23ab9 commit aa518d7
Show file tree
Hide file tree
Showing 11 changed files with 155 additions and 96 deletions.
81 changes: 16 additions & 65 deletions frame/cosmos/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down Expand Up @@ -102,21 +103,18 @@ where
pub fn check_self_contained(&self) -> Option<Result<H160, TransactionValidityError>> {
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())
Expand Down Expand Up @@ -168,6 +166,7 @@ pub trait AddressMapping<A> {
#[frame_support::pallet]
pub mod pallet {
use super::*;
use crate::context::traits::Context;
use frame_support::{
pallet_prelude::*,
traits::{fungibles::metadata::Inspect as _, Contains},
Expand Down Expand Up @@ -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]
Expand All @@ -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;
}
}

Expand Down Expand Up @@ -372,7 +323,7 @@ pub mod pallet {
#[pallet::constant]
type AddressPrefix: Get<&'static str>;

type Context: context::Context;
type Context: Context;
}

#[pallet::genesis_config]
Expand Down
45 changes: 45 additions & 0 deletions frame/cosmos/types/src/context/mod.rs
Original file line number Diff line number Diff line change
@@ -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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -45,9 +47,25 @@ pub struct EventAttribute {

pub type CosmosEvents = Vec<CosmosEvent>;

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);
}
}
25 changes: 25 additions & 0 deletions frame/cosmos/types/src/events/traits.rs
Original file line number Diff line number Diff line change
@@ -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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -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<Gas, Error>;
}

#[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 }
}
Expand Down
26 changes: 26 additions & 0 deletions frame/cosmos/types/src/gas/traits.rs
Original file line number Diff line number Diff line change
@@ -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<Gas, Error>;
}
5 changes: 2 additions & 3 deletions frame/cosmos/x/bank/src/msgs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -46,7 +45,7 @@ impl<T> Default for MsgSendHandler<T> {
impl<T, Context> pallet_cosmos_types::msgservice::MsgHandler<Context> for MsgSendHandler<T>
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 } =
Expand Down
14 changes: 7 additions & 7 deletions frame/cosmos/x/wasm/src/msgs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -65,7 +65,7 @@ impl<T> Default for MsgStoreCodeHandler<T> {
impl<T, Context> MsgHandler<Context> for MsgStoreCodeHandler<T>
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
Expand Down Expand Up @@ -116,7 +116,7 @@ impl<T, Context> MsgHandler<Context> for MsgInstantiateContract2Handler<T>
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> {
Expand Down Expand Up @@ -193,7 +193,7 @@ impl<T, Context> MsgHandler<Context> for MsgExecuteContractHandler<T>
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> {
Expand Down Expand Up @@ -250,7 +250,7 @@ impl<T> Default for MsgMigrateContractHandler<T> {
impl<T, Context> MsgHandler<Context> for MsgMigrateContractHandler<T>
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 } =
Expand Down Expand Up @@ -309,7 +309,7 @@ impl<T> Default for MsgUpdateAdminHandler<T> {
impl<T, Context> MsgHandler<Context> for MsgUpdateAdminHandler<T>
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 } =
Expand Down
Loading

0 comments on commit aa518d7

Please sign in to comment.