Skip to content

Commit

Permalink
Merge pull request #295 from NYBACHOK/polish_bank_xmod
Browse files Browse the repository at this point in the history
Polish bank xmod
  • Loading branch information
joneskm authored Oct 4, 2024
2 parents 0bdfad2 + c3e3bf4 commit a76da44
Show file tree
Hide file tree
Showing 39 changed files with 845 additions and 496 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ run:
cargo run -- run --min-gas-prices 0uatom

test:
RUST_BACKTRACE=1 cargo test --features=macros_test,it --no-fail-fast
RUST_BACKTRACE=1 cargo test --features=it --no-fail-fast

install:
# "cargo install --path" ignores the lockfile, so we need to use "--locked" to ensure we use the same versions as in the lockfile
Expand Down
2 changes: 1 addition & 1 deletion gaia-rs/src/abci_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ impl ABCIHandler for GaiaABCIHandler {
ctx: &mut InitContext<'_, DB, GaiaStoreKey>,
genesis: GenesisState,
) -> Vec<gears::tendermint::types::proto::validator::ValidatorUpdate> {
self.bank_abci_handler.genesis(ctx, genesis.bank);
self.bank_abci_handler.init_genesis(ctx, genesis.bank);
let staking_updates = self.staking_abci_handler.genesis(ctx, genesis.staking);
self.ibc_abci_handler.genesis(ctx, genesis.ibc);
self.auth_abci_handler.init_genesis(ctx, genesis.auth);
Expand Down
9 changes: 9 additions & 0 deletions gaia-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,9 @@ impl AuxHandler for GaiaCore {
genutil::gentx::gentx_cmd(cmd, "bank", "staking", &EmptyNodeFetcher)?;
}
},
GaiaAuxCmd::Bank(cmd) => {
bank::aux::handle_aux_cmd(cmd, "/app_state/bank/denom_metadata")?
}
}

Ok(NilAux)
Expand All @@ -166,6 +169,8 @@ impl AuxHandler for GaiaCore {
pub enum GaiaAuxCli<AI: ApplicationInfo> {
#[command(flatten)]
Genutil(genutil::client::cli::GenesisCommands<AI>),
#[command(flatten)]
Bank(bank::aux::cli::BankAuxCliCommands<AI>),
}

impl<AI: ApplicationInfo> TryFrom<GaiaAuxCli<AI>> for GaiaAuxCmd {
Expand All @@ -176,12 +181,16 @@ impl<AI: ApplicationInfo> TryFrom<GaiaAuxCli<AI>> for GaiaAuxCmd {
GaiaAuxCli::Genutil(var) => GaiaAuxCmd::Genutil(
genutil::client::cli::GenesisAuxCli { command: var }.try_into()?,
),
GaiaAuxCli::Bank(var) => {
GaiaAuxCmd::Bank(bank::aux::cli::BankAuxCli { command: var }.try_into()?)
}
})
}
}

pub enum GaiaAuxCmd {
Genutil(genutil::cmd::GenesisCmd),
Bank(bank::aux::BankAuxCmd),
}

impl AuxHandler for GaiaCoreClient {
Expand Down
2 changes: 1 addition & 1 deletion gaia-rs/src/modules.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use gears::x::module::Module;

#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, strum::EnumIter)]
pub enum GaiaModules {
FeeCollector,
BondedPool,
Expand Down
5 changes: 1 addition & 4 deletions gaia-rs/tests/auth_query_accounts_base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@

use auth::cli::query::{AccountsCommand, AuthCommands, AuthQueryCli, AuthQueryResponse};
use gaia_rs::{client::GaiaQueryCommands, query::GaiaQueryResponse};
use gears::{
cli::pagination::CliPaginationRequest, extensions::testing::UnwrapTesting,
types::account::Account,
};
use gears::{extensions::testing::UnwrapTesting, types::account::Account};
use utilities::GaiaNode;

#[path = "./utilities.rs"]
Expand Down
5 changes: 1 addition & 4 deletions gaia-rs/tests/auth_query_accounts_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@

use auth::cli::query::{AccountsCommand, AuthCommands, AuthQueryCli, AuthQueryResponse};
use gaia_rs::{client::GaiaQueryCommands, query::GaiaQueryResponse};
use gears::{
cli::pagination::CliPaginationRequest, extensions::testing::UnwrapTesting,
types::account::Account,
};
use gears::{extensions::testing::UnwrapTesting, types::account::Account};
use utilities::GaiaNode;

#[path = "./utilities.rs"]
Expand Down
6 changes: 6 additions & 0 deletions gears/src/types/base/coin/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,9 @@ impl FromStr for DecimalCoin {
Ok(Self { denom, amount })
}
}

impl std::fmt::Display for DecimalCoin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}{}", self.amount.to_string(), self.denom.to_string())
}
}
6 changes: 6 additions & 0 deletions gears/src/types/base/coin/unsigned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,9 @@ impl PaginationKey for UnsignedCoin {
Cow::Borrowed(self.denom.as_ref())
}
}

impl std::fmt::Display for UnsignedCoin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}{}", self.amount.to_string(), self.denom.to_string())
}
}
7 changes: 5 additions & 2 deletions gears/src/types/base/coins/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
use core_types::Protobuf;
pub use decimal::*;
use prost::Message;

pub use decimal::*;
pub use simple::*;
pub use unsigned::*;

mod decimal;
mod simple;
mod unsigned;

use std::{marker::PhantomData, str::FromStr};
Expand Down Expand Up @@ -97,7 +100,7 @@ impl<T: ZeroNumeric, U: Coin<Amount = T>> Coins<T, U> {
// denomination (i.e no duplicates). Otherwise, it returns an error.
// A valid list of coins satisfies:
// - Contains at least one coin
// - All amounts are positive
// - All amounts are positive(not zero)
// - No duplicate denominations
// - Sorted lexicographically
pub fn new(coins: impl IntoIterator<Item = U>) -> Result<Self, CoinsError> {
Expand Down
137 changes: 137 additions & 0 deletions gears/src/types/base/coins/simple.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
use bytes::Bytes;

use crate::types::base::coin::{DecimalCoin, UnsignedCoin};

use super::*;

pub type SimpleDecimalCoins = SimpleCoins<DecimalCoin>;
pub type SimpleUnsignedCoins = SimpleCoins<UnsignedCoin>;

// TODO: Allow borrowed data
#[derive(Debug, Clone)]
pub struct SimpleCoins<U>(Vec<U>);

impl<U> SimpleCoins<U> {
pub fn new(coins: impl IntoIterator<Item = U>) -> Self {
Self(coins.into_iter().collect())
}
}

impl<U: ToString> SimpleCoins<U> {
pub fn to_string_bytes(&self) -> Bytes {
self.to_string().into_bytes().into()
}
}

impl<U> From<Vec<U>> for SimpleCoins<U> {
fn from(value: Vec<U>) -> Self {
Self(value)
}
}

impl<U> From<SimpleCoins<U>> for Vec<U> {
fn from(value: SimpleCoins<U>) -> Self {
value.0
}
}

impl<T: ZeroNumeric, U: Coin<Amount = T>> TryFrom<SimpleCoins<U>> for Coins<T, U> {
type Error = CoinsError;

fn try_from(value: SimpleCoins<U>) -> Result<Self, Self::Error> {
Self::new(value.0)
}
}

impl<U: ToString> std::fmt::Display for SimpleCoins<U> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let result = self
.0
.iter()
.map(|this| this.to_string())
.collect::<Vec<_>>()
.join(",");

write!(f, "{result}")
}
}

#[cfg(test)]
mod tests {
use extensions::testing::UnwrapTesting;

use super::*;

// https://github.com/cosmos/cosmos-sdk/blob/d3f09c222243bb3da3464969f0366330dcb977a8/types/coin.go#L190-L205

#[test]
fn test_display_multiple_i32() {
let list = SimpleCoins::new([1, 2, 3]);

assert_eq!("1,2,3", list.to_string())
}

#[test]
fn test_display_single_i32() {
let list = SimpleCoins::new([1]);

assert_eq!("1", list.to_string())
}

#[test]
fn test_display_empty_i32() {
let list = SimpleCoins::<u32>::new([]);

assert_eq!("", list.to_string())
}

#[test]
fn test_display_multiple_signed() {
let list = SimpleCoins::new([
DecimalCoin::from_str("1uatom").unwrap_test(),
DecimalCoin::from_str("2uatom").unwrap_test(),
DecimalCoin::from_str("3uatom").unwrap_test(),
]);

assert_eq!("1uatom,2uatom,3uatom", list.to_string())
}

#[test]
fn test_display_single_signed() {
let list = SimpleCoins::new([DecimalCoin::from_str("1uatom").unwrap_test()]);

assert_eq!("1uatom", list.to_string())
}

#[test]
fn test_display_empty_signed() {
let list = SimpleCoins::<DecimalCoin>::new([]);

assert_eq!("", list.to_string())
}

#[test]
fn test_display_multiple_unsigned() {
let list = SimpleCoins::new([
UnsignedCoin::from_str("1uatom").unwrap_test(),
UnsignedCoin::from_str("2uatom").unwrap_test(),
UnsignedCoin::from_str("3uatom").unwrap_test(),
]);

assert_eq!("1uatom,2uatom,3uatom", list.to_string())
}

#[test]
fn test_display_single_unsigned() {
let list = SimpleCoins::new([UnsignedCoin::from_str("1uatom").unwrap_test()]);

assert_eq!("1uatom", list.to_string())
}

#[test]
fn test_display_empty_unsigned() {
let list = SimpleCoins::<UnsignedCoin>::new([]);

assert_eq!("", list.to_string())
}
}
2 changes: 1 addition & 1 deletion gears/src/x/ante.rs
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,7 @@ impl<
&self,
denom: &Denom,
) -> Result<Option<crate::types::tx::metadata::Metadata>, Self::Error> {
self.bank_keeper.get_denom_metadata(self.ctx, denom)
self.bank_keeper.denom_metadata(self.ctx, denom)
}
}

Expand Down
2 changes: 2 additions & 0 deletions gears/src/x/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,8 @@ pub enum BankKeeperError {
AccountNotFound(#[from] AccountNotFound),
#[error("account doesnt have enought permission")]
AccountPermission,
#[error("{0} is not allowed to receive funds. Probably tried send to module as account")]
Blocked(AccAddress),
#[error("{0}")]
GasError(#[from] GasStoreErrors),
}
Expand Down
2 changes: 1 addition & 1 deletion gears/src/x/keepers/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub trait AuthParams {
fn tx_cost_per_byte(&self) -> u64;
}

pub trait AuthKeeper<SK: StoreKey, M: Module>: Clone {
pub trait AuthKeeper<SK: StoreKey, M: Module>: Clone + Send + Sync + 'static {
type Params: AuthParams;

fn get_auth_params<DB: Database, CTX: QueryableContext<DB, SK>>(
Expand Down
19 changes: 16 additions & 3 deletions gears/src/x/keepers/bank.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,28 @@
use database::Database;
use extensions::pagination::{Pagination, PaginationResult};
use kv_store::StoreKey;

use crate::{
context::{QueryableContext, TransactionalContext},
types::{
address::AccAddress, base::coins::UnsignedCoins, denom::Denom,
store::gas::errors::GasStoreErrors, tx::metadata::Metadata,
address::AccAddress,
base::{coin::UnsignedCoin, coins::UnsignedCoins},
denom::Denom,
store::gas::errors::GasStoreErrors,
tx::metadata::Metadata,
},
x::{errors::BankKeeperError, module::Module},
};

pub trait BalancesKeeper<SK: StoreKey, M: Module>: Clone + Send + Sync + 'static {
fn balance_all<DB: Database, CTX: QueryableContext<DB, SK>>(
&self,
ctx: &CTX,
address: AccAddress,
pagination: Option<Pagination>,
) -> Result<(Option<PaginationResult>, Vec<UnsignedCoin>), GasStoreErrors>;
}

pub trait BankKeeper<SK: StoreKey, M: Module>: Clone + Send + Sync + 'static {
fn send_coins_from_account_to_module<DB: Database, CTX: TransactionalContext<DB, SK>>(
&self,
Expand All @@ -27,7 +40,7 @@ pub trait BankKeeper<SK: StoreKey, M: Module>: Clone + Send + Sync + 'static {
amount: UnsignedCoins,
) -> Result<(), BankKeeperError>;

fn get_denom_metadata<DB: Database, CTX: QueryableContext<DB, SK>>(
fn denom_metadata<DB: Database, CTX: QueryableContext<DB, SK>>(
&self,
ctx: &CTX,
base: &Denom,
Expand Down
12 changes: 4 additions & 8 deletions gears/src/x/keepers/gov.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,11 @@ use crate::{
x::module::Module,
};

use super::bank::BankKeeper;

pub trait GovernanceBankKeeper<SK: StoreKey, M: Module>: BankKeeper<SK, M> {
fn balance_all<DB: Database, CTX: QueryableContext<DB, SK>>(
&self,
ctx: &CTX,
address: &AccAddress,
) -> Result<Vec<UnsignedCoin>, GasStoreErrors>;
use super::bank::{BalancesKeeper, BankKeeper};

pub trait GovernanceBankKeeper<SK: StoreKey, M: Module>:
BankKeeper<SK, M> + BalancesKeeper<SK, M>
{
fn balance<DB: Database, CTX: QueryableContext<DB, SK>>(
&self,
ctx: &CTX,
Expand Down
25 changes: 23 additions & 2 deletions gears/src/x/keepers/mocks/bank.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ use kv_store::StoreKey;

use crate::{
types::{base::coin::UnsignedCoin, store::gas::errors::GasStoreErrors, tx::metadata::Metadata},
x::{errors::BankKeeperError, keepers::bank::BankKeeper, module::Module},
x::{
errors::BankKeeperError,
keepers::bank::{BalancesKeeper, BankKeeper},
module::Module,
},
};

#[derive(former::Former, Clone, Debug)]
Expand All @@ -12,6 +16,23 @@ pub struct MockBankKeeper {
pub balance: UnsignedCoin,
}

impl<SK: StoreKey, M: Module> BalancesKeeper<SK, M> for MockBankKeeper {
fn balance_all<DB: database::Database, CTX: crate::context::QueryableContext<DB, SK>>(
&self,
_ctx: &CTX,
_address: address::AccAddress,
_pagination: Option<extensions::pagination::Pagination>,
) -> Result<
(
Option<extensions::pagination::PaginationResult>,
Vec<UnsignedCoin>,
),
GasStoreErrors,
> {
Ok((None, self.balance_all.clone()))
}
}

impl<SK: StoreKey, M: Module> BankKeeper<SK, M> for MockBankKeeper {
fn send_coins_from_account_to_module<
DB: database::Database,
Expand Down Expand Up @@ -39,7 +60,7 @@ impl<SK: StoreKey, M: Module> BankKeeper<SK, M> for MockBankKeeper {
Ok(())
}

fn get_denom_metadata<DB: database::Database, CTX: crate::context::QueryableContext<DB, SK>>(
fn denom_metadata<DB: database::Database, CTX: crate::context::QueryableContext<DB, SK>>(
&self,
_: &CTX,
_: &crate::types::denom::Denom,
Expand Down
Loading

0 comments on commit a76da44

Please sign in to comment.