Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
4ac196d
inflation and rewards modules
brentstone Feb 8, 2023
0e8b201
storage types and keys for inflation
brentstone Feb 8, 2023
94449a0
log block rewards with accumulator LazyMaps and apply inflation with …
brentstone Feb 8, 2023
92609ca
trigger 2-block countdown to new epoch for Tendermint
brentstone Feb 9, 2023
33ce31f
configure genesis to set up any number of validators
brentstone Feb 9, 2023
efffafd
tests for inflation
brentstone Feb 9, 2023
11fffae
Cargo lock and tomls
brentstone Feb 9, 2023
074027b
update comments and documentation
brentstone Feb 9, 2023
b030fd8
WIP - current changes, debug printouts, etc stuff
brentstone Feb 9, 2023
a41952f
fix e2e test ibc
brentstone Feb 9, 2023
a13f673
upgrade total token supply tracking and balance tracking at genesis
brentstone Feb 9, 2023
6b0dc7f
fix e2e::ledger_tests::proposal_submission
brentstone Feb 9, 2023
6fb79a9
fix e2e::ledger_tests::pos_init_validator error
brentstone Feb 10, 2023
5b818a2
fix e2e::ledger_tests::double_signing_gets_slashed
brentstone Feb 20, 2023
59421c2
clean up documentation and print-outs
brentstone Feb 21, 2023
27c44f4
redo block proposer storage in abciplus mode
brentstone Feb 21, 2023
0b2af59
[ci] wasm checksums update
github-actions[bot] Feb 21, 2023
e427584
changelog: add #714
brentstone Feb 9, 2023
4073702
apps/ledger: only specify num of validators in "dev" build
tzemanovic Mar 14, 2023
dcca4dc
test/finalize_block: extend no-DB commit test to ensure we hit inflation
tzemanovic Mar 14, 2023
c744f89
app/ledger/finalize_block: fix and refactor block proposer look-up
tzemanovic Mar 14, 2023
0bcfed9
app/ledger: tidy up some logging
tzemanovic Mar 14, 2023
04f3392
app/ledger/finalize_block: write inflation + locked ratio via write-log
tzemanovic Mar 14, 2023
fc7fb50
pos/docs: fix docstring typo
tzemanovic Mar 14, 2023
bcd135f
fix block proposer look-up and unit tests
brentstone Mar 14, 2023
869dbbe
fix `value` types in functions that update parameters storage
brentstone Mar 14, 2023
3056d55
clean redundant code and old comments
brentstone Mar 14, 2023
655e689
app/finalize_block: refactor log_block_rewards/apply_inflation
tzemanovic Mar 15, 2023
32b21e7
apps/finalize_block: log error when last proposer is missing
tzemanovic Mar 15, 2023
e9c53ab
core/storage: refactor epoch update tracker
tzemanovic Mar 15, 2023
45f546a
app/node: tidy up some commented out code and logging
tzemanovic Mar 15, 2023
5471a00
Move inflation to core from shared
mariari Jan 13, 2023
2c3c4d4
Add Token Parameters module, and keys like inflation and lock ratio
mariari Jan 13, 2023
b0f315b
Reaplace by hand reward depositing, with a call to mint
mariari Jan 13, 2023
2d42286
Update the update_allowed_conversions to use the pd controller
mariari Jan 16, 2023
8ac033d
Add Parameter data structure for holding an initalizing token params
mariari Jan 16, 2023
7fd7f3c
Add default values for each token parameter
mariari Jan 17, 2023
db46ab5
Add the total token balance to the address of each token account
mariari Jan 17, 2023
8adf4ed
Convert test storage to use the WlStorage and added token initalizer
mariari Jan 17, 2023
77c3e42
Fix dev.toml having inconsistent token values and inconsistent dot
mariari Jan 18, 2023
7739fe4
Change the last inflation amount to reflect the actual amount minted
mariari Feb 21, 2023
878e88e
Update e2e tests
mariari Feb 22, 2023
3db724a
Make the formula for the conversion rates reliable, also dump logs fo…
mariari Feb 24, 2023
efef60c
Now handle native inflation rewards for native tokens.
mariari Mar 16, 2023
95357f3
Corrected the compounding of the MASP transparent balance.
mariari Mar 16, 2023
38bb6bb
Update the test with the correct inflation values
mariari Mar 16, 2023
b0718fe
Merge tag 'v0.16.0' into mariari/inflation-rewards
mariari Jun 5, 2023
67d9ce5
Fixup clippy issues
mariari Jun 14, 2023
5fc78f6
Merge tag 'v0.17.5' into mariari/inflation-rewards
mariari Jun 30, 2023
d92eb8f
Merge branch 'mariari/fixed-amounts-history' into mariari/inflation-r…
mariari Jul 3, 2023
7b3442b
fixup! Continue debugging
mariari Jul 3, 2023
789603c
multiply and divide stuff
juped Jul 6, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changelog/unreleased/features/714-pos-inflation-rewards.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
- Introduce infrastructure for PoS inflation and rewards. Includes inflation
using the PD controller mechanism and rewards based on validator block voting
behavior. Rewards are tracked and effectively distributed using the F1 fee
mechanism. In this PR, rewards are calculated and stored, but they are not
yet applied to voting powers or considered when unbonding and withdrawing.
([#714](https://github.com/anoma/namada/pull/714))
38 changes: 20 additions & 18 deletions apps/src/lib/config/genesis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use namada::types::key::dkg_session_keys::DkgPublicKey;
use namada::types::key::*;
use namada::types::time::{DateTimeUtc, DurationSecs};
use namada::types::token::Denomination;
use namada::types::uint::I256;
use namada::types::{storage, token};

/// Genesis configuration file format
Expand All @@ -38,6 +39,7 @@ pub mod genesis_config {
use namada::types::key::*;
use namada::types::time::Rfc3339String;
use namada::types::token::Denomination;
use namada::types::uint::I256;
use namada::types::{storage, token};
use serde::{Deserialize, Serialize};
use thiserror::Error;
Expand Down Expand Up @@ -210,6 +212,9 @@ pub mod genesis_config {
// Initial balances held by accounts defined elsewhere.
// XXX: u64 doesn't work with toml-rs!
pub balances: Option<HashMap<String, token::Amount>>,
// Token parameters
// XXX: u64 doesn't work with toml-rs!
pub parameters: Option<token::parameters::Parameters>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
Expand Down Expand Up @@ -392,6 +397,9 @@ pub mod genesis_config {
let token_vp_config = wasm.get(token_vp_name).unwrap();

TokenAccount {
last_locked_ratio: Dec::zero(),
last_inflation: I256::zero(),
parameters: config.parameters.as_ref().unwrap().to_owned(),
address: Address::decode(config.address.as_ref().unwrap()).unwrap(),
denom: config.denom,
vp_code_path: token_vp_config.filename.to_owned(),
Expand Down Expand Up @@ -806,6 +814,13 @@ pub struct TokenAccount {
/// Accounts' balances of this token
#[derivative(PartialOrd = "ignore", Ord = "ignore")]
pub balances: HashMap<Address, token::Amount>,
// please put the last inflation amount here.
/// Token parameters
pub parameters: token::parameters::Parameters,
/// Token inflation from the last epoch (read + write for every epoch)
pub last_inflation: I256,
/// Token shielded ratio from the last epoch (read + write for every epoch)
pub last_locked_ratio: Dec,
}

#[derive(
Expand Down Expand Up @@ -881,9 +896,7 @@ pub fn genesis(
}
#[cfg(any(test, feature = "dev"))]
pub fn genesis(num_validators: u64) -> Genesis {
use namada::types::address::{
self, apfel, btc, dot, eth, kartoffel, nam, schnitzel,
};
use namada::types::address::{self};

use crate::wallet;

Expand Down Expand Up @@ -1027,28 +1040,17 @@ pub fn genesis(num_validators: u64) -> Genesis {
balances.insert((&validator.account_key).into(), default_key_tokens);
}

/// Deprecated function, soon to be deleted. Generates default tokens
fn tokens() -> HashMap<Address, (&'static str, Denomination)> {
vec![
(nam(), ("NAM", 6.into())),
(btc(), ("BTC", 8.into())),
(eth(), ("ETH", 18.into())),
(dot(), ("DOT", 10.into())),
(schnitzel(), ("Schnitzel", 6.into())),
(apfel(), ("Apfel", 6.into())),
(kartoffel(), ("Kartoffel", 6.into())),
]
.into_iter()
.collect()
}
let token_accounts = tokens()
let token_accounts = address::tokens()
.into_iter()
.map(|(address, (_, denom))| TokenAccount {
address,
denom,
vp_code_path: vp_token_path.into(),
vp_sha256: Default::default(),
balances: balances.clone(),
parameters: token::parameters::Parameters::default(),
last_inflation: I256::zero(),
last_locked_ratio: Dec::zero(),
})
.collect();
Genesis {
Expand Down
1 change: 0 additions & 1 deletion apps/src/lib/node/ledger/shell/finalize_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -945,7 +945,6 @@ mod test_finalize_block {
use crate::node::ledger::shims::abcipp_shim_types::shim::request::{
FinalizeBlock, ProcessedTx,
};

/// Check that if a wrapper tx was rejected by [`process_proposal`],
/// check that the correct event is returned. Check that it does
/// not appear in the queue of txs to be decrypted
Expand Down
21 changes: 21 additions & 0 deletions apps/src/lib/node/ledger/shell/init_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,8 +277,20 @@ where
vp_code_path,
vp_sha256,
balances,
parameters,
last_inflation,
last_locked_ratio,
} in genesis.token_accounts
{
// Init token parameters and last inflation and caching rates
parameters.init_storage(&address, &mut self.wl_storage);
self.wl_storage
.write(&token::last_inflation(&address), last_inflation)
.unwrap();
self.wl_storage
.write(&token::last_locked_ratio(&address), last_locked_ratio)
.unwrap();

// associate a token with its denomination.
write_denom(
&mut self.wl_storage,
Expand Down Expand Up @@ -313,10 +325,19 @@ where
.write_bytes(&Key::validity_predicate(&address), vp_code_hash)
.unwrap();

let mut total_balance_for_token = token::Amount::default();
for (owner, amount) in balances {
total_balance_for_token += amount;
credit_tokens(&mut self.wl_storage, &address, &owner, amount)
.unwrap();
}
// Write the total amount of tokens for the ratio
self.wl_storage
.write(
&token::total_supply_key(&address),
total_balance_for_token,
)
.unwrap();
}

// Initialize genesis validator accounts
Expand Down
2 changes: 2 additions & 0 deletions apps/src/lib/node/ledger/shell/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1002,6 +1002,7 @@ mod test_utils {
use namada::ledger::storage::mockdb::MockDB;
use namada::ledger::storage::{update_allowed_conversions, Sha256Hasher};
use namada::proto::{Code, Data};
use namada::types::address::init_token_storage;
use namada::types::chain::ChainId;
use namada::types::hash::Hash;
use namada::types::key::*;
Expand Down Expand Up @@ -1235,6 +1236,7 @@ mod test_utils {
.storage
.begin_block(BlockHash::default(), BlockHeight(1))
.expect("begin_block failed");
init_token_storage(&mut shell.wl_storage, 60);
let keypair = gen_keypair();
// enqueue a wrapper tx
let mut wrapper = Tx::new(TxType::Wrapper(Box::new(WrapperTx::new(
Expand Down
2 changes: 2 additions & 0 deletions apps/src/lib/node/ledger/storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ mod tests {
types, update_allowed_conversions, WlStorage,
};
use namada::ledger::storage_api::{self, StorageWrite};
use namada::types::address::init_token_storage;
use namada::types::chain::ChainId;
use namada::types::hash::Hash;
use namada::types::storage::{BlockHash, BlockHeight, Key};
Expand Down Expand Up @@ -143,6 +144,7 @@ mod tests {
storage.block.pred_epochs.new_epoch(BlockHeight(100), 1000);
// make wl_storage to update conversion for a new epoch
let mut wl_storage = WlStorage::new(WriteLog::default(), storage);
init_token_storage(&mut wl_storage, 60);
update_allowed_conversions(&mut wl_storage)
.expect("update conversions failed");
wl_storage.commit_block().expect("commit failed");
Expand Down
59 changes: 57 additions & 2 deletions shared/src/ledger/inflation.rs → core/src/ledger/inflation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
//! proof-of-stake, providing liquity to shielded asset pools, and public goods
//! funding.

use namada_core::types::dec::Dec;

use crate::ledger::storage_api::{self, StorageRead, StorageWrite};
use crate::types::address::Address;
use crate::types::dec::Dec;
use crate::types::token;

/// The domains of inflation
Expand Down Expand Up @@ -47,6 +48,32 @@ pub struct RewardsController {
}

impl RewardsController {
/// Initialize a new PD controller
#[allow(clippy::too_many_arguments)]
pub fn new(
locked_tokens: token::Amount,
total_tokens: token::Amount,
locked_ratio_target: Dec,
locked_ratio_last: Dec,
max_reward_rate: Dec,
last_inflation_amount: token::Amount,
p_gain_nom: Dec,
d_gain_nom: Dec,
epochs_per_year: u64,
) -> Self {
Self {
locked_tokens,
total_tokens,
locked_ratio_target,
locked_ratio_last,
max_reward_rate,
last_inflation_amount,
p_gain_nom,
d_gain_nom,
epochs_per_year,
}
}

/// Calculate a new rewards rate
pub fn run(self) -> ValsToUpdate {
let Self {
Expand Down Expand Up @@ -95,3 +122,31 @@ impl RewardsController {
}
}
}

/// Function that allows the protocol to mint some number of tokens of a desired
/// type to a destination address TODO: think of error cases that must be
/// handled.
pub fn mint_tokens<S>(
storage: &mut S,
target: &Address,
token: &Address,
amount: token::Amount,
) -> storage_api::Result<()>
where
S: StorageWrite + StorageRead,
{
let dest_key = token::balance_key(token, target);
let mut dest_bal: token::Amount =
storage.read(&dest_key)?.unwrap_or_default();
dest_bal.receive(&amount);
storage.write(&dest_key, dest_bal)?;

// Update the total supply of the tokens in storage
let mut total_tokens: token::Amount = storage
.read(&token::total_supply_key(token))?
.unwrap_or_default();
total_tokens.receive(&amount);
storage.write(&token::total_supply_key(token), total_tokens)?;

Ok(())
}
1 change: 1 addition & 0 deletions core/src/ledger/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod gas;
pub mod governance;
#[cfg(any(feature = "abciplus", feature = "abcipp"))]
pub mod ibc;
pub mod inflation;
pub mod parameters;
pub mod replay_protection;
pub mod slash_fund;
Expand Down
Loading