Skip to content

Commit

Permalink
refactor(NativeCurrency): Rename NeptuneCoins to NativeCurrencyAmount
Browse files Browse the repository at this point in the history
Also renames a constructor of this struct from `new` to `coins` to
indicate that the argument it takes is a whole number of coins.

This closes #324.

Co-authored-by: Alan Szepieniec <[email protected]>
  • Loading branch information
Sword-Smith and aszepieniec committed Jan 29, 2025
1 parent 6a1c2fe commit a2038ef
Show file tree
Hide file tree
Showing 47 changed files with 813 additions and 721 deletions.
6 changes: 3 additions & 3 deletions docs/src/consensus/neptune-coins.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ Neptune Coins refers to two things
- the native currency coin type for Neptune;
- the unit in which quantities of the former are measured.

In the code, the struct `NeptuneCoins` defines the unit. The native currency type script is encapsulated as a struct `NativeCurrency` implementing trait `ConsensusProgram` in `native_currency.rs`.
In the code, the struct `NativeCurrencyAmount` defines the unit. The native currency type script is encapsulated as a struct `NativeCurrency` implementing trait `ConsensusProgram` in `native_currency.rs`.

## The Unit

One Neptune Coin equals $10^{30} \times 2^2$ *nau*, which stands for Neptune Atomic Unit. The conversion factor is such that
- The largest possible amount, corresponding to 42'000'000 Neptune Coins, can be represented in **127** bits.
- It can represent a number of Neptune Coins with up to 30 decimal symbols after the point exactly.

The struct `NeptuneCoins` is a wrapper around a `u128`. It leaves 1 bit for testing positivity.
The struct `NativeCurrencyAmount` is a wrapper around a `u128`. It leaves 1 bit for testing positivity.

## The Type Script

Expand All @@ -23,4 +23,4 @@ The Neptune Coins type script

## Additional Features

Transactions have two features that make the native currency type script special. The first is the *fee* field, which is the excess of the transaction balance that can be captured by the miner. The second is the option *coinbase* field, which stipulates by how much a transaction is allowed to exceed the sum of input amounts because it is the only transaction in a block.
Transactions have two features that make the native currency type script special. The first is the *fee* field, which is the excess of the transaction balance that can be captured by the miner. The second is the option *coinbase* field, which stipulates by how much a transaction is allowed to exceed the sum of input amounts because it is the only transaction in a block.
4 changes: 2 additions & 2 deletions docs/src/consensus/transaction.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ A transaction kernel consists of the following fields:
- `inputs: Vec<RemovalRecord>` The commitments to the UTXOs that are consumed by this transaction.
- `outputs: Vec<AdditionRecord>` The commitments to the UTXOs that are generated by this transaction.
- `public_announcements: Vec<PublicAnnouncement>` a list of self-identifying strings broadcasted to the world. These may contain encrypted secrets but only the recipient(s) can ascertain that.
- `fee: NeptuneCoins` A reward for the miner who includes this transaction in a block.
- `coinbase: Option<NeptuneCoins>` The miner is allowed to set this field to a mining reward which is determined by various variable network parameters.
- `fee: NativeCurrencyAmount` A reward for the miner who includes this transaction in a block.
- `coinbase: Option<NativeCurrencyAmount>` The miner is allowed to set this field to a mining reward which is determined by various variable network parameters.
- `timestamp: Timestamp` When the transaction took or takes place.
- `mutator_set_hash: Digest` A commitment to the mutator set that is to be updated by the transaction.

Expand Down
13 changes: 9 additions & 4 deletions src/bin/dashboard_src/history_screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crossterm::event::KeyCode;
use crossterm::event::KeyEventKind;
use itertools::Itertools;
use neptune_cash::models::blockchain::block::block_height::BlockHeight;
use neptune_cash::models::blockchain::type_scripts::neptune_coins::NeptuneCoins;
use neptune_cash::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
use neptune_cash::models::proof_abstractions::timestamp::Timestamp;
use neptune_cash::rpc_auth;
use neptune_cash::rpc_server::RPCClient;
Expand All @@ -36,7 +36,12 @@ use unicode_width::UnicodeWidthStr;
use super::dashboard_app::DashboardEvent;
use super::screen::Screen;

type BalanceUpdate = (BlockHeight, Timestamp, NeptuneCoins, NeptuneCoins);
type BalanceUpdate = (
BlockHeight,
Timestamp,
NativeCurrencyAmount,
NativeCurrencyAmount,
);
type BalanceUpdateArc = Arc<std::sync::Mutex<Vec<BalanceUpdate>>>;
type DashboardEventArc = Arc<std::sync::Mutex<Option<DashboardEvent>>>;
type JoinHandleArc = Arc<Mutex<JoinHandle<()>>>;
Expand Down Expand Up @@ -163,9 +168,9 @@ impl HistoryScreen {
_ = &mut balance_history => {
let bh = rpc_client.history(context::current(), token).await.unwrap().unwrap();
let mut history_builder = Vec::with_capacity(bh.len());
let initial_balance = NeptuneCoins::zero();
let initial_balance = NativeCurrencyAmount::zero();
let updates = bh.iter().map(|(_,_,_, delta)| *delta);
let balances = NeptuneCoins::scan_balance(&updates, initial_balance);
let balances = NativeCurrencyAmount::scan_balance(&updates, initial_balance);
for ((_, block_height, timestamp, amount), balance) in bh.iter().zip(balances) {
history_builder.push((*block_height, *timestamp, *amount, balance));
}
Expand Down
8 changes: 4 additions & 4 deletions src/bin/dashboard_src/overview_screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use itertools::Itertools;
use neptune_cash::config_models::network::Network;
use neptune_cash::models::blockchain::block::block_header::BlockHeader;
use neptune_cash::models::blockchain::block::block_height::BlockHeight;
use neptune_cash::models::blockchain::type_scripts::neptune_coins::NeptuneCoins;
use neptune_cash::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
use neptune_cash::models::state::mining_status::MiningStatus;
use neptune_cash::models::state::tx_proving_capability::TxProvingCapability;
use neptune_cash::prelude::twenty_first;
Expand All @@ -36,9 +36,9 @@ use super::screen::Screen;

#[derive(Debug, Clone, Default)]
pub struct OverviewData {
available_balance: Option<NeptuneCoins>,
available_unconfirmed_balance: Option<NeptuneCoins>,
timelocked_balance: Option<NeptuneCoins>,
available_balance: Option<NativeCurrencyAmount>,
available_unconfirmed_balance: Option<NativeCurrencyAmount>,
timelocked_balance: Option<NativeCurrencyAmount>,
confirmations: Option<BlockHeight>,
synchronization_percentage: Option<f64>,

Expand Down
6 changes: 3 additions & 3 deletions src/bin/dashboard_src/send_screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crossterm::event::Event;
use crossterm::event::KeyCode;
use crossterm::event::KeyEventKind;
use neptune_cash::config_models::network::Network;
use neptune_cash::models::blockchain::type_scripts::neptune_coins::NeptuneCoins;
use neptune_cash::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
use neptune_cash::models::state::wallet::address::ReceivingAddress;
use neptune_cash::models::state::wallet::utxo_notification::UtxoNotificationMedium;
use neptune_cash::rpc_auth;
Expand Down Expand Up @@ -105,9 +105,9 @@ impl SendScreen {
refresh_tx.send(()).await.unwrap();

// TODO: Let user specify this number
let fee = NeptuneCoins::zero();
let fee = NativeCurrencyAmount::zero();

let valid_amount = match NeptuneCoins::from_str(&amount) {
let valid_amount = match NativeCurrencyAmount::from_str(&amount) {
Ok(a) => a,
Err(e) => {
*notice_arc.lock().await = format!("amount: {}", e);
Expand Down
14 changes: 7 additions & 7 deletions src/bin/neptune-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use itertools::Itertools;
use neptune_cash::config_models::data_directory::DataDirectory;
use neptune_cash::config_models::network::Network;
use neptune_cash::models::blockchain::block::block_selector::BlockSelector;
use neptune_cash::models::blockchain::type_scripts::neptune_coins::NeptuneCoins;
use neptune_cash::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
use neptune_cash::models::state::wallet::address::KeyType;
use neptune_cash::models::state::wallet::address::ReceivingAddress;
use neptune_cash::models::state::wallet::coin_with_possible_timelock::CoinWithPossibleTimeLock;
Expand Down Expand Up @@ -47,7 +47,7 @@ const ANONYMOUS: &str = "anonymous";
#[derive(Debug, Clone)]
struct TransactionOutput {
address: String,
amount: NeptuneCoins,
amount: NativeCurrencyAmount,
}

/// represents data format of input to claim-utxo
Expand Down Expand Up @@ -108,7 +108,7 @@ impl FromStr for TransactionOutput {

Ok(Self {
address: parts[0].to_string(),
amount: NeptuneCoins::from_str(parts[1])?,
amount: NativeCurrencyAmount::from_str(parts[1])?,
})
}
}
Expand All @@ -117,7 +117,7 @@ impl TransactionOutput {
pub fn to_receiving_address_amount_tuple(
&self,
network: Network,
) -> Result<(ReceivingAddress, NeptuneCoins)> {
) -> Result<(ReceivingAddress, NativeCurrencyAmount)> {
Ok((
ReceivingAddress::from_bech32m(&self.address, network)?,
self.amount,
Expand Down Expand Up @@ -287,10 +287,10 @@ enum Command {
address: String,

/// amount to send
amount: NeptuneCoins,
amount: NativeCurrencyAmount,

/// transaction fee
fee: NeptuneCoins,
fee: NativeCurrencyAmount,

/// local tag for identifying a receiver
receiver_tag: String,
Expand All @@ -303,7 +303,7 @@ enum Command {
/// format: address:amount address:amount ...
#[clap(value_parser, num_args = 1.., required=true, value_delimiter = ' ')]
outputs: Vec<TransactionOutput>,
fee: NeptuneCoins,
fee: NativeCurrencyAmount,
},

/// pause mining
Expand Down
4 changes: 2 additions & 2 deletions src/config_models/cli_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use sysinfo::System;

use super::network::Network;
use crate::job_queue::triton_vm::TritonVmJobPriority;
use crate::models::blockchain::type_scripts::neptune_coins::NeptuneCoins;
use crate::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
use crate::models::proof_abstractions::tasm::program::TritonVmProofJobOptions;
use crate::models::proof_abstractions::tasm::prover_job::ProverJobSettings;
use crate::models::state::tx_proving_capability::TxProvingCapability;
Expand Down Expand Up @@ -128,7 +128,7 @@ pub struct Args {
/// transaction proofs. Foreign transactions where a fee below this
/// threshold cannot be collected by proof upgrading will not be upgraded.
#[clap(long, default_value = "0.01")]
pub(crate) min_gobbling_fee: NeptuneCoins,
pub(crate) min_gobbling_fee: NativeCurrencyAmount,

/// Prune the mempool when it exceeds this size in RAM.
///
Expand Down
6 changes: 3 additions & 3 deletions src/main_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1919,15 +1919,15 @@ mod test {
use crate::job_queue::triton_vm::TritonVmJobQueue;
use crate::models::blockchain::transaction::Transaction;
use crate::models::blockchain::transaction::TransactionProof;
use crate::models::blockchain::type_scripts::neptune_coins::NeptuneCoins;
use crate::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
use crate::models::peer::transfer_transaction::TransactionProofQuality;
use crate::models::proof_abstractions::timestamp::Timestamp;
use crate::models::state::wallet::utxo_notification::UtxoNotificationMedium;

async fn tx_no_outputs(
global_state_lock: &GlobalStateLock,
tx_proof_type: TxProvingCapability,
fee: NeptuneCoins,
fee: NativeCurrencyAmount,
) -> Transaction {
let change_key = global_state_lock
.lock_guard()
Expand Down Expand Up @@ -1996,7 +1996,7 @@ mod test {
"Scheduled task returns OK when run on empty mempool"
);

let fee = NeptuneCoins::new(1);
let fee = NativeCurrencyAmount::coins(1);
let proof_collection_tx = tx_no_outputs(
&main_loop_handler.global_state_lock,
TxProvingCapability::ProofCollection,
Expand Down
18 changes: 9 additions & 9 deletions src/main_loop/proof_upgrader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::models::blockchain::transaction::validity::single_proof::SingleProof;
use crate::models::blockchain::transaction::validity::single_proof::SingleProofWitness;
use crate::models::blockchain::transaction::Transaction;
use crate::models::blockchain::transaction::TransactionProof;
use crate::models::blockchain::type_scripts::neptune_coins::NeptuneCoins;
use crate::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
use crate::models::proof_abstractions::tasm::program::ConsensusProgram;
use crate::models::proof_abstractions::tasm::program::TritonVmProofJobOptions;
use crate::models::proof_abstractions::timestamp::Timestamp;
Expand Down Expand Up @@ -58,7 +58,7 @@ pub enum UpgradeJob {
kernel: TransactionKernel,
proof: ProofCollection,
mutator_set: MutatorSetAccumulator,
gobbling_fee: NeptuneCoins,
gobbling_fee: NativeCurrencyAmount,
},
Merge {
left_kernel: TransactionKernel,
Expand All @@ -67,7 +67,7 @@ pub enum UpgradeJob {
single_proof_right: Proof,
shuffle_seed: [u8; 32],
mutator_set: MutatorSetAccumulator,
gobbling_fee: NeptuneCoins,
gobbling_fee: NativeCurrencyAmount,
},
UpdateMutatorSetData(UpdateMutatorSetDataJob),
}
Expand Down Expand Up @@ -153,11 +153,11 @@ impl UpgradeJob {
}
}

fn gobbling_fee(&self) -> NeptuneCoins {
fn gobbling_fee(&self) -> NativeCurrencyAmount {
match self {
UpgradeJob::ProofCollectionToSingleProof { gobbling_fee, .. } => *gobbling_fee,
UpgradeJob::Merge { gobbling_fee, .. } => *gobbling_fee,
_ => NeptuneCoins::zero(),
_ => NativeCurrencyAmount::zero(),
}
}

Expand All @@ -184,7 +184,7 @@ impl UpgradeJob {
/// Compute the ratio of gobbling fee to number of proofs.
///
/// This number stands in for rate charged for upgrading proofs.
fn profitability(&self) -> NeptuneCoins {
fn profitability(&self) -> NativeCurrencyAmount {
match self {
UpgradeJob::ProofCollectionToSingleProof {
proof: collection,
Expand All @@ -199,7 +199,7 @@ impl UpgradeJob {
rate.div_two();
rate
}
_ => NeptuneCoins::zero(),
_ => NativeCurrencyAmount::zero(),
}
}

Expand Down Expand Up @@ -614,7 +614,7 @@ pub(super) fn get_upgrade_task_from_mempool(
if gobbling_fee >= min_gobbling_fee && tx_origin == TransactionOrigin::Foreign {
gobbling_fee
} else {
NeptuneCoins::zero()
NativeCurrencyAmount::zero()
};
let upgrade_decision = UpgradeJob::ProofCollectionToSingleProof {
kernel: kernel.to_owned(),
Expand Down Expand Up @@ -650,7 +650,7 @@ pub(super) fn get_upgrade_task_from_mempool(
let gobbling_fee = if gobbling_fee >= min_gobbling_fee {
gobbling_fee
} else {
NeptuneCoins::zero()
NativeCurrencyAmount::zero()
};
let mut rng: StdRng = SeedableRng::from_seed(global_state.shuffle_seed());
let upgrade_decision = UpgradeJob::Merge {
Expand Down
6 changes: 3 additions & 3 deletions src/mine_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -895,7 +895,7 @@ pub(crate) mod mine_loop_tests {
use crate::job_queue::triton_vm::TritonVmJobQueue;
use crate::models::blockchain::block::validity::block_primitive_witness::test::deterministic_block_primitive_witness;
use crate::models::blockchain::transaction::validity::single_proof::SingleProof;
use crate::models::blockchain::type_scripts::neptune_coins::NeptuneCoins;
use crate::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
use crate::models::proof_abstractions::mast_hash::MastHash;
use crate::models::proof_abstractions::timestamp::Timestamp;
use crate::models::proof_abstractions::verifier::verify;
Expand Down Expand Up @@ -1139,7 +1139,7 @@ pub(crate) mod mine_loop_tests {
.wallet_secret
.nth_generation_spending_key_for_tests(0);
let output_to_alice = TxOutput::offchain_native_currency(
NeptuneCoins::new(4),
NativeCurrencyAmount::coins(4),
rng.gen(),
alice_key.to_address().into(),
false,
Expand All @@ -1151,7 +1151,7 @@ pub(crate) mod mine_loop_tests {
vec![output_to_alice].into(),
alice_key.into(),
UtxoNotificationMedium::OffChain,
NeptuneCoins::new(1),
NativeCurrencyAmount::coins(1),
now,
TxProvingCapability::SingleProof,
&TritonVmJobQueue::dummy(),
Expand Down
8 changes: 4 additions & 4 deletions src/models/blockchain/block/block_height.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ mod test {
use super::*;
use crate::models::blockchain::block::Block;
use crate::models::blockchain::block::TARGET_BLOCK_INTERVAL;
use crate::models::blockchain::type_scripts::neptune_coins::NeptuneCoins;
use crate::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
use crate::models::proof_abstractions::timestamp::Timestamp;

#[traced_test]
Expand Down Expand Up @@ -171,10 +171,10 @@ mod test {
.checked_sub(&generation_0_subsidy)
.unwrap();

let designated_premine = NeptuneCoins::new(831488);
let designated_premine = NativeCurrencyAmount::coins(831488);
let asymptotic_limit = mineable_amount.checked_add(&designated_premine).unwrap();

let expected_limit = NeptuneCoins::new(42_000_000);
let expected_limit = NativeCurrencyAmount::coins(42_000_000);
assert_eq!(expected_limit, asymptotic_limit);

// Premine is less than promise of 1.98 %
Expand All @@ -187,7 +187,7 @@ mod test {
let actual_premine = Block::premine_distribution()
.iter()
.map(|(_receiving_address, amount)| *amount)
.sum::<NeptuneCoins>();
.sum::<NativeCurrencyAmount>();
assert!(
actual_premine <= designated_premine,
"Distributed premine may not exceed designated value"
Expand Down
8 changes: 4 additions & 4 deletions src/models/blockchain/block/block_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use super::difficulty_control::Difficulty;
use super::difficulty_control::ProofOfWork;
use crate::models::blockchain::block::block_height::BlockHeight;
use crate::models::blockchain::block::Block;
use crate::models::blockchain::type_scripts::neptune_coins::NeptuneCoins;
use crate::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
use crate::models::proof_abstractions::timestamp::Timestamp;
use crate::prelude::twenty_first;

Expand All @@ -25,8 +25,8 @@ pub struct BlockInfo {
pub difficulty: Difficulty,
pub num_inputs: usize,
pub num_outputs: usize,
pub coinbase_amount: NeptuneCoins,
pub fee: NeptuneCoins,
pub coinbase_amount: NativeCurrencyAmount,
pub fee: NativeCurrencyAmount,
pub is_genesis: bool,
pub is_tip: bool,
pub is_canonical: bool,
Expand Down Expand Up @@ -96,7 +96,7 @@ impl BlockInfo {
/// note that this calculated value may be more than the coinbase_amount
/// field because a miner may choose to reward themself less than the
/// calculated reward amount.
pub fn expected_coinbase_amount(&self) -> NeptuneCoins {
pub fn expected_coinbase_amount(&self) -> NativeCurrencyAmount {
Block::block_subsidy(self.height)
}
}
Loading

0 comments on commit a2038ef

Please sign in to comment.