From bfc5b95cfc4afb75ce66681f985f0b0d74f52435 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 29 Aug 2022 20:03:48 -0700 Subject: [PATCH] WIP: update sdk --- Cargo.lock | 37 ++--- Cargo.toml | 16 +- actors/account/Cargo.toml | 2 +- actors/cron/Cargo.toml | 2 +- actors/cron/src/lib.rs | 4 +- actors/cron/tests/cron_actor_test.rs | 10 +- actors/init/Cargo.toml | 2 +- actors/init/tests/init_actor_test.rs | 15 +- actors/market/Cargo.toml | 2 +- actors/market/src/balance_table.rs | 57 ++++--- actors/market/src/deal.rs | 4 - actors/market/src/ext.rs | 1 - actors/market/src/lib.rs | 20 +-- actors/market/src/policy.rs | 12 +- actors/market/src/state.rs | 8 +- actors/market/src/testing.rs | 7 +- actors/market/src/types.rs | 2 - actors/market/tests/cron_tick_deal_expiry.rs | 4 +- .../market/tests/cron_tick_deal_slashing.rs | 10 +- actors/market/tests/harness.rs | 42 ++--- actors/market/tests/market_actor_test.rs | 122 +++++++------- .../tests/publish_storage_deals_failures.rs | 37 +++-- .../tests/random_cron_epoch_during_publish.rs | 2 - actors/miner/Cargo.toml | 2 +- actors/miner/src/beneficiary.rs | 5 +- actors/miner/src/expiration_queue.rs | 3 +- actors/miner/src/expiration_queue/tests.rs | 2 +- actors/miner/src/ext.rs | 1 - actors/miner/src/internal_tests.rs | 22 +-- actors/miner/src/lib.rs | 18 +- actors/miner/src/monies.rs | 72 ++++---- actors/miner/src/policy.rs | 7 +- actors/miner/src/state.rs | 8 +- actors/miner/src/testing.rs | 15 +- actors/miner/src/types.rs | 10 -- actors/miner/src/vesting_state.rs | 9 +- .../miner/tests/aggregate_network_fee_test.rs | 52 +++--- actors/miner/tests/aggregate_prove_commit.rs | 11 +- actors/miner/tests/apply_rewards.rs | 28 ++-- .../tests/batch_method_network_fees_test.rs | 48 +++--- actors/miner/tests/change_beneficiary_test.rs | 75 +++++---- .../miner/tests/change_owner_address_test.rs | 5 +- actors/miner/tests/change_peer_id_test.rs | 4 +- .../miner/tests/change_worker_address_test.rs | 3 +- .../miner/tests/check_sector_proven_test.rs | 5 +- actors/miner/tests/compact_partitions_test.rs | 10 +- .../tests/compact_sector_numbers_tests.rs | 6 +- .../tests/confirm_update_worker_key_test.rs | 5 +- actors/miner/tests/deadline_cron.rs | 18 +- .../deadline_cron_defers_stops_restarts.rs | 10 +- actors/miner/tests/declare_faults.rs | 11 +- actors/miner/tests/declare_recoveries.rs | 16 +- ...ard_for_power_clampted_at_atto_fil_test.rs | 8 +- actors/miner/tests/expiration_queue.rs | 54 +++--- .../tests/extend_sector_expiration_test.rs | 7 +- .../tests/miner_actor_test_commitment.rs | 22 ++- .../tests/miner_actor_test_construction.rs | 11 +- .../tests/miner_actor_test_partitions.rs | 6 +- .../tests/miner_actor_test_precommit_batch.rs | 24 ++- actors/miner/tests/miner_actor_test_wpost.rs | 50 +++--- actors/miner/tests/monies_test.rs | 18 +- .../tests/pledge_penalty_for_termination.rs | 36 ++-- actors/miner/tests/policy_test.rs | 5 +- ...eposit_and_initial_pledge_positive_test.rs | 10 +- .../miner/tests/precommitted_sector_stores.rs | 18 +- actors/miner/tests/prove_commit.rs | 29 ++-- actors/miner/tests/repay_debt_test.rs | 6 +- actors/miner/tests/repay_debts.rs | 21 ++- actors/miner/tests/report_consensus_fault.rs | 5 +- actors/miner/tests/sector_assignment.rs | 8 +- actors/miner/tests/terminate_sectors_test.rs | 8 +- actors/miner/tests/util.rs | 123 +++++++------- .../miner/tests/vesting_add_locked_funds.rs | 14 +- .../tests/vesting_add_locked_funds_table.rs | 9 +- actors/miner/tests/vesting_unvested_funds.rs | 54 +++--- actors/miner/tests/withdraw_balance.rs | 55 +++--- actors/multisig/Cargo.toml | 3 +- actors/multisig/src/lib.rs | 8 +- actors/multisig/src/state.rs | 12 +- actors/multisig/src/testing.rs | 1 - actors/multisig/src/types.rs | 6 +- actors/multisig/tests/multisig_actor_test.rs | 157 +++++++++--------- actors/paych/Cargo.toml | 2 +- actors/paych/src/lib.rs | 12 +- actors/paych/src/state.rs | 6 +- actors/paych/src/testing.rs | 2 +- actors/paych/src/types.rs | 8 +- actors/paych/tests/paych_actor_test.rs | 35 ++-- actors/power/Cargo.toml | 2 +- actors/power/src/lib.rs | 8 +- actors/power/src/state.rs | 2 - actors/power/src/types.rs | 1 - actors/power/tests/harness/mod.rs | 11 +- actors/power/tests/power_actor_tests.rs | 38 ++--- actors/reward/Cargo.toml | 2 +- actors/reward/src/ext.rs | 3 - actors/reward/src/lib.rs | 11 +- actors/reward/src/logic.rs | 17 +- actors/reward/src/state.rs | 21 +-- actors/reward/src/testing.rs | 4 +- actors/reward/src/types.rs | 3 - actors/reward/tests/reward_actor_test.rs | 73 ++++---- actors/system/Cargo.toml | 2 +- actors/verifreg/Cargo.toml | 2 +- runtime/Cargo.toml | 4 +- runtime/src/builtin/network.rs | 3 - runtime/src/runtime/fvm.rs | 13 +- runtime/src/util/chaos/types.rs | 4 - runtime/tests/alpha_beta_filter_test.rs | 3 +- state/Cargo.toml | 2 +- state/src/check.rs | 6 +- test_vm/Cargo.toml | 2 +- test_vm/src/lib.rs | 34 ++-- test_vm/src/util.rs | 6 +- test_vm/tests/batch_onboarding.rs | 5 +- test_vm/tests/commit_post_test.rs | 25 ++- test_vm/tests/extend_sectors_test.rs | 8 +- test_vm/tests/market_miner_withdrawal_test.rs | 47 +++--- test_vm/tests/multisig_test.rs | 14 +- test_vm/tests/power_scenario_tests.rs | 18 +- test_vm/tests/publish_deals_test.rs | 18 +- test_vm/tests/replica_update_test.rs | 47 +++--- test_vm/tests/terminate_test.rs | 14 +- test_vm/tests/test_vm_test.rs | 36 ++-- test_vm/tests/verifreg_remove_datacap_test.rs | 2 +- 125 files changed, 1104 insertions(+), 1159 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fa6b9a6a80..2822d8e48a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -202,9 +202,6 @@ name = "bimap" version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc0455254eb5c6964c4545d8bac815e1a1be4f3afe0ae695ea539c12d728d44b" -dependencies = [ - "serde", -] [[package]] name = "bitflags" @@ -687,6 +684,7 @@ dependencies = [ "fvm_shared", "indexmap", "integer-encoding", + "lazy_static", "num-derive", "num-traits", "serde", @@ -985,8 +983,6 @@ dependencies = [ [[package]] name = "fvm_ipld_amt" version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48d09e5aa7de45452676d18fcb70b750acd65faae7a4fe18fe784b4c85f869fb" dependencies = [ "ahash", "anyhow", @@ -1002,8 +998,6 @@ dependencies = [ [[package]] name = "fvm_ipld_bitfield" version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af1587207c7455ea70a762d4360f502b6728ea6e2dfbec2b66b6d4d943ee29ae" dependencies = [ "cs_serde_bytes", "fvm_ipld_encoding", @@ -1015,8 +1009,6 @@ dependencies = [ [[package]] name = "fvm_ipld_blockstore" version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "688239a96199577f6705a3f9689abfd795f867f91f5847bc7e236017cc672df7" dependencies = [ "anyhow", "cid", @@ -1041,8 +1033,6 @@ dependencies = [ [[package]] name = "fvm_ipld_encoding" version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce9cfcb4ae444801009182fded790dd56aff9c9a567e54510e2ccf14fb9daf8e" dependencies = [ "anyhow", "cid", @@ -1059,8 +1049,6 @@ dependencies = [ [[package]] name = "fvm_ipld_hamt" version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65b5c939897aa1bfd63e7cb9c458ba10689371af3278ff20d66c6f8ca152c6c0" dependencies = [ "anyhow", "byteorder", @@ -1079,9 +1067,7 @@ dependencies = [ [[package]] name = "fvm_sdk" -version = "1.0.0-rc.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bd162cff8cab78c3798762bc6879429ecbd0f5515856bcb3bc31d197208db70" +version = "2.0.0-alpha.3" dependencies = [ "cid", "fvm_ipld_encoding", @@ -1094,12 +1080,9 @@ dependencies = [ [[package]] name = "fvm_shared" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94c2485c563703b730df0502e2e8fcea86bc183b7018a080c6a5b15b7a29c5d0" +version = "2.0.0-alpha.2" dependencies = [ "anyhow", - "bimap", "blake2b_simd", "byteorder", "cid", @@ -1315,9 +1298,9 @@ dependencies = [ [[package]] name = "multihash" -version = "0.16.2" +version = "0.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3db354f401db558759dfc1e568d010a5d4146f4d3f637be1275ec4a3cf09689" +checksum = "1c346cf9999c631f002d8f977c4eaeaa0e6386f16007202308d0b3757522c2cc" dependencies = [ "blake2b_simd", "blake2s_simd", @@ -1325,6 +1308,7 @@ dependencies = [ "core2", "digest", "multihash-derive", + "ripemd", "serde", "serde-big-array", "sha2", @@ -1591,6 +1575,15 @@ version = "0.6.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49b3de9ec5dc0a3417da371aab17d729997c15010e7fd24ff707773a33bddb64" +[[package]] +name = "ripemd" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1facec54cb5e0dc08553501fa740091086d0259ad0067e0d4103448e4cb22ed3" +dependencies = [ + "digest", +] + [[package]] name = "ryu" version = "1.0.10" diff --git a/Cargo.toml b/Cargo.toml index 77edee448c..ca8f5c181a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,14 +52,14 @@ members = [ "test_vm", ] -#[patch.crates-io] -#fvm_shared = { git = "https://github.com/filecoin-project/ref-fvm" } -#fvm_sdk = { git = "https://github.com/filecoin-project/ref-fvm" } -#fvm_ipld_hamt = { git = "https://github.com/filecoin-project/ref-fvm" } -#fvm_ipld_amt = { git = "https://github.com/filecoin-project/ref-fvm" } -#fvm_ipld_bitfield = { git = "https://github.com/filecoin-project/ref-fvm" } -#fvm_ipld_encoding = { git = "https://github.com/filecoin-project/ref-fvm" } -#fvm_ipld_blockstore = { git = "https://github.com/filecoin-project/ref-fvm" } +[patch.crates-io] +fvm_shared = { git = "https://github.com/filecoin-project/ref-fvm", branch = "backport/token-ops" } +fvm_sdk = { git = "https://github.com/filecoin-project/ref-fvm", branch = "backport/token-ops" } +fvm_ipld_hamt = { git = "https://github.com/filecoin-project/ref-fvm", branch = "backport/token-ops" } +fvm_ipld_amt = { git = "https://github.com/filecoin-project/ref-fvm", branch = "backport/token-ops" } +fvm_ipld_bitfield = { git = "https://github.com/filecoin-project/ref-fvm", branch = "backport/token-ops" } +fvm_ipld_encoding = { git = "https://github.com/filecoin-project/ref-fvm", branch = "backport/token-ops" } +fvm_ipld_blockstore = { git = "https://github.com/filecoin-project/ref-fvm", branch = "backport/token-ops" } ## Uncomment when working locally on ref-fvm and this repo simultaneously. ## Assumes the ref-fvm checkout is in a sibling directory with the same name. diff --git a/actors/account/Cargo.toml b/actors/account/Cargo.toml index febbc1dcc9..fd77ba0814 100644 --- a/actors/account/Cargo.toml +++ b/actors/account/Cargo.toml @@ -14,7 +14,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "9.0.0-alpha.1", path = "../../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } serde = { version = "1.0.136", features = ["derive"] } num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/actors/cron/Cargo.toml b/actors/cron/Cargo.toml index 08825ce03c..ceb4114bd9 100644 --- a/actors/cron/Cargo.toml +++ b/actors/cron/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "9.0.0-alpha.1", path = "../../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } num-traits = "0.2.14" num-derive = "0.3.3" log = "0.4.14" diff --git a/actors/cron/src/lib.rs b/actors/cron/src/lib.rs index 72120f6872..891a53d0fc 100644 --- a/actors/cron/src/lib.rs +++ b/actors/cron/src/lib.rs @@ -10,7 +10,7 @@ use fvm_shared::econ::TokenAmount; use fvm_shared::{MethodNum, METHOD_CONSTRUCTOR}; use num_derive::FromPrimitive; -use num_traits::FromPrimitive; +use num_traits::{FromPrimitive, Zero}; pub use self::state::{Entry, State}; @@ -68,7 +68,7 @@ impl Actor { &entry.receiver, entry.method_num, RawBytes::default(), - TokenAmount::from(0u8), + TokenAmount::zero(), ); if let Err(e) = res { log::error!( diff --git a/actors/cron/tests/cron_actor_test.rs b/actors/cron/tests/cron_actor_test.rs index 6064e66f7c..4b6201a8fe 100644 --- a/actors/cron/tests/cron_actor_test.rs +++ b/actors/cron/tests/cron_actor_test.rs @@ -7,7 +7,9 @@ use fil_actors_runtime::test_utils::*; use fil_actors_runtime::SYSTEM_ACTOR_ADDR; use fvm_ipld_encoding::RawBytes; use fvm_shared::address::Address; +use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; +use num_traits::Zero; fn check_state(rt: &MockRuntime) { let (_, acc) = check_state_invariants(&rt.get_state()); @@ -79,7 +81,7 @@ fn epoch_tick_with_entries() { entry1.receiver, entry1.method_num, RawBytes::default(), - 0u8.into(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -87,7 +89,7 @@ fn epoch_tick_with_entries() { entry2.receiver, entry2.method_num, RawBytes::default(), - 0u8.into(), + TokenAmount::zero(), RawBytes::default(), ExitCode::USR_ILLEGAL_ARGUMENT, ); @@ -95,7 +97,7 @@ fn epoch_tick_with_entries() { entry3.receiver, entry3.method_num, RawBytes::default(), - 0u8.into(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -103,7 +105,7 @@ fn epoch_tick_with_entries() { entry4.receiver, entry4.method_num, RawBytes::default(), - 0u8.into(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); diff --git a/actors/init/Cargo.toml b/actors/init/Cargo.toml index 3daaddb254..f0e1f341f2 100644 --- a/actors/init/Cargo.toml +++ b/actors/init/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "9.0.0-alpha.1", path = "../../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } fvm_ipld_hamt = "0.5.1" serde = { version = "1.0.136", features = ["derive"] } num-traits = "0.2.14" diff --git a/actors/init/tests/init_actor_test.rs b/actors/init/tests/init_actor_test.rs index cbcb9d7541..f3fbbb4ea6 100644 --- a/actors/init/tests/init_actor_test.rs +++ b/actors/init/tests/init_actor_test.rs @@ -16,6 +16,7 @@ use fvm_shared::address::Address; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; use fvm_shared::{HAMT_BIT_WIDTH, METHOD_CONSTRUCTOR}; +use num_traits::Zero; use serde::Serialize; fn check_state(rt: &MockRuntime) { @@ -72,7 +73,7 @@ fn repeated_robust_address() { expected_id_addr, METHOD_CONSTRUCTOR, RawBytes::serialize(&fake_params).unwrap(), - 0u8.into(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -116,8 +117,8 @@ fn create_2_payment_channels() { let pay_channel_string = format!("paych_{}", n); let paych = pay_channel_string.as_bytes(); - rt.set_balance(TokenAmount::from(100)); - rt.value_received = TokenAmount::from(100); + rt.set_balance(TokenAmount::from_atto(100)); + rt.value_received = TokenAmount::from_atto(100); let unique_address = Address::new_actor(paych); rt.new_actor_addr = Some(Address::new_actor(paych)); @@ -129,7 +130,7 @@ fn create_2_payment_channels() { let fake_params = ConstructorParams { network_name: String::from("fake_param") }; // expect anne creating a payment channel to trigger a send to the payment channels constructor - let balance = TokenAmount::from(100u8); + let balance = TokenAmount::from_atto(100u8); rt.expect_send( expected_id_addr, @@ -177,7 +178,7 @@ fn create_storage_miner() { expected_id_addr, METHOD_CONSTRUCTOR, RawBytes::serialize(&fake_params).unwrap(), - 0u8.into(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -228,7 +229,7 @@ fn create_multisig_actor() { expected_id_addr, METHOD_CONSTRUCTOR, RawBytes::serialize(&fake_params).unwrap(), - 0u8.into(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -263,7 +264,7 @@ fn sending_constructor_failure() { expected_id_addr, METHOD_CONSTRUCTOR, RawBytes::serialize(&fake_params).unwrap(), - 0u8.into(), + TokenAmount::zero(), RawBytes::default(), ExitCode::USR_ILLEGAL_STATE, ); diff --git a/actors/market/Cargo.toml b/actors/market/Cargo.toml index 476b32a25d..14aa9150fa 100644 --- a/actors/market/Cargo.toml +++ b/actors/market/Cargo.toml @@ -16,7 +16,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "9.0.0-alpha.1", path = "../../runtime", features = ["fil-actor"] } fvm_ipld_hamt = "0.5.1" -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } fvm_ipld_bitfield = "0.5.2" num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/actors/market/src/balance_table.rs b/actors/market/src/balance_table.rs index 9de8cb0761..d2fb2246de 100644 --- a/actors/market/src/balance_table.rs +++ b/actors/market/src/balance_table.rs @@ -5,16 +5,15 @@ use cid::Cid; use fvm_ipld_blockstore::Blockstore; use fvm_ipld_hamt::Error as HamtError; use fvm_shared::address::Address; -use fvm_shared::bigint::bigint_ser::BigIntDe; use fvm_shared::econ::TokenAmount; -use num_traits::{Signed, Zero}; +use num_traits::Zero; use fil_actors_runtime::{make_empty_map, make_map_with_root_and_bitwidth, Map}; pub const BALANCE_TABLE_BITWIDTH: u32 = 6; /// Balance table which handles getting and updating token balances specifically -pub struct BalanceTable<'a, BS>(pub Map<'a, BS, BigIntDe>); +pub struct BalanceTable<'a, BS>(pub Map<'a, BS, TokenAmount>); impl<'a, BS> BalanceTable<'a, BS> where @@ -38,9 +37,9 @@ where /// Gets token amount for given address in balance table pub fn get(&self, key: &Address) -> Result { if let Some(v) = self.0.get(&key.to_bytes())? { - Ok(v.0.clone()) + Ok(v.clone()) } else { - Ok(0.into()) + Ok(TokenAmount::zero()) } } @@ -54,7 +53,7 @@ where self.0.delete(&key.to_bytes())?; Ok(()) } else { - self.0.set(key.to_bytes().into(), BigIntDe(sum))?; + self.0.set(key.to_bytes().into(), sum)?; Ok(()) } } @@ -93,10 +92,10 @@ where /// Returns total balance held by this balance table #[allow(dead_code)] pub fn total(&self) -> Result { - let mut total = TokenAmount::default(); + let mut total = TokenAmount::zero(); - self.0.for_each(|_, v: &BigIntDe| { - total += &v.0; + self.0.for_each(|_, v: &TokenAmount| { + total += v; Ok(()) })?; @@ -119,7 +118,7 @@ mod tests { let store = MemoryBlockstore::default(); let mut bt = BalanceTable::new(&store); - assert_eq!(bt.total().unwrap(), TokenAmount::from(0u8)); + assert!(bt.total().unwrap().is_zero()); struct TotalTestCase<'a> { amount: u64, @@ -134,9 +133,9 @@ mod tests { ]; for t in cases.iter() { - bt.add(t.addr, &TokenAmount::from(t.amount)).unwrap(); + bt.add(t.addr, &TokenAmount::from_atto(t.amount)).unwrap(); - assert_eq!(bt.total().unwrap(), TokenAmount::from(t.total)); + assert_eq!(bt.total().unwrap(), TokenAmount::from_atto(t.total)); } } @@ -146,29 +145,37 @@ mod tests { let store = MemoryBlockstore::default(); let mut bt = BalanceTable::new(&store); - bt.add(&addr, &TokenAmount::from(80u8)).unwrap(); - assert_eq!(bt.get(&addr).unwrap(), TokenAmount::from(80u8)); + bt.add(&addr, &TokenAmount::from_atto(80u8)).unwrap(); + assert_eq!(bt.get(&addr).unwrap(), TokenAmount::from_atto(80u8)); // Test subtracting past minimum only subtracts correct amount assert_eq!( - bt.subtract_with_minimum(&addr, &TokenAmount::from(20u8), &TokenAmount::from(70u8)) - .unwrap(), - TokenAmount::from(10u8) + bt.subtract_with_minimum( + &addr, + &TokenAmount::from_atto(20u8), + &TokenAmount::from_atto(70u8) + ) + .unwrap(), + TokenAmount::from_atto(10u8) ); - assert_eq!(bt.get(&addr).unwrap(), TokenAmount::from(70u8)); + assert_eq!(bt.get(&addr).unwrap(), TokenAmount::from_atto(70u8)); // Test subtracting to limit assert_eq!( - bt.subtract_with_minimum(&addr, &TokenAmount::from(10u8), &TokenAmount::from(60u8)) - .unwrap(), - TokenAmount::from(10u8) + bt.subtract_with_minimum( + &addr, + &TokenAmount::from_atto(10u8), + &TokenAmount::from_atto(60u8) + ) + .unwrap(), + TokenAmount::from_atto(10u8) ); - assert_eq!(bt.get(&addr).unwrap(), TokenAmount::from(60u8)); + assert_eq!(bt.get(&addr).unwrap(), TokenAmount::from_atto(60u8)); // Test must subtract success - bt.must_subtract(&addr, &TokenAmount::from(10u8)).unwrap(); - assert_eq!(bt.get(&addr).unwrap(), TokenAmount::from(50u8)); + bt.must_subtract(&addr, &TokenAmount::from_atto(10u8)).unwrap(); + assert_eq!(bt.get(&addr).unwrap(), TokenAmount::from_atto(50u8)); // Test subtracting more than available - assert!(bt.must_subtract(&addr, &TokenAmount::from(100u8)).is_err()); + assert!(bt.must_subtract(&addr, &TokenAmount::from_atto(100u8)).is_err()); } } diff --git a/actors/market/src/deal.rs b/actors/market/src/deal.rs index 8d9a86a68b..6614618761 100644 --- a/actors/market/src/deal.rs +++ b/actors/market/src/deal.rs @@ -6,7 +6,6 @@ use fil_actors_runtime::DealWeight; use fvm_ipld_encoding::tuple::*; use fvm_ipld_encoding::{BytesSer, Cbor}; use fvm_shared::address::Address; -use fvm_shared::bigint::bigint_ser; use fvm_shared::clock::ChainEpoch; use fvm_shared::commcid::{FIL_COMMITMENT_UNSEALED, SHA2_256_TRUNC254_PADDED}; use fvm_shared::crypto::signature::Signature; @@ -108,12 +107,9 @@ pub struct DealProposal { // otherwise it is invalid. pub start_epoch: ChainEpoch, pub end_epoch: ChainEpoch, - #[serde(with = "bigint_ser")] pub storage_price_per_epoch: TokenAmount, - #[serde(with = "bigint_ser")] pub provider_collateral: TokenAmount, - #[serde(with = "bigint_ser")] pub client_collateral: TokenAmount, } diff --git a/actors/market/src/ext.rs b/actors/market/src/ext.rs index efddd9af11..1b17fffefd 100644 --- a/actors/market/src/ext.rs +++ b/actors/market/src/ext.rs @@ -52,7 +52,6 @@ pub mod power { pub raw_byte_power: StoragePower, #[serde(with = "bigint_ser")] pub quality_adj_power: StoragePower, - #[serde(with = "bigint_ser")] pub pledge_collateral: TokenAmount, pub quality_adj_power_smoothed: FilterEstimate, } diff --git a/actors/market/src/lib.rs b/actors/market/src/lib.rs index 22a7d8f6df..3913b04d87 100644 --- a/actors/market/src/lib.rs +++ b/actors/market/src/lib.rs @@ -20,7 +20,7 @@ use fvm_shared::sector::{RegisteredSealProof, SectorSize, StoragePower}; use fvm_shared::{ActorID, MethodNum, METHOD_CONSTRUCTOR, METHOD_SEND}; use log::info; use num_derive::FromPrimitive; -use num_traits::{FromPrimitive, Signed, Zero}; +use num_traits::{FromPrimitive, Zero}; use fil_actors_runtime::cbor::serialize_vec; use fil_actors_runtime::runtime::builtins::Type; @@ -114,7 +114,7 @@ impl Actor { { let msg_value = rt.message().value_received(); - if msg_value <= TokenAmount::from(0) { + if msg_value <= TokenAmount::zero() { return Err(actor_error!( illegal_argument, "balance to add must be greater than zero was: {}", @@ -163,7 +163,7 @@ impl Actor { BS: Blockstore, RT: Runtime, { - if params.amount < TokenAmount::from(0) { + if params.amount < TokenAmount::zero() { return Err(actor_error!(illegal_argument, "negative amount: {}", params.amount)); } @@ -351,7 +351,7 @@ impl Actor { deal.proposal.provider = Address::new_id(provider_id); deal.proposal.client = Address::new_id(client_id); - let pcid = deal.proposal.cid().map_err( + let pcid = deal_cid(rt, &deal.proposal).map_err( |e| actor_error!(illegal_argument; "failed to take cid of proposal {}: {}", di, e), )?; @@ -597,7 +597,7 @@ impl Actor { })? .ok_or_else(|| actor_error!(not_found, "no such deal_id: {}", deal_id))?; - let propc = cid(rt, proposal)?; + let propc = deal_cid(rt, proposal)?; let has = msm.pending_deals.as_ref().unwrap().has(&propc.to_bytes()).map_err(|e| { @@ -768,7 +768,7 @@ impl Actor { { rt.validate_immediate_caller_is(std::iter::once(&*CRON_ACTOR_ADDR))?; - let mut amount_slashed = BigInt::zero(); + let mut amount_slashed = TokenAmount::zero(); let curr_epoch = rt.curr_epoch(); let mut timed_out_verified_deals: Vec = Vec::new(); @@ -822,7 +822,7 @@ impl Actor { })? .clone(); - let dcid = cid(rt, &deal)?; + let dcid = deal_cid(rt, &deal)?; let state = msm .deal_states @@ -1293,7 +1293,7 @@ where pub const DAG_CBOR: u64 = 0x71; // TODO is there a better place to get this? -fn cid(rt: &RT, proposal: &DealProposal) -> Result +pub(crate) fn deal_cid(rt: &RT, proposal: &DealProposal) -> Result where BS: Blockstore, RT: Runtime, @@ -1346,7 +1346,7 @@ where &REWARD_ACTOR_ADDR, ext::reward::THIS_EPOCH_REWARD_METHOD, RawBytes::default(), - 0.into(), + TokenAmount::zero(), )?; let ret: ThisEpochRewardReturn = rwret.deserialize()?; Ok(ret.this_epoch_baseline_power) @@ -1365,7 +1365,7 @@ where &STORAGE_POWER_ACTOR_ADDR, ext::power::CURRENT_TOTAL_POWER_METHOD, RawBytes::default(), - 0.into(), + TokenAmount::zero(), )?; let ret: ext::power::CurrentTotalPowerReturnParams = rwret.deserialize()?; Ok((ret.raw_byte_power, ret.quality_adj_power)) diff --git a/actors/market/src/policy.rs b/actors/market/src/policy.rs index b87b30ef0c..3ca161bdc8 100644 --- a/actors/market/src/policy.rs +++ b/actors/market/src/policy.rs @@ -6,7 +6,7 @@ use std::cmp::max; use fil_actors_runtime::network::EPOCHS_IN_DAY; use fil_actors_runtime::runtime::Policy; use fil_actors_runtime::DealWeight; -use fvm_shared::bigint::Integer; +use fvm_shared::bigint::{BigInt, Integer}; use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; use fvm_shared::piece::PaddedPieceSize; @@ -38,7 +38,7 @@ pub(super) fn deal_price_per_epoch_bounds( _size: PaddedPieceSize, _duration: ChainEpoch, ) -> (TokenAmount, &'static TokenAmount) { - (0.into(), &TOTAL_FILECOIN) + (TokenAmount::zero(), &TOTAL_FILECOIN) } pub fn deal_provider_collateral_bounds( @@ -53,12 +53,12 @@ pub fn deal_provider_collateral_bounds( // dealPowerShare = dealRawPower / max(BaselinePower(t), NetworkRawPower(t), dealRawPower) let lock_target_num = network_circulating_supply * policy.prov_collateral_percent_supply_num; - let power_share_num = TokenAmount::from(size.0); + let power_share_num = BigInt::from(size.0); let power_share_denom = max(max(network_raw_power, baseline_power), &power_share_num).clone(); - let num: TokenAmount = power_share_num * lock_target_num; - let denom: TokenAmount = power_share_denom * policy.prov_collateral_percent_supply_denom; - ((num.div_floor(&denom)), TOTAL_FILECOIN.clone()) + let num: BigInt = power_share_num * lock_target_num.atto(); + let denom: BigInt = power_share_denom * policy.prov_collateral_percent_supply_denom; + (TokenAmount::from_atto(num.div_floor(&denom)), TOTAL_FILECOIN.clone()) } pub(super) fn deal_client_collateral_bounds( diff --git a/actors/market/src/state.rs b/actors/market/src/state.rs index 0c2b2a6143..9f0fe5873f 100644 --- a/actors/market/src/state.rs +++ b/actors/market/src/state.rs @@ -12,13 +12,12 @@ use fvm_ipld_blockstore::Blockstore; use fvm_ipld_encoding::tuple::*; use fvm_ipld_encoding::Cbor; use fvm_shared::address::Address; -use fvm_shared::bigint::bigint_ser; use fvm_shared::clock::{ChainEpoch, EPOCH_UNDEFINED}; use fvm_shared::deal::DealID; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; use fvm_shared::HAMT_BIT_WIDTH; -use num_traits::{Signed, Zero}; +use num_traits::Zero; use super::policy::*; use super::types::*; @@ -58,13 +57,10 @@ pub struct State { pub last_cron: ChainEpoch, /// Total Client Collateral that is locked -> unlocked when deal is terminated - #[serde(with = "bigint_ser")] pub total_client_locked_collateral: TokenAmount, /// Total Provider Collateral that is locked -> unlocked when deal is terminated - #[serde(with = "bigint_ser")] pub total_provider_locked_collateral: TokenAmount, /// Total storage fee that is locked in escrow -> unlocked when payments are made - #[serde(with = "bigint_ser")] pub total_client_storage_fee: TokenAmount, } @@ -398,7 +394,7 @@ where let num_epochs_elapsed = payment_end_epoch - payment_start_epoch; let total_payment = &deal.storage_price_per_epoch * num_epochs_elapsed; - if total_payment > 0.into() { + if total_payment.is_positive() { self.transfer_balance(&deal.client, &deal.provider, &total_payment)?; } diff --git a/actors/market/src/testing.rs b/actors/market/src/testing.rs index b808a04737..1ee2db9974 100644 --- a/actors/market/src/testing.rs +++ b/actors/market/src/testing.rs @@ -9,14 +9,13 @@ use fil_actors_runtime::{ make_map_with_root_and_bitwidth, parse_uint_key, MessageAccumulator, SetMultimap, }; use fvm_ipld_blockstore::Blockstore; -use fvm_ipld_encoding::Cbor; use fvm_shared::{ address::{Address, Protocol}, clock::{ChainEpoch, EPOCH_UNDEFINED}, deal::DealID, econ::TokenAmount, }; -use num_traits::{Signed, Zero}; +use num_traits::Zero; use crate::{balance_table::BalanceTable, DealArray, DealMetaArray, State, PROPOSALS_AMT_BITWIDTH}; @@ -90,7 +89,8 @@ pub fn check_state_invariants( match DealArray::load(&state.proposals, store) { Ok(proposals) => { let ret = proposals.for_each(|deal_id, proposal| { - let proposal_cid = proposal.cid()?; + //let proposal_cid = proposal.cid()?; + let proposal_cid = todo!(); if proposal.start_epoch >= current_epoch { expected_deal_ops.insert(deal_id); @@ -212,7 +212,6 @@ pub fn check_state_invariants( (Ok(escrow_table), Ok(lock_table)) => { let mut locked_total = TokenAmount::zero(); let ret = lock_table.0.for_each(|key, locked_amount| { - let locked_amount = &locked_amount.0; let address = Address::from_bytes(key)?; locked_total += locked_amount; diff --git a/actors/market/src/types.rs b/actors/market/src/types.rs index 0cdb08f5f6..b359c5c4f1 100644 --- a/actors/market/src/types.rs +++ b/actors/market/src/types.rs @@ -21,7 +21,6 @@ pub const STATES_AMT_BITWIDTH: u32 = 6; #[derive(Serialize_tuple, Deserialize_tuple)] pub struct WithdrawBalanceParams { pub provider_or_client: Address, - #[serde(with = "bigint_ser")] pub amount: TokenAmount, } @@ -30,7 +29,6 @@ impl Cbor for WithdrawBalanceParams {} #[derive(Serialize_tuple, Deserialize_tuple)] #[serde(transparent)] pub struct WithdrawBalanceReturn { - #[serde(with = "bigint_ser")] pub amount_withdrawn: TokenAmount, } diff --git a/actors/market/tests/cron_tick_deal_expiry.rs b/actors/market/tests/cron_tick_deal_expiry.rs index 47add376a7..f6b027724a 100644 --- a/actors/market/tests/cron_tick_deal_expiry.rs +++ b/actors/market/tests/cron_tick_deal_expiry.rs @@ -5,8 +5,6 @@ use fil_actors_runtime::network::EPOCHS_IN_DAY; use fil_actors_runtime::runtime::Policy; use fvm_shared::clock::ChainEpoch; -use num_traits::Zero; - mod harness; use harness::*; @@ -45,7 +43,7 @@ fn deal_is_correctly_processed_if_first_cron_after_expiry() { let (pay, slashed) = cron_tick_and_assert_balances(&mut rt, CLIENT_ADDR, PROVIDER_ADDR, current, deal_id); let duration = END_EPOCH - START_EPOCH; - assert_eq!(duration * &deal_proposal.storage_price_per_epoch, pay); + assert_eq!(&deal_proposal.storage_price_per_epoch * duration, pay); assert!(slashed.is_zero()); // deal should be deleted as it should have expired diff --git a/actors/market/tests/cron_tick_deal_slashing.rs b/actors/market/tests/cron_tick_deal_slashing.rs index c4b95fb17a..83bbaae42e 100644 --- a/actors/market/tests/cron_tick_deal_slashing.rs +++ b/actors/market/tests/cron_tick_deal_slashing.rs @@ -35,7 +35,7 @@ fn deal_is_slashed() { deal_end: 10 + 200 * EPOCHS_IN_DAY, activation_epoch: 5, termination_epoch: 15, - payment: TokenAmount::from(50), // (15 - 10) * 10 as deal storage fee is 10 per epoch + payment: TokenAmount::from_atto(50), // (15 - 10) * 10 as deal storage fee is 10 per epoch }, Case { name: "deal is slashed at the startepoch and then the first crontick happens", @@ -43,7 +43,7 @@ fn deal_is_slashed() { deal_end: 10 + 200 * EPOCHS_IN_DAY, activation_epoch: 5, termination_epoch: 10, - payment: TokenAmount::from(0), // (10 - 10) * 10 + payment: TokenAmount::zero(), // (10 - 10) * 10 }, Case { name: "deal is slashed before the startepoch and then the first crontick happens", @@ -51,7 +51,7 @@ fn deal_is_slashed() { deal_end: 10 + 200 * EPOCHS_IN_DAY, activation_epoch: 5, termination_epoch: 6, - payment: TokenAmount::from(0), // (10 - 10) * 10 + payment: TokenAmount::zero(), // (10 - 10) * 10 }, Case { name: "deal is terminated at the activation epoch and then the first crontick happens", @@ -59,7 +59,7 @@ fn deal_is_slashed() { deal_end: 10 + 200 * EPOCHS_IN_DAY, activation_epoch: 5, termination_epoch: 5, - payment: TokenAmount::from(0), // (10 - 10) * 10 + payment: TokenAmount::zero(), // (10 - 10) * 10 }, Case { name: "deal is slashed just BEFORE the end epoch", @@ -67,7 +67,7 @@ fn deal_is_slashed() { deal_end: 10 + 200 * EPOCHS_IN_DAY, activation_epoch: 5, termination_epoch: 19, - payment: TokenAmount::from(90), // (19 - 10) * 10 + payment: TokenAmount::from_atto(90), // (19 - 10) * 10 }, ]; for tc in cases { diff --git a/actors/market/tests/harness.rs b/actors/market/tests/harness.rs index 60d99a9b3a..827865dd7c 100644 --- a/actors/market/tests/harness.rs +++ b/actors/market/tests/harness.rs @@ -83,7 +83,7 @@ pub fn setup() -> MockRuntime { caller: *SYSTEM_ACTOR_ADDR, caller_type: *INIT_ACTOR_CODE_ID, actor_code_cids, - balance: RefCell::new(10u64.pow(19).into()), + balance: RefCell::new(TokenAmount::from_whole(10)), ..Default::default() }; @@ -137,7 +137,7 @@ pub fn expect_get_control_addresses( provider, ext::miner::CONTROL_ADDRESSES_METHOD, RawBytes::default(), - BigInt::zero(), + TokenAmount::zero(), RawBytes::serialize(result).unwrap(), ExitCode::OK, ) @@ -354,7 +354,7 @@ pub fn cron_tick_and_assert_balances( let c_escrow = get_escrow_balance(rt, &client_addr).unwrap(); let p_locked = get_locked_balance(rt, provider_addr); let p_escrow = get_escrow_balance(rt, &provider_addr).unwrap(); - let mut amount_slashed = TokenAmount::from(0u8); + let mut amount_slashed = TokenAmount::zero(); let s = get_deal_state(rt, deal_id); let d = get_deal_proposal(rt, deal_id); @@ -387,7 +387,7 @@ pub fn cron_tick_and_assert_balances( payment_start = s.last_updated_epoch; } let duration = payment_end - payment_start; - let payment = duration * d.storage_price_per_epoch; + let payment = d.storage_price_per_epoch * duration; // expected updated amounts let updated_client_escrow = c_escrow - &payment; @@ -397,8 +397,8 @@ pub fn cron_tick_and_assert_balances( // if the deal has expired or been slashed, locked amount will be zero for provider and client. let is_deal_expired = payment_end == d.end_epoch; if is_deal_expired || s.slash_epoch != EPOCH_UNDEFINED { - updated_client_locked = TokenAmount::from(0u8); - updated_provider_locked = TokenAmount::from(0u8); + updated_client_locked = TokenAmount::zero(); + updated_provider_locked = TokenAmount::zero(); } cron_tick(rt); @@ -446,7 +446,7 @@ pub fn publish_deals( addrs.provider, ext::miner::CONTROL_ADDRESSES_METHOD, RawBytes::default(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::serialize(return_value).unwrap(), ExitCode::OK, ); @@ -481,7 +481,7 @@ pub fn publish_deals( *VERIFIED_REGISTRY_ACTOR_ADDR, ext::verifreg::USE_BYTES_METHOD as u64, param, - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -578,15 +578,15 @@ pub fn cron_tick_raw(rt: &mut MockRuntime) -> Result { pub fn expect_query_network_info(rt: &mut MockRuntime) { //networkQAPower //networkBaselinePower - let reward = TokenAmount::from(10u8) * TokenAmount::from(10_i128.pow(18)); + let reward = TokenAmount::from_whole(10); let power = StoragePower::from_i128(1 << 50).unwrap(); - let epoch_reward_smooth = FilterEstimate::new(reward.clone(), BigInt::from(0u8)); + let epoch_reward_smooth = FilterEstimate::new(reward.atto().clone(), BigInt::from(0u8)); let current_power = CurrentTotalPowerReturn { raw_byte_power: StoragePower::default(), quality_adj_power: power.clone(), pledge_collateral: TokenAmount::default(), - quality_adj_power_smoothed: FilterEstimate::new(reward, TokenAmount::default()), + quality_adj_power_smoothed: FilterEstimate::new(reward.atto().clone(), BigInt::zero()), }; let current_reward = ThisEpochRewardReturn { this_epoch_baseline_power: power, @@ -785,9 +785,9 @@ pub fn generate_and_publish_deal_for_piece( piece_size: PaddedPieceSize, ) -> DealID { // generate deal - let storage_per_epoch = BigInt::from(10u8); - let client_collateral = TokenAmount::from(10u8); - let provider_collateral = TokenAmount::from(10u8); + let storage_price_per_epoch = TokenAmount::from_atto(10u8); + let client_collateral = TokenAmount::from_atto(10u8); + let provider_collateral = TokenAmount::from_atto(10u8); let deal = DealProposal { piece_cid, @@ -798,7 +798,7 @@ pub fn generate_and_publish_deal_for_piece( label: Label::String("label".to_string()), start_epoch, end_epoch, - storage_price_per_epoch: storage_per_epoch, + storage_price_per_epoch, provider_collateral, client_collateral, }; @@ -830,8 +830,8 @@ pub fn generate_deal_with_collateral_and_add_funds( rt: &mut MockRuntime, client: Address, addrs: &MinerAddresses, - provider_collateral: BigInt, - client_collateral: BigInt, + provider_collateral: TokenAmount, + client_collateral: TokenAmount, start_epoch: ChainEpoch, end_epoch: ChainEpoch, ) -> DealProposal { @@ -858,7 +858,7 @@ fn generate_deal_proposal_with_collateral( ) -> DealProposal { let piece_cid = make_piece_cid("1".as_bytes()); let piece_size = PaddedPieceSize(2048u64); - let storage_per_epoch = BigInt::from(10u8); + let storage_price_per_epoch = TokenAmount::from_atto(10u8); DealProposal { piece_cid, piece_size, @@ -868,7 +868,7 @@ fn generate_deal_proposal_with_collateral( label: Label::String("label".to_string()), start_epoch, end_epoch, - storage_price_per_epoch: storage_per_epoch, + storage_price_per_epoch, provider_collateral, client_collateral, } @@ -880,8 +880,8 @@ pub fn generate_deal_proposal( start_epoch: ChainEpoch, end_epoch: ChainEpoch, ) -> DealProposal { - let client_collateral = TokenAmount::from(10u8); - let provider_collateral = TokenAmount::from(10u8); + let client_collateral = TokenAmount::from_atto(10u8); + let provider_collateral = TokenAmount::from_atto(10u8); generate_deal_proposal_with_collateral( client, provider, diff --git a/actors/market/tests/market_actor_test.rs b/actors/market/tests/market_actor_test.rs index 59cbf7f475..810b0d7cf9 100644 --- a/actors/market/tests/market_actor_test.rs +++ b/actors/market/tests/market_actor_test.rs @@ -20,7 +20,6 @@ use fil_actors_runtime::{ use fvm_ipld_amt::Amt; use fvm_ipld_encoding::{to_vec, RawBytes}; use fvm_shared::address::Address; -use fvm_shared::bigint::bigint_ser::BigIntDe; use fvm_shared::bigint::BigInt; use fvm_shared::clock::{ChainEpoch, EPOCH_UNDEFINED}; use fvm_shared::crypto::signature::Signature; @@ -33,7 +32,7 @@ use fvm_shared::{HAMT_BIT_WIDTH, METHOD_CONSTRUCTOR, METHOD_SEND}; use regex::Regex; use std::ops::Add; -use num_traits::FromPrimitive; +use num_traits::{FromPrimitive, Zero}; mod harness; @@ -69,7 +68,7 @@ fn simple_construction() { let store = &rt.store; let empty_balance_table = - make_empty_map::<_, BigIntDe>(store, BALANCE_TABLE_BITWIDTH).flush().unwrap(); + make_empty_map::<_, TokenAmount>(store, BALANCE_TABLE_BITWIDTH).flush().unwrap(); let empty_map = make_empty_map::<_, ()>(store, HAMT_BIT_WIDTH).flush().unwrap(); let empty_proposals_array = Amt::<(), _>::new_with_bit_width(store, PROPOSALS_AMT_BITWIDTH).flush().unwrap(); @@ -192,7 +191,7 @@ fn adds_to_provider_escrow_funds() { for tc in &test_cases { rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, *caller_addr); - rt.set_value(TokenAmount::from(tc.delta)); + rt.set_value(TokenAmount::from_atto(tc.delta)); rt.expect_validate_caller_type((*CALLER_TYPES_SIGNABLE).clone()); expect_provider_control_address(&mut rt, PROVIDER_ADDR, OWNER_ADDR, WORKER_ADDR); @@ -209,7 +208,7 @@ fn adds_to_provider_escrow_funds() { assert_eq!( get_escrow_balance(&rt, &PROVIDER_ADDR).unwrap(), - TokenAmount::from(tc.total) + TokenAmount::from_atto(tc.total) ); check_state(&rt); } @@ -220,14 +219,16 @@ fn adds_to_provider_escrow_funds() { fn fails_if_withdraw_from_non_provider_funds_is_not_initiated_by_the_recipient() { let mut rt = setup(); - add_participant_funds(&mut rt, CLIENT_ADDR, TokenAmount::from(20u8)); + add_participant_funds(&mut rt, CLIENT_ADDR, TokenAmount::from_atto(20u8)); - assert_eq!(TokenAmount::from(20u8), get_escrow_balance(&rt, &CLIENT_ADDR).unwrap()); + assert_eq!(TokenAmount::from_atto(20u8), get_escrow_balance(&rt, &CLIENT_ADDR).unwrap()); rt.expect_validate_caller_addr(vec![CLIENT_ADDR]); - let params = - WithdrawBalanceParams { provider_or_client: CLIENT_ADDR, amount: TokenAmount::from(1u8) }; + let params = WithdrawBalanceParams { + provider_or_client: CLIENT_ADDR, + amount: TokenAmount::from_atto(1u8), + }; // caller is not the recipient rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, Address::new_id(909)); @@ -241,7 +242,7 @@ fn fails_if_withdraw_from_non_provider_funds_is_not_initiated_by_the_recipient() rt.verify(); // verify there was no withdrawal - assert_eq!(TokenAmount::from(20u8), get_escrow_balance(&rt, &CLIENT_ADDR).unwrap()); + assert_eq!(TokenAmount::from_atto(20u8), get_escrow_balance(&rt, &CLIENT_ADDR).unwrap()); check_state(&rt); } @@ -267,8 +268,8 @@ fn balance_after_withdrawal_must_always_be_greater_than_or_equal_to_locked_amoun assert_eq!(deal.provider_collateral, get_escrow_balance(&rt, &PROVIDER_ADDR).unwrap()); assert_eq!(deal.client_balance_requirement(), get_escrow_balance(&rt, &CLIENT_ADDR).unwrap()); - let withdraw_amount = TokenAmount::from(1u8); - let withdrawable_amount = TokenAmount::from(0u8); + let withdraw_amount = TokenAmount::from_atto(1u8); + let withdrawable_amount = TokenAmount::zero(); // client cannot withdraw any funds since all it's balance is locked withdraw_client_balance( &mut rt, @@ -287,8 +288,8 @@ fn balance_after_withdrawal_must_always_be_greater_than_or_equal_to_locked_amoun ); // add some more funds to the provider & ensure withdrawal is limited by the locked funds - let withdraw_amount = TokenAmount::from(30u8); - let withdrawable_amount = TokenAmount::from(25u8); + let withdraw_amount = TokenAmount::from_atto(30u8); + let withdrawable_amount = TokenAmount::from_atto(25u8); add_provider_funds(&mut rt, withdrawable_amount.clone(), &MinerAddresses::default()); withdraw_provider_balance( @@ -336,8 +337,8 @@ fn worker_balance_after_withdrawal_must_account_for_slashed_funds() { assert_eq!(publish_epoch + 1, st.slash_epoch); // provider cannot withdraw any funds since all it's balance is locked - let withdraw_amount = TokenAmount::from(1); - let actual_withdrawn = TokenAmount::from(0); + let withdraw_amount = TokenAmount::from_atto(1); + let actual_withdrawn = TokenAmount::zero(); withdraw_provider_balance( &mut rt, withdraw_amount, @@ -348,9 +349,9 @@ fn worker_balance_after_withdrawal_must_account_for_slashed_funds() { ); // add some more funds to the provider & ensure withdrawal is limited by the locked funds - add_provider_funds(&mut rt, TokenAmount::from(25), &MinerAddresses::default()); - let withdraw_amount = TokenAmount::from(30); - let actual_withdrawn = TokenAmount::from(25); + add_provider_funds(&mut rt, TokenAmount::from_atto(25), &MinerAddresses::default()); + let withdraw_amount = TokenAmount::from_atto(30); + let actual_withdrawn = TokenAmount::from_atto(25); withdraw_provider_balance( &mut rt, @@ -367,7 +368,7 @@ fn worker_balance_after_withdrawal_must_account_for_slashed_funds() { fn fails_unless_called_by_an_account_actor() { let mut rt = setup(); - rt.set_value(TokenAmount::from(10)); + rt.set_value(TokenAmount::from_atto(10)); rt.expect_validate_caller_type((*CALLER_TYPES_SIGNABLE).clone()); rt.set_caller(*MINER_ACTOR_CODE_ID, PROVIDER_ADDR); @@ -402,7 +403,7 @@ fn adds_to_non_provider_funds() { for tc in &test_cases { rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, *caller_addr); - rt.set_value(TokenAmount::from(tc.delta)); + rt.set_value(TokenAmount::from_atto(tc.delta)); rt.expect_validate_caller_type((*CALLER_TYPES_SIGNABLE).clone()); assert_eq!( @@ -416,7 +417,10 @@ fn adds_to_non_provider_funds() { rt.verify(); - assert_eq!(get_escrow_balance(&rt, caller_addr).unwrap(), TokenAmount::from(tc.total)); + assert_eq!( + get_escrow_balance(&rt, caller_addr).unwrap(), + TokenAmount::from_atto(tc.total) + ); check_state(&rt); } } @@ -426,13 +430,13 @@ fn adds_to_non_provider_funds() { fn withdraws_from_provider_escrow_funds_and_sends_to_owner() { let mut rt = setup(); - let amount = TokenAmount::from(20); + let amount = TokenAmount::from_atto(20); add_provider_funds(&mut rt, amount.clone(), &MinerAddresses::default()); assert_eq!(amount, get_escrow_balance(&rt, &PROVIDER_ADDR).unwrap()); // worker calls WithdrawBalance, balance is transferred to owner - let withdraw_amount = TokenAmount::from(1); + let withdraw_amount = TokenAmount::from_atto(1); withdraw_provider_balance( &mut rt, withdraw_amount.clone(), @@ -442,7 +446,7 @@ fn withdraws_from_provider_escrow_funds_and_sends_to_owner() { WORKER_ADDR, ); - assert_eq!(TokenAmount::from(19), get_escrow_balance(&rt, &PROVIDER_ADDR).unwrap()); + assert_eq!(TokenAmount::from_atto(19), get_escrow_balance(&rt, &PROVIDER_ADDR).unwrap()); check_state(&rt); } @@ -450,15 +454,15 @@ fn withdraws_from_provider_escrow_funds_and_sends_to_owner() { fn withdraws_from_non_provider_escrow_funds() { let mut rt = setup(); - let amount = TokenAmount::from(20); + let amount = TokenAmount::from_atto(20); add_participant_funds(&mut rt, CLIENT_ADDR, amount.clone()); assert_eq!(get_escrow_balance(&rt, &CLIENT_ADDR).unwrap(), amount); - let withdraw_amount = TokenAmount::from(1); + let withdraw_amount = TokenAmount::from_atto(1); withdraw_client_balance(&mut rt, withdraw_amount.clone(), withdraw_amount, CLIENT_ADDR); - assert_eq!(get_escrow_balance(&rt, &CLIENT_ADDR).unwrap(), TokenAmount::from(19)); + assert_eq!(get_escrow_balance(&rt, &CLIENT_ADDR).unwrap(), TokenAmount::from_atto(19)); check_state(&rt); } @@ -466,14 +470,14 @@ fn withdraws_from_non_provider_escrow_funds() { fn client_withdrawing_more_than_escrow_balance_limits_to_available_funds() { let mut rt = setup(); - let amount = TokenAmount::from(20); + let amount = TokenAmount::from_atto(20); add_participant_funds(&mut rt, CLIENT_ADDR, amount.clone()); // withdraw amount greater than escrow balance - let withdraw_amount = TokenAmount::from(25); + let withdraw_amount = TokenAmount::from_atto(25); withdraw_client_balance(&mut rt, withdraw_amount, amount, CLIENT_ADDR); - assert_eq!(get_escrow_balance(&rt, &CLIENT_ADDR).unwrap(), TokenAmount::from(0)); + assert_eq!(get_escrow_balance(&rt, &CLIENT_ADDR).unwrap(), TokenAmount::zero()); check_state(&rt); } @@ -481,12 +485,12 @@ fn client_withdrawing_more_than_escrow_balance_limits_to_available_funds() { fn worker_withdrawing_more_than_escrow_balance_limits_to_available_funds() { let mut rt = setup(); - let amount = TokenAmount::from(20); + let amount = TokenAmount::from_atto(20); add_provider_funds(&mut rt, amount.clone(), &MinerAddresses::default()); assert_eq!(get_escrow_balance(&rt, &PROVIDER_ADDR).unwrap(), amount); - let withdraw_amount = TokenAmount::from(25); + let withdraw_amount = TokenAmount::from_atto(25); withdraw_provider_balance( &mut rt, withdraw_amount, @@ -496,7 +500,7 @@ fn worker_withdrawing_more_than_escrow_balance_limits_to_available_funds() { WORKER_ADDR, ); - assert_eq!(get_escrow_balance(&rt, &PROVIDER_ADDR).unwrap(), TokenAmount::from(0)); + assert_eq!(get_escrow_balance(&rt, &PROVIDER_ADDR).unwrap(), TokenAmount::zero()); check_state(&rt); } @@ -505,7 +509,7 @@ fn fail_when_balance_is_zero() { let mut rt = setup(); rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, OWNER_ADDR); - rt.set_received(BigInt::from(0_i32)); + rt.set_received(TokenAmount::zero()); expect_abort( ExitCode::USR_ILLEGAL_ARGUMENT, @@ -525,7 +529,7 @@ fn fails_with_a_negative_withdraw_amount() { let params = WithdrawBalanceParams { provider_or_client: PROVIDER_ADDR, - amount: TokenAmount::from(-1_i32), + amount: TokenAmount::from_atto(-1_i32), }; expect_abort( @@ -544,15 +548,17 @@ fn fails_with_a_negative_withdraw_amount() { fn fails_if_withdraw_from_provider_funds_is_not_initiated_by_the_owner_or_worker() { let mut rt = setup(); - let amount = TokenAmount::from(20u8); + let amount = TokenAmount::from_atto(20u8); add_provider_funds(&mut rt, amount.clone(), &MinerAddresses::default()); assert_eq!(get_escrow_balance(&rt, &PROVIDER_ADDR).unwrap(), amount); // only signing parties can add balance for client AND provider. rt.expect_validate_caller_addr(vec![OWNER_ADDR, WORKER_ADDR]); - let params = - WithdrawBalanceParams { provider_or_client: PROVIDER_ADDR, amount: TokenAmount::from(1u8) }; + let params = WithdrawBalanceParams { + provider_or_client: PROVIDER_ADDR, + amount: TokenAmount::from_atto(1u8), + }; // caller is not owner or worker rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, Address::new_id(909)); @@ -790,7 +796,7 @@ fn provider_and_client_addresses_are_resolved_before_persisting_state_and_sent_t *VERIFIED_REGISTRY_ACTOR_ADDR, ext::verifreg::USE_BYTES_METHOD as u64, param, - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -859,11 +865,11 @@ fn publish_a_deal_with_enough_collateral_when_circulating_supply_is_superior_to_ let mut rt = setup(); - let client_collateral = TokenAmount::from(10u8); // min is zero so this is placeholder + let client_collateral = TokenAmount::from_atto(10u8); // min is zero so this is placeholder // given power and circ supply cancel this should be 1*dealqapower / 100 let deal_size = PaddedPieceSize(2048u64); // generateDealProposal's deal size - let provider_collateral = TokenAmount::from( + let provider_collateral = TokenAmount::from_atto( (deal_size.0 * (policy.prov_collateral_percent_supply_num as u64)) / policy.prov_collateral_percent_supply_denom as u64, ); @@ -878,7 +884,7 @@ fn publish_a_deal_with_enough_collateral_when_circulating_supply_is_superior_to_ end_epoch, ); let qa_power = StoragePower::from_i128(1 << 50).unwrap(); - rt.set_circulating_supply(qa_power); // convenient for these two numbers to cancel out + rt.set_circulating_supply(TokenAmount::from_atto(qa_power)); // convenient for these two numbers to cancel out // publish the deal successfully rt.set_epoch(publish_epoch); @@ -1188,8 +1194,8 @@ fn crontick_for_a_deal_at_its_start_epoch_results_in_zero_payment_and_no_slashin rt.set_epoch(current); let (pay, slashed) = cron_tick_and_assert_balances(&mut rt, CLIENT_ADDR, PROVIDER_ADDR, current, deal_id); - assert_eq!(TokenAmount::from(0u8), pay); - assert_eq!(TokenAmount::from(0u8), slashed); + assert_eq!(TokenAmount::zero(), pay); + assert_eq!(TokenAmount::zero(), slashed); // deal proposal and state should NOT be deleted get_deal_proposal(&mut rt, deal_id); @@ -1434,9 +1440,9 @@ fn locked_fund_tracking_states() { let st: State = rt.get_state(); // assert values are zero - assert_eq!(st.total_client_locked_collateral, BigInt::from(0_i32)); - assert_eq!(st.total_provider_locked_collateral, BigInt::from(0_i32)); - assert_eq!(st.total_client_storage_fee, BigInt::from(0_i32)); + assert!(st.total_client_locked_collateral.is_zero()); + assert!(st.total_provider_locked_collateral.is_zero()); + assert!(st.total_client_storage_fee.is_zero()); // Publish deal1, deal2, and deal3 with different client and provider let deal_id1 = generate_and_publish_deal(&mut rt, c1, &m1, start_epoch, end_epoch); @@ -1475,7 +1481,7 @@ fn locked_fund_tracking_states() { ); cron_tick(&mut rt); let duration = curr - start_epoch; - let payment = BigInt::from(2_i32) * &d1.storage_price_per_epoch * duration; + let payment: TokenAmount = 2 * &d1.storage_price_per_epoch * duration; let mut csf = (csf - payment) - d3.total_storage_fee(); let mut plc = plc - d3.provider_collateral; let mut clc = clc - d3.client_collateral; @@ -1491,8 +1497,8 @@ fn locked_fund_tracking_states() { // one more round of payment for deal1 and deal2 let curr = curr + 1; rt.set_epoch(curr); - let duration = BigInt::from(deal_updates_interval); - let payment = BigInt::from(2_i32) * d1.storage_price_per_epoch * duration; + let duration = deal_updates_interval; + let payment = 2 * d1.storage_price_per_epoch * duration; csf -= payment; cron_tick(&mut rt); assert_locked_fund_states(&rt, csf.clone(), plc.clone(), clc.clone()); @@ -1503,9 +1509,9 @@ fn locked_fund_tracking_states() { // cron tick to slash deal1 and expire deal2 rt.set_epoch(end_epoch); - csf = BigInt::from(0_i32); - clc = BigInt::from(0_i32); - plc = BigInt::from(0_i32); + csf = TokenAmount::zero(); + clc = TokenAmount::zero(); + plc = TokenAmount::zero(); rt.expect_send( *BURNT_FUNDS_ACTOR_ADDR, METHOD_SEND, @@ -1543,7 +1549,7 @@ fn market_actor_deals() { }; // test adding provider funds - let funds = TokenAmount::from_u32(20_000_000).unwrap(); + let funds = TokenAmount::from_atto(20_000_000); add_provider_funds(&mut rt, funds.clone(), &MinerAddresses::default()); assert_eq!(funds, get_escrow_balance(&rt, &PROVIDER_ADDR).unwrap()); @@ -1581,7 +1587,7 @@ fn max_deal_label_size() { }; // Test adding provider funds from both worker and owner address - let funds = TokenAmount::from_u32(20_000_000).unwrap(); + let funds = TokenAmount::from_atto(20_000_000); add_provider_funds(&mut rt, funds.clone(), &MinerAddresses::default()); assert_eq!(funds, get_escrow_balance(&rt, &PROVIDER_ADDR).unwrap()); @@ -1624,7 +1630,7 @@ fn insufficient_client_balance_in_a_batch() { ChainEpoch::from(1), 200 * EPOCHS_IN_DAY, ); - deal1.client_collateral = deal2.clone().client_collateral + 1; + deal1.client_collateral = &deal2.client_collateral + TokenAmount::from_atto(1); // Client gets enough funds for the 2nd deal add_participant_funds(&mut rt, CLIENT_ADDR, deal2.client_balance_requirement()); @@ -1718,7 +1724,7 @@ fn insufficient_provider_balance_in_a_batch() { ChainEpoch::from(1), 200 * EPOCHS_IN_DAY, ); - deal1.provider_collateral = deal2.clone().provider_collateral + 1; + deal1.provider_collateral = &deal2.provider_collateral + TokenAmount::from_atto(1); // Client gets enough funds for both deals add_participant_funds( diff --git a/actors/market/tests/publish_storage_deals_failures.rs b/actors/market/tests/publish_storage_deals_failures.rs index 9ccfde0206..5391d82e05 100644 --- a/actors/market/tests/publish_storage_deals_failures.rs +++ b/actors/market/tests/publish_storage_deals_failures.rs @@ -17,12 +17,11 @@ use fvm_shared::crypto::signature::Signature; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; use fvm_shared::piece::PaddedPieceSize; -use fvm_shared::sector::StoragePower; + use fvm_shared::TOTAL_FILECOIN; use anyhow::anyhow; use cid::Cid; -use num_traits::FromPrimitive; mod harness; use harness::*; @@ -56,7 +55,7 @@ fn deal_duration_greater_than_max_deal_duration() { #[test] fn negative_price_per_epoch() { let f = |_rt: &mut MockRuntime, d: &mut DealProposal| { - d.storage_price_per_epoch = TokenAmount::from(-1); + d.storage_price_per_epoch = TokenAmount::from_atto(-1); }; assert_deal_failure(true, f, ExitCode::USR_ILLEGAL_ARGUMENT, Ok(())); } @@ -64,7 +63,7 @@ fn negative_price_per_epoch() { #[test] fn price_per_epoch_greater_than_total_filecoin() { let f = |_rt: &mut MockRuntime, d: &mut DealProposal| { - d.storage_price_per_epoch = TOTAL_FILECOIN.clone() + 1; + d.storage_price_per_epoch = &*TOTAL_FILECOIN + TokenAmount::from_atto(1); }; assert_deal_failure(true, f, ExitCode::USR_ILLEGAL_ARGUMENT, Ok(())); } @@ -72,7 +71,7 @@ fn price_per_epoch_greater_than_total_filecoin() { #[test] fn negative_provider_collateral() { let f = |_rt: &mut MockRuntime, d: &mut DealProposal| { - d.provider_collateral = TokenAmount::from(-1); + d.provider_collateral = TokenAmount::from_atto(-1); }; assert_deal_failure(true, f, ExitCode::USR_ILLEGAL_ARGUMENT, Ok(())); } @@ -80,7 +79,7 @@ fn negative_provider_collateral() { #[test] fn provider_collateral_greater_than_max_collateral() { let f = |_rt: &mut MockRuntime, d: &mut DealProposal| { - d.provider_collateral = TOTAL_FILECOIN.clone() + 1; + d.provider_collateral = &*TOTAL_FILECOIN + TokenAmount::from_atto(1); }; assert_deal_failure(true, f, ExitCode::USR_ILLEGAL_ARGUMENT, Ok(())); } @@ -88,15 +87,15 @@ fn provider_collateral_greater_than_max_collateral() { #[test] fn provider_collateral_less_than_bound() { let f = |_rt: &mut MockRuntime, d: &mut DealProposal| { - let power = StoragePower::from_i128(1 << 50).unwrap(); + let circ_supply = TokenAmount::from_atto(1 << 50); let (provider_min, _) = deal_provider_collateral_bounds( &Policy::default(), PaddedPieceSize(2048), &BigInt::from(0u8), &BigInt::from(0u8), - &power, + &circ_supply, ); - d.provider_collateral = provider_min - 1; + d.provider_collateral = provider_min - TokenAmount::from_atto(1); }; assert_deal_failure(true, f, ExitCode::USR_ILLEGAL_ARGUMENT, Ok(())); } @@ -104,7 +103,7 @@ fn provider_collateral_less_than_bound() { #[test] fn negative_client_collateral() { let f = |_rt: &mut MockRuntime, d: &mut DealProposal| { - d.client_collateral = TokenAmount::from(-1); + d.client_collateral = TokenAmount::from_atto(-1); }; assert_deal_failure(true, f, ExitCode::USR_ILLEGAL_ARGUMENT, Ok(())); } @@ -112,7 +111,7 @@ fn negative_client_collateral() { #[test] fn client_collateral_greater_than_max_collateral() { let f = |_rt: &mut MockRuntime, d: &mut DealProposal| { - d.client_collateral = TOTAL_FILECOIN.clone() + 1; + d.client_collateral = &*TOTAL_FILECOIN + TokenAmount::from_atto(1); }; assert_deal_failure(true, f, ExitCode::USR_ILLEGAL_ARGUMENT, Ok(())); } @@ -120,7 +119,11 @@ fn client_collateral_greater_than_max_collateral() { #[test] fn client_does_not_have_enough_balance_for_collateral() { let f = |rt: &mut MockRuntime, d: &mut DealProposal| { - add_participant_funds(rt, CLIENT_ADDR, d.client_balance_requirement() - 1); + add_participant_funds( + rt, + CLIENT_ADDR, + d.client_balance_requirement() - TokenAmount::from_atto(1), + ); add_provider_funds(rt, d.provider_collateral.clone(), &MinerAddresses::default()); }; assert_deal_failure(false, f, ExitCode::USR_ILLEGAL_ARGUMENT, Ok(())); @@ -130,7 +133,11 @@ fn client_does_not_have_enough_balance_for_collateral() { fn provider_does_not_have_enough_balance_for_collateral() { let f = |rt: &mut MockRuntime, d: &mut DealProposal| { add_participant_funds(rt, CLIENT_ADDR, d.client_balance_requirement()); - add_provider_funds(rt, d.provider_collateral.clone() - 1, &MinerAddresses::default()); + add_provider_funds( + rt, + d.provider_collateral.clone() - TokenAmount::from_atto(1), + &MinerAddresses::default(), + ); }; assert_deal_failure(false, f, ExitCode::USR_ILLEGAL_ARGUMENT, Ok(())); } @@ -209,7 +216,7 @@ fn piece_size_is_not_a_power_of_2() { fn fail_when_client_has_some_funds_but_not_enough_for_a_deal() { let mut rt = setup(); - let amount = TokenAmount::from(100u8); + let amount = TokenAmount::from_atto(100u8); add_participant_funds(&mut rt, CLIENT_ADDR, amount.clone()); let start_epoch = 42; let end_epoch = start_epoch + 200 * EPOCHS_IN_DAY; @@ -233,7 +240,7 @@ fn fail_when_provider_has_some_funds_but_not_enough_for_a_deal() { let mut rt = setup(); - let amount = TokenAmount::from(1u8); + let amount = TokenAmount::from_atto(1u8); add_provider_funds(&mut rt, amount.clone(), &MinerAddresses::default()); let deal1 = generate_deal_proposal(CLIENT_ADDR, PROVIDER_ADDR, start_epoch, end_epoch); assert!(amount < deal1.client_balance_requirement()); diff --git a/actors/market/tests/random_cron_epoch_during_publish.rs b/actors/market/tests/random_cron_epoch_during_publish.rs index 9bcd5c8570..831e9beb2a 100644 --- a/actors/market/tests/random_cron_epoch_during_publish.rs +++ b/actors/market/tests/random_cron_epoch_during_publish.rs @@ -10,8 +10,6 @@ use fvm_shared::clock::ChainEpoch; use fvm_shared::error::ExitCode; use fvm_shared::METHOD_SEND; -use num_traits::Zero; - mod harness; use harness::*; diff --git a/actors/miner/Cargo.toml b/actors/miner/Cargo.toml index f49b90705b..4cdaeb683b 100644 --- a/actors/miner/Cargo.toml +++ b/actors/miner/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "9.0.0-alpha.1", path = "../../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } fvm_ipld_bitfield = "0.5.2" fvm_ipld_amt = { version = "0.4.2", features = ["go-interop"] } fvm_ipld_hamt = "0.5.1" diff --git a/actors/miner/src/beneficiary.rs b/actors/miner/src/beneficiary.rs index 911ae9d4b5..d39cb9e9ed 100644 --- a/actors/miner/src/beneficiary.rs +++ b/actors/miner/src/beneficiary.rs @@ -1,7 +1,7 @@ use fvm_ipld_encoding::tuple::*; use fvm_ipld_encoding::Cbor; use fvm_shared::address::Address; -use fvm_shared::bigint::bigint_ser; + use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; use num_traits::Zero; @@ -10,10 +10,8 @@ use std::ops::Sub; #[derive(Debug, PartialEq, Eq, Clone, Serialize_tuple, Deserialize_tuple)] pub struct BeneficiaryTerm { /// The total amount the current beneficiary can withdraw. Monotonic, but reset when beneficiary changes. - #[serde(with = "bigint_ser")] pub quota: TokenAmount, /// The amount of quota the current beneficiary has already withdrawn - #[serde(with = "bigint_ser")] pub used_quota: TokenAmount, /// The epoch at which the beneficiary's rights expire and revert to the owner pub expiration: ChainEpoch, @@ -54,7 +52,6 @@ impl BeneficiaryTerm { #[derive(Debug, PartialEq, Eq, Serialize_tuple, Deserialize_tuple)] pub struct PendingBeneficiaryChange { pub new_beneficiary: Address, - #[serde(with = "bigint_ser")] pub new_quota: TokenAmount, pub new_expiration: ChainEpoch, pub approved_by_beneficiary: bool, diff --git a/actors/miner/src/expiration_queue.rs b/actors/miner/src/expiration_queue.rs index 026bb972c9..b006f49d26 100644 --- a/actors/miner/src/expiration_queue.rs +++ b/actors/miner/src/expiration_queue.rs @@ -12,7 +12,7 @@ use fvm_ipld_amt::{Error as AmtError, ValueMut}; use fvm_ipld_bitfield::BitField; use fvm_ipld_blockstore::Blockstore; use fvm_ipld_encoding::tuple::*; -use fvm_shared::bigint::bigint_ser; + use fvm_shared::clock::{ChainEpoch, QuantSpec}; use fvm_shared::econ::TokenAmount; use fvm_shared::sector::{SectorNumber, SectorSize}; @@ -38,7 +38,6 @@ pub struct ExpirationSet { /// Sectors expiring "early" due to being faulty for too long pub early_sectors: BitField, /// Pledge total for the on-time sectors - #[serde(with = "bigint_ser")] pub on_time_pledge: TokenAmount, /// Power that is currently active (not faulty) pub active_power: PowerPair, diff --git a/actors/miner/src/expiration_queue/tests.rs b/actors/miner/src/expiration_queue/tests.rs index 5860eb7a19..796a2d4fe1 100644 --- a/actors/miner/src/expiration_queue/tests.rs +++ b/actors/miner/src/expiration_queue/tests.rs @@ -66,7 +66,7 @@ fn test_sector( sector_number, deal_weight: DealWeight::from(deal_weight), verified_deal_weight: DealWeight::from(verified_deal_weight), - initial_pledge: TokenAmount::from(initial_pledge), + initial_pledge: TokenAmount::from_atto(initial_pledge), ..Default::default() } } diff --git a/actors/miner/src/ext.rs b/actors/miner/src/ext.rs index 554865b60a..e4aa1ec3ee 100644 --- a/actors/miner/src/ext.rs +++ b/actors/miner/src/ext.rs @@ -109,7 +109,6 @@ pub mod power { pub raw_byte_power: StoragePower, #[serde(with = "bigint_ser")] pub quality_adj_power: StoragePower, - #[serde(with = "bigint_ser")] pub pledge_collateral: TokenAmount, pub quality_adj_power_smoothed: FilterEstimate, } diff --git a/actors/miner/src/internal_tests.rs b/actors/miner/src/internal_tests.rs index 2f96e1c2d8..5c31b99932 100644 --- a/actors/miner/src/internal_tests.rs +++ b/actors/miner/src/internal_tests.rs @@ -107,8 +107,8 @@ fn test_current_proving_period_start() { #[test] fn br_looks_right_in_plausible_sector_power_network_power_reward_range() { // between 10 and 100 FIL is reasonable for near-mid future - let tens_of_fil: TokenAmount = TokenAmount::from(10).pow(18) * 50; - let reward_estimate = FilterEstimate::new(tens_of_fil.clone(), Zero::zero()); + let tens_of_fil: TokenAmount = TokenAmount::from_whole(50); + let reward_estimate = FilterEstimate::new(tens_of_fil.atto().clone(), Zero::zero()); let small_power = StoragePower::from(32_u64 << 30); // 32 GiB let huge_power = StoragePower::from(1_u64 << 60); // 1 EiB let small_power_br_num = &small_power * EPOCHS_IN_DAY * &tens_of_fil; @@ -131,8 +131,8 @@ fn br_looks_right_in_plausible_sector_power_network_power_reward_range() { &huge_power, EPOCHS_IN_DAY, ); - assert_eq!(&small_power_br_num / &tens_of_eibs, br_small_low); - assert_eq!(&huge_power_br_num / &tens_of_eibs, br_huge_low); + assert_eq!(small_power_br_num.div_floor(tens_of_eibs.clone()), br_small_low); + assert_eq!(huge_power_br_num.div_floor(tens_of_eibs), br_huge_low); // 100s of EiBs // 1.2e18 * 100 bytes * 5 quality ~ 6e20 @@ -150,8 +150,8 @@ fn br_looks_right_in_plausible_sector_power_network_power_reward_range() { &huge_power, EPOCHS_IN_DAY, ); - assert_eq!(&small_power_br_num / &hundreds_of_eibs, br_small_mid); - assert_eq!(&huge_power_br_num / &hundreds_of_eibs, br_huge_mid); + assert_eq!(small_power_br_num.div_floor(hundreds_of_eibs.clone()), br_small_mid); + assert_eq!(huge_power_br_num.div_floor(hundreds_of_eibs), br_huge_mid); // 1000s of EiBs -- upper range // 1.2e18 * 1000 bytes * 10 quality = 1.2e22 ~ 2e22 @@ -169,14 +169,14 @@ fn br_looks_right_in_plausible_sector_power_network_power_reward_range() { &huge_power, EPOCHS_IN_DAY, ); - assert_eq!(&small_power_br_num / &thousands_of_eibs, br_small_upper); - assert_eq!(&huge_power_br_num / &thousands_of_eibs, br_huge_upper); + assert_eq!(small_power_br_num.div_floor(thousands_of_eibs.clone()), br_small_upper); + assert_eq!(huge_power_br_num.div_floor(thousands_of_eibs), br_huge_upper); } #[test] fn declared_and_undeclared_fault_penalties_are_linear_over_sector_qa_power_term() { // Construct plausible reward and qa power filtered estimates - let epoch_reward = TokenAmount::from(100_u64 << 53); + let epoch_reward = BigInt::from(100_u64 << 53); // not too much growth over ~3000 epoch projection in BR let reward_estimate = FilterEstimate::new(epoch_reward, Zero::zero()); @@ -213,7 +213,7 @@ fn declared_and_undeclared_fault_penalties_are_linear_over_sector_qa_power_term( // we can at best expect n calculations of 1 power to be within n of 1 calculation of n powers. let diff = &ff_all - (&ff_c + &ff_a + &ff_b); assert!(diff >= Zero::zero()); - assert!(diff < TokenAmount::from(3)); + assert!(diff < TokenAmount::from_atto(3)); // Undeclared faults let sp_a = pledge_penalty_for_termination_lower_bound( @@ -242,5 +242,5 @@ fn declared_and_undeclared_fault_penalties_are_linear_over_sector_qa_power_term( // we can at best expect n calculations of 1 power to be within n of 1 calculation of n powers. let diff = &sp_all - (&sp_c + &sp_a + &sp_b); assert!(diff >= Zero::zero()); - assert!(diff < TokenAmount::from(3)); + assert!(diff < TokenAmount::from_atto(3)); } diff --git a/actors/miner/src/lib.rs b/actors/miner/src/lib.rs index 1e6f84e588..ed13c54b9e 100644 --- a/actors/miner/src/lib.rs +++ b/actors/miner/src/lib.rs @@ -25,7 +25,6 @@ use fvm_ipld_bitfield::{BitField, UnvalidatedBitField, Validate}; use fvm_ipld_blockstore::Blockstore; use fvm_ipld_encoding::{from_slice, BytesDe, Cbor, CborStore, RawBytes}; use fvm_shared::address::{Address, Payload, Protocol}; -use fvm_shared::bigint::bigint_ser::BigIntSer; use fvm_shared::bigint::{BigInt, Integer}; use fvm_shared::clock::ChainEpoch; use fvm_shared::deal::DealID; @@ -46,7 +45,7 @@ use fvm_shared::{MethodNum, METHOD_CONSTRUCTOR, METHOD_SEND}; use log::{error, info, warn}; pub use monies::*; use num_derive::FromPrimitive; -use num_traits::{FromPrimitive, Signed, Zero}; +use num_traits::{FromPrimitive, Zero}; pub use partition_state::*; pub use policy::*; pub use sector_map::*; @@ -1793,7 +1792,7 @@ impl Actor { sectors.len() )); } - let mut fee_to_burn = TokenAmount::from(0_u32); + let mut fee_to_burn = TokenAmount::zero(); let mut needs_cron = false; rt.transaction(|state: &mut State, rt| { // Aggregate fee applies only when batching. @@ -1836,7 +1835,7 @@ impl Actor { } let mut chain_infos = Vec::with_capacity(sectors.len()); - let mut total_deposit_required = BigInt::zero(); + let mut total_deposit_required = TokenAmount::zero(); let mut clean_up_events = Vec::with_capacity(sectors.len()); let deal_count_max = sector_deals_max(rt.policy(), info.sector_size); @@ -2032,7 +2031,7 @@ impl Actor { &STORAGE_POWER_ACTOR_ADDR, ext::power::SUBMIT_POREP_FOR_BULK_VERIFY_METHOD, RawBytes::serialize(&svi)?, - BigInt::zero(), + TokenAmount::zero(), )?; Ok(()) @@ -3171,11 +3170,12 @@ impl Actor { // The policy amounts we should burn and send to reporter // These may differ from actual funds send when miner goes into fee debt - let this_epoch_reward = reward_stats.this_epoch_reward_smoothed.estimate(); + let this_epoch_reward = + TokenAmount::from_atto(reward_stats.this_epoch_reward_smoothed.estimate()); let fault_penalty = consensus_fault_penalty(this_epoch_reward.clone()); let slasher_reward = reward_for_consensus_slash_report(&this_epoch_reward); - let mut pledge_delta = TokenAmount::from(0); + let mut pledge_delta = TokenAmount::zero(); let (burn_amount, reward_amount) = rt.transaction(|st: &mut State, rt| { let mut info = get_miner_info(rt.store(), st)?; @@ -4258,7 +4258,7 @@ where Ok(()) } -fn notify_pledge_changed(rt: &mut RT, pledge_delta: &BigInt) -> Result<(), ActorError> +fn notify_pledge_changed(rt: &mut RT, pledge_delta: &TokenAmount) -> Result<(), ActorError> where BS: Blockstore, RT: Runtime, @@ -4267,7 +4267,7 @@ where rt.send( &STORAGE_POWER_ACTOR_ADDR, ext::power::UPDATE_PLEDGE_TOTAL_METHOD, - RawBytes::serialize(BigIntSer(pledge_delta))?, + RawBytes::serialize(pledge_delta)?, TokenAmount::zero(), )?; } diff --git a/actors/miner/src/monies.rs b/actors/miner/src/monies.rs index 895783a0a6..8d6e325271 100644 --- a/actors/miner/src/monies.rs +++ b/actors/miner/src/monies.rs @@ -4,15 +4,13 @@ use std::cmp::{self, max}; use fil_actors_runtime::network::EPOCHS_IN_DAY; -use fil_actors_runtime::{EXPECTED_LEADERS_PER_EPOCH, ONE_NANO_FIL}; -use fvm_shared::bigint::num_integer::div_floor; +use fil_actors_runtime::EXPECTED_LEADERS_PER_EPOCH; use fvm_shared::bigint::{BigInt, Integer}; use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; use fvm_shared::math::PRECISION; use fvm_shared::sector::StoragePower; use fvm_shared::smooth::{self, FilterEstimate}; -use fvm_shared::FILECOIN_PRECISION; use lazy_static::lazy_static; use num_traits::Zero; @@ -32,30 +30,28 @@ pub const PRE_COMMIT_DEPOSIT_PROJECTION_PERIOD: i64 = pub const INITIAL_PLEDGE_PROJECTION_PERIOD: i64 = (INITIAL_PLEDGE_FACTOR as ChainEpoch) * EPOCHS_IN_DAY; -lazy_static! { - static ref LOCK_TARGET_FACTOR_NUM: BigInt = BigInt::from(3); - static ref LOCK_TARGET_FACTOR_DENOM: BigInt = BigInt::from(10); +const LOCK_TARGET_FACTOR_NUM: u32 = 3; +const LOCK_TARGET_FACTOR_DENOM: u32 = 10; - pub static ref TERMINATION_REWARD_FACTOR_NUM: BigInt = BigInt::from(1); - pub static ref TERMINATION_REWARD_FACTOR_DENOM: BigInt = BigInt::from(2); +pub const TERMINATION_REWARD_FACTOR_NUM: u32 = 1; +pub const TERMINATION_REWARD_FACTOR_DENOM: u32 = 2; - // * go impl has 75/100 but this is just simplified - static ref LOCKED_REWARD_FACTOR_NUM: BigInt = BigInt::from(3); - static ref LOCKED_REWARD_FACTOR_DENOM: BigInt = BigInt::from(4); +// * go impl has 75/100 but this is just simplified +const LOCKED_REWARD_FACTOR_NUM: u32 = 3; +const LOCKED_REWARD_FACTOR_DENOM: u32 = 4; +lazy_static! { /// Cap on initial pledge requirement for sectors during the Space Race network. /// The target is 1 FIL (10**18 attoFIL) per 32GiB. /// This does not divide evenly, so the result is fractionally smaller. - static ref INITIAL_PLEDGE_MAX_PER_BYTE: BigInt = - BigInt::from(10_u64.pow(18) / (32 << 30)); + static ref INITIAL_PLEDGE_MAX_PER_BYTE: TokenAmount = + TokenAmount::from_whole(1).div_floor(32 << 30); /// Base reward for successfully disputing a window posts proofs. - pub static ref BASE_REWARD_FOR_DISPUTED_WINDOW_POST: BigInt = - BigInt::from(4 * FILECOIN_PRECISION); + pub static ref BASE_REWARD_FOR_DISPUTED_WINDOW_POST: TokenAmount = TokenAmount::from_whole(4); /// Base penalty for a successful disputed window post proof. - pub static ref BASE_PENALTY_FOR_DISPUTED_WINDOW_POST: BigInt = - BigInt::from(FILECOIN_PRECISION) * 20; + pub static ref BASE_PENALTY_FOR_DISPUTED_WINDOW_POST: TokenAmount = TokenAmount::from_whole(20); } // FF + 2BR const INVALID_WINDOW_POST_PROJECTION_PERIOD: ChainEpoch = @@ -93,7 +89,7 @@ pub fn expected_reward_for_power( let network_qa_power_smoothed = network_qa_power_estimate.estimate(); if network_qa_power_smoothed.is_zero() { - return reward_estimate.estimate(); + return TokenAmount::from_atto(reward_estimate.estimate()); } let expected_reward_for_proving_period = smooth::extrapolated_cum_sum_of_ratio( @@ -103,14 +99,14 @@ pub fn expected_reward_for_power( network_qa_power_estimate, ); let br128 = qa_sector_power * expected_reward_for_proving_period; // Q.0 * Q.128 => Q.128 - std::cmp::max(br128 >> PRECISION, Default::default()) + TokenAmount::from_atto(std::cmp::max(br128 >> PRECISION, Default::default())) } pub mod detail { use super::*; lazy_static! { - pub static ref BATCH_BALANCER: BigInt = BigInt::from(ONE_NANO_FIL) * BigInt::from(5); + pub static ref BATCH_BALANCER: TokenAmount = TokenAmount::from_nano(5); } // BR but zero values are clamped at 1 attofil @@ -128,8 +124,8 @@ pub mod detail { qa_sector_power, projection_duration, ); - if br.le(&TokenAmount::from(0)) { - 1.into() + if br.le(&TokenAmount::zero()) { + TokenAmount::from_atto(1) } else { br } @@ -200,8 +196,8 @@ pub fn pledge_penalty_for_termination( expected_reward += replaced_day_reward * relevant_replaced_age; - let penalized_reward = expected_reward * &*TERMINATION_REWARD_FACTOR_NUM; - let penalized_reward = penalized_reward / &*TERMINATION_REWARD_FACTOR_DENOM; + let penalized_reward = expected_reward * TERMINATION_REWARD_FACTOR_NUM; + let penalized_reward = penalized_reward.div_floor(TERMINATION_REWARD_FACTOR_DENOM); cmp::max( pledge_penalty_for_termination_lower_bound( @@ -209,7 +205,7 @@ pub fn pledge_penalty_for_termination( network_qa_power_estimate, qa_sector_power, ), - twenty_day_reward_at_activation + (penalized_reward / EPOCHS_IN_DAY), + twenty_day_reward_at_activation + (penalized_reward.div_floor(EPOCHS_IN_DAY)), ) } @@ -267,37 +263,37 @@ pub fn initial_pledge_for_power( INITIAL_PLEDGE_PROJECTION_PERIOD, ); - let lock_target_num = &*LOCK_TARGET_FACTOR_NUM * circulating_supply; - let lock_target_denom = &*LOCK_TARGET_FACTOR_DENOM; + let lock_target_num = circulating_supply.atto() * LOCK_TARGET_FACTOR_NUM; + let lock_target_denom = LOCK_TARGET_FACTOR_DENOM; let pledge_share_num = qa_power; let network_qa_power = network_qa_power_estimate.estimate(); let pledge_share_denom = cmp::max(cmp::max(&network_qa_power, baseline_power), qa_power); - let additional_ip_num: TokenAmount = lock_target_num * pledge_share_num; - let additional_ip_denom = lock_target_denom * pledge_share_denom; + let additional_ip_num = lock_target_num * pledge_share_num; + let additional_ip_denom = pledge_share_denom * lock_target_denom; let additional_ip = additional_ip_num.div_floor(&additional_ip_denom); - let nominal_pledge = ip_base + additional_ip; - let pledge_cap = &*INITIAL_PLEDGE_MAX_PER_BYTE * qa_power; + let nominal_pledge = ip_base + TokenAmount::from_atto(additional_ip); + let pledge_cap = TokenAmount::from_atto(INITIAL_PLEDGE_MAX_PER_BYTE.atto() * qa_power); cmp::min(nominal_pledge, pledge_cap) } pub fn consensus_fault_penalty(this_epoch_reward: TokenAmount) -> TokenAmount { - (this_epoch_reward * CONSENSUS_FAULT_FACTOR) - .div_floor(&TokenAmount::from(EXPECTED_LEADERS_PER_EPOCH)) + (this_epoch_reward * CONSENSUS_FAULT_FACTOR).div_floor(EXPECTED_LEADERS_PER_EPOCH) } /// Returns the amount of a reward to vest, and the vesting schedule, for a reward amount. pub fn locked_reward_from_reward(reward: TokenAmount) -> (TokenAmount, &'static VestSpec) { - let lock_amount = (reward * &*LOCKED_REWARD_FACTOR_NUM).div_floor(&*LOCKED_REWARD_FACTOR_DENOM); + let lock_amount = (reward * LOCKED_REWARD_FACTOR_NUM).div_floor(LOCKED_REWARD_FACTOR_DENOM); (lock_amount, &REWARD_VESTING_SPEC) } +const BATCH_DISCOUNT_NUM: u32 = 1; +const BATCH_DISCOUNT_DENOM: u32 = 20; + lazy_static! { static ref ESTIMATED_SINGLE_PROVE_COMMIT_GAS_USAGE: BigInt = BigInt::from(49299973); static ref ESTIMATED_SINGLE_PRE_COMMIT_GAS_USAGE: BigInt = BigInt::from(16433324); - static ref BATCH_DISCOUNT_NUM: BigInt = BigInt::from(1); - static ref BATCH_DISCOUNT_DENOM: BigInt = BigInt::from(20); } pub fn aggregate_prove_commit_network_fee( @@ -320,6 +316,6 @@ pub fn aggregate_network_fee( base_fee: &TokenAmount, ) -> TokenAmount { let effective_gas_fee = max(base_fee, &*BATCH_BALANCER); - let network_fee_num = effective_gas_fee * gas_usage * aggregate_size * &*BATCH_DISCOUNT_NUM; - div_floor(network_fee_num, BATCH_DISCOUNT_DENOM.clone()) + let network_fee_num = effective_gas_fee * gas_usage * aggregate_size * BATCH_DISCOUNT_NUM; + network_fee_num.div_floor(BATCH_DISCOUNT_DENOM) } diff --git a/actors/miner/src/policy.rs b/actors/miner/src/policy.rs index 66adf29694..1087c7dbc7 100644 --- a/actors/miner/src/policy.rs +++ b/actors/miner/src/policy.rs @@ -168,13 +168,10 @@ pub const REWARD_VESTING_SPEC: VestSpec = VestSpec { // Default share of block reward allocated as reward to the consensus fault reporter. // Applied as epochReward / (expectedLeadersPerEpoch * consensusFaultReporterDefaultShare) -pub const CONSENSUS_FAULT_REPORTER_DEFAULT_SHARE: i64 = 4; +pub const CONSENSUS_FAULT_REPORTER_DEFAULT_SHARE: u64 = 4; pub fn reward_for_consensus_slash_report(epoch_reward: &TokenAmount) -> TokenAmount { - epoch_reward.div_floor( - &(BigInt::from(EXPECTED_LEADERS_PER_EPOCH) - * BigInt::from(CONSENSUS_FAULT_REPORTER_DEFAULT_SHARE)), - ) + epoch_reward.div_floor(EXPECTED_LEADERS_PER_EPOCH * CONSENSUS_FAULT_REPORTER_DEFAULT_SHARE) } // The reward given for successfully disputing a window post. diff --git a/actors/miner/src/state.rs b/actors/miner/src/state.rs index 2cec758579..1d96132d3a 100644 --- a/actors/miner/src/state.rs +++ b/actors/miner/src/state.rs @@ -19,13 +19,13 @@ use fvm_ipld_encoding::tuple::*; use fvm_ipld_encoding::{serde_bytes, BytesDe, Cbor, CborStore}; use fvm_ipld_hamt::Error as HamtError; use fvm_shared::address::Address; -use fvm_shared::bigint::bigint_ser; + use fvm_shared::clock::{ChainEpoch, QuantSpec, EPOCH_UNDEFINED}; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; use fvm_shared::sector::{RegisteredPoStProof, SectorNumber, SectorSize, MAX_SECTOR_NUMBER}; use fvm_shared::HAMT_BIT_WIDTH; -use num_traits::{Signed, Zero}; +use num_traits::Zero; use super::beneficiary::*; use super::deadlines::new_deadline_info; @@ -53,22 +53,18 @@ pub struct State { pub info: Cid, /// Total funds locked as pre_commit_deposit - #[serde(with = "bigint_ser")] pub pre_commit_deposits: TokenAmount, /// Total rewards and added funds locked in vesting table - #[serde(with = "bigint_ser")] pub locked_funds: TokenAmount, /// VestingFunds (Vesting Funds schedule for the miner). pub vesting_funds: Cid, /// Absolute value of debt this miner owes from unpaid fees. - #[serde(with = "bigint_ser")] pub fee_debt: TokenAmount, /// Sum of initial pledge requirements of all active sectors. - #[serde(with = "bigint_ser")] pub initial_pledge: TokenAmount, /// Sectors that have been pre-committed but not yet proven. diff --git a/actors/miner/src/testing.rs b/actors/miner/src/testing.rs index b7c81c6dc0..68dd2938a0 100644 --- a/actors/miner/src/testing.rs +++ b/actors/miner/src/testing.rs @@ -8,12 +8,11 @@ use fvm_ipld_bitfield::BitField; use fvm_ipld_blockstore::Blockstore; use fvm_ipld_encoding::CborStore; use fvm_shared::address::Protocol; -use fvm_shared::bigint::BigInt; use fvm_shared::clock::{ChainEpoch, QuantSpec, NO_QUANTIZATION}; use fvm_shared::deal::DealID; use fvm_shared::econ::TokenAmount; use fvm_shared::sector::{RegisteredPoStProof, SectorNumber, SectorSize}; -use num_traits::{Signed, Zero}; +use num_traits::Zero; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; pub fn check_state_invariants( @@ -229,7 +228,7 @@ fn check_miner_balances( policy: &Policy, state: &State, store: &BS, - balance: &BigInt, + balance: &TokenAmount, acc: &MessageAccumulator, ) { acc.require( @@ -253,10 +252,10 @@ fn check_miner_balances( format!("miner fee debt is less than zero: {}", state.fee_debt), ); - acc.require(balance - &state.locked_funds - &state.pre_commit_deposits - &state.initial_pledge >= BigInt::zero(), format!("miner balance {balance} is less than sum of locked funds ({}), precommit deposit ({}) and initial pledge ({})", state.locked_funds, state.pre_commit_deposits, state.initial_pledge)); + acc.require(!(balance - &state.locked_funds - &state.pre_commit_deposits - &state.initial_pledge).is_negative(), format!("miner balance {balance} is less than sum of locked funds ({}), precommit deposit ({}) and initial pledge ({})", state.locked_funds, state.pre_commit_deposits, state.initial_pledge)); // locked funds must be sum of vesting table and vesting table payments must be quantized - let mut vesting_sum = BigInt::zero(); + let mut vesting_sum = TokenAmount::zero(); match state.load_vesting_funds(store) { Ok(funds) => { let quant = state.quant_spec_every_deadline(policy); @@ -329,7 +328,7 @@ fn check_precommits( } }; - let mut precommit_total = BigInt::zero(); + let mut precommit_total = TokenAmount::zero(); let precommited_sectors = Map::<_, SectorPreCommitOnChainInfo>::load(&state.pre_committed_sectors, store); @@ -609,7 +608,7 @@ impl ExpirationQueueStateSummary { let mut expiration_epochs: Vec = Vec::new(); let mut all_active_power = PowerPair::zero(); let mut all_faulty_power = PowerPair::zero(); - let mut all_on_time_pledge = BigInt::zero(); + let mut all_on_time_pledge = TokenAmount::zero(); let ret = expiration_queue.amt.for_each(|epoch, expiration_set| { let epoch = epoch as i64; @@ -619,7 +618,7 @@ impl ExpirationQueueStateSummary { expiration_epochs.push(epoch); - let mut on_time_sectors_pledge = BigInt::zero(); + let mut on_time_sectors_pledge = TokenAmount::zero(); for sector_number in expiration_set.on_time_sectors.iter() { // check sectors are present only once if !seen_sectors.insert(sector_number) { diff --git a/actors/miner/src/types.rs b/actors/miner/src/types.rs index 24ec1cef52..59acc5237d 100644 --- a/actors/miner/src/types.rs +++ b/actors/miner/src/types.rs @@ -227,7 +227,6 @@ pub struct ReportConsensusFaultParams { #[derive(Serialize_tuple, Deserialize_tuple)] pub struct WithdrawBalanceParams { - #[serde(with = "bigint_ser")] pub amount_requested: TokenAmount, } @@ -236,7 +235,6 @@ impl Cbor for WithdrawBalanceParams {} #[derive(Serialize_tuple, Deserialize_tuple)] #[serde(transparent)] pub struct WithdrawBalanceReturn { - #[serde(with = "bigint_ser")] pub amount_withdrawn: TokenAmount, } @@ -296,7 +294,6 @@ pub struct SectorPreCommitInfo { #[derive(Debug, PartialEq, Eq, Clone, Serialize_tuple, Deserialize_tuple)] pub struct SectorPreCommitOnChainInfo { pub info: SectorPreCommitInfo, - #[serde(with = "bigint_ser")] pub pre_commit_deposit: TokenAmount, pub pre_commit_epoch: ChainEpoch, } @@ -321,18 +318,14 @@ pub struct SectorOnChainInfo { #[serde(with = "bigint_ser")] pub verified_deal_weight: DealWeight, /// Pledge collected to commit this sector - #[serde(with = "bigint_ser")] pub initial_pledge: TokenAmount, /// Expected one day projection of reward for sector computed at activation time - #[serde(with = "bigint_ser")] pub expected_day_reward: TokenAmount, /// Expected twenty day projection of reward for sector computed at activation time - #[serde(with = "bigint_ser")] pub expected_storage_pledge: TokenAmount, /// Age of sector this sector replaced or zero pub replaced_sector_age: ChainEpoch, /// Day reward of sector this sector replace or zero - #[serde(with = "bigint_ser")] pub replaced_day_reward: TokenAmount, /// The original SealedSectorCID, only gets set on the first ReplicaUpdate pub sector_key_cid: Option, @@ -347,9 +340,7 @@ pub struct Fault { // * Added in v2 -- param was previously a big int. #[derive(Debug, Serialize_tuple, Deserialize_tuple)] pub struct ApplyRewardParams { - #[serde(with = "bigint_ser")] pub reward: TokenAmount, - #[serde(with = "bigint_ser")] pub penalty: TokenAmount, } @@ -412,7 +403,6 @@ impl Cbor for ProveReplicaUpdatesParams2 {} #[derive(Debug, Serialize_tuple, Deserialize_tuple)] pub struct ChangeBeneficiaryParams { pub new_beneficiary: Address, - #[serde(with = "bigint_ser")] pub new_quota: TokenAmount, pub new_expiration: ChainEpoch, } diff --git a/actors/miner/src/vesting_state.rs b/actors/miner/src/vesting_state.rs index de84a9005b..861e997706 100644 --- a/actors/miner/src/vesting_state.rs +++ b/actors/miner/src/vesting_state.rs @@ -4,7 +4,6 @@ use std::{iter, mem}; use fvm_ipld_encoding::tuple::*; -use fvm_shared::bigint::{bigint_ser, Integer}; use fvm_shared::clock::{ChainEpoch, QuantSpec}; use fvm_shared::econ::TokenAmount; use itertools::{EitherOrBoth, Itertools}; @@ -16,7 +15,6 @@ use super::VestSpec; #[derive(Debug, Serialize_tuple, Deserialize_tuple)] pub struct VestingFund { pub epoch: ChainEpoch, - #[serde(with = "bigint_ser")] pub amount: TokenAmount, } @@ -41,7 +39,7 @@ impl VestingFunds { .position(|fund| fund.epoch >= current_epoch) .unwrap_or(self.funds.len()); - self.funds.drain(..i).map(|fund| fund.amount).sum() + self.funds.drain(..i).map(|f| f.amount).sum() } pub fn add_locked_funds( @@ -53,7 +51,6 @@ impl VestingFunds { ) { // Quantization is aligned with when regular cron will be invoked, in the last epoch of deadlines. let vest_begin = current_epoch + spec.initial_delay; // Nothing unlocks here, this is just the start of the clock. - let vest_period = TokenAmount::from(spec.vest_period); let mut vested_so_far = TokenAmount::zero(); let mut epoch = vest_begin; @@ -73,7 +70,7 @@ impl VestingFunds { let elapsed = vest_epoch - vest_begin; let target_vest = if elapsed < spec.vest_period { // Linear vesting - (vesting_sum * elapsed).div_floor(&vest_period) + (vesting_sum * elapsed).div_floor(spec.vest_period) } else { vesting_sum.clone() }; @@ -107,7 +104,7 @@ impl VestingFunds { current_epoch: ChainEpoch, target: &TokenAmount, ) -> TokenAmount { - let mut amount_unlocked = TokenAmount::from(0); + let mut amount_unlocked = TokenAmount::zero(); let mut last = None; let mut start = 0; for (i, vf) in self.funds.iter_mut().enumerate() { diff --git a/actors/miner/tests/aggregate_network_fee_test.rs b/actors/miner/tests/aggregate_network_fee_test.rs index 9fb5fa2fcb..c78cc737cd 100644 --- a/actors/miner/tests/aggregate_network_fee_test.rs +++ b/actors/miner/tests/aggregate_network_fee_test.rs @@ -1,9 +1,6 @@ -use std::ops::{Add, Mul, Sub}; - use fil_actor_miner::detail::BATCH_BALANCER; use fil_actor_miner::{aggregate_pre_commit_network_fee, aggregate_prove_commit_network_fee}; -use fil_actors_runtime::ONE_NANO_FIL; -use fvm_shared::bigint::BigInt; +use fvm_shared::econ::TokenAmount; use num_traits::zero; #[test] @@ -13,10 +10,10 @@ fn constant_fee_per_sector_when_base_fee_is_below_5_nfil() { let ten_sector_fee = fee_func(10, &zero()); assert_eq!(&one_sector_fee * 10, ten_sector_fee); - let forty_sector_fee = fee_func(40, &ONE_NANO_FIL.into()); + let forty_sector_fee = fee_func(40, &TokenAmount::from_nano(1)); assert_eq!(&one_sector_fee * 40, forty_sector_fee); - let two_hundred_sector_fee = fee_func(200, &BigInt::from(ONE_NANO_FIL * 3)); + let two_hundred_sector_fee = fee_func(200, &TokenAmount::from_nano(3)); assert_eq!(one_sector_fee * 200, two_hundred_sector_fee); } } @@ -25,13 +22,14 @@ fn constant_fee_per_sector_when_base_fee_is_below_5_nfil() { fn fee_increases_if_basefee_crosses_threshold() { for fee_func in [aggregate_prove_commit_network_fee, aggregate_pre_commit_network_fee] { let at_no_base_fee = fee_func(10, &zero()); - let at_balance_minus_one_base_fee = fee_func(10, &BATCH_BALANCER.to_owned().sub(1)); - let at_balance_base_fee = fee_func(10, &BATCH_BALANCER); + let at_balance_minus_one_base_fee = + fee_func(10, &(&*BATCH_BALANCER - TokenAmount::from_atto(1))); + let at_balance_base_fee = fee_func(10, &*BATCH_BALANCER); let at_balance_plus_one_base_fee = - fee_func(10, &BATCH_BALANCER.to_owned().add(ONE_NANO_FIL)); + fee_func(10, &(&*BATCH_BALANCER + TokenAmount::from_nano(1))); let at_balance_plus_two_base_fee = - fee_func(10, &BATCH_BALANCER.to_owned().add(ONE_NANO_FIL * 2)); - let at_balance_times_two_base = fee_func(10, &BATCH_BALANCER.to_owned().mul(2)); + fee_func(10, &(&*BATCH_BALANCER + TokenAmount::from_nano(2))); + let at_balance_times_two_base = fee_func(10, &(2 * &*BATCH_BALANCER)); assert_eq!(at_no_base_fee, at_balance_minus_one_base_fee); assert_eq!(at_no_base_fee, at_balance_base_fee); @@ -47,40 +45,44 @@ fn regression_tests() { let fee = |aggregate_size, base_fee_multiplier| { aggregate_prove_commit_network_fee( aggregate_size, - &BigInt::from(ONE_NANO_FIL * base_fee_multiplier), + &TokenAmount::from_nano(base_fee_multiplier), ) + aggregate_pre_commit_network_fee( aggregate_size, - &BigInt::from(ONE_NANO_FIL * base_fee_multiplier), + &TokenAmount::from_nano(base_fee_multiplier), ) }; // (5/20) * x * 10 = (5/2) * x - let expected = (ONE_NANO_FIL * 5 * magic_number) / 2; - assert_eq!(BigInt::from(expected), fee(10, 0)); - assert_eq!(BigInt::from(expected), fee(10, 1)); + let expected = (TokenAmount::from_nano(5) * magic_number).div_floor(2); + assert_eq!(expected, fee(10, 0)); + assert_eq!(expected, fee(10, 1)); - let expected = ONE_NANO_FIL * 25 * magic_number; - assert_eq!(BigInt::from(expected), fee(100, 3)); + let expected = TokenAmount::from_nano(25) * magic_number; + assert_eq!(expected, fee(100, 3)); - let expected = ONE_NANO_FIL * 30 * magic_number; - assert_eq!(BigInt::from(expected), fee(100, 6)); + let expected = TokenAmount::from_nano(30) * magic_number; + assert_eq!(expected, fee(100, 6)); } #[test] fn split_25_75() { // check 25/75% split up to uFIL precision - let one_micro_fil = BigInt::from(ONE_NANO_FIL) * 1000; + let one_micro_fil = TokenAmount::from_nano(1000); for base_fee_multiplier in [0, 5, 20] { for aggregate_size in [13, 303] { let fee_pre = aggregate_pre_commit_network_fee( aggregate_size, - &BigInt::from(ONE_NANO_FIL * base_fee_multiplier), - ) / &one_micro_fil; + &TokenAmount::from_nano(base_fee_multiplier), + ) + .atto() + / one_micro_fil.atto(); let fee_prove = aggregate_prove_commit_network_fee( aggregate_size, - &BigInt::from(ONE_NANO_FIL * base_fee_multiplier), - ) / &one_micro_fil; + &TokenAmount::from_nano(base_fee_multiplier), + ) + .atto() + / one_micro_fil.atto(); assert_eq!(fee_prove, 3 * fee_pre); } } diff --git a/actors/miner/tests/aggregate_prove_commit.rs b/actors/miner/tests/aggregate_prove_commit.rs index 7185d10cb8..d4fce2cac9 100644 --- a/actors/miner/tests/aggregate_prove_commit.rs +++ b/actors/miner/tests/aggregate_prove_commit.rs @@ -7,7 +7,7 @@ use fil_actor_miner::{ }; use fil_actors_runtime::runtime::Runtime; use fvm_ipld_bitfield::BitField; -use fvm_shared::{bigint::BigInt, clock::ChainEpoch}; +use fvm_shared::{bigint::BigInt, clock::ChainEpoch, econ::TokenAmount}; mod util; use fil_actor_market::DealWeights; @@ -25,8 +25,7 @@ fn valid_precommits_then_aggregate_provecommit() { let actor = ActorHarness::new(period_offset); let mut rt = actor.new_runtime(); - let balance = BigInt::from(1_000_000u64) * BigInt::from(10u64.pow(18)); - rt.add_balance(balance); + rt.add_balance(BIG_BALANCE.clone()); let precommit_epoch = period_offset + 1; rt.set_epoch(precommit_epoch); actor.construct_and_verify(&mut rt); @@ -59,7 +58,7 @@ fn valid_precommits_then_aggregate_provecommit() { // run prove commit logic rt.set_epoch(prove_commit_epoch); - rt.set_balance(BigInt::from(1000u64) * BigInt::from(10u64.pow(18))); + rt.set_balance(TokenAmount::from_whole(1000)); let pcc = ProveCommitConfig { deal_weights: HashMap::from_iter( @@ -74,7 +73,7 @@ fn valid_precommits_then_aggregate_provecommit() { pcc, precommits, make_prove_commit_aggregate(§or_nos_bf), - BigInt::zero(), + &TokenAmount::zero(), ) .unwrap(); @@ -86,7 +85,7 @@ fn valid_precommits_then_aggregate_provecommit() { } // expect deposit to have been transferred to initial pledges - assert_eq!(BigInt::zero(), st.pre_commit_deposits); + assert!(st.pre_commit_deposits.is_zero()); // The sector is exactly full with verified deals, so expect fully verified power. let expected_power = BigInt::from(actor.sector_size as i64) diff --git a/actors/miner/tests/apply_rewards.rs b/actors/miner/tests/apply_rewards.rs index 2c0c4945ff..3d1418cda7 100644 --- a/actors/miner/tests/apply_rewards.rs +++ b/actors/miner/tests/apply_rewards.rs @@ -10,7 +10,7 @@ use fil_actors_runtime::BURNT_FUNDS_ACTOR_ADDR; use fil_actors_runtime::REWARD_ACTOR_ADDR; use fil_actors_runtime::STORAGE_POWER_ACTOR_ADDR; use fvm_ipld_encoding::RawBytes; -use fvm_shared::bigint::bigint_ser::BigIntSer; + use fvm_shared::bigint::Zero; use fvm_shared::clock::{ChainEpoch, QuantSpec}; use fvm_shared::econ::TokenAmount; @@ -19,23 +19,21 @@ use fvm_shared::METHOD_SEND; mod util; use fil_actor_miner::testing::check_state_invariants; -use num_traits::Signed; use util::*; -const BIG_BALANCE: u128 = 1_000_000_000_000_000_000_000_000u128; const PERIOD_OFFSET: ChainEpoch = 1808; #[test] fn funds_are_locked() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); - let rwd = TokenAmount::from(1_000_000); + let rwd = TokenAmount::from_atto(1_000_000); h.apply_rewards(&mut rt, rwd, TokenAmount::zero()); - let expected = TokenAmount::from(750_000); + let expected = TokenAmount::from_atto(750_000); assert_eq!(expected, h.get_locked_funds(&rt)); } @@ -43,7 +41,7 @@ fn funds_are_locked() { fn funds_vest() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let st = h.get_state(&rt); @@ -54,7 +52,7 @@ fn funds_vest() { assert!(st.locked_funds.is_zero()); // Lock some funds with AddLockedFund - let amt = TokenAmount::from(600_000); + let amt = TokenAmount::from_atto(600_000); h.apply_rewards(&mut rt, amt.clone(), TokenAmount::zero()); let st = h.get_state(&rt); let vesting_funds = st.load_vesting_funds(&rt.store).unwrap(); @@ -90,11 +88,11 @@ fn funds_vest() { fn penalty_is_burnt() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); - let rwd = TokenAmount::from(600_000); - let penalty = TokenAmount::from(300_000); + let rwd = TokenAmount::from_atto(600_000); + let penalty = TokenAmount::from_atto(300_000); rt.add_balance(rwd.clone()); h.apply_rewards(&mut rt, rwd.clone(), penalty.clone()); @@ -112,7 +110,7 @@ fn penalty_is_burnt() { fn penalty_is_partially_burnt_and_stored_as_fee_debt() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let st = h.get_state(&rt); assert!(st.fee_debt.is_zero()); @@ -160,7 +158,7 @@ fn penalty_is_partially_burnt_and_stored_as_fee_debt() { fn rewards_pay_back_fee_debt() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let mut st = h.get_state(&rt); @@ -194,8 +192,8 @@ fn rewards_pay_back_fee_debt() { rt.expect_send( *STORAGE_POWER_ACTOR_ADDR, PowerMethod::UpdatePledgeTotal as u64, - RawBytes::serialize(BigIntSer(&pledge_delta)).unwrap(), - TokenAmount::from(0u8), + RawBytes::serialize(&pledge_delta).unwrap(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); diff --git a/actors/miner/tests/batch_method_network_fees_test.rs b/actors/miner/tests/batch_method_network_fees_test.rs index 0c2f1e19e3..7ba39f4194 100644 --- a/actors/miner/tests/batch_method_network_fees_test.rs +++ b/actors/miner/tests/batch_method_network_fees_test.rs @@ -6,24 +6,21 @@ use fil_actor_miner::{ }; use fil_actors_runtime::test_utils::{expect_abort, expect_abort_contains_message}; use fvm_ipld_bitfield::BitField; -use fvm_shared::{bigint::BigInt, clock::ChainEpoch, error::ExitCode}; +use fvm_shared::{clock::ChainEpoch, econ::TokenAmount, error::ExitCode}; use lazy_static::lazy_static; mod util; -use num_traits::Zero; use util::*; lazy_static! { static ref PERIOD_OFFSET: ChainEpoch = ChainEpoch::from(100); } -const BIG_BALANCE: u128 = 1_000_000_000_000_000_000_000_000u128; - #[test] fn insufficient_funds_for_aggregated_prove_commit_network_fee() { let actor = ActorHarness::new(*PERIOD_OFFSET); let mut rt = actor.new_runtime(); - rt.set_balance(BigInt::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); let precommit_epoch = *PERIOD_OFFSET + 1; rt.set_epoch(precommit_epoch); actor.construct_and_verify(&mut rt); @@ -52,9 +49,9 @@ fn insufficient_funds_for_aggregated_prove_commit_network_fee() { // set base fee extremely high so AggregateProveCommitNetworkFee is > 1000 FIL. Set balance to 1000 FIL to easily cover IP but not cover network fee rt.set_epoch(prove_commit_epoch); - let balance = BigInt::from(1000u64) * BigInt::from(10u64.pow(18)); + let balance = TokenAmount::from_whole(1000); rt.set_balance(balance.clone()); - let base_fee = BigInt::from(10u64.pow(16)); + let base_fee = TokenAmount::from_atto(10u64.pow(16)); rt.base_fee = base_fee.clone(); assert!(aggregate_prove_commit_network_fee(precommits.len() as i64, &base_fee) > balance); @@ -63,7 +60,7 @@ fn insufficient_funds_for_aggregated_prove_commit_network_fee() { ProveCommitConfig::empty(), precommits, make_prove_commit_aggregate(§or_nos_bf), - base_fee, + &base_fee, ); expect_abort(ExitCode::USR_INSUFFICIENT_FUNDS, res); @@ -73,7 +70,7 @@ fn insufficient_funds_for_aggregated_prove_commit_network_fee() { fn insufficient_funds_for_batch_precommit_network_fee() { let actor = ActorHarness::new(*PERIOD_OFFSET); let mut rt = actor.new_runtime(); - rt.set_balance(BigInt::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); let precommit_epoch = *PERIOD_OFFSET + 1; rt.set_epoch(precommit_epoch); actor.construct_and_verify(&mut rt); @@ -91,9 +88,9 @@ fn insufficient_funds_for_batch_precommit_network_fee() { } // set base fee extremely high so AggregateProveCommitNetworkFee is > 1000 FIL. Set balance to 1000 FIL to easily cover PCD but not network fee - let balance = BigInt::from(1000u64) * BigInt::from(10u64.pow(18)); + let balance = TokenAmount::from_whole(1000); rt.set_balance(balance.clone()); - let base_fee = BigInt::from(10u64.pow(16)); + let base_fee = TokenAmount::from_atto(10u64.pow(16)); rt.base_fee = base_fee.clone(); assert!(aggregate_pre_commit_network_fee(precommits.len() as i64, &base_fee) > balance); @@ -101,12 +98,12 @@ fn insufficient_funds_for_batch_precommit_network_fee() { &mut rt, PreCommitSectorBatchParams { sectors: precommits }, &PreCommitBatchConfig { first_for_miner: true, ..Default::default() }, - base_fee, + &base_fee, ); // state untouched let state: State = rt.get_state(); - assert!(state.pre_commit_deposits == BigInt::zero()); + assert!(state.pre_commit_deposits.is_zero()); let expirations = actor.collect_precommit_expirations(&rt, &state); assert_eq!(HashMap::new(), expirations); @@ -121,7 +118,7 @@ fn insufficient_funds_for_batch_precommit_network_fee() { fn insufficient_funds_for_batch_precommit_in_combination_of_fee_debt_and_network_fee() { let actor = ActorHarness::new(*PERIOD_OFFSET); let mut rt = actor.new_runtime(); - rt.set_balance(BigInt::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); let precommit_epoch = *PERIOD_OFFSET + 1; rt.set_epoch(precommit_epoch); actor.construct_and_verify(&mut rt); @@ -139,7 +136,7 @@ fn insufficient_funds_for_batch_precommit_in_combination_of_fee_debt_and_network } // set base fee extremely high so AggregateProveCommitNetworkFee is > 1000 FIL. Set balance to 1000 FIL to easily cover PCD but not network fee - let base_fee = BigInt::from(10u64.pow(16)); + let base_fee = TokenAmount::from_atto(10u64.pow(16)); rt.base_fee = base_fee.clone(); let net_fee = aggregate_pre_commit_network_fee(precommits.len() as i64, &base_fee); @@ -149,20 +146,19 @@ fn insufficient_funds_for_batch_precommit_in_combination_of_fee_debt_and_network rt.replace_state(&state); // give miner almost enough balance to pay both - let mut balance = BigInt::from(2) * net_fee; - balance -= 1; + let balance = (2 * net_fee) - TokenAmount::from_atto(1); rt.set_balance(balance); let res = actor.pre_commit_sector_batch( &mut rt, PreCommitSectorBatchParams { sectors: precommits }, &PreCommitBatchConfig { first_for_miner: true, ..Default::default() }, - base_fee, + &base_fee, ); // state untouched let state: State = rt.get_state(); - assert!(state.pre_commit_deposits == BigInt::zero()); + assert!(state.pre_commit_deposits.is_zero()); let expirations = actor.collect_precommit_expirations(&rt, &state); assert_eq!(HashMap::new(), expirations); @@ -177,7 +173,7 @@ fn insufficient_funds_for_batch_precommit_in_combination_of_fee_debt_and_network fn enough_funds_for_fee_debt_and_network_fee_but_not_for_pcd() { let actor = ActorHarness::new(*PERIOD_OFFSET); let mut rt = actor.new_runtime(); - rt.set_balance(BigInt::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); let precommit_epoch = *PERIOD_OFFSET + 1; rt.set_epoch(precommit_epoch); actor.construct_and_verify(&mut rt); @@ -195,7 +191,7 @@ fn enough_funds_for_fee_debt_and_network_fee_but_not_for_pcd() { } // set base fee and fee debt high - let base_fee = BigInt::from(10u64.pow(16)); + let base_fee = TokenAmount::from_atto(10u64.pow(16)); rt.base_fee = base_fee.clone(); let net_fee = aggregate_pre_commit_network_fee(precommits.len() as i64, &base_fee); // setup miner to have feed debt equal to net fee @@ -211,7 +207,7 @@ fn enough_funds_for_fee_debt_and_network_fee_but_not_for_pcd() { &mut rt, PreCommitSectorBatchParams { sectors: precommits }, &PreCommitBatchConfig { first_for_miner: true, ..Default::default() }, - base_fee, + &base_fee, ); expect_abort_contains_message( @@ -231,7 +227,7 @@ fn enough_funds_for_fee_debt_and_network_fee_but_not_for_pcd() { fn enough_funds_for_everything() { let actor = ActorHarness::new(*PERIOD_OFFSET); let mut rt = actor.new_runtime(); - rt.set_balance(BigInt::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); let precommit_epoch = *PERIOD_OFFSET + 1; rt.set_epoch(precommit_epoch); actor.construct_and_verify(&mut rt); @@ -249,7 +245,7 @@ fn enough_funds_for_everything() { } // set base fee extremely high so AggregateProveCommitNetworkFee is > 1000 FIL. Set balance to 1000 FIL to easily cover PCD but not network fee - let base_fee = BigInt::from(10u64.pow(16)); + let base_fee = TokenAmount::from_atto(10u64.pow(16)); rt.base_fee = base_fee.clone(); let net_fee = aggregate_pre_commit_network_fee(precommits.len() as i64, &base_fee); @@ -259,7 +255,7 @@ fn enough_funds_for_everything() { rt.replace_state(&state); // give miner enough balance to pay both and pcd - let mut balance = BigInt::from(2) * net_fee; + let mut balance = 2 * net_fee; let expected_deposit = pre_commit_deposit_for_power( &actor.epoch_reward_smooth, &actor.epoch_qa_power_smooth, @@ -273,7 +269,7 @@ fn enough_funds_for_everything() { &mut rt, PreCommitSectorBatchParams { sectors: precommits }, &PreCommitBatchConfig { first_for_miner: true, ..Default::default() }, - base_fee, + &base_fee, ) .unwrap(); diff --git a/actors/miner/tests/change_beneficiary_test.rs b/actors/miner/tests/change_beneficiary_test.rs index 19bbe29c82..6207b60ff7 100644 --- a/actors/miner/tests/change_beneficiary_test.rs +++ b/actors/miner/tests/change_beneficiary_test.rs @@ -14,7 +14,7 @@ fn setup() -> (ActorHarness, MockRuntime) { let h = ActorHarness::new(period_offset); let mut rt = h.new_runtime(); h.construct_and_verify(&mut rt); - rt.balance.replace(TokenAmount::from(big_balance)); + rt.balance.replace(TokenAmount::from_atto(big_balance)); (h, rt) } @@ -24,8 +24,11 @@ fn successfully_change_owner_to_another_address_two_message() { let (mut h, mut rt) = setup(); let first_beneficiary_id = Address::new_id(999); - let beneficiary_change = - BeneficiaryChange::new(first_beneficiary_id, TokenAmount::from(100), ChainEpoch::from(200)); + let beneficiary_change = BeneficiaryChange::new( + first_beneficiary_id, + TokenAmount::from_atto(100), + ChainEpoch::from(200), + ); // proposal beneficiary change h.change_beneficiary(&mut rt, h.owner, &beneficiary_change, None).unwrap(); // assert change has been made in state @@ -55,14 +58,17 @@ fn successfully_change_from_not_owner_beneficiary_to_another_address_three_messa let first_beneficiary_id = Address::new_id(999); let second_beneficiary_id = Address::new_id(1001); - let first_beneficiary_term = - BeneficiaryTerm::new(TokenAmount::from(100), TokenAmount::zero(), ChainEpoch::from(200)); + let first_beneficiary_term = BeneficiaryTerm::new( + TokenAmount::from_atto(100), + TokenAmount::zero(), + ChainEpoch::from(200), + ); h.propose_approve_initial_beneficiary(&mut rt, first_beneficiary_id, first_beneficiary_term) .unwrap(); let second_beneficiary_change = BeneficiaryChange::new( second_beneficiary_id, - TokenAmount::from(101), + TokenAmount::from_atto(101), ChainEpoch::from(201), ); h.change_beneficiary(&mut rt, h.owner, &second_beneficiary_change, None).unwrap(); @@ -106,7 +112,7 @@ fn successfully_change_from_not_owner_beneficiary_to_another_address_when_benefi let first_beneficiary_id = Address::new_id(999); let second_beneficiary_id = Address::new_id(1000); - let quota = TokenAmount::from(100); + let quota = TokenAmount::from_atto(100); let expiration = ChainEpoch::from(200); h.propose_approve_initial_beneficiary( &mut rt, @@ -116,7 +122,7 @@ fn successfully_change_from_not_owner_beneficiary_to_another_address_when_benefi .unwrap(); rt.set_epoch(201); - let another_quota = TokenAmount::from(1001); + let another_quota = TokenAmount::from_atto(1001); let another_expiration = ChainEpoch::from(3); let another_beneficiary_change = BeneficiaryChange::new(second_beneficiary_id, another_quota, another_expiration); @@ -146,8 +152,11 @@ fn successfully_owner_immediate_revoking_unapproved_proposal() { let (mut h, mut rt) = setup(); let first_beneficiary_id = Address::new_id(999); - let beneficiary_change = - BeneficiaryChange::new(first_beneficiary_id, TokenAmount::from(100), ChainEpoch::from(200)); + let beneficiary_change = BeneficiaryChange::new( + first_beneficiary_id, + TokenAmount::from_atto(100), + ChainEpoch::from(200), + ); // proposal beneficiary change h.change_beneficiary(&mut rt, h.owner, &beneficiary_change, None).unwrap(); // assert change has been made in state @@ -176,7 +185,7 @@ fn successfully_immediately_change_back_to_owner_address_while_used_up_quota() { let (mut h, mut rt) = setup(); let first_beneficiary_id = Address::new_id(999); - let quota = TokenAmount::from(100); + let quota = TokenAmount::from_atto(100); let expiration = ChainEpoch::from(200); h.propose_approve_initial_beneficiary( &mut rt, @@ -205,7 +214,7 @@ fn successfully_immediately_change_back_to_owner_while_expired() { let (mut h, mut rt) = setup(); let first_beneficiary_id = Address::new_id(999); - let quota = TokenAmount::from(100); + let quota = TokenAmount::from_atto(100); let expiration = ChainEpoch::from(200); h.propose_approve_initial_beneficiary( &mut rt, @@ -233,16 +242,19 @@ fn successfully_immediately_change_back_to_owner_while_expired() { fn successfully_change_quota_and_test_withdraw() { let (mut h, mut rt) = setup(); let first_beneficiary_id = Address::new_id(999); - let beneficiary_term = - BeneficiaryTerm::new(TokenAmount::from(100), TokenAmount::zero(), ChainEpoch::from(200)); + let beneficiary_term = BeneficiaryTerm::new( + TokenAmount::from_atto(100), + TokenAmount::zero(), + ChainEpoch::from(200), + ); h.propose_approve_initial_beneficiary(&mut rt, first_beneficiary_id, beneficiary_term.clone()) .unwrap(); - let withdraw_fund = TokenAmount::from(80); + let withdraw_fund = TokenAmount::from_atto(80); h.withdraw_funds(&mut rt, h.beneficiary, &withdraw_fund, &withdraw_fund, &TokenAmount::zero()) .unwrap(); //decrease quota - let decrease_quota = TokenAmount::from(50); + let decrease_quota = TokenAmount::from_atto(50); let decrease_beneficiary_change = BeneficiaryChange::new(first_beneficiary_id, decrease_quota, beneficiary_term.expiration); h.change_beneficiary(&mut rt, h.owner, &decrease_beneficiary_change, None).unwrap(); @@ -261,7 +273,7 @@ fn successfully_change_quota_and_test_withdraw() { assert_eq!(withdraw_fund, beneficiary_return.active.term.used_quota); //withdraw 0 zero - let withdraw_left = TokenAmount::from(20); + let withdraw_left = TokenAmount::from_atto(20); h.withdraw_funds( &mut rt, h.beneficiary, @@ -271,7 +283,7 @@ fn successfully_change_quota_and_test_withdraw() { ) .unwrap(); - let increase_quota = TokenAmount::from(120); + let increase_quota = TokenAmount::from_atto(120); let increase_beneficiary_change = BeneficiaryChange::new(first_beneficiary_id, increase_quota, beneficiary_term.expiration); @@ -292,7 +304,7 @@ fn successfully_change_quota_and_test_withdraw() { assert_eq!(withdraw_fund, beneficiary_return.active.term.used_quota); //success withdraw 40 atto fil - let withdraw_left = TokenAmount::from(40); + let withdraw_left = TokenAmount::from_atto(40); h.withdraw_funds(&mut rt, h.beneficiary, &withdraw_left, &withdraw_left, &TokenAmount::zero()) .unwrap(); h.check_state(&rt); @@ -305,7 +317,7 @@ fn fails_approval_message_with_invalidate_params() { // proposal beneficiary let beneficiary_change = - &BeneficiaryChange::new(first_beneficiary_id, TokenAmount::from(100), 200); + &BeneficiaryChange::new(first_beneficiary_id, TokenAmount::from_atto(100), 200); h.change_beneficiary(&mut rt, h.owner, beneficiary_change, None).unwrap(); let beneficiary_return = h.get_beneficiary(&mut rt).unwrap(); assert_eq!( @@ -319,7 +331,7 @@ fn fails_approval_message_with_invalidate_params() { h.change_beneficiary( &mut rt, first_beneficiary_id, - &BeneficiaryChange::new(first_beneficiary_id, TokenAmount::from(100), 201), + &BeneficiaryChange::new(first_beneficiary_id, TokenAmount::from_atto(100), 201), None, ), ); @@ -330,7 +342,7 @@ fn fails_approval_message_with_invalidate_params() { h.change_beneficiary( &mut rt, first_beneficiary_id, - &BeneficiaryChange::new(first_beneficiary_id, TokenAmount::from(101), 200), + &BeneficiaryChange::new(first_beneficiary_id, TokenAmount::from_atto(101), 200), None, ), ); @@ -342,7 +354,7 @@ fn fails_approval_message_with_invalidate_params() { h.change_beneficiary( &mut rt, first_beneficiary_id, - &BeneficiaryChange::new(second_beneficiary_id, TokenAmount::from(100), 200), + &BeneficiaryChange::new(second_beneficiary_id, TokenAmount::from_atto(100), 200), None, ), ); @@ -359,7 +371,7 @@ fn fails_proposal_beneficiary_with_invalidate_params() { h.change_beneficiary( &mut rt, first_beneficiary_id, - &BeneficiaryChange::new(first_beneficiary_id, TokenAmount::from(100), 200), + &BeneficiaryChange::new(first_beneficiary_id, TokenAmount::from_atto(100), 200), None, ), ); @@ -370,7 +382,7 @@ fn fails_proposal_beneficiary_with_invalidate_params() { h.change_beneficiary( &mut rt, h.owner, - &BeneficiaryChange::new(first_beneficiary_id, TokenAmount::from(0), 200), + &BeneficiaryChange::new(first_beneficiary_id, TokenAmount::zero(), 200), None, ), ); @@ -381,7 +393,7 @@ fn fails_proposal_beneficiary_with_invalidate_params() { h.change_beneficiary( &mut rt, h.owner, - &BeneficiaryChange::new(h.owner, TokenAmount::from(20), 0), + &BeneficiaryChange::new(h.owner, TokenAmount::from_atto(20), 0), None, ), ); @@ -392,7 +404,7 @@ fn fails_proposal_beneficiary_with_invalidate_params() { h.change_beneficiary( &mut rt, h.owner, - &BeneficiaryChange::new(h.owner, TokenAmount::from(0), 1), + &BeneficiaryChange::new(h.owner, TokenAmount::zero(), 1), None, ), ); @@ -406,8 +418,11 @@ fn successfully_get_beneficiary() { assert_eq!(BeneficiaryTerm::default(), beneficiary_return.active.term); let first_beneficiary_id = Address::new_id(999); - let beneficiary_term = - BeneficiaryTerm::new(TokenAmount::from(100), TokenAmount::zero(), ChainEpoch::from(200)); + let beneficiary_term = BeneficiaryTerm::new( + TokenAmount::from_atto(100), + TokenAmount::zero(), + ChainEpoch::from(200), + ); h.propose_approve_initial_beneficiary(&mut rt, first_beneficiary_id, beneficiary_term).unwrap(); let beneficiary = h.get_beneficiary(&mut rt).unwrap(); @@ -417,7 +432,7 @@ fn successfully_get_beneficiary() { assert_eq!(beneficiary.active.term.quota, info.beneficiary_term.quota); assert_eq!(beneficiary.active.term.used_quota, info.beneficiary_term.used_quota); - let withdraw_fund = TokenAmount::from(40); + let withdraw_fund = TokenAmount::from_atto(40); h.withdraw_funds(&mut rt, h.beneficiary, &withdraw_fund, &withdraw_fund, &TokenAmount::zero()) .unwrap(); diff --git a/actors/miner/tests/change_owner_address_test.rs b/actors/miner/tests/change_owner_address_test.rs index 56fd905dc3..6e5d0f6f99 100644 --- a/actors/miner/tests/change_owner_address_test.rs +++ b/actors/miner/tests/change_owner_address_test.rs @@ -1,7 +1,7 @@ use fil_actors_runtime::test_utils::{ expect_abort, new_bls_addr, MockRuntime, ACCOUNT_ACTOR_CODE_ID, MULTISIG_ACTOR_CODE_ID, }; -use fvm_shared::{address::Address, econ::TokenAmount, error::ExitCode}; +use fvm_shared::{address::Address, error::ExitCode}; mod util; use util::*; @@ -10,13 +10,12 @@ const NEW_ADDRESS: Address = Address::new_id(1001); const OTHER_ADDRESS: Address = Address::new_id(1002); fn setup() -> (ActorHarness, MockRuntime) { - let big_balance = 20u128.pow(23); let period_offset = 100; let h = ActorHarness::new(period_offset); let mut rt = h.new_runtime(); h.construct_and_verify(&mut rt); - rt.balance.replace(TokenAmount::from(big_balance)); + rt.balance.replace(BIG_BALANCE.clone()); (h, rt) } diff --git a/actors/miner/tests/change_peer_id_test.rs b/actors/miner/tests/change_peer_id_test.rs index 08a1b03d96..1fd3cbeb20 100644 --- a/actors/miner/tests/change_peer_id_test.rs +++ b/actors/miner/tests/change_peer_id_test.rs @@ -1,18 +1,16 @@ use fil_actors_runtime::test_utils::MockRuntime; -use fvm_shared::econ::TokenAmount; mod util; use util::*; fn setup() -> (ActorHarness, MockRuntime) { - let big_balance = 20u128.pow(23); let period_offset = 100; let precommit_epoch = 1; let h = ActorHarness::new(period_offset); let mut rt = h.new_runtime(); h.construct_and_verify(&mut rt); - rt.balance.replace(TokenAmount::from(big_balance)); + rt.balance.replace(BIG_BALANCE.clone()); rt.set_epoch(precommit_epoch); (h, rt) diff --git a/actors/miner/tests/change_worker_address_test.rs b/actors/miner/tests/change_worker_address_test.rs index 6e61a8a13a..58cd4d9b16 100644 --- a/actors/miner/tests/change_worker_address_test.rs +++ b/actors/miner/tests/change_worker_address_test.rs @@ -16,13 +16,12 @@ use num_traits::Zero; use util::*; fn setup() -> (ActorHarness, MockRuntime) { - let big_balance = 20u128.pow(23); let period_offset = 100; let h = ActorHarness::new(period_offset); let mut rt = h.new_runtime(); h.construct_and_verify(&mut rt); - rt.balance.replace(TokenAmount::from(big_balance)); + rt.balance.replace(BIG_BALANCE.clone()); (h, rt) } diff --git a/actors/miner/tests/check_sector_proven_test.rs b/actors/miner/tests/check_sector_proven_test.rs index 8a2fa0030f..56223fe445 100644 --- a/actors/miner/tests/check_sector_proven_test.rs +++ b/actors/miner/tests/check_sector_proven_test.rs @@ -1,17 +1,16 @@ use fil_actors_runtime::test_utils::{expect_abort, MockRuntime}; -use fvm_shared::{econ::TokenAmount, error::ExitCode}; +use fvm_shared::error::ExitCode; mod util; use util::*; fn setup() -> (ActorHarness, MockRuntime) { - let big_balance = 20u128.pow(23); let period_offset = 100; let h = ActorHarness::new(period_offset); let mut rt = h.new_runtime(); h.construct_and_verify(&mut rt); - rt.balance.replace(TokenAmount::from(big_balance)); + rt.balance.replace(BIG_BALANCE.clone()); (h, rt) } diff --git a/actors/miner/tests/compact_partitions_test.rs b/actors/miner/tests/compact_partitions_test.rs index cbec84b3f4..a873f3f394 100644 --- a/actors/miner/tests/compact_partitions_test.rs +++ b/actors/miner/tests/compact_partitions_test.rs @@ -11,18 +11,16 @@ use fvm_ipld_bitfield::BitField; use fvm_shared::{clock::ChainEpoch, econ::TokenAmount, error::ExitCode, sector::SectorNumber}; mod util; -use fvm_shared::bigint::{BigInt, Zero}; +use fvm_shared::bigint::Zero; use itertools::Itertools; use util::*; const PERIOD_OFFSET: ChainEpoch = 100; fn setup() -> (ActorHarness, MockRuntime) { - let big_balance = 20u128.pow(23); - let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); h.construct_and_verify(&mut rt); - rt.balance.replace(TokenAmount::from(big_balance)); + rt.balance.replace(BIG_BALANCE.clone()); (h, rt) } @@ -71,7 +69,7 @@ fn compacting_a_partition_with_both_live_and_dead_sectors_removes_dead_sectors_r // terminate sector 1 rt.set_epoch(rt.epoch + 100); - h.apply_rewards(&mut rt, BIG_REWARDS.into(), BigInt::zero()); + h.apply_rewards(&mut rt, BIG_REWARDS.clone(), TokenAmount::zero()); let terminated_sector = §ors_info[0]; let sector_size = terminated_sector.seal_proof.sector_size().unwrap(); @@ -96,7 +94,7 @@ fn compacting_a_partition_with_both_live_and_dead_sectors_removes_dead_sectors_r &h.epoch_qa_power_smooth, §or_power, &h.epoch_reward_smooth, - &BigInt::zero(), + &TokenAmount::zero(), 0, ); diff --git a/actors/miner/tests/compact_sector_numbers_tests.rs b/actors/miner/tests/compact_sector_numbers_tests.rs index 79f7883da1..1ba75fa1ef 100644 --- a/actors/miner/tests/compact_sector_numbers_tests.rs +++ b/actors/miner/tests/compact_sector_numbers_tests.rs @@ -1,7 +1,7 @@ use fil_actors_runtime::test_utils::{expect_abort, MockRuntime}; use fvm_shared::address::Address; use fvm_shared::sector::MAX_SECTOR_NUMBER; -use fvm_shared::{clock::ChainEpoch, econ::TokenAmount, error::ExitCode}; +use fvm_shared::{clock::ChainEpoch, error::ExitCode}; mod util; use util::*; @@ -9,12 +9,10 @@ use util::*; const PERIOD_OFFSET: ChainEpoch = 100; fn setup() -> (ActorHarness, MockRuntime) { - let big_balance = 20u128.pow(23); - let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); h.construct_and_verify(&mut rt); - rt.balance.replace(TokenAmount::from(big_balance)); + rt.balance.replace(BIG_BALANCE.clone()); (h, rt) } diff --git a/actors/miner/tests/confirm_update_worker_key_test.rs b/actors/miner/tests/confirm_update_worker_key_test.rs index 296f2075df..d19ff46007 100644 --- a/actors/miner/tests/confirm_update_worker_key_test.rs +++ b/actors/miner/tests/confirm_update_worker_key_test.rs @@ -3,7 +3,7 @@ use fil_actors_runtime::{ runtime::{Runtime, RuntimePolicy}, test_utils::MockRuntime, }; -use fvm_shared::{address::Address, econ::TokenAmount}; +use fvm_shared::address::Address; mod util; use util::*; @@ -11,14 +11,13 @@ use util::*; const NEW_WORKER: Address = Address::new_id(999); fn setup() -> (ActorHarness, MockRuntime) { - let big_balance = 20u128.pow(23); let period_offset = 100; let current_epoch = 5; let h = ActorHarness::new(period_offset); let mut rt = h.new_runtime(); h.construct_and_verify(&mut rt); - rt.balance.replace(TokenAmount::from(big_balance)); + rt.balance.replace(BIG_BALANCE.clone()); rt.set_epoch(current_epoch); (h, rt) diff --git a/actors/miner/tests/deadline_cron.rs b/actors/miner/tests/deadline_cron.rs index 8be43ec78c..f0536fba7e 100644 --- a/actors/miner/tests/deadline_cron.rs +++ b/actors/miner/tests/deadline_cron.rs @@ -19,14 +19,12 @@ use crate::util::*; const DEFAULT_SECTOR_EXPIRATION: ChainEpoch = 220; const PERIOD_OFFSET: ChainEpoch = 100; -const BIG_BALANCE: u128 = 1_000_000_000_000_000_000_000_000u128; -const BIG_REWARDS: u128 = 1_000 * 1e18 as u128; #[test] fn cron_on_inactive_state() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let st = h.get_state(&rt); @@ -45,7 +43,7 @@ fn cron_on_inactive_state() { fn sector_expires() { let mut h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let sectors = @@ -92,7 +90,7 @@ fn sector_expires() { fn sector_expires_and_repays_fee_debt() { let mut h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let sectors = @@ -122,7 +120,7 @@ fn sector_expires_and_repays_fee_debt() { // introduce lots of fee debt let mut st = h.get_state(&rt); - let fee_debt = TokenAmount::from(400) * TokenAmount::from(1e18 as u64); + let fee_debt = TokenAmount::from_whole(400); st.fee_debt = fee_debt; rt.replace_state(&st); // Miner balance = IP, debt repayment covered by unlocked funds @@ -149,7 +147,7 @@ fn sector_expires_and_repays_fee_debt() { fn detects_and_penalizes_faults() { let mut h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let active_sectors = @@ -166,7 +164,7 @@ fn detects_and_penalizes_faults() { let all_sectors = [active_sectors.clone(), unproven_sectors].concat(); // add lots of funds so penalties come from vesting funds - h.apply_rewards(&mut rt, TokenAmount::from(BIG_REWARDS), TokenAmount::zero()); + h.apply_rewards(&mut rt, BIG_REWARDS.clone(), TokenAmount::zero()); let st = h.get_state(&rt); let (dl_idx, p_idx) = @@ -239,11 +237,11 @@ fn detects_and_penalizes_faults() { fn test_cron_run_trigger_faults() { let mut h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); // add lots of funds so we can pay penalties without going into debt - h.apply_rewards(&mut rt, TokenAmount::from(BIG_REWARDS), TokenAmount::zero()); + h.apply_rewards(&mut rt, BIG_REWARDS.clone(), TokenAmount::zero()); // create enough sectors that one will be in a different partition let all_sectors = diff --git a/actors/miner/tests/deadline_cron_defers_stops_restarts.rs b/actors/miner/tests/deadline_cron_defers_stops_restarts.rs index 684f507449..a74c16a3a6 100644 --- a/actors/miner/tests/deadline_cron_defers_stops_restarts.rs +++ b/actors/miner/tests/deadline_cron_defers_stops_restarts.rs @@ -1,17 +1,15 @@ use fvm_shared::clock::ChainEpoch; -use fvm_shared::econ::TokenAmount; mod util; use util::*; const PERIOD_OFFSET: ChainEpoch = 100; -const BIG_BALANCE: u128 = 1_000_000_000_000_000_000_000_000u128; #[test] fn cron_enrolls_on_precommit_prove_commits_and_continues_enrolling() { let mut h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let cron_ctrl = CronControl::default(); @@ -37,7 +35,7 @@ fn cron_enrolls_on_precommit_prove_commits_and_continues_enrolling() { fn cron_enrolls_on_precommit_expires_on_pcd_expiration_re_enrolls_on_new_precommit_immediately() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); let epoch = PERIOD_OFFSET + 1; rt.set_epoch(epoch); h.construct_and_verify(&mut rt); @@ -52,7 +50,7 @@ fn cron_enrolls_on_precommit_expires_on_pcd_expiration_re_enrolls_on_new_precomm ) { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); let mut epoch = PERIOD_OFFSET + 1; rt.set_epoch(epoch); h.construct_and_verify(&mut rt); @@ -71,7 +69,7 @@ fn cron_enrolls_on_precommit_expires_on_pcd_expiration_re_enrolls_on_new_precomm fn enroll_pcd_expire_re_enroll_x_3() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); let mut epoch = PERIOD_OFFSET + 1; rt.set_epoch(epoch); h.construct_and_verify(&mut rt); diff --git a/actors/miner/tests/declare_faults.rs b/actors/miner/tests/declare_faults.rs index 3e5768ecc8..3872eaf606 100644 --- a/actors/miner/tests/declare_faults.rs +++ b/actors/miner/tests/declare_faults.rs @@ -1,9 +1,11 @@ use fil_actor_miner::pledge_penalty_for_continued_fault; use fil_actor_miner::power_for_sectors; -use fvm_shared::bigint::BigInt; + use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; +use num_traits::Zero; + mod util; use crate::util::*; @@ -12,23 +14,22 @@ use crate::util::*; const DEFAULT_SECTOR_EXPIRATION: ChainEpoch = 220; const PERIOD_OFFSET: ChainEpoch = 100; -const BIG_BALANCE: u128 = 1_000_000_000_000_000_000_000_000u128; #[test] fn declare_fault_pays_fee_at_window_post() { - let big_rewards: BigInt = BigInt::from(1_000_000_000_000_000_000_000_i128); + let big_rewards = TokenAmount::from_whole(1000); // Get sector into proving state let mut h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let all_sectors = h.commit_and_prove_sectors(&mut rt, 1, DEFAULT_SECTOR_EXPIRATION as u64, vec![], true); let pwr = power_for_sectors(h.sector_size, &all_sectors); // add lots of funds so penalties come from vesting funds - h.apply_rewards(&mut rt, big_rewards, BigInt::from(0)); + h.apply_rewards(&mut rt, big_rewards, TokenAmount::zero()); // find deadline for sector let st = h.get_state(&rt); diff --git a/actors/miner/tests/declare_recoveries.rs b/actors/miner/tests/declare_recoveries.rs index 209c778af4..29ae87f3ff 100644 --- a/actors/miner/tests/declare_recoveries.rs +++ b/actors/miner/tests/declare_recoveries.rs @@ -4,18 +4,18 @@ use fil_actors_runtime::test_utils::expect_abort_contains_message; use fil_actors_runtime::test_utils::MockRuntime; use fvm_ipld_bitfield::BitField; use fvm_shared::address::Address; -use fvm_shared::bigint::BigInt; + use fvm_shared::clock::ChainEpoch; use fvm_shared::consensus::{ConsensusFault, ConsensusFaultType}; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; + use num_traits::Zero; mod util; use crate::util::*; const PERIOD_OFFSET: ChainEpoch = 100; -const BIG_BALANCE: u128 = 1_000_000_000_000_000_000_000_000u128; #[test] fn recovery_happy_path() { @@ -38,7 +38,7 @@ fn recovery_happy_path() { dl_idx, p_idx, BitField::try_from_bits([one_sector[0].sector_number]).unwrap(), - BigInt::zero(), + TokenAmount::zero(), ) .unwrap(); @@ -79,7 +79,7 @@ fn recovery_must_pay_back_fee_debt() { h.advance_deadline( &mut rt, CronConfig { - continued_faults_penalty: BigInt::zero(), // fee is instead added to debt + continued_faults_penalty: TokenAmount::zero(), // fee is instead added to debt ..Default::default() }, ); @@ -96,7 +96,7 @@ fn recovery_must_pay_back_fee_debt() { dl_idx, p_idx, BitField::try_from_bits([one_sector[0].sector_number]).unwrap(), - BigInt::zero(), + TokenAmount::zero(), ), ); @@ -116,7 +116,7 @@ fn recovery_must_pay_back_fee_debt() { let p = dl.load_partition(&rt.store, p_idx).unwrap(); assert_eq!(p.faults, p.recoveries); st = h.get_state(&rt); - assert_eq!(BigInt::zero(), st.fee_debt); + assert!(st.fee_debt.is_zero()); h.check_state(&rt); } @@ -156,7 +156,7 @@ fn recovery_fails_during_active_consensus_fault() { dl_idx, p_idx, BitField::try_from_bits([one_sector[0].sector_number]).unwrap(), - BigInt::zero(), + TokenAmount::zero(), ), ); h.check_state(&rt); @@ -166,7 +166,7 @@ fn setup() -> (ActorHarness, MockRuntime) { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); h.construct_and_verify(&mut rt); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); (h, rt) } diff --git a/actors/miner/tests/expected_reward_for_power_clampted_at_atto_fil_test.rs b/actors/miner/tests/expected_reward_for_power_clampted_at_atto_fil_test.rs index d8a76627ce..1577683bd0 100644 --- a/actors/miner/tests/expected_reward_for_power_clampted_at_atto_fil_test.rs +++ b/actors/miner/tests/expected_reward_for_power_clampted_at_atto_fil_test.rs @@ -8,7 +8,7 @@ use fvm_shared::smooth::FilterEstimate; #[test] fn expected_zero_valued_br_clamped_at_1_attofil() { - let epoch_target_reward = TokenAmount::from(1u64 << 50); + let epoch_target_reward = BigInt::from(1u64 << 50); let zero_qa_power = StoragePower::zero(); let network_qa_power = StoragePower::from(1u64 << 10); let power_rate_of_change = StoragePower::from(1 << 10); @@ -21,12 +21,12 @@ fn expected_zero_valued_br_clamped_at_1_attofil() { &zero_qa_power, 1, ); - assert_eq!(BigInt::from(1), br_clamped); + assert_eq!(TokenAmount::from_atto(1), br_clamped); } #[test] fn expected_negative_value_br_clamped_at_1_atto_fil() { - let epoch_target_reward = TokenAmount::from(1u64 << 50); + let epoch_target_reward = BigInt::from(1u64 << 50); let qa_sector_power = StoragePower::from(1u64 << 36); let network_qa_power = StoragePower::from(1u64 << 10); let power_rate_of_change = StoragePower::from(1 << 10).neg(); @@ -39,5 +39,5 @@ fn expected_negative_value_br_clamped_at_1_atto_fil() { &qa_sector_power, 4, ); - assert_eq!(BigInt::from(1), four_br_clamped); + assert_eq!(TokenAmount::from_atto(1), four_br_clamped); } diff --git a/actors/miner/tests/expiration_queue.rs b/actors/miner/tests/expiration_queue.rs index b4d58c2330..1000e3a8c7 100644 --- a/actors/miner/tests/expiration_queue.rs +++ b/actors/miner/tests/expiration_queue.rs @@ -31,7 +31,7 @@ fn early_sectors() -> BitField { mk_bitfield([2, 3]) } fn on_time_pledge() -> TokenAmount { - TokenAmount::from(1_000) + TokenAmount::from_atto(1_000) } fn active_power() -> PowerPair { PowerPair { raw: StoragePower::from(1 << 13), qa: StoragePower::from(1 << 14) } @@ -78,7 +78,7 @@ fn adds_sectors_and_power_to_non_empty_set() { set.add( &mk_bitfield([6, 7, 11]), &mk_bitfield([1, 4]), - &TokenAmount::from(300), + &TokenAmount::from_atto(300), &power_pair(3, 13), &power_pair(3, 11), ) @@ -86,7 +86,7 @@ fn adds_sectors_and_power_to_non_empty_set() { assert_eq!(set.on_time_sectors, mk_bitfield([5, 6, 7, 8, 9, 11])); assert_eq!(set.early_sectors, mk_bitfield([1, 2, 3, 4])); - assert_eq!(set.on_time_pledge, TokenAmount::from(1300)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(1300)); let active = power_pair(1, 15); assert_eq!(set.active_power, active); let faulty = power_pair(1, 13); @@ -100,7 +100,7 @@ fn removes_sectors_and_power_set() { set.remove( &mk_bitfield([9]), &mk_bitfield([2]), - &TokenAmount::from(800), + &TokenAmount::from_atto(800), &power_pair(3, 11), &power_pair(3, 9), ) @@ -108,7 +108,7 @@ fn removes_sectors_and_power_set() { assert_eq!(set.on_time_sectors, mk_bitfield([5, 8])); assert_eq!(set.early_sectors, mk_bitfield([3])); - assert_eq!(set.on_time_pledge, TokenAmount::from(200)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(200)); let active = power_pair(1, 11); assert_eq!(set.active_power, active); let faulty = power_pair(1, 9); @@ -123,7 +123,7 @@ fn remove_fails_when_pledge_underflows() { .remove( &mk_bitfield([9]), &mk_bitfield([2]), - &TokenAmount::from(1200), + &TokenAmount::from_atto(1200), &power_pair(3, 11), &power_pair(3, 9), ) @@ -178,7 +178,7 @@ fn remove_fails_when_active_or_fault_qa_power_underflows() { .remove( &mk_bitfield([9]), &mk_bitfield([2]), - &TokenAmount::from(200), + &TokenAmount::from_atto(200), &power_pair(3, 12), &power_pair(3, 9), ) @@ -195,7 +195,7 @@ fn remove_fails_when_active_or_fault_qa_power_underflows() { .remove( &mk_bitfield([9]), &mk_bitfield([2]), - &TokenAmount::from(200), + &TokenAmount::from_atto(200), &power_pair(3, 11), &power_pair(3, 10), ) @@ -259,7 +259,7 @@ fn added_sectors_can_be_popped_off_queue() { let (sec_nums, power, pledge) = queue.add_active_sectors(§ors(), SECTOR_SIZE).unwrap(); assert_eq!(sec_nums, mk_bitfield([1, 2, 3, 4, 5, 6])); assert_eq!(power, power_for_sectors(SECTOR_SIZE, §ors())); - assert_eq!(pledge, TokenAmount::from(6015)); + assert_eq!(pledge, TokenAmount::from_atto(6015)); // default test quantizing of 1 means every sector is in its own expriation set assert_eq!(sectors().len(), queue.amt.count() as usize); @@ -278,7 +278,7 @@ fn added_sectors_can_be_popped_off_queue() { let active_power = power_for_sectors(SECTOR_SIZE, §ors()[0..3]); let faulty_power = PowerPair::zero(); - assert_eq!(set.on_time_pledge, TokenAmount::from(3003)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(3003)); assert_eq!(set.active_power, active_power); assert_eq!(set.faulty_power, faulty_power); @@ -288,7 +288,7 @@ fn added_sectors_can_be_popped_off_queue() { assert_eq!(set.on_time_sectors, mk_bitfield([4, 5, 6])); assert!(set.early_sectors.is_empty()); - assert_eq!(set.on_time_pledge, TokenAmount::from(3012)); // sum of last 3 sector pledges + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(3012)); // sum of last 3 sector pledges assert_eq!(set.active_power, power_for_sectors(SECTOR_SIZE, §ors()[0..3])); assert_eq!(set.faulty_power, PowerPair::zero()); @@ -306,7 +306,7 @@ fn quantizes_added_sectors_by_expiration() { let (sec_nums, power, pledge) = queue.add_active_sectors(§ors(), SECTOR_SIZE).unwrap(); assert_eq!(sec_nums, mk_bitfield([1, 2, 3, 4, 5, 6])); assert_eq!(power, power_for_sectors(SECTOR_SIZE, §ors())); - assert_eq!(pledge, TokenAmount::from(6015)); + assert_eq!(pledge, TokenAmount::from_atto(6015)); // quantizing spec means sectors should be grouped into 3 sets expiring at 3, 8 and 13 assert_eq!(queue.amt.count(), 3); @@ -373,7 +373,7 @@ fn reschedules_sectors_as_faults() { assert_eq!(set.on_time_sectors, mk_bitfield([1, 2])); assert!(set.early_sectors.is_empty()); - assert_eq!(set.on_time_pledge, TokenAmount::from(2001)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(2001)); assert_eq!(set.active_power, power_for_sectors(SECTOR_SIZE, §ors()[0..1])); assert_eq!(set.faulty_power, power_for_sectors(SECTOR_SIZE, §ors()[1..2])); @@ -385,7 +385,7 @@ fn reschedules_sectors_as_faults() { assert_eq!(set.early_sectors, mk_bitfield([5])); // pledge is kept from original 2 sectors. Pledge from new early sector is NOT added. - assert_eq!(set.on_time_pledge, TokenAmount::from(2005)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(2005)); assert_eq!(set.active_power, PowerPair::zero()); assert_eq!(set.faulty_power, power_for_sectors(SECTOR_SIZE, §ors()[2..5])); @@ -398,7 +398,7 @@ fn reschedules_sectors_as_faults() { assert!(set.early_sectors.is_empty()); // Pledge from sector moved from this set is dropped - assert_eq!(set.on_time_pledge, TokenAmount::from(1005)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(1005)); assert_eq!(set.active_power, power_for_sectors(SECTOR_SIZE, §ors()[5..])); assert_eq!(set.faulty_power, PowerPair::zero()); @@ -428,7 +428,7 @@ fn reschedules_all_sectors_as_faults() { assert_eq!(set.on_time_sectors, mk_bitfield([1, 2])); // sectors are unmoved assert!(set.early_sectors.is_empty()); - assert_eq!(set.on_time_pledge, TokenAmount::from(2001)); // pledge is same + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(2001)); // pledge is same // active power is converted to fault power assert_eq!(set.active_power, PowerPair::zero()); @@ -442,7 +442,7 @@ fn reschedules_all_sectors_as_faults() { assert_eq!(set.early_sectors, mk_bitfield([5, 6])); // pledge is kept from original 2 sectors. Pledge from new early sectors is NOT added. - assert_eq!(set.on_time_pledge, TokenAmount::from(2005)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(2005)); // fault power is all power for sectors previously in the second and third sets assert_eq!(set.active_power, PowerPair::zero()); @@ -491,7 +491,7 @@ fn reschedule_recover_restores_all_sector_stats() { assert!(set.early_sectors.is_empty()); // pledge from both sectors - assert_eq!(set.on_time_pledge, TokenAmount::from(2001)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(2001)); assert_eq!(set.active_power, power_for_sectors(SECTOR_SIZE, §ors()[0..2])); assert_eq!(set.faulty_power, PowerPair::zero()); @@ -504,7 +504,7 @@ fn reschedule_recover_restores_all_sector_stats() { assert!(set.early_sectors.is_empty()); // pledge is kept from original 2 sectors - assert_eq!(set.on_time_pledge, TokenAmount::from(2005)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(2005)); assert_eq!(set.active_power, power_for_sectors(SECTOR_SIZE, §ors()[2..4])); assert_eq!(set.faulty_power, PowerPair::zero()); @@ -517,7 +517,7 @@ fn reschedule_recover_restores_all_sector_stats() { assert!(set.early_sectors.is_empty()); // Pledge from sector 5 is restored - assert_eq!(set.on_time_pledge, TokenAmount::from(2009)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(2009)); assert_eq!(set.active_power, power_for_sectors(SECTOR_SIZE, §ors()[4..])); assert_eq!(set.faulty_power, PowerPair::zero()); @@ -551,7 +551,7 @@ fn replaces_sectors_with_new_sectors() { assert_eq!(added, mk_bitfield([3, 5])); let added_power = power_for_sectors(SECTOR_SIZE, &to_add); assert_eq!(power_delta, &added_power - &power_for_sectors(SECTOR_SIZE, &to_remove)); - assert_eq!(TokenAmount::from(1002 + 1004 - 1000 - 1001 - 1003), pledge_delta); + assert_eq!(TokenAmount::from_atto(1002 + 1004 - 1000 - 1001 - 1003), pledge_delta); // first set is gone require_no_expiration_groups_before(9, &mut queue); @@ -563,7 +563,7 @@ fn replaces_sectors_with_new_sectors() { assert!(set.early_sectors.is_empty()); // pledge and power is only from sector 3 - assert_eq!(set.on_time_pledge, TokenAmount::from(1002)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(1002)); assert_eq!(set.active_power, power_for_sectors(SECTOR_SIZE, §ors[2..3])); assert_eq!(set.faulty_power, PowerPair::zero()); @@ -575,7 +575,7 @@ fn replaces_sectors_with_new_sectors() { assert!(set.early_sectors.is_empty()); // pledge and power are the sum of old and new sectors - assert_eq!(set.on_time_pledge, TokenAmount::from(2009)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(2009)); assert_eq!(set.active_power, power_for_sectors(SECTOR_SIZE, §ors[4..])); assert_eq!(set.faulty_power, PowerPair::zero()); } @@ -611,7 +611,7 @@ fn removes_sectors() { // assert all return values are correct assert_eq!(removed.on_time_sectors, mk_bitfield([1, 4])); assert_eq!(removed.early_sectors, mk_bitfield([5, 6])); - assert_eq!(removed.on_time_pledge, TokenAmount::from(1000 + 1003)); // only on-time sectors + assert_eq!(removed.on_time_pledge, TokenAmount::from_atto(1000 + 1003)); // only on-time sectors assert_eq!(removed.active_power, power_for_sectors(SECTOR_SIZE, §ors()[0..1])); assert_eq!(removed.faulty_power, power_for_sectors(SECTOR_SIZE, §ors()[3..6])); assert_eq!(recovering_power, power_for_sectors(SECTOR_SIZE, §ors()[5..6])); @@ -624,7 +624,7 @@ fn removes_sectors() { assert_eq!(set.on_time_sectors, mk_bitfield([2])); assert!(set.early_sectors.is_empty()); - assert_eq!(set.on_time_pledge, TokenAmount::from(1001)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(1001)); assert_eq!(set.active_power, PowerPair::zero()); assert_eq!(set.faulty_power, power_for_sectors(SECTOR_SIZE, §ors()[1..2])); @@ -634,7 +634,7 @@ fn removes_sectors() { assert_eq!(set.on_time_sectors, mk_bitfield([3])); assert!(set.early_sectors.is_empty()); - assert_eq!(set.on_time_pledge, TokenAmount::from(1002)); + assert_eq!(set.on_time_pledge, TokenAmount::from_atto(1002)); assert_eq!(set.active_power, PowerPair::zero()); assert_eq!(set.faulty_power, power_for_sectors(SECTOR_SIZE, §ors()[2..3])); @@ -703,7 +703,7 @@ fn test_sector( sector_number, deal_weight: DealWeight::from(weight), verified_deal_weight: DealWeight::from(vweight), - initial_pledge: TokenAmount::from(pledge), + initial_pledge: TokenAmount::from_atto(pledge), sealed_cid: make_sealed_cid(format!("commR-{}", sector_number).as_bytes()), ..Default::default() } diff --git a/actors/miner/tests/extend_sector_expiration_test.rs b/actors/miner/tests/extend_sector_expiration_test.rs index 47268dc96d..dd40efa168 100644 --- a/actors/miner/tests/extend_sector_expiration_test.rs +++ b/actors/miner/tests/extend_sector_expiration_test.rs @@ -7,9 +7,7 @@ use fil_actors_runtime::{ test_utils::{expect_abort_contains_message, MockRuntime}, }; use fvm_ipld_bitfield::{BitField, UnvalidatedBitField}; -use fvm_shared::{ - clock::ChainEpoch, econ::TokenAmount, error::ExitCode, sector::RegisteredSealProof, -}; +use fvm_shared::{clock::ChainEpoch, error::ExitCode, sector::RegisteredSealProof}; mod util; use itertools::Itertools; @@ -19,7 +17,6 @@ use util::*; const DEFAULT_SECTOR_EXPIRATION: ChainEpoch = 220; fn setup() -> (ActorHarness, MockRuntime) { - let big_balance = 10u128.pow(24); let period_offset = 100; let precommit_epoch = 1; @@ -28,7 +25,7 @@ fn setup() -> (ActorHarness, MockRuntime) { // if changed to V1P1 the rejects_extension_past_max_for_seal_proof test fails h.set_proof_type(RegisteredSealProof::StackedDRG512MiBV1); let mut rt = h.new_runtime(); - rt.balance.replace(TokenAmount::from(big_balance)); + rt.balance.replace(BIG_BALANCE.clone()); rt.set_epoch(precommit_epoch); (h, rt) diff --git a/actors/miner/tests/miner_actor_test_commitment.rs b/actors/miner/tests/miner_actor_test_commitment.rs index a6d2a1a4cd..ee972ee4c1 100644 --- a/actors/miner/tests/miner_actor_test_commitment.rs +++ b/actors/miner/tests/miner_actor_test_commitment.rs @@ -24,7 +24,6 @@ use util::*; const DEFAULT_SECTOR_EXPIRATION: i64 = 220; // A balance for use in tests where the miner's low balance is not interesting. -const BIG_BALANCE: u128 = 1_000_000_000_000_000_000_000_000u128; fn assert_simple_pre_commit(sector_number: SectorNumber, deal_ids: &[DealID]) { let period_offset = ChainEpoch::from(100); @@ -32,7 +31,7 @@ fn assert_simple_pre_commit(sector_number: SectorNumber, deal_ids: &[DealID]) { let mut h = ActorHarness::new(period_offset); h.set_proof_type(RegisteredSealProof::StackedDRG64GiBV1); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); rt.set_received(TokenAmount::zero()); let precommit_epoch = period_offset + 1; @@ -108,7 +107,7 @@ mod miner_actor_test_commitment { #[test] fn insufficient_funds_for_pre_commit() { let period_offset = ChainEpoch::from(100); - let insufficient_balance = TokenAmount::from(10u8); // 10 AttoFIL + let insufficient_balance = TokenAmount::from_atto(10u8); // 10 AttoFIL let mut h = ActorHarness::new(period_offset); h.set_proof_type(RegisteredSealProof::StackedDRG64GiBV1); @@ -140,7 +139,7 @@ mod miner_actor_test_commitment { let mut h = ActorHarness::new(period_offset); h.set_proof_type(RegisteredSealProof::StackedDRG64GiBV1); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); rt.set_received(TokenAmount::zero()); let precommit_epoch = period_offset + 1; @@ -152,7 +151,7 @@ mod miner_actor_test_commitment { deadline.period_end() + DEFAULT_SECTOR_EXPIRATION * rt.policy.wpost_proving_period; let mut st: State = rt.get_state(); - st.fee_debt = TokenAmount::from(9999); + st.fee_debt = TokenAmount::from_atto(9999); rt.replace_state(&st); let precommit_params = h.make_pre_commit_params(101, challenge_epoch, expiration, vec![1]); @@ -170,7 +169,7 @@ mod miner_actor_test_commitment { let mut h = ActorHarness::new(period_offset); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); rt.set_received(TokenAmount::zero()); let precommit_epoch = period_offset + 1; @@ -415,8 +414,7 @@ mod miner_actor_test_commitment { // Try to precommit while in fee debt with insufficient balance { let mut st: State = rt.get_state(); - st.fee_debt = - rt.balance.borrow().clone() + TokenAmount::from(10_000_000_000_000_000_000i128); + st.fee_debt = &*rt.balance.borrow() + TokenAmount::from_whole(10); rt.replace_state(&st); let precommit_params = h.make_pre_commit_params(102, challenge_epoch, expiration, vec![]); @@ -470,7 +468,7 @@ mod miner_actor_test_commitment { let mut h = ActorHarness::new(period_offset); h.set_proof_type(proof); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); rt.set_received(TokenAmount::zero()); rt.set_epoch(period_offset + 1); @@ -535,7 +533,7 @@ mod miner_actor_test_commitment { let h = ActorHarness::new(period_offset); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); rt.set_received(TokenAmount::zero()); h.construct_and_verify(&mut rt); @@ -578,7 +576,7 @@ mod miner_actor_test_commitment { let mut h = ActorHarness::new(period_offset); h.set_proof_type(RegisteredSealProof::StackedDRG32GiBV1P1); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); rt.set_received(TokenAmount::zero()); let precommit_epoch = period_offset + 1; rt.set_epoch(precommit_epoch); @@ -596,7 +594,7 @@ mod miner_actor_test_commitment { .add_locked_funds( &rt.store, rt.epoch, - &TokenAmount::from(1000u16), + &TokenAmount::from_atto(1000u16), &VestSpec { initial_delay: 0, vest_period: 1, step_duration: 1, quantization: 1 }, ) .unwrap(); diff --git a/actors/miner/tests/miner_actor_test_construction.rs b/actors/miner/tests/miner_actor_test_construction.rs index 4243fa2672..9f8c770cd4 100644 --- a/actors/miner/tests/miner_actor_test_construction.rs +++ b/actors/miner/tests/miner_actor_test_construction.rs @@ -13,6 +13,7 @@ use fvm_shared::error::ExitCode; use fvm_shared::sector::{RegisteredPoStProof, SectorSize}; use cid::Cid; +use num_traits::Zero; mod util; @@ -72,7 +73,7 @@ fn simple_construction() { env.worker, AccountMethod::PubkeyAddress as u64, RawBytes::default(), - TokenAmount::from(0), + TokenAmount::zero(), RawBytes::serialize(env.worker_key).unwrap(), ExitCode::OK, ); @@ -96,8 +97,8 @@ fn simple_construction() { assert_eq!(SectorSize::_32GiB, info.sector_size); assert_eq!(2349, info.window_post_partition_sectors); - assert_eq!(TokenAmount::from(0), state.pre_commit_deposits); - assert_eq!(TokenAmount::from(0), state.locked_funds); + assert_eq!(TokenAmount::zero(), state.pre_commit_deposits); + assert_eq!(TokenAmount::zero(), state.locked_funds); assert_ne!(Cid::default(), state.pre_committed_sectors); assert_ne!(Cid::default(), state.sectors); @@ -145,7 +146,7 @@ fn control_addresses_are_resolved_during_construction() { env.worker, AccountMethod::PubkeyAddress as u64, RawBytes::default(), - TokenAmount::from(0), + TokenAmount::zero(), RawBytes::serialize(env.worker_key).unwrap(), ExitCode::OK, ); @@ -179,7 +180,7 @@ fn fails_if_control_address_is_not_an_account_actor() { env.worker, AccountMethod::PubkeyAddress as u64, RawBytes::default(), - TokenAmount::from(0), + TokenAmount::zero(), RawBytes::serialize(env.worker_key).unwrap(), ExitCode::OK, ); diff --git a/actors/miner/tests/miner_actor_test_partitions.rs b/actors/miner/tests/miner_actor_test_partitions.rs index de6af74ef6..99f4e77fec 100644 --- a/actors/miner/tests/miner_actor_test_partitions.rs +++ b/actors/miner/tests/miner_actor_test_partitions.rs @@ -479,7 +479,7 @@ mod miner_actor_test_partitions { // remove 3 sectors starting with 2 let old_sectors = sectors()[1..4].to_vec(); let old_sector_power = power_for_sectors(SECTOR_SIZE, &old_sectors); - let old_sector_pledge: u64 = 1001 + 1002 + 1003; + let old_sector_pledge = TokenAmount::from_atto(1001 + 1002 + 1003); // replace 1 and add 2 new sectors let new_sectors = vec![ @@ -488,7 +488,7 @@ mod miner_actor_test_partitions { test_sector(18, 8, 152, 262, 3002), ]; let new_sector_power = power_for_sectors(SECTOR_SIZE, &new_sectors); - let new_sector_pledge = TokenAmount::from(3000u64 + 3001 + 3002); + let new_sector_pledge = TokenAmount::from_atto(3000u64 + 3001 + 3002); let (power_delta, pledge_delta) = partition .replace_sectors(&rt.store, &old_sectors, &new_sectors, SECTOR_SIZE, QUANT_SPEC) @@ -782,7 +782,7 @@ mod miner_actor_test_partitions { assert_bitfield_equals(&expset.on_time_sectors, &[1, 2]); assert_bitfield_equals(&expset.early_sectors, &[4]); - assert_eq!(TokenAmount::from(1000u64 + 1001), expset.on_time_pledge); + assert_eq!(TokenAmount::from_atto(1000u64 + 1001), expset.on_time_pledge); // active power only contains power from non-faulty sectors assert_eq!(expset.active_power, power_for_sectors(SECTOR_SIZE, §ors()[..2])); diff --git a/actors/miner/tests/miner_actor_test_precommit_batch.rs b/actors/miner/tests/miner_actor_test_precommit_batch.rs index 0dd5d255ed..eab3940072 100644 --- a/actors/miner/tests/miner_actor_test_precommit_batch.rs +++ b/actors/miner/tests/miner_actor_test_precommit_batch.rs @@ -5,14 +5,13 @@ use fil_actor_miner::{ }; use fil_actors_runtime::runtime::Policy; use fil_actors_runtime::test_utils::*; -use fvm_shared::bigint::BigInt; use fvm_shared::clock::ChainEpoch; use fvm_shared::deal::DealID; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; use fvm_shared::sector::SectorNumber; -use num_traits::{Signed, Zero}; +use num_traits::Zero; use cid::Cid; use std::collections::HashMap; @@ -25,7 +24,6 @@ use util::*; const DEFAULT_SECTOR_EXPIRATION: i64 = 220; // A balance for use in tests where the miner's low balance is not interesting. -const BIG_BALANCE: u128 = 1_000_000_000_000_000_000_000_000u128; #[derive(Default, Clone)] struct DealSpec { @@ -61,7 +59,7 @@ fn assert_simple_batch( sector_deal_data: vec![SectorDealData::default(); batch_size], first_for_miner: true, }; - let mut deposits = vec![BigInt::default(); batch_size]; + let mut deposits = vec![TokenAmount::zero(); batch_size]; for i in 0..batch_size { let mut deals = DealSpec::default(); @@ -84,8 +82,8 @@ fn assert_simple_batch( ); } let net_fee = aggregate_pre_commit_network_fee(batch_size as i64, &base_fee); - let total_deposit: BigInt = deposits.iter().sum(); - let total_balance = net_fee + total_deposit.clone(); + let total_deposit: TokenAmount = deposits.iter().sum(); + let total_balance = net_fee + &total_deposit; rt.set_balance(total_balance + balance_surplus); if exit_code != ExitCode::OK { @@ -96,7 +94,7 @@ fn assert_simple_batch( &mut rt, PreCommitSectorBatchParams { sectors }, &conf, - base_fee, + &base_fee, ), ); rt.reset(); @@ -112,7 +110,7 @@ fn assert_simple_batch( &mut rt, PreCommitSectorBatchParams { sectors: sectors.clone() }, &conf, - base_fee, + &base_fee, ); // Check precommits @@ -218,7 +216,7 @@ mod miner_actor_precommit_batch { fn insufficient_balance() { assert_simple_batch( 10, - TokenAmount::from(-1), + TokenAmount::from_atto(-1), TokenAmount::zero(), &[], ExitCode::USR_INSUFFICIENT_FUNDS, @@ -236,7 +234,7 @@ mod miner_actor_precommit_batch { let h = ActorHarness::new(period_offset); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); rt.set_received(TokenAmount::zero()); let precommit_epoch = period_offset + 1; @@ -259,7 +257,7 @@ mod miner_actor_precommit_batch { &mut rt, PreCommitSectorBatchParams { sectors }, &PreCommitBatchConfig { sector_deal_data: vec![], first_for_miner: true }, - BigInt::zero(), + &TokenAmount::zero(), ), ); rt.reset(); @@ -271,7 +269,7 @@ mod miner_actor_precommit_batch { let h = ActorHarness::new(period_offset); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); rt.set_received(TokenAmount::zero()); let precommit_epoch = period_offset + 1; @@ -294,7 +292,7 @@ mod miner_actor_precommit_batch { &mut rt, PreCommitSectorBatchParams { sectors }, &PreCommitBatchConfig { sector_deal_data: vec![], first_for_miner: true }, - BigInt::zero(), + &TokenAmount::zero(), ), ); rt.reset(); diff --git a/actors/miner/tests/miner_actor_test_wpost.rs b/actors/miner/tests/miner_actor_test_wpost.rs index 193d108ea0..f6047a8441 100644 --- a/actors/miner/tests/miner_actor_test_wpost.rs +++ b/actors/miner/tests/miner_actor_test_wpost.rs @@ -15,15 +15,13 @@ use fvm_shared::sector::RegisteredSealProof; mod util; +use num_traits::Zero; use util::*; // an expiration ~10 days greater than effective min expiration taking into account 30 days max // between pre and prove commit const DEFAULT_SECTOR_EXPIRATION: u64 = 220; -const BIG_BALANCE: u128 = 1_000_000_000_000_000_000_000_000u128; -const BIG_REWARDS: u128 = 1_000_000_000_000_000_000_000u128; - #[test] fn basic_post_and_dispute() { let period_offset = ChainEpoch::from(100); @@ -34,7 +32,7 @@ fn basic_post_and_dispute() { let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); @@ -106,7 +104,7 @@ fn invalid_submissions() { let mut h = ActorHarness::new(period_offset); let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); @@ -502,7 +500,7 @@ fn duplicate_proof_rejected() { let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); @@ -584,7 +582,7 @@ fn duplicate_proof_rejected_with_many_partitions() { let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); @@ -689,14 +687,14 @@ fn successful_recoveries_recover_power() { let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let infos = h.commit_and_prove_sectors(&mut rt, 1, DEFAULT_SECTOR_EXPIRATION, vec![], true); let pwr = miner::power_for_sectors(h.sector_size, &infos); - h.apply_rewards(&mut rt, TokenAmount::from(BIG_REWARDS), TokenAmount::from(0u8)); + h.apply_rewards(&mut rt, BIG_REWARDS.clone(), TokenAmount::zero()); let initial_locked = h.get_locked_funds(&rt); // Submit first PoSt to ensure we are sufficiently early to add a fault @@ -715,7 +713,7 @@ fn successful_recoveries_recover_power() { let (dlidx, pidx) = state.find_sector(&rt.policy, &rt.store, infos[0].sector_number).unwrap(); let mut bf = BitField::new(); bf.set(infos[0].sector_number); - h.declare_recoveries(&mut rt, dlidx, pidx, bf, TokenAmount::from(0u8)).unwrap(); + h.declare_recoveries(&mut rt, dlidx, pidx, bf, TokenAmount::zero()).unwrap(); // advance to epoch when submitPoSt is due let mut dlinfo = h.deadline(&rt); @@ -761,13 +759,13 @@ fn skipped_faults_adjust_power() { let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let infos = h.commit_and_prove_sectors(&mut rt, 2, DEFAULT_SECTOR_EXPIRATION, vec![], true); - h.apply_rewards(&mut rt, TokenAmount::from(BIG_REWARDS), TokenAmount::from(0u8)); + h.apply_rewards(&mut rt, BIG_REWARDS.clone(), TokenAmount::zero()); // Skip to the due deadline. let state = h.get_state(&rt); @@ -848,13 +846,13 @@ fn skipping_all_sectors_in_a_partition_rejected() { let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let infos = h.commit_and_prove_sectors(&mut rt, 2, DEFAULT_SECTOR_EXPIRATION, vec![], true); - h.apply_rewards(&mut rt, TokenAmount::from(BIG_REWARDS), TokenAmount::from(0u8)); + h.apply_rewards(&mut rt, BIG_REWARDS.clone(), TokenAmount::zero()); // Skip to the due deadline. let state = h.get_state(&rt); @@ -883,7 +881,7 @@ fn skipping_all_sectors_in_a_partition_rejected() { rt.reset(); // These sectors are detected faulty and pay no penalty this time. - h.advance_deadline(&mut rt, CronConfig::with_continued_faults_penalty(TokenAmount::from(0u8))); + h.advance_deadline(&mut rt, CronConfig::with_continued_faults_penalty(TokenAmount::zero())); h.check_state(&rt); } @@ -897,13 +895,13 @@ fn skipped_recoveries_are_penalized_and_do_not_recover_power() { let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let infos = h.commit_and_prove_sectors(&mut rt, 2, DEFAULT_SECTOR_EXPIRATION, vec![], true); - h.apply_rewards(&mut rt, TokenAmount::from(BIG_REWARDS), TokenAmount::from(0u8)); + h.apply_rewards(&mut rt, BIG_REWARDS.clone(), TokenAmount::zero()); // Submit first PoSt to ensure we are sufficiently early to add a fault // advance to next proving period @@ -922,7 +920,7 @@ fn skipped_recoveries_are_penalized_and_do_not_recover_power() { let (dlidx, pidx) = state.find_sector(&rt.policy, &rt.store, infos[0].sector_number).unwrap(); let mut bf = BitField::new(); bf.set(infos[0].sector_number); - h.declare_recoveries(&mut rt, dlidx, pidx, bf, TokenAmount::from(0u8)).unwrap(); + h.declare_recoveries(&mut rt, dlidx, pidx, bf, TokenAmount::zero()).unwrap(); // Skip to the due deadline. let dlinfo = h.advance_to_deadline(&mut rt, dlidx); @@ -950,7 +948,7 @@ fn skipping_a_fault_from_the_wrong_partition_is_an_error() { let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); @@ -1002,7 +1000,7 @@ fn cannot_dispute_posts_when_the_challenge_window_is_open() { let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); @@ -1054,7 +1052,7 @@ fn can_dispute_up_till_window_end_but_not_after() { let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); @@ -1116,7 +1114,7 @@ fn cant_dispute_up_with_an_invalid_deadline() { let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); @@ -1143,7 +1141,7 @@ fn can_dispute_test_after_proving_period_changes() { let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); @@ -1229,7 +1227,7 @@ fn bad_post_fails_when_verified() { let mut rt = h.new_runtime(); rt.epoch = precommit_epoch; - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); @@ -1237,7 +1235,7 @@ fn bad_post_fails_when_verified() { let power_for_sectors = &miner::power_for_sectors(h.sector_size, &vec![infos[0].clone(), infos[1].clone()]); - h.apply_rewards(&mut rt, TokenAmount::from(BIG_REWARDS), TokenAmount::from(0u8)); + h.apply_rewards(&mut rt, BIG_REWARDS.clone(), TokenAmount::zero()); let state = h.get_state(&rt); let (dlidx, pidx) = state.find_sector(&rt.policy, &rt.store, infos[0].sector_number).unwrap(); @@ -1265,7 +1263,7 @@ fn bad_post_fails_when_verified() { let mut bf = BitField::new(); bf.set(infos[0].sector_number); bf.set(infos[1].sector_number); - h.declare_recoveries(&mut rt, dlidx, pidx, bf, TokenAmount::from(0u8)).unwrap(); + h.declare_recoveries(&mut rt, dlidx, pidx, bf, TokenAmount::zero()).unwrap(); // Now submit a PoSt, but a BAD one let dlinfo = h.advance_to_deadline(&mut rt, dlidx); diff --git a/actors/miner/tests/monies_test.rs b/actors/miner/tests/monies_test.rs index 96e1b5a6dd..bb8f447205 100644 --- a/actors/miner/tests/monies_test.rs +++ b/actors/miner/tests/monies_test.rs @@ -1,14 +1,14 @@ use fil_actor_miner::{expected_reward_for_power, pledge_penalty_for_continued_fault}; use fvm_shared::bigint::{BigInt, Zero}; -use fvm_shared::{econ::TokenAmount, smooth::FilterEstimate}; +use fvm_shared::smooth::FilterEstimate; use std::ops::Neg; #[test] fn negative_br_clamp() { - let epoch_target_reward = TokenAmount::from(1_u64 << 50); - let qa_sector_power = TokenAmount::from(1_u64 << 36); - let network_qa_power = TokenAmount::from(1_u64 << 10); - let power_rate_of_change = TokenAmount::from(1_u64 << 10).neg(); + let epoch_target_reward = BigInt::from(1_u64 << 50); + let qa_sector_power = BigInt::from(1_u64 << 36); + let network_qa_power = BigInt::from(1_u64 << 10); + let power_rate_of_change = BigInt::from(1_u64 << 10).neg(); let reward_estimate = FilterEstimate::new(epoch_target_reward, BigInt::zero()); let power_estimate = FilterEstimate::new(network_qa_power.clone(), power_rate_of_change); assert!(power_estimate.extrapolate(4) < network_qa_power); @@ -19,10 +19,10 @@ fn negative_br_clamp() { #[test] fn zero_power_means_zero_fault_penalty() { - let epoch_target_reward = TokenAmount::from(1_u64 << 50); - let zero_qa_power = TokenAmount::zero(); - let network_qa_power = TokenAmount::from(1_u64 << 10); - let power_rate_of_change = TokenAmount::from(1_u64 << 10); + let epoch_target_reward = BigInt::from(1_u64 << 50); + let zero_qa_power = BigInt::zero(); + let network_qa_power = BigInt::from(1_u64 << 10); + let power_rate_of_change = BigInt::from(1_u64 << 10); let reward_estimate = FilterEstimate::new(epoch_target_reward, BigInt::zero()); let power_estimate = FilterEstimate::new(network_qa_power, power_rate_of_change); diff --git a/actors/miner/tests/pledge_penalty_for_termination.rs b/actors/miner/tests/pledge_penalty_for_termination.rs index 6a71f3174c..2246e20570 100644 --- a/actors/miner/tests/pledge_penalty_for_termination.rs +++ b/actors/miner/tests/pledge_penalty_for_termination.rs @@ -10,7 +10,7 @@ use fvm_shared::sector::StoragePower; use fvm_shared::smooth::FilterEstimate; fn epoch_target_reward() -> TokenAmount { - TokenAmount::from(1_u128 << 50) + TokenAmount::from_atto(1_u128 << 50) } // 1 64 GiB sector @@ -25,7 +25,7 @@ fn network_qa_power() -> StoragePower { // exactly 1 attoFIL per byte of power, no estimated changes fn reward_estimate() -> FilterEstimate { - FilterEstimate::new(epoch_target_reward(), BigInt::zero()) + FilterEstimate::new(epoch_target_reward().atto().clone(), BigInt::zero()) } fn power_estimate() -> FilterEstimate { @@ -43,8 +43,8 @@ fn undeclared_penalty() -> TokenAmount { #[test] fn when_undeclared_fault_fee_exceeds_expected_reward_returns_undeclared_fault_fee() { // small pledge compared to current expected reward means - let initial_pledge = TokenAmount::from(1 << 10); - let day_reward = initial_pledge / INITIAL_PLEDGE_FACTOR; + let initial_pledge = TokenAmount::from_atto(1 << 10); + let day_reward = initial_pledge.div_floor(INITIAL_PLEDGE_FACTOR); let twenty_day_reward = &day_reward * INITIAL_PLEDGE_FACTOR; let sector_age_in_days = 20; let sector_age = sector_age_in_days * EPOCHS_IN_DAY; @@ -67,7 +67,7 @@ fn when_undeclared_fault_fee_exceeds_expected_reward_returns_undeclared_fault_fe fn when_expected_reward_exceeds_undeclared_fault_fee_returns_expected_reward() { // initialPledge equal to undeclaredPenalty guarantees expected reward is greater let initial_pledge = undeclared_penalty(); - let day_reward = &initial_pledge / INITIAL_PLEDGE_FACTOR; + let day_reward = initial_pledge.div_floor(INITIAL_PLEDGE_FACTOR); let twenty_day_reward = &day_reward * INITIAL_PLEDGE_FACTOR; let sector_age_in_days = 20; let sector_age = sector_age_in_days * EPOCHS_IN_DAY; @@ -85,15 +85,15 @@ fn when_expected_reward_exceeds_undeclared_fault_fee_returns_expected_reward() { // expect fee to be pledge + br * age * factor where br = pledge/initialPledgeFactor let expected_fee = &initial_pledge - + (&day_reward * sector_age_in_days * &*TERMINATION_REWARD_FACTOR_NUM) - / &*TERMINATION_REWARD_FACTOR_DENOM; + + (&day_reward * sector_age_in_days * TERMINATION_REWARD_FACTOR_NUM) + .div_floor(TERMINATION_REWARD_FACTOR_DENOM); assert_eq!(expected_fee, fee); } #[test] fn sector_age_is_capped() { let initial_pledge = undeclared_penalty(); - let day_reward = &initial_pledge / INITIAL_PLEDGE_FACTOR; + let day_reward = initial_pledge.div_floor(INITIAL_PLEDGE_FACTOR); let twenty_day_reward = &day_reward * INITIAL_PLEDGE_FACTOR; let sector_age_in_days = 500; let sector_age = sector_age_in_days * EPOCHS_IN_DAY; @@ -111,8 +111,8 @@ fn sector_age_is_capped() { // expect fee to be pledge * br * age-cap * factor where br = pledge/initialPledgeFactor let expected_fee = &initial_pledge - + (&day_reward * TERMINATION_LIFETIME_CAP * &*TERMINATION_REWARD_FACTOR_NUM) - / &*TERMINATION_REWARD_FACTOR_DENOM; + + (&day_reward * TERMINATION_LIFETIME_CAP * TERMINATION_REWARD_FACTOR_NUM) + .div_floor(TERMINATION_REWARD_FACTOR_DENOM); assert_eq!(expected_fee, fee); } @@ -120,7 +120,7 @@ fn sector_age_is_capped() { fn fee_for_replacement_eq_fee_for_original_sector_when_power_br_are_unchanged() { // initialPledge equal to undeclaredPenalty guarantees expected reward is greater let initial_pledge = undeclared_penalty(); - let day_reward = &initial_pledge / INITIAL_PLEDGE_FACTOR; + let day_reward = initial_pledge.div_floor(INITIAL_PLEDGE_FACTOR); let twenty_day_reward = &day_reward * INITIAL_PLEDGE_FACTOR; let sector_age = 20 * EPOCHS_IN_DAY; let replacement_age = 2 * EPOCHS_IN_DAY; @@ -159,7 +159,7 @@ fn fee_for_replacement_eq_fee_for_original_sector_when_power_br_are_unchanged() fn fee_for_replacement_eq_fee_for_same_sector_without_replacement_after_lifetime_cap() { // initialPledge equal to undeclaredPenalty guarantees expected reward is greater let initial_pledge = undeclared_penalty(); - let day_reward = &initial_pledge / INITIAL_PLEDGE_FACTOR; + let day_reward = initial_pledge.div_floor(INITIAL_PLEDGE_FACTOR); let twenty_day_reward = &day_reward * INITIAL_PLEDGE_FACTOR; let sector_age = 20 * EPOCHS_IN_DAY; let replacement_age = (TERMINATION_LIFETIME_CAP + 1) * EPOCHS_IN_DAY; @@ -198,8 +198,8 @@ fn fee_for_replacement_eq_fee_for_same_sector_without_replacement_after_lifetime fn charges_for_replaced_sector_at_replaced_sector_day_rate() { // initialPledge equal to undeclaredPenalty guarantees expected reward is greater let initial_pledge = undeclared_penalty(); - let day_reward = &initial_pledge / INITIAL_PLEDGE_FACTOR; - let old_day_reward = 2 * &day_reward; + let day_reward = initial_pledge.div_floor(INITIAL_PLEDGE_FACTOR); + let old_day_reward = &day_reward * 2; let twenty_day_reward = &day_reward * INITIAL_PLEDGE_FACTOR; let old_sector_age_in_days = 20; let old_sector_age = old_sector_age_in_days * EPOCHS_IN_DAY; @@ -209,10 +209,10 @@ fn charges_for_replaced_sector_at_replaced_sector_day_rate() { // use low power, so termination fee exceeds SP let power = BigInt::from(1); - let old_penalty = (&old_day_reward * old_sector_age_in_days * &*TERMINATION_REWARD_FACTOR_NUM) - / &*TERMINATION_REWARD_FACTOR_DENOM; - let new_penalty = (&day_reward * replacement_age_in_days * &*TERMINATION_REWARD_FACTOR_NUM) - / &*TERMINATION_REWARD_FACTOR_DENOM; + let old_penalty = (&old_day_reward * old_sector_age_in_days * TERMINATION_REWARD_FACTOR_NUM) + .div_floor(TERMINATION_REWARD_FACTOR_DENOM); + let new_penalty = (&day_reward * replacement_age_in_days * TERMINATION_REWARD_FACTOR_NUM) + .div_floor(TERMINATION_REWARD_FACTOR_DENOM); let expected_fee = &twenty_day_reward + old_penalty + new_penalty; let fee = pledge_penalty_for_termination( diff --git a/actors/miner/tests/policy_test.rs b/actors/miner/tests/policy_test.rs index 5d3cdf9649..a5b0ec6e33 100644 --- a/actors/miner/tests/policy_test.rs +++ b/actors/miner/tests/policy_test.rs @@ -6,13 +6,12 @@ use fil_actor_miner::{ use fil_actors_runtime::{EPOCHS_IN_DAY, SECONDS_IN_DAY}; use fvm_shared::bigint::{BigInt, Zero}; use fvm_shared::clock::ChainEpoch; -use fvm_shared::econ::TokenAmount; use fvm_shared::sector::SectorSize; #[test] fn quality_is_independent_of_size_and_duration() { // Quality of space with no deals. This doesn't depend on either the sector size or duration. - let empty_quality = TokenAmount::from(1 << SECTOR_QUALITY_PRECISION); + let empty_quality = BigInt::from(1 << SECTOR_QUALITY_PRECISION); // Quality space filled with non-verified deals. let deal_quality = &empty_quality * (DEAL_WEIGHT_MULTIPLIER.clone() / QUALITY_BASE_MULTIPLIER.clone()); @@ -56,7 +55,7 @@ fn quality_is_independent_of_size_and_duration() { #[test] fn quality_scales_with_verified_weight_proportion() { // Quality of space with no deals. This doesn't depend on either the sector size or duration. - let empty_quality = TokenAmount::from(1 << SECTOR_QUALITY_PRECISION); + let empty_quality = BigInt::from(1 << SECTOR_QUALITY_PRECISION); // Quality space filled with verified deals. let verified_quality = &empty_quality * (VERIFIED_DEAL_WEIGHT_MULTIPLIER.clone() / QUALITY_BASE_MULTIPLIER.clone()); diff --git a/actors/miner/tests/precommit_deposit_and_initial_pledge_positive_test.rs b/actors/miner/tests/precommit_deposit_and_initial_pledge_positive_test.rs index d7e2692400..2e0f2f0620 100644 --- a/actors/miner/tests/precommit_deposit_and_initial_pledge_positive_test.rs +++ b/actors/miner/tests/precommit_deposit_and_initial_pledge_positive_test.rs @@ -17,7 +17,11 @@ my_const!(qa_sector_power, StoragePower, StoragePower::from(1u64 << 36)); my_const!(network_qa_power, StoragePower, StoragePower::from(1u64 << 10)); my_const!(baseline_power, StoragePower, network_qa_power()); my_const!(power_rate_of_change, StoragePower, StoragePower::from(1u64 << 10)); -my_const!(reward_estimate, FilterEstimate, FilterEstimate::new(epoch_target_reward(), zero())); +my_const!( + reward_estimate, + FilterEstimate, + FilterEstimate::new(epoch_target_reward().atto().clone(), zero()) +); my_const!( power_estimate, FilterEstimate, @@ -35,12 +39,12 @@ fn initial_pledge_clamped_at_one_attofil() { &power_estimate(), &circulating_supply(), ); - assert_eq!(TokenAmount::from(1), initial_pledge); + assert_eq!(TokenAmount::from_atto(1), initial_pledge); } #[test] fn precommit_deposit_is_clamped_at_one_attofil() { let precommit_deposit = pre_commit_deposit_for_power(&reward_estimate(), &power_estimate(), &qa_sector_power()); - assert_eq!(TokenAmount::from(1), precommit_deposit); + assert_eq!(TokenAmount::from_atto(1), precommit_deposit); } diff --git a/actors/miner/tests/precommitted_sector_stores.rs b/actors/miner/tests/precommitted_sector_stores.rs index 3a8c903eff..164ba5cd36 100644 --- a/actors/miner/tests/precommitted_sector_stores.rs +++ b/actors/miner/tests/precommitted_sector_stores.rs @@ -13,16 +13,20 @@ use state_harness::*; fn put_get_and_delete() { let mut h = StateHarness::new(0); - let pc1 = new_pre_commit_on_chain(1, make_sealed_cid("1".as_bytes()), TokenAmount::from(1), 1); + let pc1 = + new_pre_commit_on_chain(1, make_sealed_cid("1".as_bytes()), TokenAmount::from_atto(1), 1); h.put_precommitted_sectors(vec![pc1.clone()]).unwrap(); assert_eq!(pc1, h.get_precommit(1)); - let pc2 = new_pre_commit_on_chain(2, make_sealed_cid("2".as_bytes()), TokenAmount::from(1), 1); + let pc2 = + new_pre_commit_on_chain(2, make_sealed_cid("2".as_bytes()), TokenAmount::from_atto(1), 1); h.put_precommitted_sectors(vec![pc2.clone()]).unwrap(); assert_eq!(pc2, h.get_precommit(2)); - let pc3 = new_pre_commit_on_chain(3, make_sealed_cid("2".as_bytes()), TokenAmount::from(1), 1); - let pc4 = new_pre_commit_on_chain(4, make_sealed_cid("2".as_bytes()), TokenAmount::from(1), 1); + let pc3 = + new_pre_commit_on_chain(3, make_sealed_cid("2".as_bytes()), TokenAmount::from_atto(1), 1); + let pc4 = + new_pre_commit_on_chain(4, make_sealed_cid("2".as_bytes()), TokenAmount::from_atto(1), 1); h.put_precommitted_sectors(vec![pc3.clone(), pc4.clone()]).unwrap(); assert_eq!(pc3, h.get_precommit(3)); assert_eq!(pc4, h.get_precommit(4)); @@ -48,14 +52,16 @@ fn has_nonexistent_value_returns_false() { fn duplicate_put_rejected() { let mut h = StateHarness::new(0); - let pc1 = new_pre_commit_on_chain(1, make_sealed_cid("1".as_bytes()), TokenAmount::from(1), 1); + let pc1 = + new_pre_commit_on_chain(1, make_sealed_cid("1".as_bytes()), TokenAmount::from_atto(1), 1); // In sequence assert!(h.put_precommitted_sectors(vec![pc1.clone()]).is_ok()); assert!(h.put_precommitted_sectors(vec![pc1]).is_err()); // In batch - let pc2 = new_pre_commit_on_chain(2, make_sealed_cid("2".as_bytes()), TokenAmount::from(1), 1); + let pc2 = + new_pre_commit_on_chain(2, make_sealed_cid("2".as_bytes()), TokenAmount::from_atto(1), 1); assert!(h.put_precommitted_sectors(vec![pc2.clone(), pc2]).is_err()); } diff --git a/actors/miner/tests/prove_commit.rs b/actors/miner/tests/prove_commit.rs index 20fe26dfc7..eb1cd1b93e 100644 --- a/actors/miner/tests/prove_commit.rs +++ b/actors/miner/tests/prove_commit.rs @@ -25,14 +25,13 @@ const DEFAULT_SECTOR_EXPIRATION: ChainEpoch = 220; const VERIFIED_DEAL_WEIGHT_MULTIPLIER: u64 = 100; const QUALITY_BASE_MULTIPLIER: u64 = 10; -const BIG_BALANCE: u128 = 1_000_000_000_000_000_000_000_000u128; const PERIOD_OFFSET: ChainEpoch = 100; #[test] fn prove_single_sector() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); let precommit_epoch = PERIOD_OFFSET + 1; rt.set_epoch(precommit_epoch); @@ -75,7 +74,7 @@ fn prove_single_sector() { // run prove commit logic rt.set_epoch(prove_commit_epoch); - rt.balance.replace(TokenAmount::from(1000u64) * 1e18 as u64); + rt.balance.replace(TokenAmount::from_whole(1000)); let pcc = ProveCommitConfig { deal_weights: HashMap::from([(sector_no, deal_weight.clone())]), ..Default::default() @@ -166,7 +165,7 @@ fn prove_single_sector() { fn prove_sectors_from_batch_pre_commit() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); let precommit_epoch = PERIOD_OFFSET + 1; rt.set_epoch(precommit_epoch); @@ -208,7 +207,7 @@ fn prove_sectors_from_batch_pre_commit() { &mut rt, PreCommitSectorBatchParams { sectors }, &conf, - TokenAmount::zero(), + &TokenAmount::zero(), ); rt.set_epoch(prove_commit_epoch); @@ -326,7 +325,7 @@ fn prove_sectors_from_batch_pre_commit() { fn invalid_proof_rejected() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); let precommit_epoch = PERIOD_OFFSET + 1; rt.set_epoch(precommit_epoch); @@ -404,7 +403,7 @@ fn invalid_proof_rejected() { ); rt.reset(); - rt.balance.replace(TokenAmount::from(1_000) * 1e18 as u64); + rt.balance.replace(TokenAmount::from_whole(1_000)); let prove_commit = h.make_prove_commit_params(sector_no); h.prove_commit_sector_and_confirm( @@ -443,14 +442,14 @@ fn invalid_proof_rejected() { fn prove_commit_aborts_if_pledge_requirement_not_met() { let mut h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); // Set the circulating supply high and expected reward low in order to coerce // pledge requirements (BR + share of money supply, but capped at 1FIL) // to exceed pre-commit deposit (BR only). - rt.set_circulating_supply(TokenAmount::from(100_000_000) * 1e18 as u64); + rt.set_circulating_supply(TokenAmount::from_whole(100_000_000)); h.epoch_reward_smooth = FilterEstimate::new(BigInt::from(1e15 as u64), BigInt::zero()); // prove one sector to establish collateral and locked funds @@ -503,7 +502,7 @@ fn prove_commit_aborts_if_pledge_requirement_not_met() { fn drop_invalid_prove_commit_while_processing_valid_one() { let mut h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); @@ -544,7 +543,7 @@ fn drop_invalid_prove_commit_while_processing_valid_one() { fn prove_commit_just_after_period_start_permits_post() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); // Epoch PERIOD_OFFSET+1 should be at the beginning of the miner's proving period so there will be time to commit // and PoSt a sector. @@ -565,7 +564,7 @@ fn prove_commit_just_after_period_start_permits_post() { fn sector_with_non_positive_lifetime_is_skipped_in_confirmation() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); let precommit_epoch = PERIOD_OFFSET + 1; rt.set_epoch(precommit_epoch); @@ -610,7 +609,7 @@ fn sector_with_non_positive_lifetime_is_skipped_in_confirmation() { fn verify_proof_does_not_vest_funds() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.balance.replace(TokenAmount::from(BIG_BALANCE)); + rt.balance.replace(BIG_BALANCE.clone()); let precommit_epoch = PERIOD_OFFSET + 1; rt.set_epoch(precommit_epoch); @@ -634,14 +633,14 @@ fn verify_proof_does_not_vest_funds() { .add_locked_funds( &rt.store, rt.epoch, - &TokenAmount::from(1000), + &TokenAmount::from_atto(1000), &VestSpec { initial_delay: 0, vest_period: 1, step_duration: 1, quantization: 1 }, ) .unwrap(); rt.replace_state(&st); rt.set_epoch(precommit_epoch + rt.policy.pre_commit_challenge_delay + 1); - rt.balance.replace(TokenAmount::from(1000) * 1e18 as u64); + rt.balance.replace(TokenAmount::from_whole(1000)); let mut prove_commit = h.make_prove_commit_params(sector_no); prove_commit.proof.resize(192, 0); diff --git a/actors/miner/tests/repay_debt_test.rs b/actors/miner/tests/repay_debt_test.rs index eae450d243..a1b60c7913 100644 --- a/actors/miner/tests/repay_debt_test.rs +++ b/actors/miner/tests/repay_debt_test.rs @@ -8,8 +8,8 @@ use num_traits::Zero; fn repay_debt_in_priority_order() { let mut h = StateHarness::new(0); - let current_balance = TokenAmount::from(300u16); - let fee = TokenAmount::from(1000); + let current_balance = TokenAmount::from_atto(300u16); + let fee = TokenAmount::from_atto(1000); h.st.apply_penalty(&fee).unwrap(); assert_eq!(h.st.fee_debt, fee); @@ -23,7 +23,7 @@ fn repay_debt_in_priority_order() { assert_eq!(expected_debt, h.st.fee_debt); let current_balance = TokenAmount::zero(); - let fee = TokenAmount::from(2050); + let fee = TokenAmount::from_atto(2050); h.st.apply_penalty(&fee).unwrap(); h.st.repay_partial_debt_in_priority_order(&h.store, 33, ¤t_balance).unwrap(); diff --git a/actors/miner/tests/repay_debts.rs b/actors/miner/tests/repay_debts.rs index 9f52693006..d4dba48cd0 100644 --- a/actors/miner/tests/repay_debts.rs +++ b/actors/miner/tests/repay_debts.rs @@ -6,7 +6,6 @@ use fvm_shared::econ::TokenAmount; mod util; use util::*; -const BIG_BALANCE: u128 = 1_000_000_000_000_000_000_000_000u128; const PERIOD_OFFSET: ChainEpoch = 100; #[test] @@ -17,7 +16,7 @@ fn repay_with_no_available_funds_does_nothing() { // introduce fee debt let mut st = h.get_state(&rt); - let fee_debt: TokenAmount = 4 * TokenAmount::from(BIG_BALANCE); + let fee_debt: TokenAmount = 4 * &*BIG_BALANCE; st.fee_debt = fee_debt.clone(); rt.replace_state(&st); @@ -37,7 +36,7 @@ fn pay_debt_entirely_from_balance() { // introduce fee debt let mut st = h.get_state(&rt); - let fee_debt: TokenAmount = 4 * TokenAmount::from(BIG_BALANCE); + let fee_debt: TokenAmount = 4 * &*BIG_BALANCE; st.fee_debt = fee_debt.clone(); rt.replace_state(&st); @@ -57,15 +56,15 @@ fn partially_repay_debt() { // introduce fee debt let mut st = h.get_state(&rt); - let fee_debt: TokenAmount = 4 * TokenAmount::from(BIG_BALANCE); + let fee_debt: TokenAmount = 4 * &*BIG_BALANCE; st.fee_debt = fee_debt.clone(); rt.replace_state(&st); - let debt_to_repay = 3 * (&fee_debt / 4); + let debt_to_repay = 3 * (&fee_debt.div_floor(4)); h.repay_debts(&mut rt, &debt_to_repay, &TokenAmount::zero(), &debt_to_repay).unwrap(); let st = h.get_state(&rt); - assert_eq!(&fee_debt / 4, st.fee_debt); + assert_eq!(fee_debt.div_floor(4), st.fee_debt); h.check_state(&rt); } @@ -75,7 +74,7 @@ fn pay_debt_partially_from_vested_funds() { let mut rt = h.new_runtime(); h.construct_and_verify(&mut rt); - let reward_amount: TokenAmount = 4 * TokenAmount::from(BIG_BALANCE); + let reward_amount: TokenAmount = 4 * &*BIG_BALANCE; let (amount_locked, _) = locked_reward_from_reward(reward_amount.clone()); rt.set_balance(amount_locked.clone()); h.apply_rewards(&mut rt, reward_amount, TokenAmount::zero()); @@ -83,15 +82,15 @@ fn pay_debt_partially_from_vested_funds() { // introduce fee debt let mut st = h.get_state(&rt); - st.fee_debt = 4 * TokenAmount::from(BIG_BALANCE); + st.fee_debt = 4 * &*BIG_BALANCE; rt.replace_state(&st); // send 1 FIL and repay all debt from vesting funds and balance h.repay_debts( &mut rt, - &TokenAmount::from(BIG_BALANCE), // send 1 FIL - &amount_locked, // 3 FIL comes from vesting funds - &TokenAmount::from(BIG_BALANCE), // 1 FIL sent from balance + &*BIG_BALANCE, // send 1 FIL + &amount_locked, // 3 FIL comes from vesting funds + &*BIG_BALANCE, // 1 FIL sent from balance ) .unwrap(); diff --git a/actors/miner/tests/report_consensus_fault.rs b/actors/miner/tests/report_consensus_fault.rs index 75f27e9401..23df39e3f5 100644 --- a/actors/miner/tests/report_consensus_fault.rs +++ b/actors/miner/tests/report_consensus_fault.rs @@ -4,20 +4,19 @@ use fil_actors_runtime::test_utils::{expect_abort, expect_abort_contains_message use fvm_shared::address::Address; use fvm_shared::clock::ChainEpoch; use fvm_shared::consensus::{ConsensusFault, ConsensusFaultType}; -use fvm_shared::econ::TokenAmount; + use fvm_shared::error::ExitCode; mod util; use util::*; -const BIG_BALANCE: u128 = 1_000_000_000_000_000_000_000_000u128; const PERIOD_OFFSET: ChainEpoch = 100; fn setup() -> (ActorHarness, MockRuntime) { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); (h, rt) } diff --git a/actors/miner/tests/sector_assignment.rs b/actors/miner/tests/sector_assignment.rs index c012b42b12..ae9374123c 100644 --- a/actors/miner/tests/sector_assignment.rs +++ b/actors/miner/tests/sector_assignment.rs @@ -5,8 +5,9 @@ use cid::Cid; use fil_actor_miner::{power_for_sectors, Deadline, PoStPartition, PowerPair, SectorOnChainInfo}; use fil_actors_runtime::{runtime::Policy, test_utils::make_sealed_cid}; use fvm_ipld_bitfield::{BitField, UnvalidatedBitField}; +use fvm_shared::bigint::BigInt; use fvm_shared::clock::ChainEpoch; -use fvm_shared::econ::TokenAmount; + use fvm_shared::sector::RegisteredSealProof; use fvm_shared::sector::SectorNumber; @@ -20,7 +21,7 @@ use state_harness::*; fn new_sector_on_chain_info( sector_number: SectorNumber, sealed_cid: Cid, - weight: TokenAmount, + weight: BigInt, activation: ChainEpoch, ) -> SectorOnChainInfo { SectorOnChainInfo { @@ -36,6 +37,7 @@ fn new_sector_on_chain_info( } mod sector_assignment { + use super::*; #[test] @@ -53,7 +55,7 @@ mod sector_assignment { new_sector_on_chain_info( i as SectorNumber, make_sealed_cid("{i}".as_bytes()), - TokenAmount::from(1u8), + BigInt::from(1u8), 0, ) }) diff --git a/actors/miner/tests/terminate_sectors_test.rs b/actors/miner/tests/terminate_sectors_test.rs index 2a37345e37..c751381e98 100644 --- a/actors/miner/tests/terminate_sectors_test.rs +++ b/actors/miner/tests/terminate_sectors_test.rs @@ -11,7 +11,7 @@ use fvm_ipld_encoding::RawBytes; use fvm_shared::{econ::TokenAmount, error::ExitCode}; mod util; -use fvm_shared::bigint::BigInt; + use num_traits::Zero; use util::*; @@ -23,7 +23,7 @@ fn setup() -> (ActorHarness, MockRuntime) { let h = ActorHarness::new(period_offset); let mut rt = h.new_runtime(); h.construct_and_verify(&mut rt); - rt.balance.replace(TokenAmount::from(big_balance)); + rt.balance.replace(TokenAmount::from_atto(big_balance)); rt.set_epoch(precommit_epoch); (h, rt) @@ -42,7 +42,7 @@ fn removes_sector_with_correct_accounting() { // A miner will pay the minimum of termination fee and locked funds. Add some locked funds to ensure // correct fee calculation is used. - h.apply_rewards(&mut rt, BIG_REWARDS.into(), BigInt::zero()); + h.apply_rewards(&mut rt, BIG_REWARDS.clone(), TokenAmount::zero()); let state: State = rt.get_state(); let initial_locked_funds = state.locked_funds; @@ -68,7 +68,7 @@ fn removes_sector_with_correct_accounting() { &h.epoch_qa_power_smooth, §or_power, &h.epoch_reward_smooth, - &BigInt::zero(), + &TokenAmount::zero(), 0, ); diff --git a/actors/miner/tests/util.rs b/actors/miner/tests/util.rs index 27ea19755e..4311d91a47 100644 --- a/actors/miner/tests/util.rs +++ b/actors/miner/tests/util.rs @@ -48,7 +48,6 @@ use fvm_ipld_encoding::de::Deserialize; use fvm_ipld_encoding::ser::Serialize; use fvm_ipld_encoding::{BytesDe, Cbor, CborStore, RawBytes}; use fvm_shared::address::Address; -use fvm_shared::bigint::bigint_ser::BigIntSer; use fvm_shared::bigint::BigInt; use fvm_shared::clock::QuantSpec; use fvm_shared::clock::{ChainEpoch, NO_QUANTIZATION}; @@ -67,9 +66,9 @@ use fvm_shared::{HAMT_BIT_WIDTH, METHOD_SEND}; use cid::Cid; use itertools::Itertools; +use lazy_static::lazy_static; use multihash::derive::Multihash; use multihash::MultihashDigest; -use num_traits::sign::Signed; use fil_actor_miner::testing::{ check_deadline_state_invariants, check_state_invariants, DeadlineStateSummary, @@ -82,14 +81,18 @@ const RECEIVER_ID: u64 = 1000; pub type SectorsMap = BTreeMap; -// A reward amount for use in tests where the vesting amount wants to be large enough to cover penalties. -#[allow(dead_code)] -pub const BIG_REWARDS: u128 = 10u128.pow(24); - // an expriration ~10 days greater than effective min expiration taking into account 30 days max between pre and prove commit #[allow(dead_code)] pub const DEFAULT_SECTOR_EXPIRATION: u64 = 220; +lazy_static! { + pub static ref BIG_BALANCE: TokenAmount = TokenAmount::from_whole(1_000_000); + pub static ref ONE_PERCENT_BALANCE: TokenAmount = BIG_BALANCE.div_floor(100); + + // A reward amount for use in tests where the vesting amount wants to be large enough to cover penalties. + pub static ref BIG_REWARDS: TokenAmount = TokenAmount::from_whole(1_000); +} + #[allow(dead_code)] pub fn setup() -> (ActorHarness, MockRuntime) { let mut rt = MockRuntime::default(); @@ -132,7 +135,7 @@ impl ActorHarness { let control_addrs = vec![Address::new_id(999), Address::new_id(998), Address::new_id(997)]; let worker_key = new_bls_addr(0); let receiver = Address::new_id(RECEIVER_ID); - let rwd = TokenAmount::from(10_000_000_000_000_000_000i128); + let rwd = TokenAmount::from_whole(10); let pwr = StoragePower::from(1i128 << 50); let proof_type = RegisteredSealProof::StackedDRG32GiBV1P1; @@ -152,12 +155,12 @@ impl ActorHarness { period_offset: proving_period_offset, next_sector_no: 0, - network_pledge: rwd.clone() * TokenAmount::from(1000), + network_pledge: rwd.clone() * 1000, network_raw_power: pwr.clone(), network_qa_power: pwr.clone(), baseline_power: pwr.clone(), - epoch_reward_smooth: FilterEstimate::new(rwd, BigInt::from(0)), + epoch_reward_smooth: FilterEstimate::new(rwd.atto().clone(), BigInt::from(0)), epoch_qa_power_smooth: FilterEstimate::new(pwr, BigInt::from(0)), } } @@ -217,7 +220,7 @@ impl ActorHarness { self.worker, AccountMethod::PubkeyAddress as u64, RawBytes::default(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::serialize(self.worker_key).unwrap(), ExitCode::OK, ); @@ -454,7 +457,7 @@ impl ActorHarness { rt: &mut MockRuntime, params: PreCommitSectorBatchParams, conf: &PreCommitBatchConfig, - base_fee: TokenAmount, + base_fee: &TokenAmount, ) -> Result { rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, self.worker); rt.expect_validate_caller_addr(self.caller_addrs()); @@ -492,7 +495,7 @@ impl ActorHarness { *STORAGE_MARKET_ACTOR_ADDR, MarketMethod::VerifyDealsForActivation as u64, RawBytes::serialize(vdparams).unwrap(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::serialize(vdreturn).unwrap(), ExitCode::OK, ); @@ -500,9 +503,9 @@ impl ActorHarness { let state = self.get_state(rt); // burn networkFee - if state.fee_debt > TokenAmount::from(0u8) || params.sectors.len() > 1 { + if state.fee_debt > TokenAmount::zero() || params.sectors.len() > 1 { let expected_network_fee = - aggregate_pre_commit_network_fee(params.sectors.len() as i64, &base_fee); + aggregate_pre_commit_network_fee(params.sectors.len() as i64, base_fee); let expected_burn = expected_network_fee + state.fee_debt; rt.expect_send( *BURNT_FUNDS_ACTOR_ADDR, @@ -525,7 +528,7 @@ impl ActorHarness { *STORAGE_POWER_ACTOR_ADDR, PowerMethod::EnrollCronEvent as u64, RawBytes::serialize(cron_params).unwrap(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -543,7 +546,7 @@ impl ActorHarness { rt: &mut MockRuntime, params: PreCommitSectorBatchParams, conf: &PreCommitBatchConfig, - base_fee: TokenAmount, + base_fee: &TokenAmount, ) -> Vec { let result = self.pre_commit_sector_batch(rt, params.clone(), conf, base_fee).unwrap(); @@ -578,7 +581,7 @@ impl ActorHarness { *STORAGE_MARKET_ACTOR_ADDR, MarketMethod::VerifyDealsForActivation as u64, RawBytes::serialize(vdparams).unwrap(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::serialize(vdreturn).unwrap(), ExitCode::OK, ); @@ -586,7 +589,7 @@ impl ActorHarness { // in the original test the else branch does some redundant checks which we can omit. let state = self.get_state(rt); - if state.fee_debt > TokenAmount::from(0u8) { + if state.fee_debt > TokenAmount::zero() { rt.expect_send( *BURNT_FUNDS_ACTOR_ADDR, METHOD_SEND, @@ -608,7 +611,7 @@ impl ActorHarness { *STORAGE_POWER_ACTOR_ADDR, PowerMethod::EnrollCronEvent as u64, RawBytes::serialize(cron_params).unwrap(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -665,7 +668,7 @@ impl ActorHarness { *REWARD_ACTOR_ADDR, RewardMethod::ThisEpochReward as u64, RawBytes::default(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::serialize(current_reward).unwrap(), ExitCode::OK, ); @@ -673,7 +676,7 @@ impl ActorHarness { *STORAGE_POWER_ACTOR_ADDR, PowerMethod::CurrentTotalPower as u64, RawBytes::default(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::serialize(current_power).unwrap(), ExitCode::OK, ); @@ -733,7 +736,7 @@ impl ActorHarness { *STORAGE_POWER_ACTOR_ADDR, PowerMethod::SubmitPoRepForBulkVerify as u64, RawBytes::serialize(seal).unwrap(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -753,7 +756,7 @@ impl ActorHarness { config: ProveCommitConfig, precommits: Vec, params: ProveCommitAggregateParams, - base_fee: BigInt, + base_fee: &TokenAmount, ) -> Result<(), ActorError> { let comm_ds: Vec<_> = precommits .iter() @@ -807,8 +810,8 @@ impl ActorHarness { self.confirm_sector_proofs_valid_internal(rt, config, &precommits); // burn network fee - let expected_fee = aggregate_prove_commit_network_fee(precommits.len() as i64, &base_fee); - assert!(expected_fee > BigInt::zero()); + let expected_fee = aggregate_prove_commit_network_fee(precommits.len() as i64, base_fee); + assert!(expected_fee.is_positive()); rt.expect_send( *BURNT_FUNDS_ACTOR_ADDR, METHOD_SEND, @@ -896,7 +899,7 @@ impl ActorHarness { *STORAGE_MARKET_ACTOR_ADDR, MarketMethod::ActivateDeals as u64, RawBytes::serialize(params).unwrap(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::serialize(ret).unwrap(), exit, ); @@ -906,7 +909,7 @@ impl ActorHarness { } if !valid_pcs.is_empty() { - let mut expected_pledge = TokenAmount::from(0u8); + let mut expected_pledge = TokenAmount::zero(); let mut expected_qa_power = BigInt::from(0); let mut expected_raw_power = BigInt::from(0); @@ -936,12 +939,12 @@ impl ActorHarness { } } - if expected_pledge != TokenAmount::from(0u8) { + if expected_pledge != TokenAmount::zero() { rt.expect_send( *STORAGE_POWER_ACTOR_ADDR, PowerMethod::UpdatePledgeTotal as u64, - RawBytes::serialize(BigIntSer(&expected_pledge)).unwrap(), - TokenAmount::from(0u8), + RawBytes::serialize(&expected_pledge).unwrap(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -1013,20 +1016,20 @@ impl ActorHarness { *STORAGE_POWER_ACTOR_ADDR, PowerMethod::UpdateClaimedPower as u64, RawBytes::serialize(params).unwrap(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); } - let mut penalty_total = TokenAmount::from(0u8); - let mut pledge_delta = TokenAmount::from(0u8); + let mut penalty_total = TokenAmount::zero(); + let mut pledge_delta = TokenAmount::zero(); penalty_total += cfg.continued_faults_penalty.clone(); penalty_total += cfg.repaid_fee_debt.clone(); penalty_total += cfg.expired_precommit_penalty.clone(); - if penalty_total != TokenAmount::from(0u8) { + if penalty_total != TokenAmount::zero() { rt.expect_send( *BURNT_FUNDS_ACTOR_ADDR, METHOD_SEND, @@ -1050,12 +1053,12 @@ impl ActorHarness { pledge_delta += cfg.expired_sectors_pledge_delta; pledge_delta -= immediately_vesting_funds(rt, &state); - if pledge_delta != TokenAmount::from(0u8) { + if pledge_delta != TokenAmount::zero() { rt.expect_send( *STORAGE_POWER_ACTOR_ADDR, PowerMethod::UpdatePledgeTotal as u64, - RawBytes::serialize(BigIntSer(&pledge_delta)).unwrap(), - TokenAmount::from(0u8), + RawBytes::serialize(&pledge_delta).unwrap(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -1068,7 +1071,7 @@ impl ActorHarness { *STORAGE_POWER_ACTOR_ADDR, PowerMethod::EnrollCronEvent as u64, RawBytes::serialize(params).unwrap(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -1186,7 +1189,7 @@ impl ActorHarness { *STORAGE_POWER_ACTOR_ADDR, PowerMethod::UpdateClaimedPower as u64, RawBytes::serialize(claim).unwrap(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -1294,7 +1297,7 @@ impl ActorHarness { *STORAGE_POWER_ACTOR_ADDR, PowerMethod::UpdateClaimedPower as u64, RawBytes::serialize(claim).unwrap(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -1329,8 +1332,8 @@ impl ActorHarness { rt.expect_send( *STORAGE_POWER_ACTOR_ADDR, PowerMethod::UpdatePledgeTotal as u64, - RawBytes::serialize(BigIntSer(&expected_pledge_delta)).unwrap(), - TokenAmount::from(0u8), + RawBytes::serialize(&expected_pledge_delta).unwrap(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -1398,13 +1401,13 @@ impl ActorHarness { rt.expect_send( *STORAGE_POWER_ACTOR_ADDR, PowerMethod::UpdatePledgeTotal as u64, - RawBytes::serialize(BigIntSer(&pledge_delta)).unwrap(), - TokenAmount::from(0u8), + RawBytes::serialize(&pledge_delta).unwrap(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); - if penalty > TokenAmount::from(0u8) { + if penalty > TokenAmount::zero() { rt.expect_send( *BURNT_FUNDS_ACTOR_ADDR, METHOD_SEND, @@ -1558,7 +1561,7 @@ impl ActorHarness { *STORAGE_POWER_ACTOR_ADDR, PowerMethod::UpdateClaimedPower as u64, RawBytes::serialize(claim).unwrap(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -1584,7 +1587,7 @@ impl ActorHarness { rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, self.worker); rt.expect_validate_caller_addr(self.caller_addrs()); - if expected_debt_repaid > TokenAmount::from(0u8) { + if expected_debt_repaid > TokenAmount::zero() { rt.expect_send( *BURNT_FUNDS_ACTOR_ADDR, METHOD_SEND, @@ -1702,11 +1705,11 @@ impl ActorHarness { *REWARD_ACTOR_ADDR, RewardMethod::ThisEpochReward as u64, RawBytes::default(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::serialize(current_reward).unwrap(), ExitCode::OK, ); - let this_epoch_reward = self.epoch_reward_smooth.estimate(); + let this_epoch_reward = TokenAmount::from_atto(self.epoch_reward_smooth.estimate()); let penalty_total = consensus_fault_penalty(this_epoch_reward.clone()); let reward_total = reward_for_consensus_slash_report(&this_epoch_reward); rt.expect_send( @@ -1795,7 +1798,7 @@ impl ActorHarness { self.expect_query_network_info(rt); - let mut pledge_delta = BigInt::zero(); + let mut pledge_delta = TokenAmount::zero(); if expected_fee.is_positive() { rt.expect_send( *BURNT_FUNDS_ACTOR_ADDR, @@ -1817,8 +1820,8 @@ impl ActorHarness { rt.expect_send( *STORAGE_POWER_ACTOR_ADDR, UPDATE_PLEDGE_TOTAL_METHOD, - RawBytes::serialize(BigIntSer(&pledge_delta)).unwrap(), - BigInt::zero(), + RawBytes::serialize(&pledge_delta).unwrap(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -1913,7 +1916,7 @@ impl ActorHarness { rt.expect_send( *STORAGE_POWER_ACTOR_ADDR, PowerMethod::UpdatePledgeTotal as u64, - RawBytes::serialize(BigIntSer(&pledge_delta)).unwrap(), + RawBytes::serialize(&pledge_delta).unwrap(), TokenAmount::zero(), RawBytes::default(), ExitCode::OK, @@ -2315,11 +2318,11 @@ impl CronConfig { expected_enrollment: 0, detected_faults_power_delta: None, expired_sectors_power_delta: None, - expired_sectors_pledge_delta: TokenAmount::from(0u8), - continued_faults_penalty: TokenAmount::from(0u8), - expired_precommit_penalty: TokenAmount::from(0u8), - repaid_fee_debt: TokenAmount::from(0u8), - penalty_from_unlocked: TokenAmount::from(0u8), + expired_sectors_pledge_delta: TokenAmount::zero(), + continued_faults_penalty: TokenAmount::zero(), + expired_precommit_penalty: TokenAmount::zero(), + repaid_fee_debt: TokenAmount::zero(), + penalty_from_unlocked: TokenAmount::zero(), } } @@ -2428,7 +2431,7 @@ enum MhCode { fn immediately_vesting_funds(rt: &MockRuntime, state: &State) -> TokenAmount { let vesting = rt.store.get_cbor::(&state.vesting_funds).unwrap().unwrap(); - let mut sum = TokenAmount::from(0u8); + let mut sum = TokenAmount::zero(); for vf in vesting.funds { if vf.epoch < rt.epoch { sum += vf.amount; @@ -2558,7 +2561,7 @@ pub fn test_sector( sector_number, deal_weight: DealWeight::from(deal_weight), verified_deal_weight: DealWeight::from(verified_deal_weight), - initial_pledge: TokenAmount::from(pledge), + initial_pledge: TokenAmount::from_atto(pledge), sealed_cid: make_sealed_cid(format!("commR-{sector_number}").as_bytes()), ..Default::default() } diff --git a/actors/miner/tests/vesting_add_locked_funds.rs b/actors/miner/tests/vesting_add_locked_funds.rs index 463fdcaf25..b585772e5b 100644 --- a/actors/miner/tests/vesting_add_locked_funds.rs +++ b/actors/miner/tests/vesting_add_locked_funds.rs @@ -11,7 +11,7 @@ fn locked_funds_increases_with_sequential_calls() { let vspec = VestSpec { initial_delay: 0, vest_period: 1, step_duration: 1, quantization: 1 }; let vest_start = 10; - let vest_sum = TokenAmount::from(100); + let vest_sum = TokenAmount::from_atto(100); h.add_locked_funds(vest_start, &vest_sum, &vspec).unwrap(); assert_eq!(vest_sum, h.st.locked_funds); @@ -26,7 +26,7 @@ fn vests_when_quantize_step_duration_and_vesting_period_are_coprime() { let vspec = VestSpec { initial_delay: 0, vest_period: 27, step_duration: 5, quantization: 7 }; let vest_start = 10; - let vest_sum = TokenAmount::from(100); + let vest_sum = TokenAmount::from_atto(100); h.add_locked_funds(vest_start, &vest_sum, &vspec).unwrap(); assert_eq!(vest_sum, h.st.locked_funds); @@ -35,19 +35,19 @@ fn vests_when_quantize_step_duration_and_vesting_period_are_coprime() { let amount_vested = h.unlock_vested_funds(e).unwrap(); match e { 22 => { - assert_eq!(TokenAmount::from(40), amount_vested); + assert_eq!(TokenAmount::from_atto(40), amount_vested); } 29 => { - assert_eq!(TokenAmount::from(26), amount_vested); + assert_eq!(TokenAmount::from_atto(26), amount_vested); } 36 => { - assert_eq!(TokenAmount::from(26), amount_vested); + assert_eq!(TokenAmount::from_atto(26), amount_vested); } 43 => { - assert_eq!(TokenAmount::from(8), amount_vested); + assert_eq!(TokenAmount::from_atto(8), amount_vested); } _ => { - assert_eq!(TokenAmount::from(0), amount_vested); + assert_eq!(TokenAmount::zero(), amount_vested); } } total_vested += amount_vested; diff --git a/actors/miner/tests/vesting_add_locked_funds_table.rs b/actors/miner/tests/vesting_add_locked_funds_table.rs index b66c7eae65..e4b1c26de5 100644 --- a/actors/miner/tests/vesting_add_locked_funds_table.rs +++ b/actors/miner/tests/vesting_add_locked_funds_table.rs @@ -1,5 +1,4 @@ use fil_actor_miner::VestSpec; -use fvm_shared::bigint::Zero; use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; @@ -150,18 +149,18 @@ fn test_vesting() { let vest_start = tc.period_start + vest_start_delay; - h.st.add_locked_funds(&h.store, vest_start, &TokenAmount::from(vest_sum), &tc.vspec) + h.st.add_locked_funds(&h.store, vest_start, &TokenAmount::from_atto(vest_sum), &tc.vspec) .unwrap(); - assert_eq!(TokenAmount::from(vest_sum), h.st.locked_funds); + assert_eq!(TokenAmount::from_atto(vest_sum), h.st.locked_funds); let mut total_vested = 0; for (e, &v) in tc.vepocs.iter().enumerate() { assert_eq!( - TokenAmount::from(v), + TokenAmount::from_atto(v), h.st.unlock_vested_funds(&h.store, vest_start + e as ChainEpoch).unwrap() ); total_vested += v; - assert_eq!(TokenAmount::from(vest_sum - total_vested), h.st.locked_funds); + assert_eq!(TokenAmount::from_atto(vest_sum - total_vested), h.st.locked_funds); } assert_eq!(vest_sum, total_vested); diff --git a/actors/miner/tests/vesting_unvested_funds.rs b/actors/miner/tests/vesting_unvested_funds.rs index 0bb51ab64f..6cc1cae641 100644 --- a/actors/miner/tests/vesting_unvested_funds.rs +++ b/actors/miner/tests/vesting_unvested_funds.rs @@ -13,27 +13,27 @@ fn unlock_unvested_funds_leaving_bucket_with_non_zero_tokens() { let vspec = VestSpec { initial_delay: 0, vest_period: 5, step_duration: 1, quantization: 1 }; let vest_start = 100; - let vest_sum = TokenAmount::from(100); + let vest_sum = TokenAmount::from_atto(100); h.add_locked_funds(vest_start, &vest_sum, &vspec).unwrap(); - let amount_unlocked = h.unlock_unvested_funds(vest_start, &TokenAmount::from(39)).unwrap(); - assert_eq!(TokenAmount::from(39), amount_unlocked); + let amount_unlocked = h.unlock_unvested_funds(vest_start, &TokenAmount::from_atto(39)).unwrap(); + assert_eq!(TokenAmount::from_atto(39), amount_unlocked); // no vested funds available to unlock until strictly after first vesting epoch - assert_eq!(TokenAmount::from(0), h.unlock_vested_funds(vest_start).unwrap()); - assert_eq!(TokenAmount::from(0), h.unlock_vested_funds(vest_start + 1).unwrap()); + assert_eq!(TokenAmount::zero(), h.unlock_vested_funds(vest_start).unwrap()); + assert_eq!(TokenAmount::zero(), h.unlock_vested_funds(vest_start + 1).unwrap()); // expected to be zero due to unlocking of UNvested funds - assert_eq!(TokenAmount::from(0), h.unlock_vested_funds(vest_start + 2).unwrap()); + assert_eq!(TokenAmount::zero(), h.unlock_vested_funds(vest_start + 2).unwrap()); // expected to be partially unlocked already du to unlocking of UNvested funds - assert_eq!(TokenAmount::from(1), h.unlock_vested_funds(vest_start + 3).unwrap()); + assert_eq!(TokenAmount::from_atto(1), h.unlock_vested_funds(vest_start + 3).unwrap()); - assert_eq!(TokenAmount::from(20), h.unlock_vested_funds(vest_start + 4).unwrap()); - assert_eq!(TokenAmount::from(20), h.unlock_vested_funds(vest_start + 5).unwrap()); - assert_eq!(TokenAmount::from(20), h.unlock_vested_funds(vest_start + 6).unwrap()); + assert_eq!(TokenAmount::from_atto(20), h.unlock_vested_funds(vest_start + 4).unwrap()); + assert_eq!(TokenAmount::from_atto(20), h.unlock_vested_funds(vest_start + 5).unwrap()); + assert_eq!(TokenAmount::from_atto(20), h.unlock_vested_funds(vest_start + 6).unwrap()); - assert_eq!(TokenAmount::from(0), h.unlock_vested_funds(vest_start + 7).unwrap()); + assert_eq!(TokenAmount::zero(), h.unlock_vested_funds(vest_start + 7).unwrap()); assert!(h.st.locked_funds.is_zero()); assert!(h.vesting_funds_store_empty()) @@ -45,25 +45,25 @@ fn unlock_unvested_funds_leaving_bucket_with_zero_tokens() { let vspec = VestSpec { initial_delay: 0, vest_period: 5, step_duration: 1, quantization: 1 }; let vest_start = 100; - let vest_sum = TokenAmount::from(100); + let vest_sum = TokenAmount::from_atto(100); h.add_locked_funds(vest_start, &vest_sum, &vspec).unwrap(); - let amount_unlocked = h.unlock_unvested_funds(vest_start, &TokenAmount::from(40)).unwrap(); - assert_eq!(TokenAmount::from(40), amount_unlocked); + let amount_unlocked = h.unlock_unvested_funds(vest_start, &TokenAmount::from_atto(40)).unwrap(); + assert_eq!(TokenAmount::from_atto(40), amount_unlocked); - assert_eq!(TokenAmount::from(0), h.unlock_vested_funds(vest_start).unwrap()); - assert_eq!(TokenAmount::from(0), h.unlock_vested_funds(vest_start + 1).unwrap()); + assert_eq!(TokenAmount::zero(), h.unlock_vested_funds(vest_start).unwrap()); + assert_eq!(TokenAmount::zero(), h.unlock_vested_funds(vest_start + 1).unwrap()); // expected to be zero due to unlocking of UNvested funds - assert_eq!(TokenAmount::from(0), h.unlock_vested_funds(vest_start + 2).unwrap()); - assert_eq!(TokenAmount::from(0), h.unlock_vested_funds(vest_start + 3).unwrap()); + assert_eq!(TokenAmount::zero(), h.unlock_vested_funds(vest_start + 2).unwrap()); + assert_eq!(TokenAmount::zero(), h.unlock_vested_funds(vest_start + 3).unwrap()); - assert_eq!(TokenAmount::from(20), h.unlock_vested_funds(vest_start + 4).unwrap()); - assert_eq!(TokenAmount::from(20), h.unlock_vested_funds(vest_start + 5).unwrap()); - assert_eq!(TokenAmount::from(20), h.unlock_vested_funds(vest_start + 6).unwrap()); + assert_eq!(TokenAmount::from_atto(20), h.unlock_vested_funds(vest_start + 4).unwrap()); + assert_eq!(TokenAmount::from_atto(20), h.unlock_vested_funds(vest_start + 5).unwrap()); + assert_eq!(TokenAmount::from_atto(20), h.unlock_vested_funds(vest_start + 6).unwrap()); - assert_eq!(TokenAmount::from(0), h.unlock_vested_funds(vest_start + 7).unwrap()); + assert_eq!(TokenAmount::zero(), h.unlock_vested_funds(vest_start + 7).unwrap()); assert!(h.st.locked_funds.is_zero()); assert!(h.vesting_funds_store_empty()) @@ -75,7 +75,7 @@ fn unlock_all_unvested_funds() { let vspec = VestSpec { initial_delay: 0, vest_period: 5, step_duration: 1, quantization: 1 }; let vest_start = 10; - let vest_sum = TokenAmount::from(100); + let vest_sum = TokenAmount::from_atto(100); h.add_locked_funds(vest_start, &vest_sum, &vspec).unwrap(); let unvested_funds = h.unlock_unvested_funds(vest_start, &vest_sum).unwrap(); @@ -91,9 +91,9 @@ fn unlock_unvested_funds_value_greater_than_locked_funds() { let vspec = VestSpec { initial_delay: 0, vest_period: 5, step_duration: 1, quantization: 1 }; let vest_start = 10; - let vest_sum = TokenAmount::from(100); + let vest_sum = TokenAmount::from_atto(100); h.add_locked_funds(vest_start, &vest_sum, &vspec).unwrap(); - let unvested_funds = h.unlock_unvested_funds(vest_start, &TokenAmount::from(200)).unwrap(); + let unvested_funds = h.unlock_unvested_funds(vest_start, &TokenAmount::from_atto(200)).unwrap(); assert_eq!(vest_sum, unvested_funds); assert!(h.st.locked_funds.is_zero()); @@ -106,14 +106,14 @@ fn unlock_unvested_funds_when_there_are_vested_funds_in_the_table() { let vspec = VestSpec { initial_delay: 0, vest_period: 50, step_duration: 1, quantization: 1 }; let vest_start = 10; - let vest_sum = TokenAmount::from(100); + let vest_sum = TokenAmount::from_atto(100); // will lock funds from epochs 11 to 60 h.add_locked_funds(vest_start, &vest_sum, &vspec).unwrap(); // unlock funds from epochs 30 to 60 let new_epoch = 30; - let target = TokenAmount::from(60); + let target = TokenAmount::from_atto(60); let remaining = &vest_sum - ⌖ let unvested_funds = h.unlock_unvested_funds(new_epoch, &target).unwrap(); assert_eq!(target, unvested_funds); diff --git a/actors/miner/tests/withdraw_balance.rs b/actors/miner/tests/withdraw_balance.rs index 01133796d2..b0d59e3c28 100644 --- a/actors/miner/tests/withdraw_balance.rs +++ b/actors/miner/tests/withdraw_balance.rs @@ -5,27 +5,24 @@ use fvm_shared::bigint::Zero; use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; -use std::ops::Deref; mod util; use util::*; -const BIG_BALANCE: u128 = 1_000_000_000_000_000_000_000_000u128; -const ONE_PERCENT_BALANCE: u128 = BIG_BALANCE / 100; const PERIOD_OFFSET: ChainEpoch = 100; #[test] fn happy_path_withdraws_funds() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); h.withdraw_funds( &mut rt, h.owner, - &TokenAmount::from(ONE_PERCENT_BALANCE), - &TokenAmount::from(ONE_PERCENT_BALANCE), + &ONE_PERCENT_BALANCE, + &ONE_PERCENT_BALANCE, &TokenAmount::zero(), ) .unwrap(); @@ -36,11 +33,11 @@ fn happy_path_withdraws_funds() { fn fails_if_miner_cant_repay_fee_debt() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let mut st = h.get_state(&rt); - st.fee_debt = rt.balance.borrow().deref() + TokenAmount::from(1e18 as u64); + st.fee_debt = &*rt.balance.borrow() + TokenAmount::from_whole(1); rt.replace_state(&st); expect_abort_contains_message( ExitCode::USR_INSUFFICIENT_FUNDS, @@ -48,8 +45,8 @@ fn fails_if_miner_cant_repay_fee_debt() { h.withdraw_funds( &mut rt, h.owner, - &TokenAmount::from(ONE_PERCENT_BALANCE), - &TokenAmount::from(ONE_PERCENT_BALANCE), + &*ONE_PERCENT_BALANCE, + &*ONE_PERCENT_BALANCE, &TokenAmount::zero(), ), ); @@ -60,11 +57,11 @@ fn fails_if_miner_cant_repay_fee_debt() { fn withdraw_only_what_we_can_after_fee_debt() { let h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let mut st = h.get_state(&rt); - let fee_debt = TokenAmount::from(BIG_BALANCE - ONE_PERCENT_BALANCE); + let fee_debt = &*BIG_BALANCE - &*ONE_PERCENT_BALANCE; st.fee_debt = fee_debt.clone(); rt.replace_state(&st); @@ -78,18 +75,18 @@ fn withdraw_only_what_we_can_after_fee_debt() { fn successfully_withdraw() { let mut h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); - let one = TokenAmount::from(1); + let one = TokenAmount::from_atto(1); h.withdraw_funds(&mut rt, h.owner, &one, &one, &TokenAmount::zero()).unwrap(); let first_beneficiary_id = Address::new_id(999); - let quota = TokenAmount::from(ONE_PERCENT_BALANCE); + let quota = &*ONE_PERCENT_BALANCE; h.propose_approve_initial_beneficiary( &mut rt, first_beneficiary_id, - BeneficiaryTerm::new(quota, TokenAmount::zero(), PERIOD_OFFSET + 100), + BeneficiaryTerm::new(quota.clone(), TokenAmount::zero(), PERIOD_OFFSET + 100), ) .unwrap(); h.withdraw_funds(&mut rt, h.owner, &one, &one, &TokenAmount::zero()).unwrap(); @@ -101,14 +98,14 @@ fn successfully_withdraw() { fn successfully_withdraw_allow_zero() { let mut h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let first_beneficiary_id = Address::new_id(999); h.propose_approve_initial_beneficiary( &mut rt, first_beneficiary_id, - BeneficiaryTerm::new(TokenAmount::from(1), TokenAmount::zero(), PERIOD_OFFSET + 100), + BeneficiaryTerm::new(TokenAmount::from_atto(1), TokenAmount::zero(), PERIOD_OFFSET + 100), ) .unwrap(); h.withdraw_funds( @@ -126,11 +123,11 @@ fn successfully_withdraw_allow_zero() { fn successfully_withdraw_limited_to_quota() { let mut h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let first_beneficiary_id = Address::new_id(999); - let quota = TokenAmount::from(ONE_PERCENT_BALANCE); + let quota = &*ONE_PERCENT_BALANCE; h.propose_approve_initial_beneficiary( &mut rt, first_beneficiary_id, @@ -138,8 +135,8 @@ fn successfully_withdraw_limited_to_quota() { ) .unwrap(); - let withdraw_amount = TokenAmount::from(ONE_PERCENT_BALANCE * 2); - h.withdraw_funds(&mut rt, h.beneficiary, &withdraw_amount, "a, &TokenAmount::zero()) + let withdraw_amount = &*ONE_PERCENT_BALANCE * 2; + h.withdraw_funds(&mut rt, h.beneficiary, &withdraw_amount, quota, &TokenAmount::zero()) .unwrap(); h.check_state(&rt); } @@ -148,11 +145,11 @@ fn successfully_withdraw_limited_to_quota() { fn allow_withdraw_but_no_send_when_beneficiary_not_efficient() { let mut h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let first_beneficiary_id = Address::new_id(999); - let quota = TokenAmount::from(ONE_PERCENT_BALANCE); + let quota = &*ONE_PERCENT_BALANCE; h.propose_approve_initial_beneficiary( &mut rt, first_beneficiary_id, @@ -162,7 +159,7 @@ fn allow_withdraw_but_no_send_when_beneficiary_not_efficient() { let info = h.get_info(&rt); assert_eq!(PERIOD_OFFSET - 10, info.beneficiary_term.expiration); rt.set_epoch(100); - h.withdraw_funds(&mut rt, h.beneficiary, "a, &TokenAmount::zero(), &TokenAmount::zero()) + h.withdraw_funds(&mut rt, h.beneficiary, quota, &TokenAmount::zero(), &TokenAmount::zero()) .unwrap(); h.check_state(&rt); } @@ -171,13 +168,13 @@ fn allow_withdraw_but_no_send_when_beneficiary_not_efficient() { fn fail_withdraw_from_non_beneficiary() { let mut h = ActorHarness::new(PERIOD_OFFSET); let mut rt = h.new_runtime(); - rt.set_balance(TokenAmount::from(BIG_BALANCE)); + rt.set_balance(BIG_BALANCE.clone()); h.construct_and_verify(&mut rt); let first_beneficiary_id = Address::new_id(999); let another_actor = Address::new_id(1000); - let quota = TokenAmount::from(ONE_PERCENT_BALANCE); - let one = TokenAmount::from(1); + let quota = &*ONE_PERCENT_BALANCE; + let one = TokenAmount::from_atto(1); expect_abort( ExitCode::USR_FORBIDDEN, @@ -193,7 +190,7 @@ fn fail_withdraw_from_non_beneficiary() { h.propose_approve_initial_beneficiary( &mut rt, first_beneficiary_id, - BeneficiaryTerm::new(quota, TokenAmount::zero(), PERIOD_OFFSET - 10), + BeneficiaryTerm::new(quota.clone(), TokenAmount::zero(), PERIOD_OFFSET - 10), ) .unwrap(); diff --git a/actors/multisig/Cargo.toml b/actors/multisig/Cargo.toml index a1003310e4..382d24ab2b 100644 --- a/actors/multisig/Cargo.toml +++ b/actors/multisig/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "9.0.0-alpha.1", path = "../../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } fvm_ipld_hamt = "0.5.1" num-traits = "0.2.14" num-derive = "0.3.3" @@ -29,6 +29,7 @@ fvm_ipld_encoding = "0.2.2" [dev-dependencies] fil_actors_runtime = { path = "../../runtime", features = ["test_utils", "sector-default"] } +lazy_static = "1.4.0" [features] fil-actor = [] diff --git a/actors/multisig/src/lib.rs b/actors/multisig/src/lib.rs index 726db39e79..b9749ebe01 100644 --- a/actors/multisig/src/lib.rs +++ b/actors/multisig/src/lib.rs @@ -12,12 +12,12 @@ use fil_actors_runtime::{ use fvm_ipld_blockstore::Blockstore; use fvm_ipld_encoding::RawBytes; use fvm_shared::address::Address; -use fvm_shared::bigint::Sign; + use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; use fvm_shared::{MethodNum, HAMT_BIT_WIDTH, METHOD_CONSTRUCTOR}; use num_derive::FromPrimitive; -use num_traits::{FromPrimitive, Signed}; +use num_traits::{FromPrimitive, Zero}; pub use self::state::*; pub use self::types::*; @@ -110,7 +110,7 @@ impl Actor { signers: resolved_signers, num_approvals_threshold: params.num_approvals_threshold, pending_txs: empty_root, - initial_balance: TokenAmount::from(0), + initial_balance: TokenAmount::zero(), next_tx_id: Default::default(), start_epoch: Default::default(), unlock_duration: Default::default(), @@ -137,7 +137,7 @@ impl Actor { rt.validate_immediate_caller_type(CALLER_TYPES_SIGNABLE.iter())?; let proposer: Address = rt.message().caller(); - if params.value.sign() == Sign::Minus { + if params.value.is_negative() { return Err(actor_error!( illegal_argument, "proposed value must be non-negative, was {}", diff --git a/actors/multisig/src/state.rs b/actors/multisig/src/state.rs index 4e9360aa84..67d387503f 100644 --- a/actors/multisig/src/state.rs +++ b/actors/multisig/src/state.rs @@ -7,7 +7,8 @@ use fvm_ipld_blockstore::Blockstore; use fvm_ipld_encoding::tuple::*; use fvm_ipld_encoding::Cbor; use fvm_shared::address::Address; -use fvm_shared::bigint::{bigint_ser, Integer}; +use fvm_shared::bigint::BigInt; +use fvm_shared::bigint::Integer; use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; use indexmap::IndexMap; @@ -25,7 +26,6 @@ pub struct State { pub next_tx_id: TxnID, // Linear unlock - #[serde(with = "bigint_ser")] pub initial_balance: TokenAmount, pub start_epoch: ChainEpoch, pub unlock_duration: ChainEpoch, @@ -54,7 +54,7 @@ impl State { /// Returns amount locked in multisig contract pub fn amount_locked(&self, elapsed_epoch: ChainEpoch) -> TokenAmount { if elapsed_epoch >= self.unlock_duration { - return TokenAmount::from(0); + return TokenAmount::zero(); } if elapsed_epoch <= 0 { return self.initial_balance.clone(); @@ -64,9 +64,9 @@ impl State { // locked = ceil(InitialBalance * remainingLockDuration / UnlockDuration) let numerator: TokenAmount = &self.initial_balance * remaining_lock_duration; - let denominator = TokenAmount::from(self.unlock_duration); + let denominator = BigInt::from(self.unlock_duration); - numerator.div_ceil(&denominator) + TokenAmount::from_atto(numerator.atto().div_ceil(&denominator)) } /// Iterates all pending transactions and removes an address from each list of approvals, @@ -111,7 +111,7 @@ impl State { amount_to_spend: &TokenAmount, curr_epoch: ChainEpoch, ) -> anyhow::Result<()> { - if amount_to_spend < &0.into() { + if amount_to_spend.is_negative() { return Err(anyhow!("amount to spend {} less than zero", amount_to_spend)); } if &balance < amount_to_spend { diff --git a/actors/multisig/src/testing.rs b/actors/multisig/src/testing.rs index 3f0359fea3..58dc328dce 100644 --- a/actors/multisig/src/testing.rs +++ b/actors/multisig/src/testing.rs @@ -5,7 +5,6 @@ use fil_actors_runtime::{Map, MessageAccumulator}; use fvm_ipld_blockstore::Blockstore; use fvm_shared::address::Address; use integer_encoding::VarInt; -use num_traits::Zero; use crate::{State, Transaction, TxnID, SIGNERS_MAX}; diff --git a/actors/multisig/src/types.rs b/actors/multisig/src/types.rs index b4ba99669e..51ed789922 100644 --- a/actors/multisig/src/types.rs +++ b/actors/multisig/src/types.rs @@ -7,7 +7,7 @@ use fvm_ipld_encoding::tuple::*; use fvm_ipld_encoding::{serde_bytes, Cbor, RawBytes}; use fvm_ipld_hamt::BytesKey; use fvm_shared::address::Address; -use fvm_shared::bigint::bigint_ser; + use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; @@ -40,7 +40,6 @@ impl Display for TxnID { #[derive(Clone, PartialEq, Eq, Debug, Serialize_tuple, Deserialize_tuple)] pub struct Transaction { pub to: Address, - #[serde(with = "bigint_ser")] pub value: TokenAmount, pub method: MethodNum, pub params: RawBytes, @@ -58,7 +57,6 @@ pub struct Transaction { pub struct ProposalHashData<'a> { pub requester: Option<&'a Address>, pub to: &'a Address, - #[serde(with = "bigint_ser")] pub value: &'a TokenAmount, pub method: &'a MethodNum, pub params: &'a RawBytes, @@ -78,7 +76,6 @@ pub struct ConstructorParams { #[derive(Serialize_tuple, Deserialize_tuple)] pub struct ProposeParams { pub to: Address, - #[serde(with = "bigint_ser")] pub value: TokenAmount, pub method: MethodNum, pub params: RawBytes, @@ -164,6 +161,5 @@ pub struct ChangeNumApprovalsThresholdParams { pub struct LockBalanceParams { pub start_epoch: ChainEpoch, pub unlock_duration: ChainEpoch, - #[serde(with = "bigint_ser")] pub amount: TokenAmount, } diff --git a/actors/multisig/tests/multisig_actor_test.rs b/actors/multisig/tests/multisig_actor_test.rs index 645c818247..9a6d00c571 100644 --- a/actors/multisig/tests/multisig_actor_test.rs +++ b/actors/multisig/tests/multisig_actor_test.rs @@ -10,7 +10,7 @@ use fil_actors_runtime::{INIT_ACTOR_ADDR, SYSTEM_ACTOR_ADDR}; use fvm_ipld_encoding::tuple::*; use fvm_ipld_encoding::RawBytes; use fvm_shared::address::{Address, BLS_PUB_LEN}; -use fvm_shared::bigint::bigint_ser; + use fvm_shared::bigint::Zero; use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; @@ -54,7 +54,7 @@ mod constructor_tests { start_epoch: 100, }; - rt.set_received(TokenAmount::from(100u8)); + rt.set_received(TokenAmount::from_atto(100u8)); rt.expect_validate_caller_addr(vec![*INIT_ACTOR_ADDR]); rt.set_caller(*INIT_ACTOR_CODE_ID, *INIT_ACTOR_ADDR); let ret = rt.call::( @@ -67,7 +67,7 @@ mod constructor_tests { let st: State = rt.get_state(); assert_eq!(params.signers, st.signers); assert_eq!(params.num_approvals_threshold, st.num_approvals_threshold); - assert_eq!(TokenAmount::from(100u8), st.initial_balance); + assert_eq!(TokenAmount::from_atto(100u8), st.initial_balance); assert_eq!(200, st.unlock_duration); assert_eq!(100, st.start_epoch); h.assert_transactions(&rt, vec![]); @@ -284,6 +284,7 @@ mod constructor_tests { #[cfg(test)] mod vesting_tests { use super::*; + use lazy_static::lazy_static; const MSIG: Address = Address::new_id(1000); const ANNE: Address = Address::new_id(101); @@ -293,15 +294,18 @@ mod vesting_tests { const UNLOCK_DURATION: ChainEpoch = 10; const START_EPOCH: ChainEpoch = 0; - const MSIG_INITIAL_BALANCE: u8 = 100; + + lazy_static! { + static ref MSIG_INITIAL_BALANCE: TokenAmount = TokenAmount::from_atto(100); + } #[test] fn happy_path_full_vesting() { let mut rt = construct_runtime(MSIG); let h = util::ActorHarness::new(); - rt.set_balance(TokenAmount::from(MSIG_INITIAL_BALANCE)); - rt.set_received(TokenAmount::from(MSIG_INITIAL_BALANCE)); + rt.set_balance(MSIG_INITIAL_BALANCE.clone()); + rt.set_received(MSIG_INITIAL_BALANCE.clone()); h.construct_and_verify(&mut rt, 2, UNLOCK_DURATION, START_EPOCH, vec![ANNE, BOB, CHARLIE]); rt.set_received(TokenAmount::zero()); @@ -310,7 +314,7 @@ mod vesting_tests { let proposal_hash = h.propose_ok( &mut rt, DARLENE, - TokenAmount::from(MSIG_INITIAL_BALANCE), + MSIG_INITIAL_BALANCE.clone(), METHOD_SEND, RawBytes::default(), ); @@ -326,7 +330,7 @@ mod vesting_tests { DARLENE, METHOD_SEND, RawBytes::default(), - TokenAmount::from(MSIG_INITIAL_BALANCE), + MSIG_INITIAL_BALANCE.clone(), RawBytes::default(), ExitCode::OK, ); @@ -341,8 +345,8 @@ mod vesting_tests { let mut rt = construct_runtime(MSIG); let h = util::ActorHarness::new(); - rt.set_balance(TokenAmount::from(MSIG_INITIAL_BALANCE)); - rt.set_received(TokenAmount::from(MSIG_INITIAL_BALANCE)); + rt.set_balance(MSIG_INITIAL_BALANCE.clone()); + rt.set_received(MSIG_INITIAL_BALANCE.clone()); h.construct_and_verify(&mut rt, 2, UNLOCK_DURATION, START_EPOCH, vec![ANNE, BOB, CHARLIE]); rt.set_received(TokenAmount::zero()); @@ -350,7 +354,7 @@ mod vesting_tests { let proposal_hash = h.propose_ok( &mut rt, DARLENE, - TokenAmount::from(MSIG_INITIAL_BALANCE / 2), + MSIG_INITIAL_BALANCE.div_floor(2), METHOD_SEND, RawBytes::default(), ); @@ -360,7 +364,7 @@ mod vesting_tests { DARLENE, METHOD_SEND, RawBytes::default(), - TokenAmount::from(MSIG_INITIAL_BALANCE / 2), + MSIG_INITIAL_BALANCE.div_floor(2), RawBytes::default(), ExitCode::OK, ); @@ -374,8 +378,8 @@ mod vesting_tests { let mut rt = construct_runtime(MSIG); let h = util::ActorHarness::new(); - rt.set_balance(TokenAmount::from(MSIG_INITIAL_BALANCE)); - rt.set_received(TokenAmount::from(MSIG_INITIAL_BALANCE)); + rt.set_balance(MSIG_INITIAL_BALANCE.clone()); + rt.set_received(MSIG_INITIAL_BALANCE.clone()); h.construct_and_verify(&mut rt, 1, UNLOCK_DURATION, START_EPOCH, vec![ANNE, BOB, CHARLIE]); rt.set_received(TokenAmount::zero()); @@ -385,14 +389,14 @@ mod vesting_tests { h.propose( &mut rt, DARLENE, - TokenAmount::from(MSIG_INITIAL_BALANCE), + MSIG_INITIAL_BALANCE.clone(), METHOD_SEND, RawBytes::default(), ), ); rt.reset(); rt.set_epoch(START_EPOCH + UNLOCK_DURATION / 10); - let amount_out = TokenAmount::from(MSIG_INITIAL_BALANCE / 10); + let amount_out = MSIG_INITIAL_BALANCE.div_floor(10); rt.expect_send( DARLENE, METHOD_SEND, @@ -411,8 +415,8 @@ mod vesting_tests { let mut rt = construct_runtime(MSIG); let h = util::ActorHarness::new(); - rt.set_balance(TokenAmount::from(MSIG_INITIAL_BALANCE)); - rt.set_received(TokenAmount::from(MSIG_INITIAL_BALANCE)); + rt.set_balance(MSIG_INITIAL_BALANCE.clone()); + rt.set_received(MSIG_INITIAL_BALANCE.clone()); h.construct_and_verify(&mut rt, 2, UNLOCK_DURATION, START_EPOCH, vec![ANNE, BOB, CHARLIE]); rt.set_received(TokenAmount::zero()); @@ -420,7 +424,7 @@ mod vesting_tests { let proposal_hash = h.propose_ok( &mut rt, DARLENE, - TokenAmount::from(MSIG_INITIAL_BALANCE / 2), + MSIG_INITIAL_BALANCE.div_floor(2), METHOD_SEND, RawBytes::default(), ); @@ -435,8 +439,8 @@ mod vesting_tests { let mut rt = construct_runtime(MSIG); let h = util::ActorHarness::new(); - let locked_balance = TokenAmount::from(UNLOCK_DURATION - 1); // balance < duration - let one = TokenAmount::from(1u8); + let locked_balance = TokenAmount::from_atto(UNLOCK_DURATION - 1); // balance < duration + let one = TokenAmount::from_atto(1u8); rt.set_balance(locked_balance.clone()); rt.set_received(locked_balance.clone()); h.construct_and_verify(&mut rt, 1, UNLOCK_DURATION, START_EPOCH, vec![ANNE, BOB, CHARLIE]); @@ -510,8 +514,8 @@ mod vesting_tests { let mut rt = construct_runtime(MSIG); let h = util::ActorHarness::new(); - rt.set_balance(TokenAmount::from(MSIG_INITIAL_BALANCE)); - rt.set_received(TokenAmount::from(MSIG_INITIAL_BALANCE)); + rt.set_balance(MSIG_INITIAL_BALANCE.clone()); + rt.set_received(MSIG_INITIAL_BALANCE.clone()); h.construct_and_verify(&mut rt, 2, UNLOCK_DURATION, START_EPOCH, vec![ANNE, BOB, CHARLIE]); rt.set_received(TokenAmount::zero()); @@ -534,11 +538,12 @@ mod vesting_tests { h.construct_and_verify(&mut rt, 1, 0, START_EPOCH, vec![ANNE]); rt.set_caller(*MULTISIG_ACTOR_CODE_ID, MSIG); - rt.set_balance(TokenAmount::from(10u8)); - rt.set_received(TokenAmount::from(10u8)); + rt.set_balance(TokenAmount::from_atto(10u8)); + rt.set_received(TokenAmount::from_atto(10u8)); // lock up funds the actor doesn't have yet - h.lock_balance(&mut rt, START_EPOCH, UNLOCK_DURATION, TokenAmount::from(10u8)).unwrap(); + h.lock_balance(&mut rt, START_EPOCH, UNLOCK_DURATION, TokenAmount::from_atto(10u8)) + .unwrap(); // make a tx that transfers no value let send_amount = TokenAmount::zero(); @@ -554,7 +559,7 @@ mod vesting_tests { h.propose_ok(&mut rt, BOB, send_amount, METHOD_SEND, RawBytes::default()); // verify that sending any value is prevented - let send_amount = TokenAmount::from(1u8); + let send_amount = TokenAmount::from_atto(1u8); expect_abort( ExitCode::USR_INSUFFICIENT_FUNDS, h.propose(&mut rt, BOB, send_amount, METHOD_SEND, RawBytes::default()), @@ -578,7 +583,7 @@ fn test_simple_propose() { let start_epoch = 0; let signers = vec![anne, bob]; - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); h.construct_and_verify(&mut rt, 2, no_unlock_duration, start_epoch, signers); rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, anne); h.propose_ok(&mut rt, chuck, send_value.clone(), METHOD_SEND, RawBytes::default()); @@ -605,12 +610,12 @@ fn test_propose_with_threshold_met() { let bob = Address::new_id(102); let chuck = Address::new_id(103); let fake_params = RawBytes::from([99u8; 3].to_vec()); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let no_unlock_duration = 0; let start_epoch = 0; let signers = vec![anne, bob]; - rt.set_balance(TokenAmount::from(10u8)); + rt.set_balance(TokenAmount::from_atto(10u8)); rt.set_received(TokenAmount::zero()); h.construct_and_verify(&mut rt, num_approvals, no_unlock_duration, start_epoch, signers); @@ -639,12 +644,12 @@ fn test_propose_with_threshold_and_non_empty_return_value() { let bob = Address::new_id(102); let chuck = Address::new_id(103); let fake_params = RawBytes::from([99u8; 3].to_vec()); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let no_unlock_duration = 0; let start_epoch = 0; let signers = vec![anne, bob]; - rt.set_balance(TokenAmount::from(20u8)); + rt.set_balance(TokenAmount::from_atto(20u8)); rt.set_received(TokenAmount::zero()); h.construct_and_verify(&mut rt, num_approvals, no_unlock_duration, start_epoch, signers); @@ -652,14 +657,13 @@ fn test_propose_with_threshold_and_non_empty_return_value() { struct FakeReturn { addr1: Address, addr2: Address, - #[serde(with = "bigint_ser")] tokens: TokenAmount, } let propose_ret = FakeReturn { addr1: Address::new_id(1), addr2: Address::new_id(2), - tokens: TokenAmount::from(77u8), + tokens: TokenAmount::from_atto(77u8), }; let inner_ret_bytes = serialize(&propose_ret, "fake proposal return value").unwrap(); let fake_method = 42u64; @@ -695,7 +699,7 @@ fn test_fail_propose_with_threshold_met_and_insufficient_balance() { let bob = Address::new_id(102); let chuck = Address::new_id(103); let fake_params = RawBytes::from([99u8; 3].to_vec()); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let no_unlock_duration = 0; let start_epoch = 0; let signers = vec![anne, bob]; @@ -725,7 +729,7 @@ fn test_fail_propose_from_non_signer() { let bob = Address::new_id(102); let chuck = Address::new_id(103); let fake_params = RawBytes::from([99u8; 3].to_vec()); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let no_unlock_duration = 0; let start_epoch = 0; let signers = vec![anne, bob]; @@ -1305,7 +1309,7 @@ mod approval_tests { let fake_params = RawBytes::from(vec![1, 2, 3, 4]); let fake_method = 42; let fake_ret = RawBytes::from(vec![4, 3, 2, 1]); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, anne); let proposal_hash = h.propose_ok(&mut rt, chuck, send_value.clone(), fake_method, fake_params.clone()); @@ -1337,7 +1341,7 @@ mod approval_tests { let chuck = Address::new_id(103); let signers = vec![anne, bob]; let mut rt = construct_runtime(msig); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let h = util::ActorHarness::new(); rt.set_balance(send_value.clone()); rt.set_received(TokenAmount::zero()); @@ -1366,7 +1370,7 @@ mod approval_tests { let chuck = Address::new_id(103); let signers = vec![anne, bob]; let mut rt = construct_runtime(msig); - let send_value = TokenAmount::from(20u8); + let send_value = TokenAmount::from_atto(20u8); let unlock_duration = 20; let start_epoch = 10; let h = util::ActorHarness::new(); @@ -1415,9 +1419,9 @@ mod approval_tests { let chuck = Address::new_id(103); let signers = vec![anne, bob]; let mut rt = construct_runtime(msig); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let h = util::ActorHarness::new(); - rt.set_balance(send_value.clone() - 1); + rt.set_balance(send_value.clone() - TokenAmount::from_atto(1)); rt.set_received(TokenAmount::zero()); h.construct_and_verify(&mut rt, 2, 0, 0, signers); @@ -1452,7 +1456,7 @@ mod approval_tests { let chuck = Address::new_id(103); let signers = vec![anne, bob]; let mut rt = construct_runtime(msig); - let send_value = TokenAmount::from(20u8); + let send_value = TokenAmount::from_atto(20u8); let unlock_duration = 20; let start_epoch = 10; let h = util::ActorHarness::new(); @@ -1492,7 +1496,7 @@ mod approval_tests { let chuck = Address::new_id(103); let signers = vec![anne, bob]; let mut rt = construct_runtime(msig); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let h = util::ActorHarness::new(); rt.set_balance(send_value.clone()); rt.set_received(TokenAmount::zero()); @@ -1526,7 +1530,7 @@ mod approval_tests { let chuck = Address::new_id(103); let signers = vec![anne, bob]; let mut rt = construct_runtime(msig); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let h = util::ActorHarness::new(); rt.set_balance(send_value.clone()); rt.set_received(TokenAmount::zero()); @@ -1562,7 +1566,7 @@ mod approval_tests { let chuck = Address::new_id(103); let signers = vec![anne, bob]; let mut rt = construct_runtime(msig); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let h = util::ActorHarness::new(); rt.set_balance(send_value.clone()); rt.set_received(TokenAmount::zero()); @@ -1601,7 +1605,7 @@ mod approval_tests { let bob = Address::new_id(102); let signers = vec![anne, bob]; let mut rt = construct_runtime(msig); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let h = util::ActorHarness::new(); rt.set_balance(send_value); rt.set_received(TokenAmount::zero()); @@ -1624,7 +1628,7 @@ mod approval_tests { let chuck = Address::new_id(103); let signers = vec![anne, bob]; let mut rt = construct_runtime(msig); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let h = util::ActorHarness::new(); rt.set_balance(send_value.clone()); rt.set_received(TokenAmount::zero()); @@ -1664,7 +1668,7 @@ mod approval_tests { let chuck = Address::new_id(103); let signers = vec![anne, bob]; let mut rt = construct_runtime(msig); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let h = util::ActorHarness::new(); rt.set_balance(send_value.clone()); rt.set_received(TokenAmount::zero()); @@ -1704,7 +1708,7 @@ mod approval_tests { let chuck = Address::new_id(103); let signers = vec![anne, bob, chuck]; let mut rt = construct_runtime(msig); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let h = util::ActorHarness::new(); rt.set_balance(send_value.clone()); rt.set_received(TokenAmount::zero()); @@ -1749,7 +1753,7 @@ mod approval_tests { let chuck = Address::new_id(103); let signers = vec![anne, bob]; let mut rt = construct_runtime(msig); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let h = util::ActorHarness::new(); rt.set_balance(send_value.clone()); rt.set_received(TokenAmount::zero()); @@ -1808,7 +1812,7 @@ mod cancel_tests { let fake_params = RawBytes::from(vec![1, 2, 3, 4]); let fake_method = 42; - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); // anne proposes tx rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, anne); let proposal_hash = h.propose_ok(&mut rt, chuck, send_value, fake_method, fake_params); @@ -1828,7 +1832,7 @@ mod cancel_tests { let anne = Address::new_id(101); let bob = Address::new_id(102); let chuck = Address::new_id(103); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let mut rt = construct_runtime(msig); let h = util::ActorHarness::new(); @@ -1856,7 +1860,7 @@ mod cancel_tests { let anne = Address::new_id(101); let bob = Address::new_id(102); let chuck = Address::new_id(103); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let mut rt = construct_runtime(msig); let h = util::ActorHarness::new(); @@ -1898,7 +1902,7 @@ mod cancel_tests { let anne = Address::new_id(101); let bob = Address::new_id(102); let chuck = Address::new_id(103); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let mut rt = construct_runtime(msig); let h = util::ActorHarness::new(); @@ -1939,7 +1943,7 @@ mod cancel_tests { let anne = Address::new_id(101); let bob = Address::new_id(102); let chuck = Address::new_id(103); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let mut rt = construct_runtime(msig); let h = util::ActorHarness::new(); @@ -1981,7 +1985,7 @@ mod cancel_tests { let anne = Address::new_id(101); let bob = Address::new_id(102); let chuck = Address::new_id(103); - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); let num_approvers = 3; let mut rt = construct_runtime(msig); @@ -2120,7 +2124,7 @@ mod change_threshold_tests { // anne proposes tx id 0 let fake_method = 42; - let send_value = TokenAmount::from(10u8); + let send_value = TokenAmount::from_atto(10u8); rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, anne); let proposal_hash = h.propose_ok(&mut rt, chuck, send_value.clone(), fake_method, RawBytes::default()); @@ -2166,13 +2170,13 @@ mod lock_balance_tests { // some time later, initialize vesting rt.set_epoch(200); let vest_start = 0; - let lock_amount = TokenAmount::from(100_000u32); + let lock_amount = TokenAmount::from_atto(100_000u32); let vest_duration = 1000; rt.set_caller(*MULTISIG_ACTOR_CODE_ID, msig); h.lock_balance(&mut rt, vest_start, vest_duration, lock_amount.clone()).unwrap(); rt.set_epoch(300); - let vested = TokenAmount::from(30_000); + let vested = TokenAmount::from_atto(30_000); rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, anne); // Fail to spend balance the multisig doesn't have @@ -2189,7 +2193,7 @@ mod lock_balance_tests { h.propose( &mut rt, bob, - vested.clone() + TokenAmount::from(1), + vested.clone() + TokenAmount::from_atto(1), METHOD_SEND, RawBytes::default(), ), @@ -2212,13 +2216,13 @@ mod lock_balance_tests { rt.set_balance(lock_amount - vested); expect_abort( ExitCode::USR_INSUFFICIENT_FUNDS, - h.propose(&mut rt, bob, TokenAmount::from(1), METHOD_SEND, RawBytes::default()), + h.propose(&mut rt, bob, TokenAmount::from_atto(1), METHOD_SEND, RawBytes::default()), ); rt.reset(); // later can spend the rest rt.set_epoch(vest_start + vest_duration); - let rested = TokenAmount::from(70_000u32); + let rested = TokenAmount::from_atto(70_000u32); rt.expect_send( bob, METHOD_SEND, @@ -2246,7 +2250,7 @@ mod lock_balance_tests { // some time later initialize vesting rt.set_epoch(200); let vest_start = 1000; - let lock_amount = TokenAmount::from(100_000); + let lock_amount = TokenAmount::from_atto(100_000); let vest_duration = 1000; rt.set_caller(*MULTISIG_ACTOR_CODE_ID, msig); h.lock_balance(&mut rt, vest_start, vest_duration, lock_amount.clone()).unwrap(); @@ -2254,28 +2258,28 @@ mod lock_balance_tests { // oversupply the wallet allow spending the oversupply rt.set_epoch(300); rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, anne); - rt.set_balance(lock_amount.clone() + TokenAmount::from(1)); + rt.set_balance(lock_amount.clone() + TokenAmount::from_atto(1)); rt.expect_send( bob, METHOD_SEND, RawBytes::default(), - TokenAmount::from(1), + TokenAmount::from_atto(1), RawBytes::default(), ExitCode::OK, ); - h.propose_ok(&mut rt, bob, TokenAmount::from(1), METHOD_SEND, RawBytes::default()); + h.propose_ok(&mut rt, bob, TokenAmount::from_atto(1), METHOD_SEND, RawBytes::default()); // fail to spend locked funds before vesting starts rt.set_balance(lock_amount.clone()); expect_abort( ExitCode::USR_INSUFFICIENT_FUNDS, - h.propose(&mut rt, bob, TokenAmount::from(1), METHOD_SEND, RawBytes::default()), + h.propose(&mut rt, bob, TokenAmount::from_atto(1), METHOD_SEND, RawBytes::default()), ); rt.reset(); // can spend partially vested amount rt.set_epoch(vest_start + 200); - let expect_vested = TokenAmount::from(20_000); + let expect_vested = TokenAmount::from_atto(20_000); rt.expect_send( bob, METHOD_SEND, @@ -2290,12 +2294,12 @@ mod lock_balance_tests { rt.set_balance(lock_amount - expect_vested); expect_abort( ExitCode::USR_INSUFFICIENT_FUNDS, - h.propose(&mut rt, bob, TokenAmount::from(1), METHOD_SEND, RawBytes::default()), + h.propose(&mut rt, bob, TokenAmount::from_atto(1), METHOD_SEND, RawBytes::default()), ); // later, can spend the rest rt.set_epoch(vest_start + vest_duration); - let rested = TokenAmount::from(80_000); + let rested = TokenAmount::from_atto(80_000); rt.expect_send( bob, METHOD_SEND, @@ -2322,7 +2326,7 @@ mod lock_balance_tests { // initialize vesting from zero let vest_start = 0; - let lock_amount = TokenAmount::from(100_000); + let lock_amount = TokenAmount::from_atto(100_000); let vest_duration = 1000; rt.set_caller(*MULTISIG_ACTOR_CODE_ID, msig); h.lock_balance(&mut rt, vest_start, vest_duration, lock_amount.clone()).unwrap(); @@ -2342,7 +2346,12 @@ mod lock_balance_tests { // can't change locked amount expect_abort( ExitCode::USR_FORBIDDEN, - h.lock_balance(&mut rt, vest_start, vest_duration, lock_amount - TokenAmount::from(1)), + h.lock_balance( + &mut rt, + vest_start, + vest_duration, + lock_amount - TokenAmount::from_atto(1), + ), ); rt.reset(); check_state(&rt); @@ -2381,7 +2390,7 @@ mod lock_balance_tests { h.construct_and_verify(&mut rt, 1, 0, 0, vec![anne]); let vest_start = 0_i64; - let lock_amount = TokenAmount::from(100_000u32); + let lock_amount = TokenAmount::from_atto(100_000u32); let vest_duration = 1000_i64; // Disallow negative duration but allow negative start epoch @@ -2394,7 +2403,7 @@ mod lock_balance_tests { // Disallow negative amount expect_abort( ExitCode::USR_ILLEGAL_ARGUMENT, - h.lock_balance(&mut rt, vest_start, vest_duration, TokenAmount::from(-1i32)), + h.lock_balance(&mut rt, vest_start, vest_duration, TokenAmount::from_atto(-1i32)), ); check_state(&rt); } diff --git a/actors/paych/Cargo.toml b/actors/paych/Cargo.toml index cb651062a2..641d1a916c 100644 --- a/actors/paych/Cargo.toml +++ b/actors/paych/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "9.0.0-alpha.1", path = "../../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } num-traits = "0.2.14" num-derive = "0.3.3" serde = { version = "1.0.136", features = ["derive"] } diff --git a/actors/paych/src/lib.rs b/actors/paych/src/lib.rs index 7ccde472ff..cd16267fd2 100644 --- a/actors/paych/src/lib.rs +++ b/actors/paych/src/lib.rs @@ -9,12 +9,12 @@ use fil_actors_runtime::{ use fvm_ipld_blockstore::Blockstore; use fvm_ipld_encoding::RawBytes; use fvm_shared::address::Address; -use fvm_shared::bigint::{BigInt, Sign}; + use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; use fvm_shared::{MethodNum, METHOD_CONSTRUCTOR, METHOD_SEND}; use num_derive::FromPrimitive; -use num_traits::FromPrimitive; +use num_traits::{FromPrimitive, Zero}; pub use self::state::{LaneState, Merge, State}; pub use self::types::*; @@ -163,7 +163,7 @@ impl Actor { return Err(actor_error!(illegal_argument; "this voucher has expired")); } - if sv.amount.sign() == Sign::Minus { + if sv.amount.is_negative() { return Err(actor_error!(illegal_argument; "voucher amount must be non-negative, was {}", sv.amount)); } @@ -176,7 +176,7 @@ impl Actor { } if let Some(extra) = &sv.extra { - rt.send(&extra.actor, extra.method, extra.data.clone(), TokenAmount::from(0u8)) + rt.send(&extra.actor, extra.method, extra.data.clone(), TokenAmount::zero()) .map_err(|e| e.wrap("spend voucher verification failed"))?; } @@ -203,7 +203,7 @@ impl Actor { // The next section actually calculates the payment amounts to update // the payment channel state // 1. (optional) sum already redeemed value of all merging lanes - let mut redeemed_from_others = BigInt::default(); + let mut redeemed_from_others = TokenAmount::zero(); for merge in sv.merges { if merge.lane == sv.lane { return Err(actor_error!(illegal_argument; @@ -242,7 +242,7 @@ impl Actor { // 4. check operation validity let new_send_balance = balance_delta + &st.to_send; - if new_send_balance < TokenAmount::from(0) { + if new_send_balance < TokenAmount::zero() { return Err(actor_error!(illegal_argument; "voucher would leave channel balance negative")); } diff --git a/actors/paych/src/state.rs b/actors/paych/src/state.rs index aeeb10ddae..c67a02d266 100644 --- a/actors/paych/src/state.rs +++ b/actors/paych/src/state.rs @@ -5,7 +5,7 @@ use cid::Cid; use fvm_ipld_encoding::tuple::*; use fvm_ipld_encoding::Cbor; use fvm_shared::address::Address; -use fvm_shared::bigint::{bigint_ser, BigInt}; + use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; @@ -19,7 +19,6 @@ pub struct State { /// Recipient of payouts from channel. pub to: Address, /// Amount successfully redeemed through the payment channel, paid out on `Collect`. - #[serde(with = "bigint_ser")] pub to_send: TokenAmount, /// Height at which the channel can be collected. pub settling_at: ChainEpoch, @@ -46,8 +45,7 @@ impl State { /// as well as the amount it has already redeemed. #[derive(Default, Clone, PartialEq, Eq, Debug, Serialize_tuple, Deserialize_tuple)] pub struct LaneState { - #[serde(with = "bigint_ser")] - pub redeemed: BigInt, + pub redeemed: TokenAmount, pub nonce: u64, } diff --git a/actors/paych/src/testing.rs b/actors/paych/src/testing.rs index b3b7600845..79e3b965da 100644 --- a/actors/paych/src/testing.rs +++ b/actors/paych/src/testing.rs @@ -3,7 +3,7 @@ use fil_actors_runtime::MessageAccumulator; use fvm_ipld_amt::Amt; use fvm_ipld_blockstore::Blockstore; use fvm_shared::{address::Protocol, econ::TokenAmount}; -use num_traits::{Signed, Zero}; +use num_traits::Zero; use crate::{LaneState, State}; diff --git a/actors/paych/src/types.rs b/actors/paych/src/types.rs index d5c79ecb7f..f09d9e47e1 100644 --- a/actors/paych/src/types.rs +++ b/actors/paych/src/types.rs @@ -5,9 +5,9 @@ use fil_actors_runtime::network::EPOCHS_IN_HOUR; use fvm_ipld_encoding::tuple::*; use fvm_ipld_encoding::{serde_bytes, to_vec, Error, RawBytes}; use fvm_shared::address::Address; -use fvm_shared::bigint::{bigint_ser, BigInt}; use fvm_shared::clock::ChainEpoch; use fvm_shared::crypto::signature::Signature; +use fvm_shared::econ::TokenAmount; use fvm_shared::MethodNum; use super::Merge; @@ -49,8 +49,7 @@ pub struct SignedVoucher { /// Set by `from` to prevent redemption of stale vouchers on a lane pub nonce: u64, /// Amount voucher can be redeemed for - #[serde(with = "bigint_ser")] - pub amount: BigInt, + pub amount: TokenAmount, /// (optional) Can extend channel min_settle_height if needed pub min_settle_height: ChainEpoch, @@ -74,8 +73,7 @@ impl SignedVoucher { pub extra: &'a Option, pub lane: u64, pub nonce: u64, - #[serde(with = "bigint_ser")] - pub amount: &'a BigInt, + pub amount: &'a TokenAmount, pub min_settle_height: ChainEpoch, pub merges: &'a [Merge], pub signature: (), diff --git a/actors/paych/tests/paych_actor_test.rs b/actors/paych/tests/paych_actor_test.rs index ba7694736f..769c6ec8b6 100644 --- a/actors/paych/tests/paych_actor_test.rs +++ b/actors/paych/tests/paych_actor_test.rs @@ -18,12 +18,12 @@ use fil_actors_runtime::INIT_ACTOR_ADDR; use fvm_ipld_amt::Amt; use fvm_ipld_encoding::RawBytes; use fvm_shared::address::Address; -use fvm_shared::bigint::BigInt; use fvm_shared::clock::ChainEpoch; use fvm_shared::crypto::signature::Signature; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; use fvm_shared::METHOD_CONSTRUCTOR; +use num_traits::Zero; const PAYCH_ID: u64 = 100; const PAYER_ID: u64 = 102; @@ -33,7 +33,7 @@ struct LaneParams { epoch_num: ChainEpoch, from: Address, to: Address, - amt: BigInt, + amt: TokenAmount, lane: u64, nonce: u64, } @@ -69,6 +69,7 @@ fn check_state(rt: &MockRuntime) { mod paych_constructor { use fvm_shared::METHOD_CONSTRUCTOR; use fvm_shared::METHOD_SEND; + use num_traits::Zero; use super::*; @@ -218,7 +219,7 @@ mod paych_constructor { non_id_addr, METHOD_SEND, Default::default(), - TokenAmount::from(0u8), + TokenAmount::zero(), Default::default(), ExitCode::OK, ); @@ -255,7 +256,7 @@ mod paych_constructor { non_id_addr, METHOD_SEND, Default::default(), - TokenAmount::from(0u8), + TokenAmount::zero(), Default::default(), ExitCode::OK, ); @@ -324,7 +325,7 @@ mod create_lane_tests { let paych_addr = Address::new_id(PAYCH_ADDR); let payer_addr = Address::new_id(PAYER_ADDR); let payee_addr = Address::new_id(PAYEE_ADDR); - let paych_balance = TokenAmount::from(PAYCH_BALANCE); + let paych_balance = TokenAmount::from_atto(PAYCH_BALANCE); let paych_non_id = Address::new_bls(&[201; fvm_shared::address::BLS_PUB_LEN]).unwrap(); let sig = Option::Some(Signature::new_bls("doesn't matter".as_bytes().to_vec())); @@ -428,7 +429,7 @@ mod create_lane_tests { secret_pre_image: test_case.secret_preimage.clone(), lane: test_case.lane, nonce: test_case.nonce, - amount: BigInt::from(test_case.amt), + amount: TokenAmount::from_atto(test_case.amt), signature: test_case.sig.clone(), channel_addr: test_case.payment_channel, extra: Default::default(), @@ -492,7 +493,7 @@ mod update_channel_state_redeem { rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, payee_addr); rt.expect_validate_caller_addr(vec![state.from, state.to]); - sv.amount = BigInt::from(9); + sv.amount = TokenAmount::from_atto(9); let payer_addr = Address::new_id(PAYER_ID); @@ -510,11 +511,11 @@ mod update_channel_state_redeem { ); rt.verify(); - let exp_ls = LaneState { redeemed: BigInt::from(9), nonce: 2 }; + let exp_ls = LaneState { redeemed: TokenAmount::from_atto(9), nonce: 2 }; let exp_state = PState { from: state.from, to: state.to, - to_send: TokenAmount::from(9), + to_send: TokenAmount::from_atto(9), settling_at: state.settling_at, min_settle_height: state.min_settle_height, lane_states: construct_lane_state_amt(&rt, vec![exp_ls]), @@ -532,7 +533,7 @@ mod update_channel_state_redeem { rt.expect_validate_caller_addr(vec![state.from, state.to]); let initial_amount = state.to_send; - sv.amount = BigInt::from(9); + sv.amount = TokenAmount::from_atto(9); sv.lane = 1; let ls_to_update: LaneState = get_lane_state(&rt, &state.lane_states, sv.lane); @@ -574,7 +575,7 @@ mod update_channel_state_redeem { rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, payee_addr); rt.expect_validate_caller_addr(vec![state.from, state.to]); - sv.amount = BigInt::from(9); + sv.amount = TokenAmount::from_atto(9); sv.nonce = 1; let payer_addr = Address::new_id(PAYER_ID); @@ -711,7 +712,7 @@ mod merge_tests { let num_lanes = 2; let (mut rt, mut sv, state) = construct_runtime(num_lanes); - rt.set_balance(TokenAmount::from(tc.balance as u64)); + rt.set_balance(TokenAmount::from_atto(tc.balance)); sv.lane = 0; sv.nonce = tc.voucher; @@ -741,7 +742,7 @@ mod merge_tests { sv.lane = MAX_LANE + 1; sv.nonce += 1; - sv.amount = BigInt::from(100); + sv.amount = TokenAmount::from_atto(100); failure_end(&mut rt, sv, ExitCode::USR_ILLEGAL_ARGUMENT); } } @@ -775,7 +776,7 @@ mod update_channel_state_extra { other_addr, Method::UpdateChannelState as u64, fake_params, - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::default(), exit_code, ); @@ -1124,8 +1125,8 @@ fn require_create_channel_with_lanes(num_lanes: u64) -> (MockRuntime, SignedVouc let paych_addr = Address::new_id(100); let payer_addr = Address::new_id(PAYER_ID); let payee_addr = Address::new_id(PAYEE_ID); - let balance = TokenAmount::from(100_000); - let received = TokenAmount::from(0); + let balance = TokenAmount::from_atto(100_000); + let received = TokenAmount::zero(); let curr_epoch = 2; let mut actor_code_cids = HashMap::default(); @@ -1151,7 +1152,7 @@ fn require_create_channel_with_lanes(num_lanes: u64) -> (MockRuntime, SignedVouc epoch_num: curr_epoch, from: payer_addr, to: payee_addr, - amt: (BigInt::from(i) + 1), + amt: (TokenAmount::from_atto(i + 1)), lane: i as u64, nonce: i + 1, }; diff --git a/actors/power/Cargo.toml b/actors/power/Cargo.toml index eaa6c47c8b..9e5df2a10d 100644 --- a/actors/power/Cargo.toml +++ b/actors/power/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "9.0.0-alpha.1", path = "../../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } fvm_ipld_hamt = "0.5.1" num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/actors/power/src/lib.rs b/actors/power/src/lib.rs index 91a9f41275..b421e67b35 100644 --- a/actors/power/src/lib.rs +++ b/actors/power/src/lib.rs @@ -15,7 +15,7 @@ use fil_actors_runtime::{ use fvm_ipld_blockstore::Blockstore; use fvm_ipld_encoding::RawBytes; use fvm_shared::address::Address; -use fvm_shared::bigint::bigint_ser::{BigIntDe, BigIntSer}; +use fvm_shared::bigint::bigint_ser::BigIntSer; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; use fvm_shared::reward::ThisEpochRewardReturn; @@ -23,7 +23,7 @@ use fvm_shared::sector::SealVerifyInfo; use fvm_shared::{MethodNum, HAMT_BIT_WIDTH, METHOD_CONSTRUCTOR}; use log::{debug, error}; use num_derive::FromPrimitive; -use num_traits::{FromPrimitive, Signed, Zero}; +use num_traits::{FromPrimitive, Zero}; pub use self::policy::*; pub use self::state::*; @@ -282,7 +282,7 @@ impl Actor { &REWARD_ACTOR_ADDR, ext::reward::UPDATE_NETWORK_KPI, this_epoch_raw_byte_power?, - TokenAmount::from(0_u32), + TokenAmount::zero(), ) .map_err(|e| e.wrap("failed to update network KPI with reward actor"))?; @@ -686,7 +686,7 @@ impl ActorCode for Actor { Ok(RawBytes::default()) } Some(Method::UpdatePledgeTotal) => { - let BigIntDe(param) = cbor::deserialize_params(params)?; + let param: TokenAmount = cbor::deserialize_params(params)?; Self::update_pledge_total(rt, param)?; Ok(RawBytes::default()) } diff --git a/actors/power/src/state.rs b/actors/power/src/state.rs index 1203dfacc1..3f5e8503d5 100644 --- a/actors/power/src/state.rs +++ b/actors/power/src/state.rs @@ -46,14 +46,12 @@ pub struct State { pub total_quality_adj_power: StoragePower, #[serde(with = "bigint_ser")] pub total_qa_bytes_committed: StoragePower, - #[serde(with = "bigint_ser")] pub total_pledge_collateral: TokenAmount, #[serde(with = "bigint_ser")] pub this_epoch_raw_byte_power: StoragePower, #[serde(with = "bigint_ser")] pub this_epoch_quality_adj_power: StoragePower, - #[serde(with = "bigint_ser")] pub this_epoch_pledge_collateral: TokenAmount, pub this_epoch_qa_power_smoothed: FilterEstimate, diff --git a/actors/power/src/types.rs b/actors/power/src/types.rs index 99c0e88901..521be8f833 100644 --- a/actors/power/src/types.rs +++ b/actors/power/src/types.rs @@ -62,7 +62,6 @@ pub struct CurrentTotalPowerReturn { pub raw_byte_power: StoragePower, #[serde(with = "bigint_ser")] pub quality_adj_power: StoragePower, - #[serde(with = "bigint_ser")] pub pledge_collateral: TokenAmount, pub quality_adj_power_smoothed: FilterEstimate, } diff --git a/actors/power/tests/harness/mod.rs b/actors/power/tests/harness/mod.rs index 51bd66486c..24c1b70241 100644 --- a/actors/power/tests/harness/mod.rs +++ b/actors/power/tests/harness/mod.rs @@ -22,6 +22,7 @@ use fvm_ipld_hamt::Error; use fvm_shared::address::Address; use fvm_shared::bigint::bigint_ser::BigIntDe; use fvm_shared::bigint::bigint_ser::BigIntSer; +use fvm_shared::bigint::BigInt; use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; @@ -71,13 +72,13 @@ pub fn new_runtime() -> MockRuntime { } pub fn new_harness() -> Harness { - let rwd = TokenAmount::from(10) * TokenAmount::from(10_i128.pow(18)); + let rwd = TokenAmount::from_whole(10); Harness { miner_seq: 0, seal_proof: RegisteredSealProof::StackedDRG32GiBV1P1, window_post_proof: RegisteredPoStProof::StackedDRGWindow32GiBV1, this_epoch_baseline_power: StoragePower::from(1i64 << 50), - this_epoch_reward_smoothed: FilterEstimate::new(rwd, TokenAmount::zero()), + this_epoch_reward_smoothed: FilterEstimate::new(rwd.atto().clone(), BigInt::zero()), } } @@ -196,7 +197,7 @@ impl Harness { peer, vec![], self.window_post_proof, - &TokenAmount::from(0), + &TokenAmount::zero(), ) } @@ -289,7 +290,7 @@ impl Harness { rt.expect_validate_caller_type(vec![*MINER_ACTOR_CODE_ID]); rt.call::( Method::UpdatePledgeTotal as MethodNum, - &RawBytes::serialize(BigIntDe(delta.clone())).unwrap(), + &RawBytes::serialize(delta).unwrap(), ) .unwrap(); rt.verify(); @@ -380,7 +381,7 @@ impl Harness { *REWARD_ACTOR_ADDR, ThisEpochReward as u64, RawBytes::default(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::serialize(current_reward).unwrap(), ExitCode::OK, ); diff --git a/actors/power/tests/power_actor_tests.rs b/actors/power/tests/power_actor_tests.rs index f6ecb037d7..9b754a0641 100644 --- a/actors/power/tests/power_actor_tests.rs +++ b/actors/power/tests/power_actor_tests.rs @@ -48,7 +48,7 @@ fn create_miner() { peer, multiaddrs, RegisteredPoStProof::StackedDRGWindow32GiBV1, - &TokenAmount::from(10), + &TokenAmount::from_atto(10), ) .unwrap(); @@ -119,8 +119,8 @@ fn create_miner_given_send_to_init_actor_fails_should_fail() { // owner send CreateMiner to Actor rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, *OWNER); - rt.value_received = TokenAmount::from(10); - rt.set_balance(TokenAmount::from(10)); + rt.value_received = TokenAmount::from_atto(10); + rt.set_balance(TokenAmount::from_atto(10)); rt.expect_validate_caller_type(CALLER_TYPES_SIGNABLE.to_vec()); let message_params = ExecParams { @@ -140,7 +140,7 @@ fn create_miner_given_send_to_init_actor_fails_should_fail() { *INIT_ACTOR_ADDR, EXEC_METHOD, RawBytes::serialize(message_params).unwrap(), - TokenAmount::from(10), + TokenAmount::from_atto(10), RawBytes::default(), ExitCode::SYS_INSUFFICIENT_FUNDS, ); @@ -234,9 +234,9 @@ fn power_and_pledge_accounted_below_threshold() { // Add power and pledge for miner2 h.update_claimed_power(&mut rt, MINER2, small_power_unit, small_power_unit); - h.update_pledge_total(&mut rt, MINER1, &TokenAmount::from(1_000_000)); + h.update_pledge_total(&mut rt, MINER1, &TokenAmount::from_atto(1_000_000)); h.expect_total_power_eager(&mut rt, small_power_unit_x2, small_power_unit_x3); - h.expect_total_pledge_eager(&mut rt, &TokenAmount::from(1_000_000)); + h.expect_total_pledge_eager(&mut rt, &TokenAmount::from_atto(1_000_000)); rt.verify(); @@ -251,9 +251,9 @@ fn power_and_pledge_accounted_below_threshold() { // Subtract power and some pledge for miner2 h.update_claimed_power(&mut rt, MINER2, &small_power_unit.neg(), &small_power_unit.neg()); - h.update_pledge_total(&mut rt, MINER2, &TokenAmount::from(100_000).neg()); + h.update_pledge_total(&mut rt, MINER2, &TokenAmount::from_atto(100_000).neg()); h.expect_total_power_eager(&mut rt, small_power_unit, small_power_unit_x2); - h.expect_total_pledge_eager(&mut rt, &TokenAmount::from(900_000)); + h.expect_total_pledge_eager(&mut rt, &TokenAmount::from_atto(900_000)); let claim2 = h.get_claim(&rt, &MINER2).unwrap(); assert!(claim2.raw_byte_power.is_zero()); @@ -604,7 +604,7 @@ fn given_no_miner_claim_update_pledge_total_should_abort() { "unknown miner", rt.call::( Method::UpdatePledgeTotal as u64, - &RawBytes::serialize(BigIntSer(&TokenAmount::from(1_000_000))).unwrap(), + &RawBytes::serialize(&TokenAmount::from_atto(1_000_000)).unwrap(), ), ); @@ -679,7 +679,7 @@ mod cron_tests { let expected_power: BigInt = power_unit * 4u8; - let delta = TokenAmount::from(1u8); + let delta = TokenAmount::from_atto(1u8); h.update_pledge_total(&mut rt, miner1, &delta); h.on_epoch_tick_end(&mut rt, 0, &expected_power, Vec::new(), Vec::new()); @@ -751,7 +751,7 @@ mod cron_tests { *REWARD_ACTOR_ADDR, UPDATE_NETWORK_KPI, RawBytes::serialize(BigIntSer(&expected_raw_byte_power)).unwrap(), - BigInt::zero(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -779,7 +779,7 @@ mod cron_tests { *REWARD_ACTOR_ADDR, UPDATE_NETWORK_KPI, RawBytes::serialize(BigIntSer(&expected_raw_byte_power)).unwrap(), - BigInt::zero(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -818,7 +818,7 @@ mod cron_tests { *REWARD_ACTOR_ADDR, UPDATE_NETWORK_KPI, RawBytes::serialize(BigIntSer(&expected_raw_byte_power)).unwrap(), - BigInt::zero(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -895,7 +895,7 @@ mod cron_tests { *REWARD_ACTOR_ADDR, UPDATE_NETWORK_KPI, RawBytes::serialize(BigIntSer(&BigInt::zero())).unwrap(), - BigInt::zero(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -972,7 +972,7 @@ mod cron_tests { *REWARD_ACTOR_ADDR, UPDATE_NETWORK_KPI, RawBytes::serialize(BigIntSer(&BigInt::zero())).unwrap(), - BigInt::zero(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -999,7 +999,7 @@ mod cron_tests { *REWARD_ACTOR_ADDR, UPDATE_NETWORK_KPI, RawBytes::serialize(BigIntSer(&BigInt::zero())).unwrap(), - BigInt::zero(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -1233,7 +1233,7 @@ mod cron_batch_proof_verifies_tests { cs.miner, CONFIRM_SECTOR_PROOFS_VALID_METHOD, RawBytes::serialize(params).unwrap(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -1245,7 +1245,7 @@ mod cron_batch_proof_verifies_tests { *REWARD_ACTOR_ADDR, UPDATE_NETWORK_KPI, RawBytes::serialize(BigIntSer(&BigInt::zero())).unwrap(), - TokenAmount::from(0u8), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); @@ -1281,7 +1281,7 @@ mod cron_batch_proof_verifies_tests { *REWARD_ACTOR_ADDR, UPDATE_NETWORK_KPI, RawBytes::serialize(BigIntSer(&BigInt::zero())).unwrap(), - BigInt::zero(), + TokenAmount::zero(), RawBytes::default(), ExitCode::OK, ); diff --git a/actors/reward/Cargo.toml b/actors/reward/Cargo.toml index d4d71faa0c..8e1c8c9826 100644 --- a/actors/reward/Cargo.toml +++ b/actors/reward/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "9.0.0-alpha.1", path = "../../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } num-traits = "0.2.14" num-derive = "0.3.3" log = "0.4.14" diff --git a/actors/reward/src/ext.rs b/actors/reward/src/ext.rs index f3bb1073a0..c9cad048f3 100644 --- a/actors/reward/src/ext.rs +++ b/actors/reward/src/ext.rs @@ -1,5 +1,4 @@ use fvm_ipld_encoding::tuple::*; -use fvm_shared::bigint::bigint_ser; use fvm_shared::econ::TokenAmount; pub mod miner { @@ -9,9 +8,7 @@ pub mod miner { #[derive(Debug, Serialize_tuple, Deserialize_tuple)] pub struct ApplyRewardParams { - #[serde(with = "bigint_ser")] pub reward: TokenAmount, - #[serde(with = "bigint_ser")] pub penalty: TokenAmount, } } diff --git a/actors/reward/src/lib.rs b/actors/reward/src/lib.rs index 5852f87ebc..21db9bdf67 100644 --- a/actors/reward/src/lib.rs +++ b/actors/reward/src/lib.rs @@ -10,13 +10,12 @@ use fvm_ipld_blockstore::Blockstore; use fvm_ipld_encoding::RawBytes; use fvm_shared::address::Address; use fvm_shared::bigint::bigint_ser::BigIntDe; -use fvm_shared::bigint::{Integer, Sign}; use fvm_shared::econ::TokenAmount; use fvm_shared::sector::StoragePower; use fvm_shared::{MethodNum, METHOD_CONSTRUCTOR, METHOD_SEND}; use log::{error, warn}; use num_derive::FromPrimitive; -use num_traits::{FromPrimitive, Signed}; +use num_traits::FromPrimitive; pub use self::logic::*; pub use self::state::{Reward, State, VestingFunction}; @@ -92,10 +91,10 @@ impl Actor { { rt.validate_immediate_caller_is(std::iter::once(&*SYSTEM_ACTOR_ADDR))?; let prior_balance = rt.current_balance(); - if params.penalty.sign() == Sign::Minus { + if params.penalty.is_negative() { return Err(actor_error!(illegal_argument, "negative penalty {}", params.penalty)); } - if params.gas_reward.sign() == Sign::Minus { + if params.gas_reward.is_negative() { return Err(actor_error!( illegal_argument, "negative gas reward {}", @@ -121,8 +120,8 @@ impl Actor { let penalty: TokenAmount = ¶ms.penalty * PENALTY_MULTIPLIER; let total_reward = rt.transaction(|st: &mut State, rt| { - let mut block_reward: TokenAmount = (&st.this_epoch_reward * params.win_count) - .div_floor(&TokenAmount::from(EXPECTED_LEADERS_PER_EPOCH)); + let mut block_reward: TokenAmount = + (&st.this_epoch_reward * params.win_count).div_rem(EXPECTED_LEADERS_PER_EPOCH).0; let mut total_reward = ¶ms.gas_reward + &block_reward; let curr_balance = rt.current_balance(); if total_reward > curr_balance { diff --git a/actors/reward/src/logic.rs b/actors/reward/src/logic.rs index ad5b5d1cb2..9f8522bfb5 100644 --- a/actors/reward/src/logic.rs +++ b/actors/reward/src/logic.rs @@ -8,7 +8,6 @@ use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; use fvm_shared::math::PRECISION; use fvm_shared::sector::StoragePower; -use fvm_shared::FILECOIN_PRECISION; use lazy_static::lazy_static; use super::expneg::expneg; @@ -29,9 +28,9 @@ lazy_static! { ((BASELINE_INITIAL_VALUE.clone() << (2*PRECISION)) / &*BASELINE_EXPONENT) >> PRECISION; /// 330M for mainnet - pub(super) static ref SIMPLE_TOTAL: BigInt = BigInt::from(330_000_000) * FILECOIN_PRECISION; + pub(super) static ref SIMPLE_TOTAL: TokenAmount = TokenAmount::from_whole(330_000_000); /// 770M for mainnet - pub(super) static ref BASELINE_TOTAL: BigInt = BigInt::from(770_000_000) * FILECOIN_PRECISION; + pub(super) static ref BASELINE_TOTAL: TokenAmount = TokenAmount::from_whole(770_000_000); /// expLamSubOne = e^lambda - 1 /// for Q.128: int(expLamSubOne * 2^128) static ref EXP_LAM_SUB_ONE: BigInt = BigInt::from(37396273494747879394193016954629u128); @@ -76,19 +75,19 @@ pub(crate) fn compute_reward( epoch: ChainEpoch, prev_theta: BigInt, curr_theta: BigInt, - simple_total: &BigInt, - baseline_total: &BigInt, + simple_total: &TokenAmount, + baseline_total: &TokenAmount, ) -> TokenAmount { - let mut simple_reward = simple_total * &*EXP_LAM_SUB_ONE; + let mut simple_reward = simple_total.atto() * &*EXP_LAM_SUB_ONE; let epoch_lam = &*LAMBDA * epoch; simple_reward *= expneg(&epoch_lam); simple_reward >>= PRECISION; - let baseline_reward = compute_baseline_supply(curr_theta, baseline_total) - - compute_baseline_supply(prev_theta, baseline_total); + let baseline_reward = compute_baseline_supply(curr_theta, baseline_total.atto()) + - compute_baseline_supply(prev_theta, baseline_total.atto()); - (simple_reward + baseline_reward) >> PRECISION + TokenAmount::from_atto((simple_reward + baseline_reward) >> PRECISION) } /// Computes baseline supply based on theta in Q.128 format. diff --git a/actors/reward/src/state.rs b/actors/reward/src/state.rs index 2ed75ea479..de04c6acec 100644 --- a/actors/reward/src/state.rs +++ b/actors/reward/src/state.rs @@ -4,7 +4,7 @@ use fvm_ipld_encoding::repr::*; use fvm_ipld_encoding::tuple::*; use fvm_ipld_encoding::Cbor; -use fvm_shared::bigint::{bigint_ser, Integer}; +use fvm_shared::bigint::bigint_ser; use fvm_shared::clock::{ChainEpoch, EPOCH_UNDEFINED}; use fvm_shared::econ::TokenAmount; @@ -17,9 +17,9 @@ use super::logic::*; lazy_static! { /// 36.266260308195979333 FIL - pub static ref INITIAL_REWARD_POSITION_ESTIMATE: TokenAmount = TokenAmount::from(36266260308195979333u128); + pub static ref INITIAL_REWARD_POSITION_ESTIMATE: TokenAmount = TokenAmount::from_atto(36266260308195979333u128); /// -1.0982489*10^-7 FIL per epoch. Change of simple minted tokens between epochs 0 and 1. - pub static ref INITIAL_REWARD_VELOCITY_ESTIMATE: TokenAmount = TokenAmount::from(-109897758509i64); + pub static ref INITIAL_REWARD_VELOCITY_ESTIMATE: TokenAmount = TokenAmount::from_atto(-109897758509i64); } /// Reward actor state @@ -48,7 +48,6 @@ pub struct State { /// The reward to be paid in per WinCount to block producers. /// The actual reward total paid out depends on the number of winners in any round. /// This value is recomputed every non-null epoch and used in the next non-null epoch. - #[serde(with = "bigint_ser")] pub this_epoch_reward: TokenAmount, /// Smoothed `this_epoch_reward`. pub this_epoch_reward_smoothed: FilterEstimate, @@ -61,7 +60,6 @@ pub struct State { pub epoch: ChainEpoch, // TotalStoragePowerReward tracks the total FIL awarded to block miners - #[serde(with = "bigint_ser")] pub total_storage_power_reward: TokenAmount, // Simple and Baseline totals are constants used for computing rewards. @@ -69,9 +67,7 @@ pub struct State { // in a way that depended on the history leading immediately up to the // migration fixing the value. These values can be moved from state back // into a code constant in a subsequent upgrade. - #[serde(with = "bigint_ser")] pub simple_total: TokenAmount, - #[serde(with = "bigint_ser")] pub baseline_total: TokenAmount, } @@ -82,8 +78,8 @@ impl State { this_epoch_baseline_power: INIT_BASELINE_POWER.clone(), epoch: EPOCH_UNDEFINED, this_epoch_reward_smoothed: FilterEstimate::new( - INITIAL_REWARD_POSITION_ESTIMATE.clone(), - INITIAL_REWARD_VELOCITY_ESTIMATE.clone(), + INITIAL_REWARD_POSITION_ESTIMATE.atto().clone(), + INITIAL_REWARD_VELOCITY_ESTIMATE.atto().clone(), ), simple_total: SIMPLE_TOTAL.clone(), baseline_total: BASELINE_TOTAL.clone(), @@ -141,7 +137,7 @@ impl State { let filter_reward = AlphaBetaFilter::load(&self.this_epoch_reward_smoothed, &DEFAULT_ALPHA, &DEFAULT_BETA); self.this_epoch_reward_smoothed = - filter_reward.next_estimate(&self.this_epoch_reward, delta); + filter_reward.next_estimate(self.this_epoch_reward.atto(), delta); } pub fn into_total_storage_power_reward(self) -> TokenAmount { @@ -164,9 +160,7 @@ pub struct Reward { pub vesting_function: VestingFunction, pub start_epoch: ChainEpoch, pub end_epoch: ChainEpoch, - #[serde(with = "bigint_ser")] pub value: TokenAmount, - #[serde(with = "bigint_ser")] pub amount_withdrawn: TokenAmount, } @@ -180,8 +174,7 @@ impl Reward { if elapsed >= vest_duration { self.value.clone() } else { - (self.value.clone() * elapsed as u64) - .div_floor(&TokenAmount::from(vest_duration)) + (self.value.clone() * elapsed as u64).div_rem(vest_duration).0 } } } diff --git a/actors/reward/src/testing.rs b/actors/reward/src/testing.rs index d4d8f69ea6..cfddba4413 100644 --- a/actors/reward/src/testing.rs +++ b/actors/reward/src/testing.rs @@ -1,6 +1,5 @@ use crate::{baseline_power_from_prev, State}; use fil_actors_runtime::MessageAccumulator; -use fvm_shared::bigint::BigInt; use fvm_shared::{clock::ChainEpoch, econ::TokenAmount}; use num_traits::Signed; @@ -14,8 +13,7 @@ pub fn check_state_invariants( ) -> (StateSummary, MessageAccumulator) { let acc = MessageAccumulator::default(); - let fil = 10u64.pow(18); - let storage_mining_allocation_check = BigInt::from(1_100_000_000) * fil; + let storage_mining_allocation_check = TokenAmount::from_whole(1_100_000_000); // Can't assert equality because anyone can send funds to reward actor (and already have on mainnet) acc.require( diff --git a/actors/reward/src/types.rs b/actors/reward/src/types.rs index 42b733a777..c5db7e2e3e 100644 --- a/actors/reward/src/types.rs +++ b/actors/reward/src/types.rs @@ -3,15 +3,12 @@ use fvm_ipld_encoding::tuple::*; use fvm_shared::address::Address; -use fvm_shared::bigint::bigint_ser; use fvm_shared::econ::TokenAmount; #[derive(Clone, Debug, PartialEq, Eq, Serialize_tuple, Deserialize_tuple)] pub struct AwardBlockRewardParams { pub miner: Address, - #[serde(with = "bigint_ser")] pub penalty: TokenAmount, - #[serde(with = "bigint_ser")] pub gas_reward: TokenAmount, pub win_count: i64, } diff --git a/actors/reward/tests/reward_actor_test.rs b/actors/reward/tests/reward_actor_test.rs index b000c2855e..f8ed63937c 100644 --- a/actors/reward/tests/reward_actor_test.rs +++ b/actors/reward/tests/reward_actor_test.rs @@ -24,11 +24,13 @@ use num_traits::FromPrimitive; lazy_static! { static ref EPOCH_ZERO_REWARD: TokenAmount = - TokenAmount::from_i128(36_266_264_293_777_134_739).unwrap(); + TokenAmount::from_atto(36_266_264_293_777_134_739i128); static ref WINNER: Address = Address::new_id(1000); } mod construction_tests { + use num::Zero; + use super::*; #[test] @@ -53,7 +55,7 @@ mod construction_tests { let state: State = rt.get_state(); assert_eq!(ChainEpoch::from(0), state.epoch); assert_eq!(start_realized_power, state.cumsum_realized); - assert_ne!(TokenAmount::from(0), state.this_epoch_reward); + assert_ne!(TokenAmount::zero(), state.this_epoch_reward); } #[test] @@ -78,6 +80,7 @@ mod test_award_block_reward { use fvm_shared::error::ExitCode; use fvm_shared::sector::StoragePower; use fvm_shared::METHOD_SEND; + use num::Zero; use super::*; @@ -85,17 +88,17 @@ mod test_award_block_reward { fn rejects_gas_reward_exceeding_balance() { let mut rt = construct_and_verify(&StoragePower::default()); - rt.set_balance(TokenAmount::from(9)); + rt.set_balance(TokenAmount::from_atto(9)); rt.expect_validate_caller_addr(vec![*SYSTEM_ACTOR_ADDR]); assert_eq!( ExitCode::USR_ILLEGAL_STATE, award_block_reward( &mut rt, *WINNER, - TokenAmount::from(0), - TokenAmount::from(10), + TokenAmount::zero(), + TokenAmount::from_atto(10), 1, - TokenAmount::from(0) + TokenAmount::zero() ) .unwrap_err() .exit_code() @@ -105,7 +108,7 @@ mod test_award_block_reward { #[test] fn rejects_negative_penalty_or_reward() { let mut rt = construct_and_verify(&StoragePower::default()); - rt.set_balance(TokenAmount::from(10_i128.pow(18))); + rt.set_balance(TokenAmount::from_whole(1)); rt.expect_validate_caller_addr(vec![*SYSTEM_ACTOR_ADDR]); let reward_penalty_pairs = [(-1, 0), (0, -1)]; @@ -116,10 +119,10 @@ mod test_award_block_reward { award_block_reward( &mut rt, *WINNER, - TokenAmount::from(*penalty), - TokenAmount::from(*reward), + TokenAmount::from_atto(*penalty), + TokenAmount::from_atto(*reward), 1, - TokenAmount::from(0) + TokenAmount::zero() ) .unwrap_err() .exit_code() @@ -131,16 +134,16 @@ mod test_award_block_reward { #[test] fn rejects_zero_wincount() { let mut rt = construct_and_verify(&StoragePower::default()); - rt.set_balance(TokenAmount::from(10_i128.pow(18))); + rt.set_balance(TokenAmount::from_whole(1)); rt.expect_validate_caller_addr(vec![*SYSTEM_ACTOR_ADDR]); assert!(award_block_reward( &mut rt, *WINNER, - TokenAmount::from(0), - TokenAmount::from(0), + TokenAmount::zero(), + TokenAmount::zero(), 0, - TokenAmount::from(0) + TokenAmount::zero() ) .is_err()); rt.reset(); @@ -149,12 +152,12 @@ mod test_award_block_reward { #[test] fn pays_reward_and_tracks_penalty() { let mut rt = construct_and_verify(&StoragePower::default()); - rt.set_balance(TokenAmount::from(10_i128.pow(27))); + rt.set_balance(TokenAmount::from_whole(1_000_000_000)); rt.expect_validate_caller_addr(vec![*SYSTEM_ACTOR_ADDR]); - let penalty: TokenAmount = TokenAmount::from(100); - let gas_reward: TokenAmount = TokenAmount::from(200); + let penalty: TokenAmount = TokenAmount::from_atto(100); + let gas_reward: TokenAmount = TokenAmount::from_atto(200); let expected_reward: TokenAmount = - &*EPOCH_ZERO_REWARD / EXPECTED_LEADERS_PER_EPOCH + &gas_reward; + EPOCH_ZERO_REWARD.div_floor(EXPECTED_LEADERS_PER_EPOCH) + &gas_reward; let miner_penalty = PENALTY_MULTIPLIER * &penalty; let params = RawBytes::serialize(&ext::miner::ApplyRewardParams { reward: expected_reward.clone(), @@ -185,8 +188,8 @@ mod test_award_block_reward { let mut rt = construct_and_verify(&StoragePower::from(1)); // Total reward is a huge number, upon writing ~1e18, so 300 should be way less - let small_reward = TokenAmount::from(300); - let penalty = TokenAmount::from(100); + let small_reward = TokenAmount::from_atto(300); + let penalty = TokenAmount::from_atto(100); rt.set_balance(small_reward.clone()); rt.expect_validate_caller_addr(vec![*SYSTEM_ACTOR_ADDR]); @@ -208,7 +211,7 @@ mod test_award_block_reward { let params = AwardBlockRewardParams { miner: *WINNER, penalty, - gas_reward: TokenAmount::from(0), + gas_reward: TokenAmount::zero(), win_count: 1, }; assert!(rt @@ -225,22 +228,22 @@ mod test_award_block_reward { let mut rt = construct_and_verify(&StoragePower::from(1)); let mut state: State = rt.get_state(); - assert_eq!(TokenAmount::from(0), state.total_storage_power_reward); - state.this_epoch_reward = TokenAmount::from(5000); + assert_eq!(TokenAmount::zero(), state.total_storage_power_reward); + state.this_epoch_reward = TokenAmount::from_atto(5000); rt.replace_state(&state); - let total_payout = TokenAmount::from(3500); + let total_payout = TokenAmount::from_atto(3500); rt.set_balance(total_payout.clone()); for i in &[1000, 1000, 1000, 500] { assert!(award_block_reward( &mut rt, *WINNER, - TokenAmount::from(0), - TokenAmount::from(0), + TokenAmount::zero(), + TokenAmount::zero(), 1, - TokenAmount::from(*i) + TokenAmount::from_atto(*i) ) .is_ok()); } @@ -254,15 +257,15 @@ mod test_award_block_reward { let mut rt = construct_and_verify(&StoragePower::from(1)); let mut state: State = rt.get_state(); - assert_eq!(TokenAmount::from(0), state.total_storage_power_reward); - state.this_epoch_reward = TokenAmount::from(5000); + assert_eq!(TokenAmount::zero(), state.total_storage_power_reward); + state.this_epoch_reward = TokenAmount::from_atto(5000); rt.replace_state(&state); // enough balance to pay 3 full rewards and one partial - rt.set_balance(TokenAmount::from(3500)); + rt.set_balance(TokenAmount::from_atto(3500)); rt.expect_validate_caller_addr(vec![*SYSTEM_ACTOR_ADDR]); - let expected_reward = TokenAmount::from(1000); - let miner_penalty = TokenAmount::from(0); + let expected_reward = TokenAmount::from_atto(1000); + let miner_penalty = TokenAmount::zero(); let params = RawBytes::serialize(&ext::miner::ApplyRewardParams { reward: expected_reward.clone(), penalty: miner_penalty, @@ -287,8 +290,8 @@ mod test_award_block_reward { let params = AwardBlockRewardParams { miner: *WINNER, - penalty: TokenAmount::from(0), - gas_reward: TokenAmount::from(0), + penalty: TokenAmount::zero(), + gas_reward: TokenAmount::zero(), win_count: 1, }; @@ -373,7 +376,7 @@ fn award_block_reward( ExitCode::OK, ); - if penalty > TokenAmount::from(0) { + if penalty.is_positive() { rt.expect_send( *BURNT_FUNDS_ACTOR_ADDR, METHOD_SEND, diff --git a/actors/system/Cargo.toml b/actors/system/Cargo.toml index 455c633d4b..324eab8173 100644 --- a/actors/system/Cargo.toml +++ b/actors/system/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "9.0.0-alpha.1", path = "../../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } fvm_ipld_encoding = "0.2.2" fvm_ipld_blockstore = "0.1.1" num-traits = "0.2.14" diff --git a/actors/verifreg/Cargo.toml b/actors/verifreg/Cargo.toml index 8cccfd7262..704a3b7249 100644 --- a/actors/verifreg/Cargo.toml +++ b/actors/verifreg/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "9.0.0-alpha.1", path = "../../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } serde = { version = "1.0.136", features = ["derive"] } num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index b8c47361f8..3983b8ed82 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -10,7 +10,7 @@ repository = "https://github.com/filecoin-project/builtin-actors" [dependencies] fvm_ipld_hamt = "0.5.1" fvm_ipld_amt = { version = "0.4.2", features = ["go-interop"] } -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } num-traits = "0.2.14" num-derive = "0.3.3" serde = { version = "1.0.136", features = ["derive"] } @@ -27,7 +27,7 @@ thiserror = "1.0.30" getrandom = { version = "0.2.5", features = ["js"] } hex = { version = "0.4.3", optional = true } anyhow = "1.0.56" -fvm_sdk = { version = "1.0.0-rc.3", optional = true } +fvm_sdk = { version = "2.0.0-alpha.3", optional = true } blake2b_simd = "1.0" fvm_ipld_blockstore = "0.1.1" fvm_ipld_encoding = "0.2.2" diff --git a/runtime/src/builtin/network.rs b/runtime/src/builtin/network.rs index 13a0df1d1f..37b8d61d05 100644 --- a/runtime/src/builtin/network.rs +++ b/runtime/src/builtin/network.rs @@ -10,6 +10,3 @@ pub const SECONDS_IN_YEAR: i64 = 31556925; pub const EPOCHS_IN_HOUR: i64 = SECONDS_IN_HOUR / EPOCH_DURATION_SECONDS; pub const EPOCHS_IN_DAY: i64 = SECONDS_IN_DAY / EPOCH_DURATION_SECONDS; pub const EPOCHS_IN_YEAR: i64 = SECONDS_IN_YEAR / EPOCH_DURATION_SECONDS; - -// 1 NanoFIL -pub const ONE_NANO_FIL: u64 = 10u64.pow(9); diff --git a/runtime/src/runtime/fvm.rs b/runtime/src/runtime/fvm.rs index ebdc1ba42d..04097c9fb1 100644 --- a/runtime/src/runtime/fvm.rs +++ b/runtime/src/runtime/fvm.rs @@ -167,12 +167,11 @@ where } fn resolve_builtin_actor_type(&self, code_id: &Cid) -> Option { - fvm::actor::get_builtin_actor_type(code_id).and_then(|t| Type::from_i32(t as i32)) + fvm::actor::get_builtin_actor_type(code_id).and_then(Type::from_i32) } fn get_code_cid_for_type(&self, typ: Type) -> Cid { - let t = fvm_shared::actor::builtin::Type::from_i32(typ as i32).unwrap(); - fvm::actor::get_code_cid_for_type(t) + fvm::actor::get_code_cid_for_type(typ as i32) } fn get_randomness_from_tickets( @@ -191,7 +190,9 @@ where // // Since that behaviour changes, we may as well abort with a more appropriate exit code // explicitly. - fvm::rand::get_chain_randomness(personalization as i64, rand_epoch, entropy).map_err(|e| { + fvm::rand::get_chain_randomness(personalization as i64, rand_epoch, entropy) + .map(|v|Randomness(v.into())) + .map_err(|e| { if self.network_version() < NetworkVersion::V16 { ActorError::unchecked(ExitCode::SYS_ILLEGAL_INSTRUCTION, "failed to get chain randomness".into()) @@ -213,7 +214,9 @@ where entropy: &[u8], ) -> Result { // See note on exit codes in get_randomness_from_tickets. - fvm::rand::get_beacon_randomness(personalization as i64, rand_epoch, entropy).map_err(|e| { + fvm::rand::get_beacon_randomness(personalization as i64, rand_epoch, entropy) + .map(|v|Randomness(v.into())) + .map_err(|e| { if self.network_version() < NetworkVersion::V16 { ActorError::unchecked(ExitCode::SYS_ILLEGAL_INSTRUCTION, "failed to get chain randomness".into()) diff --git a/runtime/src/util/chaos/types.rs b/runtime/src/util/chaos/types.rs index c61bb6fb6c..21829fde15 100644 --- a/runtime/src/util/chaos/types.rs +++ b/runtime/src/util/chaos/types.rs @@ -5,7 +5,6 @@ use cid::Cid; use fvm_ipld_encoding::tuple::*; use fvm_ipld_encoding::RawBytes; use fvm_shared::address::Address; -use fvm_shared::bigint::bigint_ser; use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; @@ -31,7 +30,6 @@ pub struct ResolveAddressResponse { #[derive(Serialize_tuple, Deserialize_tuple)] pub struct SendArgs { pub to: Address, - #[serde(with = "bigint_ser")] pub value: TokenAmount, #[serde(rename = "MethodNum")] pub method: u64, @@ -62,10 +60,8 @@ pub struct AbortWithArgs { pub struct InspectRuntimeReturn { pub caller: Address, pub receiver: Address, - #[serde(with = "bigint_ser")] pub value_received: TokenAmount, pub curr_epoch: ChainEpoch, - #[serde(with = "bigint_ser")] pub current_balance: TokenAmount, pub state: State, } diff --git a/runtime/tests/alpha_beta_filter_test.rs b/runtime/tests/alpha_beta_filter_test.rs index e4a78c361f..cb55369f76 100644 --- a/runtime/tests/alpha_beta_filter_test.rs +++ b/runtime/tests/alpha_beta_filter_test.rs @@ -4,6 +4,7 @@ use fil_actors_runtime::EPOCHS_IN_DAY; use fvm_shared::bigint::{BigInt, Integer}; use fvm_shared::clock::ChainEpoch; +use fvm_shared::econ::TokenAmount; use fvm_shared::math::{poly_parse, PRECISION}; use fvm_shared::sector::StoragePower; use fvm_shared::smooth::{extrapolated_cum_sum_of_ratio as ecsor, *}; @@ -148,7 +149,7 @@ fn flipped_signs() { #[test] fn values_in_range() { - let tens_of_fil = BigInt::from(50 * 10_i128.pow(18)); + let tens_of_fil = TokenAmount::from_whole(50).atto().clone(); let one_fil_per_sec = BigInt::from(25); let four_fil_per_second = BigInt::from(100); diff --git a/state/Cargo.toml b/state/Cargo.toml index bdd8b1f767..b38471ea57 100644 --- a/state/Cargo.toml +++ b/state/Cargo.toml @@ -26,7 +26,7 @@ fil_actor_reward = { version = "9.0.0-alpha.1", path = "../actors/reward"} fil_actor_system = { version = "9.0.0-alpha.1", path = "../actors/system"} fil_actor_init = { version = "9.0.0-alpha.1", path = "../actors/init"} fil_actors_runtime = { version = "9.0.0-alpha.1", path = "../runtime"} -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } fvm_ipld_encoding = "0.2.2" fvm_ipld_blockstore = "0.1.1" num-traits = "0.2.14" diff --git a/state/src/check.rs b/state/src/check.rs index 66453c42cf..0649e083a0 100644 --- a/state/src/check.rs +++ b/state/src/check.rs @@ -28,14 +28,13 @@ use fvm_ipld_encoding::from_slice; use fvm_ipld_encoding::CborStore; use fvm_shared::address::Address; use fvm_shared::address::Protocol; -use fvm_shared::bigint::BigInt; + use fvm_shared::clock::ChainEpoch; use fvm_shared::econ::TokenAmount; use num_traits::Zero; use anyhow::anyhow; use fvm_ipld_encoding::tuple::*; -use fvm_shared::bigint::bigint_ser; use fil_actor_account::testing as account; use fil_actor_cron::testing as cron; @@ -59,7 +58,6 @@ pub struct Actor { pub head: Cid, /// `call_seq_num` for the next message to be received by the actor (non-zero for accounts only) pub call_seq_num: u64, - #[serde(with = "bigint_ser")] /// Token balance of the actor pub balance: TokenAmount, } @@ -115,7 +113,7 @@ pub fn check_state_invariants<'a, BS: Blockstore + Debug>( prior_epoch: ChainEpoch, ) -> anyhow::Result { let acc = MessageAccumulator::default(); - let mut total_fil = BigInt::zero(); + let mut total_fil = TokenAmount::zero(); let mut init_summary: Option = None; let mut cron_summary: Option = None; diff --git a/test_vm/Cargo.toml b/test_vm/Cargo.toml index 83d95f4375..36528f30d4 100644 --- a/test_vm/Cargo.toml +++ b/test_vm/Cargo.toml @@ -25,7 +25,7 @@ fil_actor_market = { version = "9.0.0-alpha.1", path = "../actors/market" } fil_actor_verifreg = { version = "9.0.0-alpha.1", path = "../actors/verifreg" } fil_actor_miner = { version = "9.0.0-alpha.1", path = "../actors/miner" } lazy_static = "1.4.0" -fvm_shared = { version = "0.8.0", default-features = false } +fvm_shared = { version = "2.0.0-alpha.2", default-features = false } fvm_ipld_encoding = { version = "0.2.2", default-features = false } fvm_ipld_blockstore = { version = "0.1.1", default-features = false } fvm_ipld_bitfield = "0.5.2" diff --git a/test_vm/src/lib.rs b/test_vm/src/lib.rs index a65486bf36..340ee4659b 100644 --- a/test_vm/src/lib.rs +++ b/test_vm/src/lib.rs @@ -34,7 +34,7 @@ use fvm_ipld_encoding::{Cbor, CborStore, RawBytes}; use fvm_ipld_hamt::{BytesKey, Hamt, Sha256}; use fvm_shared::address::Payload; use fvm_shared::address::{Address, Protocol}; -use fvm_shared::bigint::{bigint_ser, BigInt, Zero}; +use fvm_shared::bigint::Zero; use fvm_shared::clock::ChainEpoch; use fvm_shared::consensus::ConsensusFault; use fvm_shared::crypto::signature::Signature; @@ -49,7 +49,6 @@ use fvm_shared::sector::{ use fvm_shared::smooth::FilterEstimate; use fvm_shared::version::NetworkVersion; use fvm_shared::{ActorID, MethodNum, METHOD_CONSTRUCTOR, METHOD_SEND}; -use num_traits::Signed; use regex::Regex; use serde::ser; use std::cell::{RefCell, RefMut}; @@ -130,12 +129,8 @@ impl<'bs> VM<'bs> { } pub fn new_with_singletons(store: &'bs MemoryBlockstore) -> VM<'bs> { - // funding - let fil = TokenAmount::from(1_000_000_000i32) - .checked_mul(&TokenAmount::from(1_000_000_000i32)) - .unwrap(); - let reward_total = TokenAmount::from(1_100_000_000i32).checked_mul(&fil).unwrap(); - let faucet_total = TokenAmount::from(1_000_000_000u32).checked_mul(&fil).unwrap(); + let reward_total = TokenAmount::from_whole(1_100_000_000i64); + let faucet_total = TokenAmount::from_whole(1_000_000_000i64); let v = VM::new(store).with_total_fil(&reward_total + &faucet_total); @@ -217,7 +212,7 @@ impl<'bs> VM<'bs> { .apply_message( *SYSTEM_ACTOR_ADDR, *INIT_ACTOR_ADDR, - BigInt::zero(), + TokenAmount::zero(), fil_actor_init::Method::Exec as u64, fil_actor_init::ExecParams { code_cid: *MULTISIG_ACTOR_CODE_ID, @@ -403,7 +398,7 @@ impl<'bs> VM<'bs> { originator_stable_addr: from, _originator_call_seq: call_seq, new_actor_addr_count: RefCell::new(0), - circ_supply: TokenAmount::from(1e9 as u128 * 1e18 as u128), + circ_supply: TokenAmount::from_whole(1_000_000_000), }; let msg = InternalMessage { from: from_id, @@ -485,10 +480,10 @@ impl<'bs> VM<'bs> { pub fn get_total_actor_balance( &self, store: &MemoryBlockstore, - ) -> anyhow::Result { + ) -> anyhow::Result { let state_tree = Tree::load(store, &self.checkpoint())?; - let mut total = BigInt::zero(); + let mut total = TokenAmount::zero(); state_tree.for_each(|_, actor| { total += &actor.balance.clone(); Ok(()) @@ -502,7 +497,7 @@ pub struct TopCtx { originator_stable_addr: Address, _originator_call_seq: u64, new_actor_addr_count: RefCell, - circ_supply: BigInt, + circ_supply: TokenAmount, } #[derive(Clone, Debug)] @@ -622,13 +617,13 @@ impl<'invocation, 'bs> InvocationCtx<'invocation, 'bs> { // Transfer funds let mut from_actor = self.v.get_actor(self.msg.from).unwrap(); if !self.msg.value.is_zero() { - if self.msg.value.lt(&BigInt::zero()) { + if self.msg.value.is_negative() { return Err(ActorError::unchecked( ExitCode::SYS_ASSERTION_FAILED, "attempt to transfer negative value".to_string(), )); } - if from_actor.balance.lt(&self.msg.value) { + if from_actor.balance < self.msg.value { return Err(ActorError::unchecked( ExitCode::SYS_INSUFFICIENT_FUNDS, "insufficient balance to transfer".to_string(), @@ -637,7 +632,7 @@ impl<'invocation, 'bs> InvocationCtx<'invocation, 'bs> { } // Load, deduct, store from actor before loading to actor to handle self-send case - from_actor.balance = from_actor.balance.abs_sub(&self.msg.value); + from_actor.balance -= &self.msg.value; self.v.set_actor(self.msg.from, from_actor); let (mut to_actor, to_addr) = self.resolve_target(&self.msg.to)?; @@ -690,7 +685,7 @@ impl<'invocation, 'bs> Runtime<&'bs MemoryBlockstore> for InvocationCtx<'invocat "attempt to create new actor at existing address".to_string(), )); } - let a = actor(code_id, self.v.empty_obj_cid, 0, BigInt::zero()); + let a = actor(code_id, self.v.empty_obj_cid, 0, TokenAmount::zero()); self.v.set_actor(addr, a); Ok(()) } @@ -825,7 +820,7 @@ impl<'invocation, 'bs> Runtime<&'bs MemoryBlockstore> for InvocationCtx<'invocat _rand_epoch: ChainEpoch, _entropy: &[u8], ) -> Result { - Ok(Randomness(TEST_VM_RAND_STRING.as_bytes().to_vec())) + Ok(Randomness(TEST_VM_RAND_STRING.as_bytes().into())) } fn get_randomness_from_beacon( @@ -834,7 +829,7 @@ impl<'invocation, 'bs> Runtime<&'bs MemoryBlockstore> for InvocationCtx<'invocat _rand_epoch: ChainEpoch, _entropy: &[u8], ) -> Result { - Ok(Randomness(TEST_VM_RAND_STRING.as_bytes().to_vec())) + Ok(Randomness(TEST_VM_RAND_STRING.as_bytes().into())) } fn create(&mut self, obj: &C) -> Result<(), ActorError> { @@ -1031,7 +1026,6 @@ pub struct Actor { pub code: Cid, pub head: Cid, pub call_seq_num: u64, - #[serde(with = "bigint_ser")] pub balance: TokenAmount, } diff --git a/test_vm/src/util.rs b/test_vm/src/util.rs index 74101bb907..5c23c4eb49 100644 --- a/test_vm/src/util.rs +++ b/test_vm/src/util.rs @@ -576,9 +576,9 @@ pub fn publish_deal( label, start_epoch: deal_start, end_epoch: deal_start + deal_lifetime, - storage_price_per_epoch: TokenAmount::from((1 << 20) as u64), - provider_collateral: TokenAmount::from(2e18 as u64), - client_collateral: TokenAmount::from(1e18 as u64), + storage_price_per_epoch: TokenAmount::from_atto((1 << 20) as u64), + provider_collateral: TokenAmount::from_whole(2), + client_collateral: TokenAmount::from_whole(1), }; let publish_params = PublishStorageDealsParams { diff --git a/test_vm/tests/batch_onboarding.rs b/test_vm/tests/batch_onboarding.rs index 22b5e5919d..38f5f606aa 100644 --- a/test_vm/tests/batch_onboarding.rs +++ b/test_vm/tests/batch_onboarding.rs @@ -12,7 +12,6 @@ use fvm_ipld_encoding::RawBytes; use fvm_shared::bigint::{BigInt, Zero}; use fvm_shared::econ::TokenAmount; use fvm_shared::sector::{RegisteredSealProof, SectorNumber}; -use num_traits::Signed; use test_vm::util::{ advance_to_proving_deadline, apply_ok, create_accounts, create_miner, invariant_failure_patterns, precommit_sectors, prove_commit_sectors, submit_windowed_post, @@ -49,7 +48,7 @@ impl Onboarding { fn batch_onboarding() { let store = MemoryBlockstore::new(); let mut v = VM::new_with_singletons(&store); - let addrs = create_accounts(&v, 1, TokenAmount::from(10_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(10_000)); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (owner, worker) = (addrs[0], addrs[0]); let (id_addr, _) = create_miner( @@ -57,7 +56,7 @@ fn batch_onboarding() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); let mut v = v.with_epoch(200); diff --git a/test_vm/tests/commit_post_test.rs b/test_vm/tests/commit_post_test.rs index 4f21efdc2b..55b48b284c 100644 --- a/test_vm/tests/commit_post_test.rs +++ b/test_vm/tests/commit_post_test.rs @@ -23,7 +23,6 @@ use fvm_shared::error::ExitCode; use fvm_shared::randomness::Randomness; use fvm_shared::sector::{PoStProof, RegisteredSealProof, SectorNumber, MAX_SECTOR_NUMBER}; use fvm_shared::METHOD_SEND; -use num_traits::sign::Signed; use test_vm::util::{ advance_by_deadline_to_epoch, advance_to_proving_deadline, apply_code, apply_ok, create_accounts, create_miner, invariant_failure_patterns, precommit_sectors, @@ -47,7 +46,7 @@ struct MinerInfo { fn setup(store: &'_ MemoryBlockstore) -> (VM<'_>, MinerInfo, SectorInfo) { let mut v = VM::new_with_singletons(store); - let addrs = create_accounts(&v, 1, TokenAmount::from(10_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(10_000)); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (owner, worker) = (addrs[0], addrs[0]); let (id_addr, robust_addr) = create_miner( @@ -55,7 +54,7 @@ fn setup(store: &'_ MemoryBlockstore) -> (VM<'_>, MinerInfo, SectorInfo) { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); let mut v = v.with_epoch(200); @@ -312,7 +311,7 @@ fn overdue_precommit() { let store = MemoryBlockstore::new(); let policy = &Policy::default(); let mut v = VM::new_with_singletons(&store); - let addrs = create_accounts(&v, 1, TokenAmount::from(10_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(10_000)); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (owner, worker) = (addrs[0], addrs[0]); let id_addr = create_miner( @@ -320,7 +319,7 @@ fn overdue_precommit() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ) .0; let mut v = v.with_epoch(200); @@ -426,7 +425,7 @@ fn overdue_precommit() { fn aggregate_bad_sector_number() { let store = MemoryBlockstore::new(); let mut v = VM::new_with_singletons(&store); - let addrs = create_accounts(&v, 1, TokenAmount::from(10_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(10_000)); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (owner, worker) = (addrs[0], addrs[0]); let (id_addr, robust_addr) = create_miner( @@ -434,7 +433,7 @@ fn aggregate_bad_sector_number() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); let mut v = v.with_epoch(200); let policy = &Policy::default(); @@ -507,7 +506,7 @@ fn aggregate_size_limits() { let oversized_batch = 820; let store = MemoryBlockstore::new(); let mut v = VM::new_with_singletons(&store); - let addrs = create_accounts(&v, 1, TokenAmount::from(100_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(100_000)); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (owner, worker) = (addrs[0], addrs[0]); let (id_addr, robust_addr) = create_miner( @@ -515,7 +514,7 @@ fn aggregate_size_limits() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(100_000e18 as i128), + TokenAmount::from_whole(100_000), ); let mut v = v.with_epoch(200); let policy = &Policy::default(); @@ -640,7 +639,7 @@ fn aggregate_size_limits() { fn aggregate_bad_sender() { let store = MemoryBlockstore::new(); let mut v = VM::new_with_singletons(&store); - let addrs = create_accounts(&v, 2, TokenAmount::from(10_000e18 as i128)); + let addrs = create_accounts(&v, 2, TokenAmount::from_whole(10_000)); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (owner, worker) = (addrs[0], addrs[0]); let (id_addr, robust_addr) = create_miner( @@ -648,7 +647,7 @@ fn aggregate_bad_sender() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); let mut v = v.with_epoch(200); let policy = &Policy::default(); @@ -716,7 +715,7 @@ fn aggregate_bad_sender() { fn aggregate_one_precommit_expires() { let store = MemoryBlockstore::new(); let mut v = VM::new_with_singletons(&store); - let addrs = create_accounts(&v, 1, TokenAmount::from(10_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(10_000)); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (owner, worker) = (addrs[0], addrs[0]); let (id_addr, robust_addr) = create_miner( @@ -724,7 +723,7 @@ fn aggregate_one_precommit_expires() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); let mut v = v.with_epoch(200); let policy = &Policy::default(); diff --git a/test_vm/tests/extend_sectors_test.rs b/test_vm/tests/extend_sectors_test.rs index 226dca2239..dd9591df4a 100644 --- a/test_vm/tests/extend_sectors_test.rs +++ b/test_vm/tests/extend_sectors_test.rs @@ -32,7 +32,7 @@ use test_vm::{ExpectInvocation, VM}; fn extend_sector_with_deals() { let store = MemoryBlockstore::new(); let mut v = VM::new_with_singletons(&store); - let addrs = create_accounts(&v, 3, TokenAmount::from(10_000e18 as i128)); + let addrs = create_accounts(&v, 3, TokenAmount::from_whole(10_000)); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (owner, worker, verifier, verified_client) = (addrs[0], addrs[0], addrs[1], addrs[2]); let sector_number: SectorNumber = 100; @@ -46,7 +46,7 @@ fn extend_sector_with_deals() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(1_000e18 as i128), + TokenAmount::from_whole(1_000), ) .0; let mut v = v.with_epoch(200); @@ -72,7 +72,7 @@ fn extend_sector_with_deals() { ); // add market collateral for clients and miner - let mut collateral = TokenAmount::from(3e18 as i128); + let mut collateral = TokenAmount::from_whole(3); apply_ok( &v, verified_client, @@ -81,7 +81,7 @@ fn extend_sector_with_deals() { MarketMethod::AddBalance as u64, verified_client, ); - collateral = TokenAmount::from(64e18 as i128); + collateral = TokenAmount::from_whole(64); apply_ok( &v, worker, diff --git a/test_vm/tests/market_miner_withdrawal_test.rs b/test_vm/tests/market_miner_withdrawal_test.rs index 1a12a51646..632e8802da 100644 --- a/test_vm/tests/market_miner_withdrawal_test.rs +++ b/test_vm/tests/market_miner_withdrawal_test.rs @@ -7,8 +7,7 @@ use fil_actors_runtime::STORAGE_MARKET_ACTOR_ADDR; use fvm_ipld_blockstore::MemoryBlockstore; use fvm_ipld_encoding::RawBytes; use fvm_shared::address::Address; -use fvm_shared::bigint::bigint_ser::BigIntDe; -use fvm_shared::bigint::BigInt; + use fvm_shared::bigint::Zero; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; @@ -27,7 +26,7 @@ mod market_tests { let store = MemoryBlockstore::new(); let (v, caller) = market_setup(&store); - let three_fil = TokenAmount::from(3) * BigInt::from(1e18 as i128); + let three_fil = TokenAmount::from_whole(3); assert_add_collateral_and_withdraw( &v, three_fil.clone(), @@ -44,8 +43,8 @@ mod market_tests { let (v, caller) = market_setup(&store); // Add 2 FIL of collateral and attempt to withdraw 3 - let two_fil = TokenAmount::from(2) * BigInt::from(1e18 as i128); - let three_fil = TokenAmount::from(3) * BigInt::from(1e18 as i128); + let two_fil = TokenAmount::from_whole(2); + let three_fil = TokenAmount::from_whole(3); assert_add_collateral_and_withdraw( &v, two_fil.clone(), @@ -62,7 +61,7 @@ mod market_tests { let (v, caller) = market_setup(&store); // Add 0 FIL of collateral and attempt to withdraw 3 - let three_fil = TokenAmount::from(3) * BigInt::from(1e18 as i128); + let three_fil = TokenAmount::from_whole(3); assert_add_collateral_and_withdraw( &v, TokenAmount::zero(), @@ -83,7 +82,7 @@ mod miner_tests { let store = MemoryBlockstore::new(); let (v, _, owner, m_addr) = miner_setup(&store); - let three_fil = TokenAmount::from(3) * BigInt::from(1e18 as i128); + let three_fil = TokenAmount::from_whole(3); assert_add_collateral_and_withdraw( &v, three_fil.clone(), @@ -99,8 +98,8 @@ mod miner_tests { let store = MemoryBlockstore::new(); let (v, _, owner, m_addr) = miner_setup(&store); - let two_fil = TokenAmount::from(2) * BigInt::from(1e18 as i128); - let three_fil = TokenAmount::from(3) * BigInt::from(1e18 as i128); + let two_fil = TokenAmount::from_whole(2); + let three_fil = TokenAmount::from_whole(3); assert_add_collateral_and_withdraw(&v, two_fil.clone(), two_fil, three_fil, m_addr, owner); } @@ -109,7 +108,7 @@ mod miner_tests { let store = MemoryBlockstore::new(); let (v, _, owner, m_addr) = miner_setup(&store); - let three_fil = TokenAmount::from(3) * BigInt::from(1e18 as i128); + let three_fil = TokenAmount::from_whole(3); assert_add_collateral_and_withdraw( &v, TokenAmount::zero(), @@ -125,7 +124,7 @@ mod miner_tests { let store = MemoryBlockstore::new(); let (v, worker, _, m_addr) = miner_setup(&store); - let one_fil = TokenAmount::from(1) * BigInt::from(1e18 as i128); + let one_fil = TokenAmount::from_whole(1); let params = MinerWithdrawBalanceParams { amount_requested: one_fil }; apply_code( &v, @@ -163,7 +162,7 @@ fn assert_add_collateral_and_withdraw( let caller_initial_balance = c.balance; // add collateral - if collateral > BigInt::zero() { + if collateral.is_positive() { match a_type { x if x == *MINER_ACTOR_CODE_ID => { apply_ok(v, caller, escrow, collateral.clone(), METHOD_SEND, RawBytes::default()) @@ -184,12 +183,19 @@ fn assert_add_collateral_and_withdraw( assert_eq!(&caller_initial_balance - &collateral, c.balance); // attempt to withdraw withdrawal - let ret: BigIntDe = match a_type { + let withdrawn: TokenAmount = match a_type { x if x == *MINER_ACTOR_CODE_ID => { let params = MinerWithdrawBalanceParams { amount_requested: requested }; - apply_ok(v, caller, escrow, BigInt::zero(), MinerMethod::WithdrawBalance as u64, params) - .deserialize() - .unwrap() + apply_ok( + v, + caller, + escrow, + TokenAmount::zero(), + MinerMethod::WithdrawBalance as u64, + params, + ) + .deserialize() + .unwrap() } x if x == *MARKET_ACTOR_CODE_ID => { let params = @@ -198,7 +204,7 @@ fn assert_add_collateral_and_withdraw( v, caller, escrow, - BigInt::zero(), + TokenAmount::zero(), MarketMethod::WithdrawBalance as u64, params, ) @@ -207,7 +213,6 @@ fn assert_add_collateral_and_withdraw( } _ => panic!("unreachable"), }; - let withdrawn = ret.0; assert_eq!(expected_withdrawn, withdrawn); c = require_actor(v, caller); @@ -220,7 +225,7 @@ fn require_actor(v: &VM, addr: Address) -> Actor { fn market_setup(store: &'_ MemoryBlockstore) -> (VM<'_>, Address) { let v = VM::new_with_singletons(store); - let initial_balance = BigInt::from(6) * BigInt::from(1e18 as i128); + let initial_balance = TokenAmount::from_whole(6); let addrs = create_accounts(&v, 1, initial_balance); let caller = addrs[0]; (v, caller) @@ -228,7 +233,7 @@ fn market_setup(store: &'_ MemoryBlockstore) -> (VM<'_>, Address) { fn miner_setup(store: &'_ MemoryBlockstore) -> (VM<'_>, Address, Address, Address) { let mut v = VM::new_with_singletons(store); - let initial_balance = BigInt::from(10_000) * BigInt::from(1e18 as i128); + let initial_balance = TokenAmount::from_whole(10_000); let addrs = create_accounts(&v, 2, initial_balance); let (worker, owner) = (addrs[0], addrs[1]); @@ -238,7 +243,7 @@ fn miner_setup(store: &'_ MemoryBlockstore) -> (VM<'_>, Address, Address, Addres owner, worker, RegisteredPoStProof::StackedDRGWindow32GiBV1, - TokenAmount::from(0), + TokenAmount::zero(), ); (v, worker, owner, m_addr) diff --git a/test_vm/tests/multisig_test.rs b/test_vm/tests/multisig_test.rs index f176b256e9..2c30104ac8 100644 --- a/test_vm/tests/multisig_test.rs +++ b/test_vm/tests/multisig_test.rs @@ -23,7 +23,7 @@ use test_vm::{ExpectInvocation, VM}; fn test_proposal_hash() { let store = MemoryBlockstore::new(); let v = VM::new_with_singletons(&store); - let addrs = create_accounts(&v, 3, TokenAmount::from(10_000e18 as u64)); + let addrs = create_accounts(&v, 3, TokenAmount::from_whole(10_000)); let alice = addrs[0]; let bob = addrs[1]; let sys_act_start_bal = v.get_actor(*SYSTEM_ACTOR_ADDR).unwrap().balance; @@ -31,7 +31,7 @@ fn test_proposal_hash() { let msig_addr = create_msig(&v, addrs, 2); // fund msig and propose send funds to system actor - let fil_delta = TokenAmount::from(3 * 1_000_000_000_u64); // 3 nFIL + let fil_delta = TokenAmount::from_atto(3 * 1_000_000_000_u64); // 3 nFIL let propose_send_sys_params = ProposeParams { to: *SYSTEM_ACTOR_ADDR, value: fil_delta.clone(), @@ -49,7 +49,7 @@ fn test_proposal_hash() { let wrong_tx = Transaction { to: *SYSTEM_ACTOR_ADDR, - value: fil_delta.clone() - 1_u64, // incorrect send amount not consistent with proposal + value: &fil_delta - TokenAmount::from_atto(1), // incorrect send amount not consistent with proposal method: METHOD_SEND, approved: vec![alice], params: RawBytes::default(), @@ -103,7 +103,7 @@ fn test_delete_self() { let test = |threshold: usize, signers: u64, remove_idx: usize| { let store = MemoryBlockstore::new(); let v = VM::new_with_singletons(&store); - let addrs = create_accounts(&v, signers, TokenAmount::from(10_000e18 as u64)); + let addrs = create_accounts(&v, signers, TokenAmount::from_whole(10_000)); let msig_addr = create_msig(&v, addrs.clone(), threshold as u64); @@ -175,7 +175,7 @@ fn test_delete_self() { fn swap_self_1_of_2() { let store = MemoryBlockstore::new(); let v = VM::new_with_singletons(&store); - let addrs = create_accounts(&v, 3, TokenAmount::from(10_000e18 as u64)); + let addrs = create_accounts(&v, 3, TokenAmount::from_whole(10_000)); let (alice, bob, chuck) = (addrs[0], addrs[1], addrs[2]); let msig_addr = create_msig(&v, vec![alice, bob], 1); @@ -204,7 +204,7 @@ fn swap_self_1_of_2() { fn swap_self_2_of_3() { let store = MemoryBlockstore::new(); let v = VM::new_with_singletons(&store); - let addrs = create_accounts(&v, 4, TokenAmount::from(10_000e18 as u64)); + let addrs = create_accounts(&v, 4, TokenAmount::from_whole(10_000)); let (alice, bob, chuck, dinesh) = (addrs[0], addrs[1], addrs[2], addrs[3]); let msig_addr = create_msig(&v, vec![alice, bob, chuck], 2); @@ -289,7 +289,7 @@ fn create_msig(v: &VM, signers: Vec
, threshold: u64) -> Address { v, signers[0], *INIT_ACTOR_ADDR, - TokenAmount::from(0_u64), + TokenAmount::zero(), fil_actor_init::Method::Exec as u64, fil_actor_init::ExecParams { code_cid: *MULTISIG_ACTOR_CODE_ID, diff --git a/test_vm/tests/power_scenario_tests.rs b/test_vm/tests/power_scenario_tests.rs index 566c4d0974..7512b1faa7 100644 --- a/test_vm/tests/power_scenario_tests.rs +++ b/test_vm/tests/power_scenario_tests.rs @@ -15,7 +15,7 @@ use fil_actors_runtime::{ use fvm_ipld_blockstore::MemoryBlockstore; use fvm_ipld_encoding::{BytesDe, RawBytes}; use fvm_shared::address::Address; -use fvm_shared::bigint::BigInt; + use fvm_shared::econ::TokenAmount; use fvm_shared::sector::{RegisteredPoStProof, RegisteredSealProof}; use fvm_shared::METHOD_SEND; @@ -34,7 +34,7 @@ fn create_miner_test() { v.apply_message( TEST_FAUCET_ADDR, owner, - TokenAmount::from(10_000u32), + TokenAmount::from_atto(10_000u32), METHOD_SEND, RawBytes::default(), ) @@ -53,7 +53,7 @@ fn create_miner_test() { .apply_message( owner, *STORAGE_POWER_ACTOR_ADDR, - TokenAmount::from(1000u32), + TokenAmount::from_atto(1000u32), PowerMethod::CreateMiner as u64, params.clone(), ) @@ -105,7 +105,7 @@ fn test_cron_tick() { let store = MemoryBlockstore::new(); let mut vm = VM::new_with_singletons(&store); - let addrs = create_accounts(&vm, 1, BigInt::from(10_000u64) * BigInt::from(10u64.pow(18))); + let addrs = create_accounts(&vm, 1, TokenAmount::from_whole(10_000)); // create a miner let (id_addr, robust_addr) = create_miner( @@ -113,7 +113,7 @@ fn test_cron_tick() { addrs[0], addrs[0], RegisteredPoStProof::StackedDRGWindow32GiBV1, - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); // create precommit @@ -137,7 +137,7 @@ fn test_cron_tick() { &vm, addrs[0], robust_addr, - TokenAmount::from(0u32), + TokenAmount::zero(), MinerMethod::PreCommitSector as u64, precommit_params, ); @@ -153,7 +153,7 @@ fn test_cron_tick() { &v, *CRON_ACTOR_ADDR, *STORAGE_POWER_ACTOR_ADDR, - BigInt::zero(), + TokenAmount::zero(), PowerMethod::OnEpochTickEnd as u64, RawBytes::default(), ); @@ -190,7 +190,7 @@ fn test_cron_tick() { &v, *CRON_ACTOR_ADDR, *STORAGE_POWER_ACTOR_ADDR, - BigInt::zero(), + TokenAmount::zero(), PowerMethod::OnEpochTickEnd as u64, RawBytes::default(), ); @@ -207,7 +207,7 @@ fn test_cron_tick() { to: id_addr, method: MinerMethod::OnDeferredCronEvent as u64, from: Some(*STORAGE_POWER_ACTOR_ADDR), - value: Some(BigInt::zero()), + value: Some(TokenAmount::zero()), ..Default::default() }, // expect call to reward to update kpi diff --git a/test_vm/tests/publish_deals_test.rs b/test_vm/tests/publish_deals_test.rs index c34e164b12..4c9b8dcabf 100644 --- a/test_vm/tests/publish_deals_test.rs +++ b/test_vm/tests/publish_deals_test.rs @@ -36,22 +36,22 @@ struct Addrs { const DEAL_LIFETIME: ChainEpoch = 181 * EPOCHS_IN_DAY; fn token_defaults() -> (TokenAmount, TokenAmount, TokenAmount) { - let price_per_epoch = TokenAmount::from(1 << 20); - let provider_collateral = TokenAmount::from(2e18 as u128); - let client_collateral = TokenAmount::from(1e18 as u128); + let price_per_epoch = TokenAmount::from_atto(1 << 20); + let provider_collateral = TokenAmount::from_whole(2); + let client_collateral = TokenAmount::from_whole(1); (price_per_epoch, provider_collateral, client_collateral) } // create miner and client and add collateral fn setup(store: &'_ MemoryBlockstore) -> (VM<'_>, Addrs, ChainEpoch) { let mut v = VM::new_with_singletons(store); - let addrs = create_accounts(&v, 7, TokenAmount::from(10_000e18 as i128)); + let addrs = create_accounts(&v, 7, TokenAmount::from_whole(10_000)); let (worker, client1, client2, not_miner, cheap_client, verifier, verified_client) = (addrs[0], addrs[1], addrs[2], addrs[3], addrs[4], addrs[5], addrs[6]); let owner = worker; // setup provider - let miner_balance = TokenAmount::from(100e18 as i128); + let miner_balance = TokenAmount::from_whole(100); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let maddr = create_miner( @@ -78,7 +78,7 @@ fn setup(store: &'_ MemoryBlockstore) -> (VM<'_>, Addrs, ChainEpoch) { add_client_params, ); - let client_collateral = TokenAmount::from(100e18 as i128); + let client_collateral = TokenAmount::from_whole(100); apply_ok( &v, client1, @@ -104,7 +104,7 @@ fn setup(store: &'_ MemoryBlockstore) -> (VM<'_>, Addrs, ChainEpoch) { verified_client, ); - let miner_collateral = TokenAmount::from(100e18 as i128); + let miner_collateral = TokenAmount::from_whole(100); apply_ok( &v, worker, @@ -256,13 +256,13 @@ fn psd_not_enough_provider_lockup_for_batch() { let (mut v, a, deal_start) = setup(&store); // note different seed, different address - let cheap_worker = create_accounts_seeded(&v, 1, TokenAmount::from(10_000e18 as u128), 444)[0]; + let cheap_worker = create_accounts_seeded(&v, 1, TokenAmount::from_whole(10_000), 444)[0]; let cheap_maddr = create_miner( &mut v, cheap_worker, cheap_worker, fvm_shared::sector::RegisteredPoStProof::StackedDRGWindow32GiBV1, - TokenAmount::from(100e18 as u128), + TokenAmount::from_whole(100), ) .0; // add one deal of collateral to provider's market account diff --git a/test_vm/tests/replica_update_test.rs b/test_vm/tests/replica_update_test.rs index da2579ca2a..f074cd4121 100644 --- a/test_vm/tests/replica_update_test.rs +++ b/test_vm/tests/replica_update_test.rs @@ -25,7 +25,6 @@ use fvm_shared::error::ExitCode; use fvm_shared::sector::SectorSize; use fvm_shared::sector::StoragePower; use fvm_shared::sector::{RegisteredSealProof, SectorNumber}; -use num_traits::sign::Signed; use test_vm::util::{ advance_by_deadline_to_epoch, advance_by_deadline_to_index, advance_to_proving_deadline, apply_code, apply_ok, bf_all, check_sector_active, check_sector_faulty, create_accounts, @@ -165,7 +164,7 @@ fn prove_replica_update_multi_dline() { let store = &MemoryBlockstore::new(); let policy = Policy::default(); let mut v = VM::new_with_singletons(store); - let addrs = create_accounts(&v, 1, TokenAmount::from(1_000_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(1_000_000)); let (worker, owner) = (addrs[0], addrs[0]); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (maddr, _) = create_miner( @@ -173,7 +172,7 @@ fn prove_replica_update_multi_dline() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(100_000e18 as i128), + TokenAmount::from_whole(100_000), ); v = v.with_epoch(1440); // something offset far away from deadline 0 and 1 @@ -304,7 +303,7 @@ fn prove_replica_update_multi_dline() { fn immutable_deadline_failure() { let store = &MemoryBlockstore::new(); let mut v = VM::new_with_singletons(store); - let addrs = create_accounts(&v, 1, TokenAmount::from(100_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(100_000)); let (worker, owner) = (addrs[0], addrs[0]); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (maddr, robust) = create_miner( @@ -312,7 +311,7 @@ fn immutable_deadline_failure() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); // advance to have seal randomness epoch in the past @@ -355,7 +354,7 @@ fn unhealthy_sector_failure() { let store = &MemoryBlockstore::new(); let policy = Policy::default(); let mut v = VM::new_with_singletons(store); - let addrs = create_accounts(&v, 1, TokenAmount::from(100_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(100_000)); let (worker, owner) = (addrs[0], addrs[0]); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (maddr, robust) = create_miner( @@ -363,7 +362,7 @@ fn unhealthy_sector_failure() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); // advance to have seal randomness epoch in the past @@ -410,7 +409,7 @@ fn unhealthy_sector_failure() { fn terminated_sector_failure() { let store = &MemoryBlockstore::new(); let mut v = VM::new_with_singletons(store); - let addrs = create_accounts(&v, 1, TokenAmount::from(100_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(100_000)); let (worker, owner) = (addrs[0], addrs[0]); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (maddr, robust) = create_miner( @@ -418,7 +417,7 @@ fn terminated_sector_failure() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); // advance to have seal randomness epoch in the past @@ -476,7 +475,7 @@ fn bad_batch_size_failure() { let store = &MemoryBlockstore::new(); let policy = Policy::default(); let mut v = VM::new_with_singletons(store); - let addrs = create_accounts(&v, 1, TokenAmount::from(100_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(100_000)); let (worker, owner) = (addrs[0], addrs[0]); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (maddr, robust) = create_miner( @@ -484,7 +483,7 @@ fn bad_batch_size_failure() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); // advance to have seal randomness epoch in the past @@ -577,7 +576,7 @@ fn bad_post_upgrade_dispute() { let store = &MemoryBlockstore::new(); let policy = Policy::default(); let mut v = VM::new_with_singletons(store); - let addrs = create_accounts(&v, 1, TokenAmount::from(100_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(100_000)); let (worker, owner) = (addrs[0], addrs[0]); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (maddr, robust) = create_miner( @@ -585,7 +584,7 @@ fn bad_post_upgrade_dispute() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); // advance to have seal randomness epoch in the past @@ -731,7 +730,7 @@ fn wrong_deadline_index_failure() { let store = &MemoryBlockstore::new(); let policy = Policy::default(); let mut v = VM::new_with_singletons(store); - let addrs = create_accounts(&v, 1, TokenAmount::from(100_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(100_000)); let (worker, owner) = (addrs[0], addrs[0]); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (maddr, robust) = create_miner( @@ -739,7 +738,7 @@ fn wrong_deadline_index_failure() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); // advance to have seal randomness epoch in the past @@ -788,7 +787,7 @@ fn wrong_partition_index_failure() { let store = &MemoryBlockstore::new(); let policy = Policy::default(); let mut v = VM::new_with_singletons(store); - let addrs = create_accounts(&v, 1, TokenAmount::from(100_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(100_000)); let (worker, owner) = (addrs[0], addrs[0]); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (maddr, robust) = create_miner( @@ -796,7 +795,7 @@ fn wrong_partition_index_failure() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); // advance to have seal randomness epoch in the past @@ -845,7 +844,7 @@ fn deal_included_in_multiple_sectors_failure() { let store = &MemoryBlockstore::new(); let policy = Policy::default(); let mut v = VM::new_with_singletons(store); - let addrs = create_accounts(&v, 1, TokenAmount::from(100_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(100_000)); let (worker, owner) = (addrs[0], addrs[0]); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (maddr, _) = create_miner( @@ -853,7 +852,7 @@ fn deal_included_in_multiple_sectors_failure() { owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); // @@ -973,7 +972,7 @@ fn create_miner_and_upgrade_sector( store: &MemoryBlockstore, ) -> (VM, SectorOnChainInfo, Address, Address, u64, u64, SectorSize) { let mut v = VM::new_with_singletons(store); - let addrs = create_accounts(&v, 1, TokenAmount::from(100_000e18 as i128)); + let addrs = create_accounts(&v, 1, TokenAmount::from_whole(100_000)); let (worker, owner) = (addrs[0], addrs[0]); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; let (maddr, robust) = create_miner( @@ -981,7 +980,7 @@ fn create_miner_and_upgrade_sector( owner, worker, seal_proof.registered_window_post_proof().unwrap(), - TokenAmount::from(10_000e18 as i128), + TokenAmount::from_whole(10_000), ); // advance to have seal randomness epoch in the past @@ -1100,7 +1099,7 @@ fn create_sector( (v, d_idx, p_idx) } fn create_deals( - num_deals: u128, + num_deals: u32, v: &VM, client: Address, worker: Address, @@ -1110,14 +1109,14 @@ fn create_deals( } fn create_deals_frac( - num_deals: u128, + num_deals: u32, v: &VM, client: Address, worker: Address, maddr: Address, size_frac: u8, ) -> Vec { - let collateral = TokenAmount::from(3 * num_deals * 1e18 as u128); + let collateral = TokenAmount::from_whole(3 * num_deals as i64); apply_ok( v, client, diff --git a/test_vm/tests/terminate_test.rs b/test_vm/tests/terminate_test.rs index 93f92bf7b3..36ddff82ec 100644 --- a/test_vm/tests/terminate_test.rs +++ b/test_vm/tests/terminate_test.rs @@ -36,12 +36,12 @@ use test_vm::{ExpectInvocation, VM}; fn terminate_sectors() { let store = MemoryBlockstore::new(); let mut v = VM::new_with_singletons(&store); - let addrs = create_accounts(&v, 4, TokenAmount::from(10_000e18 as i128)); + let addrs = create_accounts(&v, 4, TokenAmount::from_whole(10_000)); let (owner, verifier, unverified_client, verified_client) = (addrs[0], addrs[1], addrs[2], addrs[3]); let worker = owner; - let miner_balance = TokenAmount::from(1_000e18 as i128); + let miner_balance = TokenAmount::from_whole(1_000); let sector_number = 100; let sealed_cid = make_sealed_cid(b"s100"); let seal_proof = RegisteredSealProof::StackedDRG32GiBV1P1; @@ -71,7 +71,7 @@ fn terminate_sectors() { ); // add market collateral - let collateral = TokenAmount::from(3e18 as u64); + let collateral = TokenAmount::from_whole(3); apply_ok( &v, unverified_client, @@ -89,7 +89,7 @@ fn terminate_sectors() { verified_client, ); - let miner_collateral = TokenAmount::from(64e18 as u128); + let miner_collateral = TokenAmount::from_whole(64); apply_ok( &v, worker, @@ -324,7 +324,7 @@ fn terminate_sectors() { ); // because of rounding error it's annoying to compute exact withdrawable balance which is 2.9999.. FIL // withdrawing 2 FIL proves out that the claim to 1 FIL per deal (2 deals for this client) is removed at termination - let withdrawal = TokenAmount::from(2e18 as u64); + let withdrawal = TokenAmount::from_whole(2); apply_ok( &v, verified_client, @@ -359,8 +359,8 @@ fn terminate_sectors() { // miner add 64 balance. Each of 3 deals required 2 FIL collateral, so provider collateral should have been // slashed by 6 FIL. Miner's remaining market balance should be 64 - 6 + payment, where payment is for storage // before the slash and should be << 1 FIL. Actual amount withdrawn should be between 58 and 59 FIL. - assert!(TokenAmount::from(58e18 as u128) < value_withdrawn); - assert!(TokenAmount::from(59e18 as u128) > value_withdrawn); + assert!(TokenAmount::from_whole(58) < value_withdrawn); + assert!(TokenAmount::from_whole(59) > value_withdrawn); v.expect_state_invariants( &[invariant_failure_patterns::REWARD_STATE_EPOCH_MISMATCH.to_owned()], diff --git a/test_vm/tests/test_vm_test.rs b/test_vm/tests/test_vm_test.rs index 0c3b0081dc..1e17fe49c3 100644 --- a/test_vm/tests/test_vm_test.rs +++ b/test_vm/tests/test_vm_test.rs @@ -6,6 +6,7 @@ use fvm_shared::address::Address; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; use fvm_shared::METHOD_SEND; +use num_traits::Zero; use test_vm::util::pk_addrs_from; use test_vm::{actor, FIRST_TEST_USER_ADDR, TEST_FAUCET_ADDR, VM}; @@ -17,13 +18,14 @@ fn state_control() { let addr2 = Address::new_id(2222); // set actor - let a1 = actor(*ACCOUNT_ACTOR_CODE_ID, make_builtin(b"a1-head"), 42, TokenAmount::from(10u8)); + let a1 = + actor(*ACCOUNT_ACTOR_CODE_ID, make_builtin(b"a1-head"), 42, TokenAmount::from_atto(10u8)); v.set_actor(addr1, a1.clone()); let out = v.get_actor(addr1).unwrap(); assert_eq!(out, a1); let check = v.checkpoint(); - let a2 = actor(*PAYCH_ACTOR_CODE_ID, make_builtin(b"a2-head"), 88, TokenAmount::from(1u8)); + let a2 = actor(*PAYCH_ACTOR_CODE_ID, make_builtin(b"a2-head"), 88, TokenAmount::from_atto(1u8)); v.set_actor(addr2, a2.clone()); assert_eq!(v.get_actor(addr2).unwrap(), a2); // rollback removes a2 but not a1 @@ -63,53 +65,53 @@ fn test_sent() { v.apply_message( TEST_FAUCET_ADDR, addr1, - TokenAmount::from(42u8), + TokenAmount::from_atto(42u8), METHOD_SEND, RawBytes::default(), ) .unwrap(); let expect_id_addr1 = Address::new_id(FIRST_TEST_USER_ADDR); - assert_account_actor(0, TokenAmount::from(42u8), addr1, &v, expect_id_addr1); + assert_account_actor(0, TokenAmount::from_atto(42u8), addr1, &v, expect_id_addr1); // send from this account actor to another uninit account actor let addr2 = Address::new_bls(&[2; fvm_shared::address::BLS_PUB_LEN]).unwrap(); - v.apply_message(addr1, addr2, TokenAmount::from(41u8), METHOD_SEND, RawBytes::default()) + v.apply_message(addr1, addr2, TokenAmount::from_atto(41u8), METHOD_SEND, RawBytes::default()) .unwrap(); let expect_id_addr2 = Address::new_id(FIRST_TEST_USER_ADDR + 1); - assert_account_actor(0, TokenAmount::from(41u8), addr2, &v, expect_id_addr2); + assert_account_actor(0, TokenAmount::from_atto(41u8), addr2, &v, expect_id_addr2); // send between two initialized account actors - v.apply_message(addr2, addr1, TokenAmount::from(41u8), METHOD_SEND, RawBytes::default()) + v.apply_message(addr2, addr1, TokenAmount::from_atto(41u8), METHOD_SEND, RawBytes::default()) .unwrap(); - assert_account_actor(1, TokenAmount::from(42u8), addr1, &v, expect_id_addr1); - assert_account_actor(1, TokenAmount::from(0u8), addr2, &v, expect_id_addr2); + assert_account_actor(1, TokenAmount::from_atto(42u8), addr1, &v, expect_id_addr1); + assert_account_actor(1, TokenAmount::zero(), addr2, &v, expect_id_addr2); // self send is noop - v.apply_message(addr1, addr1, TokenAmount::from(1u8), METHOD_SEND, RawBytes::default()) + v.apply_message(addr1, addr1, TokenAmount::from_atto(1u8), METHOD_SEND, RawBytes::default()) .unwrap(); - assert_account_actor(2, TokenAmount::from(42u8), addr1, &v, expect_id_addr1); + assert_account_actor(2, TokenAmount::from_atto(42u8), addr1, &v, expect_id_addr1); // fail with insufficient funds let mres = v - .apply_message(addr2, addr1, TokenAmount::from(1u8), METHOD_SEND, RawBytes::default()) + .apply_message(addr2, addr1, TokenAmount::from_atto(1u8), METHOD_SEND, RawBytes::default()) .unwrap(); assert_eq!(ExitCode::SYS_INSUFFICIENT_FUNDS, mres.code); - assert_account_actor(2, TokenAmount::from(42u8), addr1, &v, expect_id_addr1); - assert_account_actor(2, TokenAmount::from(0u8), addr2, &v, expect_id_addr2); + assert_account_actor(2, TokenAmount::from_atto(42u8), addr1, &v, expect_id_addr1); + assert_account_actor(2, TokenAmount::zero(), addr2, &v, expect_id_addr2); // fail to send to non existent id actor (vm doesn't create those on send) let mres = v .apply_message( addr1, Address::new_id(88), - TokenAmount::from(1u8), + TokenAmount::from_atto(1u8), METHOD_SEND, RawBytes::default(), ) .unwrap(); assert_eq!(ExitCode::SYS_INVALID_RECEIVER, mres.code); - assert_account_actor(3, TokenAmount::from(42u8), addr1, &v, expect_id_addr1); - assert_account_actor(2, TokenAmount::from(0u8), addr2, &v, expect_id_addr2); + assert_account_actor(3, TokenAmount::from_atto(42u8), addr1, &v, expect_id_addr1); + assert_account_actor(2, TokenAmount::zero(), addr2, &v, expect_id_addr2); v.assert_state_invariants(); } diff --git a/test_vm/tests/verifreg_remove_datacap_test.rs b/test_vm/tests/verifreg_remove_datacap_test.rs index 93cab2f92d..f6ce95e746 100644 --- a/test_vm/tests/verifreg_remove_datacap_test.rs +++ b/test_vm/tests/verifreg_remove_datacap_test.rs @@ -22,7 +22,7 @@ use test_vm::{ExpectInvocation, TEST_VERIFREG_ROOT_ADDR, VM}; fn remove_datacap_simple_successful_path() { let store = MemoryBlockstore::new(); let v = VM::new_with_singletons(&store); - let addrs = create_accounts(&v, 4, TokenAmount::from(10_000e18 as i128)); + let addrs = create_accounts(&v, 4, TokenAmount::from_whole(10_000)); let (verifier1, verifier2, verified_client) = (addrs[0], addrs[1], addrs[2]); let verifier1_id_addr = v.normalize_address(&verifier1).unwrap();