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

Init genesis in gov xmod #110

Merged
merged 14 commits into from
Jun 12, 2024
10 changes: 10 additions & 0 deletions Cargo.lock

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

10 changes: 8 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ members = [
"x/auth",
"x/bank",
"x/ibc-rs",
"x/staking",
"x/staking",
"x/gov",

# new unsorted
]
Expand All @@ -42,6 +43,7 @@ nutype = { version = "0.4.0" }
url = { version = "2.5.0" }
time = "0.3.34"
ux = "0.1.6"
chrono = "0.4.38"

# serialization
serde = { version = "1.0", default-features = false }
Expand Down Expand Up @@ -106,4 +108,8 @@ rpassword = { version = "7.2.0" }

[workspace.lints.clippy]
unused_async = "deny"
# large_enum_variant = "deny"
rust_2018_idioms = "deny"
missing_docs = "deny"
missing_debug_implementations = "deny" # opt out where Debug is really redundant
future_incompatible = "deny"
unsafe-code = "deny"
1 change: 1 addition & 0 deletions gears/src/application/keepers/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod params;
34 changes: 34 additions & 0 deletions gears/src/application/keepers/params.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use database::Database;
use kv_store::StoreKey;

use crate::{
context::{InfallibleContext, InfallibleContextMut, QueryableContext, TransactionalContext},
params::{ParamsDeserialize, ParamsSerialize, ParamsSubspaceKey},
types::store::gas::errors::GasStoreErrors,
};

pub trait ParamsKeeper<PSK: ParamsSubspaceKey> {
type Param: ParamsSerialize + ParamsDeserialize;

fn get<DB: Database, SK: StoreKey, CTX: InfallibleContext<DB, SK>>(
&self,
ctx: &CTX,
) -> Self::Param;

fn try_get<DB: Database, SK: StoreKey, CTX: QueryableContext<DB, SK>>(
&self,
ctx: &CTX,
) -> Result<Self::Param, GasStoreErrors>;

fn set<DB: Database, SK: StoreKey, KV: InfallibleContextMut<DB, SK>>(
&self,
ctx: &mut KV,
params: Self::Param,
);

fn try_set<DB: Database, SK: StoreKey, KV: TransactionalContext<DB, SK>>(
&self,
ctx: &mut KV,
params: Self::Param,
) -> Result<(), GasStoreErrors>;
}
1 change: 1 addition & 0 deletions gears/src/application/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod client;
pub mod handlers;
pub mod keepers;
pub mod node;

pub trait ApplicationInfo: Clone + Sync + Send + 'static {
Expand Down
6 changes: 6 additions & 0 deletions gears/src/types/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,12 @@ impl<const PREFIX: u8> BaseAddress<PREFIX> {
}
}

impl<const PREFIX: u8> AsRef<[u8]> for BaseAddress<PREFIX> {
fn as_ref(&self) -> &[u8] {
&self.0
}
}

impl<const PREFIX: u8> Serialize for BaseAddress<PREFIX> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down
2 changes: 1 addition & 1 deletion gears/src/types/store/gas/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod ext;
mod constants;
pub mod errors;
pub mod ext;
pub mod guard;
pub mod kv;
pub mod prefix;
Expand Down
13 changes: 11 additions & 2 deletions gears/src/x/keepers/bank.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ use crate::{
context::{QueryableContext, TransactionalContext},
error::AppError,
types::{
address::AccAddress, base::send::SendCoins, denom::Denom,
store::gas::errors::GasStoreErrors, tx::metadata::Metadata,
address::AccAddress,
base::{coin::Coin, send::SendCoins},
denom::Denom,
store::gas::errors::GasStoreErrors,
tx::metadata::Metadata,
},
x::module::Module,
};
Expand All @@ -25,4 +28,10 @@ pub trait BankKeeper<SK: StoreKey, M: Module>: Clone + Send + Sync + 'static {
ctx: &CTX,
base: &Denom,
) -> Result<Option<Metadata>, GasStoreErrors>;

fn balance_all<DB: Database, CTX: QueryableContext<DB, SK>>(
&self,
ctx: &CTX,
address: &AccAddress,
) -> Result<Vec<Coin>, GasStoreErrors>;
}
9 changes: 9 additions & 0 deletions x/bank/src/keeper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ impl<SK: StoreKey, PSK: ParamsSubspaceKey, AK: AuthKeeper<SK, M>, M: Module> Ban
.unwrap_or_corrupt()
}))
}

fn balance_all<DB: Database, CTX: QueryableContext<DB, SK>>(
&self,
_ctx: &CTX,
_address: &AccAddress,
) -> Result<Vec<Coin>, GasStoreErrors> {
unimplemented!() // TODO:NOW IMPLEMENT THIS ONE
}
}

impl<SK: StoreKey, PSK: ParamsSubspaceKey, AK: AuthKeeper<SK, M>, M: Module>
Expand Down Expand Up @@ -164,6 +172,7 @@ impl<SK: StoreKey, PSK: ParamsSubspaceKey, AK: AuthKeeper<SK, M>, M: Module>
}

// TODO: can we reuse with unwrap from `query_balance`?
// See no issue with it. Except new expect
pub fn balance<DB: Database, CTX: QueryableContext<DB, SK>>(
&self,
ctx: &CTX,
Expand Down
13 changes: 13 additions & 0 deletions x/gov/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "gov"
version = "0.1.0"
edition = "2021"

[dependencies]
gears = { path = "../../gears", features = ["cli", "export", "xmods"] }
serde = { workspace = true }
serde_json = { workspace = true }
chrono = { workspace = true }

[lints]
workspace = true
2 changes: 2 additions & 0 deletions x/gov/src/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub const SERDE_JSON_CONVERSION: &str = "conversion to json shouldn't fail";
pub const EXISTS: &str = "value guaranteed to exists";
28 changes: 28 additions & 0 deletions x/gov/src/genesis.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use crate::{
params::GovParams,
types::{deposit::Deposit, proposal::Proposal, vote::Vote},
};

pub struct GovGenesisState {
pub starting_proposal_id: u64,
pub deposits: Vec<Deposit>,
pub votes: Vec<Vote>,
pub proposals: Vec<Proposal>,
pub params: GovParams,
}

impl Default for GovGenesisState {
fn default() -> Self {
Self {
starting_proposal_id: 1,
deposits: Vec::new(),
votes: Vec::new(),
proposals: Vec::new(),
params: GovParams {
tally: Default::default(),
voting: Default::default(),
deposit: Default::default(),
},
}
}
}
136 changes: 136 additions & 0 deletions x/gov/src/keeper.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
use std::marker::PhantomData;

use gears::{
application::keepers::params::ParamsKeeper,
context::init::InitContext,
params::ParamsSubspaceKey,
store::{database::Database, StoreKey},
types::store::gas::ext::GasResultExt,
x::{keepers::bank::BankKeeper, module::Module},
};

use crate::{
errors::SERDE_JSON_CONVERSION, genesis::GovGenesisState, params::GovParamsKeeper,
types::proposal::ProposalStatus,
};

const PROPOSAL_ID_KEY: [u8; 1] = [0x03];
pub(crate) const KEY_PROPOSAL_PREFIX: [u8; 1] = [0x00];
pub(crate) const KEY_DEPOSIT_PREFIX: [u8; 1] = [0x10];
pub(crate) const KEY_VOTES_PREFIX: [u8; 1] = [0x20];

#[allow(dead_code)]
pub struct GovKeeper<
SK: StoreKey,
PSK: ParamsSubspaceKey,
M: Module,
BM: Module,
BK: BankKeeper<SK, BM>,
> {
store_key: SK,
gov_params_keeper: GovParamsKeeper<PSK>,
gov_mod: M,
bank_keeper: BK,
_bank_marker: PhantomData<BM>,
}

impl<SK: StoreKey, PSK: ParamsSubspaceKey, M: Module, BM: Module, BK: BankKeeper<SK, BM>>
GovKeeper<SK, PSK, M, BM, BK>
{
pub fn new(store_key: SK, params_subspace_key: PSK, gov_mod: M, bank_keeper: BK) -> Self {
Self {
store_key,
gov_params_keeper: GovParamsKeeper {
params_subspace_key,
},
gov_mod,
bank_keeper,
_bank_marker: PhantomData,
}
}

pub fn init_genesis<DB: Database>(
&self,
ctx: &mut InitContext<'_, DB, SK>,
GovGenesisState {
starting_proposal_id,
deposits,
votes,
proposals,
params,
}: GovGenesisState,
) {
{
let mut store = ctx.kv_store_mut(&self.store_key);
store.set(PROPOSAL_ID_KEY, starting_proposal_id.to_be_bytes())
}
self.gov_params_keeper.set(ctx, params);

let total_deposits = {
let mut store_mut = ctx.kv_store_mut(&self.store_key);

let total_deposits = {
let mut total_deposits = Vec::with_capacity(deposits.len());
for deposit in deposits {
store_mut.set(
deposit.key(),
serde_json::to_vec(&deposit).expect(SERDE_JSON_CONVERSION),
); // TODO:NOW IS THIS CORRECT SERIALIZATION?
total_deposits.push(deposit.amount);
}

total_deposits.into_iter().flatten().collect::<Vec<_>>()
};

for vote in votes {
store_mut.set(
vote.key(),
serde_json::to_vec(&vote).expect(SERDE_JSON_CONVERSION),
)
}

for proposal in proposals {
match proposal.status {
ProposalStatus::DepositPeriod => {
store_mut.set(
proposal.inactive_queue_key(),
proposal.proposal_id.to_be_bytes(),
);
}
ProposalStatus::VotingPeriod => store_mut.set(
proposal.active_queue_key(),
proposal.proposal_id.to_be_bytes(),
),
_ => (),
}

store_mut.set(
proposal.key(),
serde_json::to_vec(&proposal).expect(SERDE_JSON_CONVERSION),
);
}

total_deposits
};

let balance = self
.bank_keeper
.balance_all(ctx, &self.gov_mod.get_address())
.unwrap_gas();
/*
Okay. I think that in our implementation there is no need to create account if it.

So I should omit this lines...
if balance.is_empty() || balance.iter().any(|this| this.amount.is_zero()) {
https://github.com/cosmos/cosmos-sdk/blob/d3f09c222243bb3da3464969f0366330dcb977a8/x/gov/genesis.go#L47
}
*/

if !(balance == total_deposits) {
panic!(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So we're expecting that in the bank module init genesis the gov_mod account will be initialized to the right amount?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right. But I need to make sure that it created before usage(I suspected that It doesn't) and additional thing to note is denom.

"expected module account was {:?} but we got {:?}",
balance, total_deposits
)
}
}
}
5 changes: 5 additions & 0 deletions x/gov/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pub mod errors;
pub mod genesis;
pub mod keeper;
pub mod params;
pub mod types;
Loading