Skip to content

Commit

Permalink
Merge pull request #3482 from anoma/tomas/di-gov
Browse files Browse the repository at this point in the history
DI - governance
  • Loading branch information
mergify[bot] authored Jul 30, 2024
2 parents a7daf2e + 1fbb9fd commit d9b61de
Show file tree
Hide file tree
Showing 15 changed files with 53 additions and 48 deletions.
2 changes: 2 additions & 0 deletions .changelog/unreleased/improvements/3482-di-gov.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- Replaced cross-system dependencies in namada_governance crate with dependency-
injection. ([\#3482](https://github.com/anoma/namada/pull/3482))
2 changes: 0 additions & 2 deletions Cargo.lock

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

2 changes: 0 additions & 2 deletions crates/governance/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,8 @@ namada_core = { path = "../core" }
namada_events = { path = "../events", default-features = false }
namada_macros = { path = "../macros" }
namada_migrations = { path= "../migrations", optional = true }
namada_parameters = { path = "../parameters" }
namada_state = { path = "../state" }
namada_systems = { path = "../systems" }
namada_trans_token = { path = "../trans_token" }
namada_tx = { path = "../tx" }
namada_vp = { path = "../vp" }

Expand Down
19 changes: 9 additions & 10 deletions crates/governance/src/pgf/inflation.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,37 @@
//! PGF lib code.

use namada_core::address::Address;
use namada_parameters::storage as params_storage;
use namada_state::{StorageRead, StorageResult, StorageWrite};
use namada_trans_token::{credit_tokens, get_effective_total_native_supply};
use namada_systems::{parameters, trans_token};

use crate::pgf::storage::{
get_continuous_pgf_payments, get_parameters, get_stewards,
};
use crate::storage::proposal::{PGFIbcTarget, PGFTarget};

/// Apply the PGF inflation.
pub fn apply_inflation<S, F>(
pub fn apply_inflation<S, Params, TransToken, F>(
storage: &mut S,
transfer_over_ibc: F,
) -> StorageResult<()>
where
S: StorageWrite + StorageRead,
Params: parameters::Read<S>,
TransToken: trans_token::Read<S> + trans_token::Write<S>,
F: Fn(&mut S, &Address, &Address, &PGFIbcTarget) -> StorageResult<()>,
{
let pgf_parameters = get_parameters(storage)?;
let staking_token = storage.get_native_token()?;

let epochs_per_year: u64 = storage
.read(&params_storage::get_epochs_per_year_key())?
.expect("Epochs per year should exist in storage");
let total_supply = get_effective_total_native_supply(storage)?;
let epochs_per_year = Params::epochs_per_year(storage)?;
let total_supply = TransToken::get_effective_total_native_supply(storage)?;

let pgf_inflation_amount = total_supply
.mul_floor(pgf_parameters.pgf_inflation_rate)?
.checked_div_u64(epochs_per_year)
.unwrap_or_default();

credit_tokens(
TransToken::credit_tokens(
storage,
&staking_token,
&super::ADDRESS,
Expand All @@ -52,7 +51,7 @@ where

for funding in pgf_fundings {
let result = match &funding.detail {
PGFTarget::Internal(target) => namada_trans_token::transfer(
PGFTarget::Internal(target) => TransToken::transfer(
storage,
&staking_token,
&super::ADDRESS,
Expand Down Expand Up @@ -96,7 +95,7 @@ where
let pgf_steward_reward =
pgf_steward_inflation.mul_floor(percentage)?;

if credit_tokens(
if TransToken::credit_tokens(
storage,
&staking_token,
&address,
Expand Down
8 changes: 5 additions & 3 deletions crates/governance/src/storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ use namada_core::address::Address;
use namada_core::borsh::BorshDeserialize;
use namada_core::collections::HashSet;
use namada_core::storage::Epoch;
use namada_core::token;
use namada_state::{
iter_prefix, StorageError, StorageRead, StorageResult, StorageWrite,
};
use namada_trans_token as token;
use namada_systems::trans_token;

use crate::parameters::GovernanceParameters;
use crate::storage::keys as governance_keys;
Expand All @@ -28,14 +29,15 @@ use crate::utils::{ProposalResult, Vote};
use crate::ADDRESS as governance_address;

/// A proposal creation transaction.
pub fn init_proposal<S>(
pub fn init_proposal<S, TransToken>(
storage: &mut S,
data: &InitProposalData,
content: Vec<u8>,
code: Option<Vec<u8>>,
) -> StorageResult<u64>
where
S: StorageRead + StorageWrite,
TransToken: trans_token::Write<S>,
{
let counter_key = governance_keys::get_counter_key();
let proposal_id = storage.read(&counter_key)?.expect(
Expand Down Expand Up @@ -98,7 +100,7 @@ where
);
storage.write(&committing_proposals_key, ())?;

token::transfer(
TransToken::transfer(
storage,
&storage.get_native_token()?,
&data.author,
Expand Down
13 changes: 7 additions & 6 deletions crates/governance/src/storage/proposal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ use namada_core::address::Address;
use namada_core::hash::Hash;
use namada_core::ibc::core::host::types::identifiers::{ChannelId, PortId};
use namada_core::storage::Epoch;
use namada_core::token;
use namada_macros::BorshDeserializer;
#[cfg(feature = "migrations")]
use namada_migrations::*;
use namada_trans_token::Amount;
use serde::{Deserialize, Serialize};
use thiserror::Error;

Expand Down Expand Up @@ -282,7 +282,7 @@ impl PGFTarget {
}

/// Returns the funding amount
pub fn amount(&self) -> Amount {
pub fn amount(&self) -> token::Amount {
match self {
PGFTarget::Internal(t) => t.amount,
PGFTarget::Ibc(t) => t.amount,
Expand Down Expand Up @@ -323,7 +323,7 @@ pub struct PGFInternalTarget {
/// The target address
pub target: Address,
/// The amount of token to fund the target address
pub amount: Amount,
pub amount: token::Amount,
}

/// The target of a PGF payment
Expand All @@ -343,7 +343,7 @@ pub struct PGFIbcTarget {
/// The target address on the target chain
pub target: String,
/// The amount of token to fund the target address
pub amount: Amount,
pub amount: token::Amount,
/// Port ID to fund
pub port_id: PortId,
/// Channel ID to fund
Expand All @@ -368,7 +368,8 @@ impl borsh::BorshDeserialize for PGFIbcTarget {
) -> std::io::Result<Self> {
use std::io::{Error, ErrorKind};
let target: String = BorshDeserialize::deserialize_reader(reader)?;
let amount: Amount = BorshDeserialize::deserialize_reader(reader)?;
let amount: token::Amount =
BorshDeserialize::deserialize_reader(reader)?;
let port_id: String = BorshDeserialize::deserialize_reader(reader)?;
let port_id: PortId = port_id.parse().map_err(|err| {
Error::new(
Expand Down Expand Up @@ -401,7 +402,7 @@ impl borsh::BorshSchema for PGFIbcTarget {
) {
let fields = borsh::schema::Fields::NamedFields(vec![
("target".into(), String::declaration()),
("amount".into(), Amount::declaration()),
("amount".into(), token::Amount::declaration()),
("port_id".into(), String::declaration()),
("channel_id".into(), String::declaration()),
]);
Expand Down
2 changes: 1 addition & 1 deletion crates/governance/src/vp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1236,11 +1236,11 @@ mod test {
use namada_core::borsh::BorshSerializeExt;
use namada_core::key::testing::keypair_1;
use namada_core::key::RefTo;
use namada_core::parameters::Parameters;
use namada_core::storage::testing::get_dummy_header;
use namada_core::time::DateTimeUtc;
use namada_core::token;
use namada_gas::{TxGasMeter, VpGasMeter};
use namada_parameters::Parameters;
use namada_proof_of_stake::bond_tokens;
use namada_proof_of_stake::test_utils::get_dummy_genesis_validator;
use namada_state::mockdb::MockDB;
Expand Down
11 changes: 5 additions & 6 deletions crates/ibc/src/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ use namada_events::EmitEvents;
use namada_governance::storage::proposal::PGFIbcTarget;
use namada_parameters::read_epoch_duration_parameter;
use namada_state::{
DBIter, Epochs, ResultExt, State, StorageError, StorageHasher, StorageRead,
StorageResult, StorageWrite, WlState, DB,
Epochs, ResultExt, State, StorageError, StorageRead, StorageResult,
StorageWrite,
};
use namada_token as token;

Expand Down Expand Up @@ -182,15 +182,14 @@ impl<S> IbcCommonContext for IbcProtocolContext<'_, S> where
}

/// Transfer tokens over IBC
pub fn transfer_over_ibc<D, H>(
state: &mut WlState<D, H>,
pub fn transfer_over_ibc<S>(
state: &mut S,
token: &Address,
source: &Address,
target: &PGFIbcTarget,
) -> StorageResult<()>
where
D: DB + for<'iter> DBIter<'iter> + 'static,
H: StorageHasher + 'static,
S: State + EmitEvents,
{
let token = PrefixedCoin {
denom: token.to_string().parse().expect("invalid token"),
Expand Down
18 changes: 13 additions & 5 deletions crates/node/src/shell/finalize_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,10 +298,7 @@ where
)?;

// Pgf inflation
pgf_inflation::apply_inflation(
self.state.restrict_writes_to_write_log(),
ibc::transfer_over_ibc,
)?;
pgf_apply_inflation(self.state.restrict_writes_to_write_log())?;

// Take events that may be emitted from PGF
for event in self.state.write_log_mut().take_events() {
Expand Down Expand Up @@ -1149,6 +1146,17 @@ where
)
}

/// Dependency-injection indirection for PGF inflation
fn pgf_apply_inflation<S>(storage: &mut S) -> StorageResult<()>
where
S: State + EmitEvents,
{
pgf_inflation::apply_inflation::<_, parameters::Store<_>, token::Store<_>, _>(
storage,
ibc::transfer_over_ibc,
)
}

/// We test the failure cases of [`finalize_block`]. The happy flows
/// are covered by the e2e tests.
#[allow(clippy::arithmetic_side_effects, clippy::cast_possible_truncation)]
Expand Down Expand Up @@ -1830,7 +1838,7 @@ mod test_finalize_block {
r#type: ProposalType::Default,
};

namada_sdk::governance::init_proposal(
namada_sdk::governance::init_proposal::<_, token::Store<_>>(
&mut shell.state,
&proposal,
vec![],
Expand Down
5 changes: 3 additions & 2 deletions crates/systems/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ lazy_static! {
/// cross-dependencies (with an exception of dev-deps).
static ref SYSTEMS: HashSet<&'static str> =
HashSet::from_iter([
"namada_shielded_token",
"namada_governance",
"namada_parameters",
"namada_trans_token",
"namada_shielded_token",
"namada_token",
"namada_trans_token",
]);
}

Expand Down
6 changes: 3 additions & 3 deletions crates/systems/src/trans_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ pub trait Write<S>: Read<S> {
token: &Address,
src: &Address,
dest: &Address,
amount: Amount,
amount: token::Amount,
) -> Result<()>;

/// Burn a specified amount of tokens from some address. If the burn amount
Expand All @@ -77,7 +77,7 @@ pub trait Write<S>: Read<S> {
storage: &mut S,
token: &Address,
source: &Address,
amount: Amount,
amount: token::Amount,
) -> Result<()>;

/// Credit tokens to an account, to be used only by protocol. In
Expand All @@ -86,6 +86,6 @@ pub trait Write<S>: Read<S> {
storage: &mut S,
token: &Address,
dest: &Address,
amount: Amount,
amount: token::Amount,
) -> Result<()>;
}
2 changes: 1 addition & 1 deletion crates/tx_prelude/src/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use namada_token::event::{TokenEvent, TokenOperation};
#[cfg(any(test, feature = "testing"))]
pub use namada_token::testing;
pub use namada_token::{
storage_key, utils, Amount, DenominatedAmount, Transfer,
storage_key, utils, Amount, DenominatedAmount, Store, Transfer,
};
use namada_tx_env::TxEnv;

Expand Down
2 changes: 0 additions & 2 deletions wasm/Cargo.lock

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

7 changes: 4 additions & 3 deletions wasm/tx_init_proposal/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,10 @@ fn apply_tx(ctx: &mut Ctx, tx_data: BatchedTx) -> TxResult {

log_string("apply_tx called to create a new governance proposal");

let proposal_id =
governance::init_proposal(ctx, &tx_data, content, code)
.wrap_err("Failed to initialize new governance proposal")?;
let proposal_id = governance::init_proposal::<_, token::Store<_>>(
ctx, &tx_data, content, code,
)
.wrap_err("Failed to initialize new governance proposal")?;

ctx.emit_event(GovernanceEvent::new_proposal(proposal_id, tx_data.r#type))
}
2 changes: 0 additions & 2 deletions wasm_for_tests/Cargo.lock

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

0 comments on commit d9b61de

Please sign in to comment.