Skip to content

Commit

Permalink
Correcting variable names, documentation, and redundant code.
Browse files Browse the repository at this point in the history
  • Loading branch information
murisi committed Feb 5, 2025
1 parent cb6794c commit a8c2006
Show file tree
Hide file tree
Showing 7 changed files with 47 additions and 48 deletions.
10 changes: 7 additions & 3 deletions crates/core/src/masp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use crate::string_encoding::{
self, MASP_EXT_FULL_VIEWING_KEY_HRP, MASP_EXT_SPENDING_KEY_HRP,
MASP_PAYMENT_ADDRESS_HRP,
};
use crate::token::{Denomination, MaspDigitPos};
use crate::token::{Denomination, MaspDigitPos, NATIVE_MAX_DECIMAL_PLACES};

/// Serialize the given TxId
pub fn serialize_txid<S>(txid: &TxIdInner, s: S) -> Result<S::Ok, S::Error>
Expand Down Expand Up @@ -238,11 +238,15 @@ pub fn encode_asset_type(
.encode()
}

/// Encode the assets that are used for masp rewards
/// Encode the assets that are used for masp rewards. The address supplied to
/// this function must be that of the native token.
pub fn encode_reward_asset_types(
native_token: &Address,
) -> Result<[AssetType; 4], std::io::Error> {
use crate::token::{MaspDigitPos, NATIVE_MAX_DECIMAL_PLACES};
// Construct MASP asset type for rewards. Always deflate and timestamp
// reward tokens with the zeroth epoch to minimize the number of convert
// notes clients have to use. This trick works under the assumption that
// reward tokens will then be reinflated back to the current epoch.
Ok([
encode_asset_type(
native_token.clone(),
Expand Down
8 changes: 2 additions & 6 deletions crates/shielded_token/src/conversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ where
TransToken::read_balance(storage, token, &masp_addr)?;
// Since dated and undated tokens are stored together in the pool, subtract
// the latter to get the dated balance
let masp_dated_balance = read_undated_balance(storage, token)?;
Ok(checked!(total_tokens_in_masp - masp_dated_balance)?)
let masp_undated_balance = read_undated_balance(storage, token)?;
Ok(checked!(total_tokens_in_masp - masp_undated_balance)?)
}

/// Compute the MASP rewards by applying the PD-controller to the genesis
Expand Down Expand Up @@ -319,10 +319,6 @@ where
// The total transparent value of the rewards being distributed
let mut total_reward = Amount::zero();

// Construct MASP asset type for rewards. Always deflate and timestamp
// reward tokens with the zeroth epoch to minimize the number of convert
// notes clients have to use. This trick works under the assumption that
// reward tokens will then be reinflated back to the current epoch.
let reward_assets =
encode_reward_asset_types(&native_token).into_storage_result()?;
// Conversions from the previous to current asset for each address
Expand Down
4 changes: 2 additions & 2 deletions crates/shielded_token/src/masp/shielded_wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1828,10 +1828,10 @@ pub trait ShieldedApi<U: ShieldedUtils + MaybeSend + MaybeSync>:
.encode()
.map_err(|_| eyre!("unable to create asset type"))?;
if self.decode_asset_type(client, asset_type).await.is_none() {
// If we fail to decode the epoched asset type, then remove the
// If we fail to decode the dated asset type, then remove the
// epoch
tracing::debug!(
"Failed to decode epoched asset type, undating it: {:#?}",
"Failed to decode dated asset type, undating it: {:#?}",
decoded
);
decoded.undate();
Expand Down
6 changes: 2 additions & 4 deletions crates/shielded_token/src/storage_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,8 @@ pub fn is_masp_undated_balance_key(key: &storage::Key) -> Option<Address> {
/// Obtain the storage key for the undated balance of a token
pub fn masp_undated_balance_key(token_address: &Address) -> storage::Key {
storage::Key::from(address::MASP.to_db_key())
.push(&MASP_UNDATED_BALANCE_KEY.to_owned())
.expect("Cannot obtain a storage key")
.push(&token_address.to_string().to_db_key())
.expect("Cannot obtain a storage key")
.with_segment(MASP_UNDATED_BALANCE_KEY.to_owned())
.with_segment(token_address.to_string().to_db_key())
}

/// Check if the given storage key is MASP transparent balance key
Expand Down
50 changes: 25 additions & 25 deletions crates/shielded_token/src/vp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ pub struct MaspVp<'ctx, CTX, Params, Gov, Ibc, TransToken, Transfer> {
// Balances changed by a transaction
#[derive(Debug, Clone)]
struct ChangedBalances {
// Maps unepoched asset types to their decodings
unepoched_tokens:
// Maps undated asset types to their decodings
undated_tokens:
BTreeMap<AssetType, (Address, token::Denomination, MaspDigitPos)>,
// Map between MASP transparent address and Namada types
decoder: BTreeMap<TransparentAddress, TAddrData>,
Expand All @@ -66,7 +66,7 @@ struct ChangedBalances {
impl Default for ChangedBalances {
fn default() -> Self {
Self {
unepoched_tokens: Default::default(),
undated_tokens: Default::default(),
decoder: Default::default(),
pre: Default::default(),
post: Default::default(),
Expand Down Expand Up @@ -225,26 +225,26 @@ where
for token in keys_changed.iter().filter_map(is_masp_undated_balance_key)
{
// Read and store the undated balance before this tx is applied
let pre_reward_balance: Amount = ctx
let pre_undated_balance: Amount = ctx
.read_pre(&masp_undated_balance_key(&token))?
.unwrap_or_default();
// Attach the token type to the undated balance
let pre_reward_balance =
ValueSum::from_pair(token.clone(), pre_reward_balance);
let pre_undated_balance =
ValueSum::from_pair(token.clone(), pre_undated_balance);
// Now finally record the undated balance
result.undated_pre =
checked!(result.undated_pre.clone() + &pre_reward_balance)
checked!(result.undated_pre.clone() + &pre_undated_balance)
.map_err(Error::new)?;
// Read and store the undated balance after this tx is applied
let post_reward_balance: Amount = ctx
let post_undated_balance: Amount = ctx
.read_post(&masp_undated_balance_key(&token))?
.unwrap_or_default();
// Attach the token type to the undated balance
let post_reward_balance =
ValueSum::from_pair(token, post_reward_balance);
let post_undated_balance =
ValueSum::from_pair(token, post_undated_balance);
// Now finally record the undated balance
result.undated_post =
checked!(result.undated_post.clone() + &post_reward_balance)
checked!(result.undated_post.clone() + &post_undated_balance)
.map_err(Error::new)?;
}
Ok(result)
Expand Down Expand Up @@ -357,7 +357,7 @@ where
"No denomination found in storage for the given token",
)?;
// Record the token without an epoch to facilitate later decoding
unepoched_tokens(token, denom, &mut result.unepoched_tokens)?;
undated_tokens(token, denom, &mut result.undated_tokens)?;
let counterpart_balance_key =
TransToken::balance_key(token, counterpart);
let pre_balance: Amount =
Expand Down Expand Up @@ -423,7 +423,7 @@ where

// Note the balance changes they imply
let ChangedBalances {
unepoched_tokens,
undated_tokens,
decoder,
pre,
post,
Expand All @@ -438,7 +438,7 @@ where
keys_changed,
)?;
Ok(ChangedBalances {
unepoched_tokens,
undated_tokens,
decoder,
pre,
post,
Expand Down Expand Up @@ -522,7 +522,7 @@ where
&changed_balances.undated_post,
&shielded_tx.sapling_value_balance(),
masp_epoch,
&changed_balances.unepoched_tokens,
&changed_balances.undated_tokens,
conversion_state,
)?;

Expand Down Expand Up @@ -671,7 +671,7 @@ where
}

// Make a map to help recognize asset types lacking an epoch
fn unepoched_tokens(
fn undated_tokens(
token: &Address,
denom: token::Denomination,
tokens: &mut BTreeMap<
Expand Down Expand Up @@ -730,18 +730,18 @@ fn validate_transparent_input<A: Authorization>(
}
// Maybe the asset type has no attached epoch
None if changed_balances
.unepoched_tokens
.undated_tokens
.contains_key(&vin.asset_type) =>
{
let (token, denom, digit) =
&changed_balances.unepoched_tokens[&vin.asset_type];
// Determine what the asset type would be if it were epoched
let epoched_asset_type =
&changed_balances.undated_tokens[&vin.asset_type];
// Determine what the asset type would be if it were dated
let dated_asset_type =
encode_asset_type(token.clone(), *denom, *digit, Some(epoch))
.wrap_err("unable to create asset type")?;
if conversion_state.assets.contains_key(&epoched_asset_type) {
// If such an epoched asset type is available in the
// conversion tree, then we must reject the unepoched
if conversion_state.assets.contains_key(&dated_asset_type) {
// If such a dated asset type is available in the
// conversion tree, then we must reject the undated
// variant
let error =
Error::new_const("epoch is missing from asset type");
Expand Down Expand Up @@ -814,12 +814,12 @@ fn validate_transparent_output(
}
// Maybe the asset type has no attached epoch
None if changed_balances
.unepoched_tokens
.undated_tokens
.contains_key(&out.asset_type) =>
{
// Otherwise note the contribution to this transparent output
let (token, _denom, digit) =
&changed_balances.unepoched_tokens[&out.asset_type];
&changed_balances.undated_tokens[&out.asset_type];
let amount =
token::Amount::from_masp_denominated(out.value, *digit);
*bal_ref = bal_ref
Expand Down
14 changes: 7 additions & 7 deletions crates/token/src/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ where
)))?;
// Record undated balance changes
let mut undated_balances = BTreeMap::new();
let mut asset_types = BTreeMap::new();
let mut undated_asset_types = BTreeMap::new();
let asset_type_err = |err| {
Error::new_alloc(format!("unable to create asset type: {err}"))
};
// First construct a map to decode asset types
for token in tokens {
let Some(denom) = read_denom(env, &token)? else {
Expand All @@ -115,20 +118,17 @@ where
let undated_balance = read_undated_balance(env, &token)?;
// Save the undated balance in a map for updating
undated_balances.insert(token.clone(), I320::from(undated_balance));
let asset_type_err = |err| {
Error::new_alloc(format!("unable to create asset type: {err}"))
};
// Store the encoding for each digit
for digit in MaspDigitPos::iter() {
let atype = encode_asset_type(token.clone(), denom, digit, None)
.map_err(asset_type_err)?;
asset_types.insert(atype, (token.clone(), denom, digit));
undated_asset_types.insert(atype, (token.clone(), denom, digit));
}
}
// Update the undated balances with the Sapling value balance
for (asset_type, val) in shielded.sapling_value_balance().components() {
let Some((token, _denom, digit)) = asset_types.get(asset_type) else {
// Assume that token cannot be decoded because it's epoched
let Some((token, _denom, digit)) = undated_asset_types.get(asset_type) else {
// Assume that token cannot be decoded because it's dated
continue;
};
// Retrieve the current undated balance
Expand Down
3 changes: 2 additions & 1 deletion crates/trans_token/src/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ impl CreditOrDebit for BTreeMap<(Address, Address), Amount> {
///
/// Returns an `Err` if any source has insufficient balance or if the transfer
/// to any destination would overflow (This can only happen if the total supply
/// doesn't fit in `token::Amount`). Returns the set of debited accounts.
/// doesn't fit in `token::Amount`). Returns a pair comprising the set of
/// debited accounts and the set of tokens debited and credited by the transfer.
pub fn multi_transfer<ENV>(
env: &mut ENV,
sources: impl CreditOrDebit,
Expand Down

0 comments on commit a8c2006

Please sign in to comment.