Skip to content

Commit

Permalink
Rename Balance to TokenAmount
Browse files Browse the repository at this point in the history
  • Loading branch information
yanliu38 committed Dec 8, 2024
1 parent f9c9b1b commit 1c0b62b
Show file tree
Hide file tree
Showing 16 changed files with 116 additions and 98 deletions.
6 changes: 3 additions & 3 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use candid::{Decode, Encode, Nat, Principal as IcPrincipal};
use chrono::DateTime;
use dcc_common::{
account_balance_get_as_string, amount_as_string, cursor_from_data,
offerings::do_get_matching_offerings, refresh_caches_from_ledger, reputation_get, Balance,
offerings::do_get_matching_offerings, refresh_caches_from_ledger, reputation_get, TokenAmount,
CursorDirection, DccIdentity, FundsTransfer, IcrcCompatibleAccount, LedgerCursor,
DATA_PULL_BYTES_BEFORE_LEN, DC_TOKEN_DECIMALS_DIV, LABEL_DC_TOKEN_TRANSFER,
};
Expand Down Expand Up @@ -121,9 +121,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
if let Some(transfer_to_account) = arg_matches.get_one::<String>("transfer-to") {
let transfer_to_account = IcrcCompatibleAccount::from(transfer_to_account);
let transfer_amount_e9s = match arg_matches.get_one::<String>("amount-dct") {
Some(value) => value.parse::<Balance>()? * DC_TOKEN_DECIMALS_DIV,
Some(value) => value.parse::<TokenAmount>()? * DC_TOKEN_DECIMALS_DIV,
None => match arg_matches.get_one::<String>("amount-e9s") {
Some(value) => value.parse::<Balance>()?,
Some(value) => value.parse::<TokenAmount>()?,
None => {
panic!("You must specify either --amount-dct or --amount-e9s")
}
Expand Down
33 changes: 16 additions & 17 deletions common/src/account_transfers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use std::cell::RefCell;

use crate::{
account_balance_add, account_balance_get, account_balance_sub, get_timestamp_ns,
ledger_add_reputation_change, slice_to_32_bytes_array, Balance, DccIdentity, TransferError,
ledger_add_reputation_change, slice_to_32_bytes_array, DccIdentity, TokenAmount, TransferError,
LABEL_DC_TOKEN_TRANSFER, MINTING_ACCOUNT, MINTING_ACCOUNT_PRINCIPAL,
};

Expand Down Expand Up @@ -64,8 +64,7 @@ pub fn ledger_funds_transfer(

pub fn charge_fees_to_account_and_bump_reputation(
ledger: &mut LedgerMap,
dcc_identity: &DccIdentity,
amount_e9s: Balance,
amount_e9s: TokenAmount,
) -> Result<(), String> {
if amount_e9s == 0 {
return Ok(());
Expand All @@ -90,7 +89,7 @@ pub fn charge_fees_to_account_and_bump_reputation(
Ok(_) => Ok(ledger_add_reputation_change(
ledger,
dcc_identity,
amount_e9s.min(i64::MAX as Balance) as i64,
amount_e9s.min(i64::MAX as TokenAmount) as i64,
)?),
Err(e) => {
info!("Failed to charge fees: {}", e);
Expand All @@ -102,7 +101,7 @@ pub fn charge_fees_to_account_and_bump_reputation(
pub fn charge_fees_to_account_no_bump_reputation(
ledger: &mut LedgerMap,
dcc_identity: &DccIdentity,
amount_e9s: Balance,
amount_e9s: TokenAmount,
) -> Result<(), String> {
if amount_e9s == 0 {
return Ok(());
Expand Down Expand Up @@ -293,13 +292,13 @@ impl std::fmt::Display for IcrcCompatibleAccount {
pub struct FundsTransferV1 {
pub from: IcrcCompatibleAccount,
pub to: IcrcCompatibleAccount,
pub fee: Option<Balance>,
pub fee: Option<TokenAmount>,
pub fees_accounts: Option<Vec<IcrcCompatibleAccount>>,
pub created_at_time: Option<u64>,
pub memo: Vec<u8>,
pub amount: Balance,
pub balance_from_after: Balance,
pub balance_to_after: Balance,
pub amount: TokenAmount,
pub balance_from_after: TokenAmount,
pub balance_to_after: TokenAmount,
}

#[derive(BorshSerialize, BorshDeserialize, Clone, Debug, PartialEq, Eq)]
Expand All @@ -313,13 +312,13 @@ impl FundsTransfer {
pub fn new(
from: IcrcCompatibleAccount,
to: IcrcCompatibleAccount,
fee: Option<Balance>,
fee: Option<TokenAmount>,
fees_accounts: Option<Vec<IcrcCompatibleAccount>>,
created_at_time: Option<u64>,
memo: Vec<u8>,
amount: Balance,
balance_from_after: Balance,
balance_to_after: Balance,
amount: TokenAmount,
balance_from_after: TokenAmount,
balance_to_after: TokenAmount,
) -> Self {
FundsTransfer::V1(FundsTransferV1 {
from,
Expand All @@ -346,7 +345,7 @@ impl FundsTransfer {
}
}

pub fn fee(&self) -> Option<Balance> {
pub fn fee(&self) -> Option<TokenAmount> {
match self {
FundsTransfer::V1(ft) => ft.fee,
}
Expand All @@ -370,19 +369,19 @@ impl FundsTransfer {
}
}

pub fn amount(&self) -> Balance {
pub fn amount(&self) -> TokenAmount {
match self {
FundsTransfer::V1(ft) => ft.amount,
}
}

pub fn balance_from_after(&self) -> Balance {
pub fn balance_from_after(&self) -> TokenAmount {
match self {
FundsTransfer::V1(ft) => ft.balance_from_after,
}
}

pub fn balance_to_after(&self) -> Balance {
pub fn balance_to_after(&self) -> TokenAmount {
match self {
FundsTransfer::V1(ft) => ft.balance_to_after,
}
Expand Down
14 changes: 7 additions & 7 deletions common/src/account_transfers_errors.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
use icrc_ledger_types::icrc1::transfer::BlockIndex;
use ledger_map::LedgerError;

use crate::Balance;
use crate::TokenAmount;
use crate::Icrc1Account;
use candid::Nat;

#[derive(Debug)]
pub enum TransferError {
BadFee {
expected_fee: Balance,
expected_fee: TokenAmount,
},
BadBurn {
min_burn_amount: Balance,
min_burn_amount: TokenAmount,
},
InsufficientFunds {
account: Icrc1Account,
current_balance: Balance,
requested_amount: Balance,
current_balance: TokenAmount,
requested_amount: TokenAmount,
},
// From amount does not match to amount
AmountMismatch {
from_amount: Balance,
to_amount: Balance,
from_amount: TokenAmount,
to_amount: TokenAmount,
},
TooOld,
CreatedInFuture {
Expand Down
34 changes: 17 additions & 17 deletions common/src/cache_balances.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use crate::account_transfers::IcrcCompatibleAccount;
use crate::{AHashMap, Balance, DC_TOKEN_DECIMALS_DIV};
use crate::{AHashMap, TokenAmount, DC_TOKEN_DECIMALS_DIV};
#[cfg(target_arch = "wasm32")]
#[allow(unused_imports)]
use ic_cdk::println;
use std::{cell::RefCell, collections::HashMap};

thread_local! {
static ACCOUNT_BALANCES: RefCell<AHashMap<IcrcCompatibleAccount, Balance>> = RefCell::new(HashMap::default());
static ACCOUNT_BALANCES: RefCell<AHashMap<IcrcCompatibleAccount, TokenAmount>> = RefCell::new(HashMap::default());
}

pub fn account_balance_get(account: &IcrcCompatibleAccount) -> Balance {
pub fn account_balance_get(account: &IcrcCompatibleAccount) -> TokenAmount {
ACCOUNT_BALANCES.with(|balances| {
let balances = balances.borrow();
balances.get(account).copied().unwrap_or_default()
Expand All @@ -20,22 +20,22 @@ pub fn account_balance_get_as_string(account: &IcrcCompatibleAccount) -> String
amount_as_string(account_balance_get(account))
}

pub fn amount_as_string(amount: Balance) -> String {
pub fn amount_as_string(amount: TokenAmount) -> String {
if amount == 0 {
return "0.0".to_string();
}
format!(
"{}.{}",
amount / DC_TOKEN_DECIMALS_DIV as Balance,
amount % DC_TOKEN_DECIMALS_DIV as Balance
amount / DC_TOKEN_DECIMALS_DIV as TokenAmount,
amount % DC_TOKEN_DECIMALS_DIV as TokenAmount
)
}

#[allow(dead_code)]
pub fn account_balance_sub(
account: &IcrcCompatibleAccount,
amount: Balance,
) -> anyhow::Result<Balance> {
amount: TokenAmount,
) -> anyhow::Result<TokenAmount> {
ACCOUNT_BALANCES.with(|balances| {
let mut balances = balances.borrow_mut();
let balance = balances.entry(account.clone()).or_default();
Expand All @@ -49,8 +49,8 @@ pub fn account_balance_sub(

pub fn account_balance_add(
account: &IcrcCompatibleAccount,
amount: Balance,
) -> anyhow::Result<Balance> {
amount: TokenAmount,
) -> anyhow::Result<TokenAmount> {
ACCOUNT_BALANCES.with(|balances| {
let mut balances = balances.borrow_mut();
let balance = balances.entry(account.clone()).or_default();
Expand Down Expand Up @@ -82,12 +82,12 @@ mod tests {
assert_eq!(account_balance_get(&account_1), 0);
assert_eq!(
account_balance_add(&account_1, 100u32.into()).unwrap(),
100u32 as Balance
100u32 as TokenAmount
);
assert_eq!(account_balance_get(&account_1), 100u32 as Balance);
assert_eq!(account_balance_get(&account_1), 100u32 as TokenAmount);
assert_eq!(
account_balance_sub(&account_1, 50u32.into()).unwrap(),
50u32 as Balance
50u32 as TokenAmount
);
assert_eq!(
account_balance_sub(&account_1, 100u32.into())
Expand All @@ -97,11 +97,11 @@ mod tests {
);
assert_eq!(
account_balance_sub(&account_1, 50u32.into()).unwrap(),
0u32 as Balance
0u32 as TokenAmount
);
assert_eq!(
account_balance_sub(&account_1, 0u32.into()).unwrap(),
0u32 as Balance
0u32 as TokenAmount
);
assert_eq!(
account_balance_sub(&account_1, 1u32.into())
Expand All @@ -111,9 +111,9 @@ mod tests {
);
assert_eq!(
account_balance_add(&account_1, 100u32.into()).unwrap(),
100u32 as Balance
100u32 as TokenAmount
);
account_balances_clear();
assert_eq!(account_balance_get(&account_1), 0u32 as Balance);
assert_eq!(account_balance_get(&account_1), 0u32 as TokenAmount);
}
}
6 changes: 3 additions & 3 deletions common/src/cache_transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ impl RecentCache {

#[cfg(test)]
mod tests {
use crate::{account_balance_get, get_timestamp_ns, Balance, MINTING_ACCOUNT};
use crate::{account_balance_get, get_timestamp_ns, TokenAmount, MINTING_ACCOUNT};

use super::*;
use candid::Principal;
Expand Down Expand Up @@ -200,7 +200,7 @@ mod tests {
fn test_parse_ledger_block() {
RecentCache::clear_cache();

fn create_dummy_funds_transfer(to: u64, amount: Balance) -> FundsTransfer {
fn create_dummy_funds_transfer(to: u64, amount: TokenAmount) -> FundsTransfer {
let account = crate::IcrcCompatibleAccount {
owner: Principal::from_slice(&to.to_be_bytes()),
subaccount: None,
Expand All @@ -222,7 +222,7 @@ mod tests {
// Create a dummy LedgerBlock
let mut entries = Vec::new();
for i in 0..103 {
let transfer = create_dummy_funds_transfer(i, (i + 1) as Balance);
let transfer = create_dummy_funds_transfer(i, (i + 1) as TokenAmount);
let entry = ledger_map::LedgerEntry::new(
LABEL_DC_TOKEN_TRANSFER,
transfer.to_tx_id(),
Expand Down
14 changes: 7 additions & 7 deletions common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@ use std::{collections::HashMap, hash::BuildHasherDefault};
pub type AHashMap<K, V> = HashMap<K, V, BuildHasherDefault<ahash::AHasher>>;

pub const BLOCK_INTERVAL_SECS: u64 = 600;
pub const DC_TOKEN_DECIMALS_DIV: Balance = (10u32 as Balance).pow(DC_TOKEN_DECIMALS as u32);
pub const DC_TOKEN_DECIMALS_DIV: TokenAmount = (10u32 as TokenAmount).pow(DC_TOKEN_DECIMALS as u32);
pub const DC_TOKEN_DECIMALS: u8 = 9;
pub const DC_TOKEN_NAME: &str = "Decent Cloud";
pub const DC_TOKEN_SYMBOL: &str = "DC";
pub const DC_TOKEN_TOTAL_SUPPLY: Balance = 21_000_000 * DC_TOKEN_DECIMALS_DIV;
pub const DC_TOKEN_TRANSFER_FEE_E9S: Balance = 1_000_000;
pub const DC_TOKEN_TOTAL_SUPPLY: TokenAmount = 21_000_000 * DC_TOKEN_DECIMALS_DIV;
pub const DC_TOKEN_TRANSFER_FEE_E9S: TokenAmount = 1_000_000;
pub const DC_TOKEN_LOGO: &str = include_str!("./token-logo.base64");
pub const ED25519_SIGNATURE_LENGTH: usize = 64;
pub const ED25519_SIGN_CONTEXT: &[u8] = b"decent-cloud";
Expand Down Expand Up @@ -105,13 +105,13 @@ pub const DATA_PULL_BYTES_BEFORE_LEN: u16 = 16; // How many bytes before the pul
// python3 -c "from datetime import datetime; print(int(datetime.strptime('2024-01-01 00:00:00', '%Y-%m-%d %H:%M:%S').timestamp()), '* 1_000_000_000')"
pub const FIRST_BLOCK_TIMESTAMP_NS: u64 = 1704063600 * 1_000_000_000;

pub type Balance = u64;
pub type TokenAmount = u64;

pub fn nat_to_balance(nat: &Nat) -> Balance {
pub fn nat_to_balance(nat: &Nat) -> TokenAmount {
nat.0
.to_u128()
.map(|n| n.min(Balance::MAX as u128))
.unwrap_or(0) as Balance
.map(|n| n.min(TokenAmount::MAX as u128))
.unwrap_or(0) as TokenAmount
}

pub fn get_account_from_pubkey(pubkey_bytes: &[u8]) -> IcrcCompatibleAccount {
Expand Down
4 changes: 2 additions & 2 deletions common/src/offerings.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
amount_as_string, charge_fees_to_account_no_bump_reputation, fn_info, reward_e9s_per_block,
warn, Balance, DccIdentity, LABEL_NP_OFFERING, MAX_NP_OFFERING_BYTES,
warn, TokenAmount, DccIdentity, LABEL_NP_OFFERING, MAX_NP_OFFERING_BYTES,
};
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
Expand All @@ -12,7 +12,7 @@ use ic_cdk::println;
use ledger_map::LedgerMap;
use np_offering::Offering;

fn np_offering_update_fee_e9s() -> Balance {
fn np_offering_update_fee_e9s() -> TokenAmount {
reward_e9s_per_block() / 10000
}

Expand Down
4 changes: 2 additions & 2 deletions common/src/platform_specific_x86_64.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::Balance;
use crate::TokenAmount;
use icrc_ledger_types::icrc1::account::Account;
use std::{cell::RefCell, time::Duration};

Expand Down Expand Up @@ -30,6 +30,6 @@ pub(crate) fn get_commit_interval() -> Duration {
COMMIT_INTERVAL.with(|commit_interval| *commit_interval)
}

pub fn ledger_get_account_balance(_account: Account) -> Result<Balance, String> {
pub fn ledger_get_account_balance(_account: Account) -> Result<TokenAmount, String> {
Ok(0)
}
4 changes: 2 additions & 2 deletions common/src/profiles.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
amount_as_string, charge_fees_to_account_no_bump_reputation, fn_info, reputation_get,
reward_e9s_per_block, Balance, DccIdentity, LABEL_NP_PROFILE, MAX_NP_PROFILE_BYTES,
reward_e9s_per_block, DccIdentity, TokenAmount, LABEL_NP_PROFILE, MAX_NP_PROFILE_BYTES,
};
use borsh::{BorshDeserialize, BorshSerialize};
use function_name::named;
Expand All @@ -11,7 +11,7 @@ use ledger_map::LedgerMap;
use np_profile::Profile;
use serde::Serialize;

pub fn np_profile_update_fee_e9s() -> Balance {
pub fn np_profile_update_fee_e9s() -> TokenAmount {
reward_e9s_per_block() / 1000
}

Expand Down
Loading

0 comments on commit 1c0b62b

Please sign in to comment.