From 5d71765b5e2a6a5f288d59a0a77e5190649df5e4 Mon Sep 17 00:00:00 2001 From: OzzyHelper <346962152+OzzyHelper@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:26:07 +0000 Subject: [PATCH] fix(usdfc): keep MockUSDFC distribution within the 1M token supply Startup funding granted 100k tokens to each of the three users and 200k to every active PDP SP. With four or more SPs the schedule asked the deployer to transfer up to 1.3M tokens from a 1M supply, so the last transfers failed with an insufficient balance. Derive the per-SP grant from the remaining supply instead: three users keep their 100k each, SPs share what is left up to the nominal 200k. The default two-SP topology is unchanged; four SPs get 175k and the maximum five get 140k, so the plan always fits. Also: - plan balance checks, transfers, and verification from one function so they cannot drift apart - drop the duplicated supply constant from usdfc_deploy_step and pass INITIAL_SUPPLY explicitly to the forge script from the shared constant - reject configurations in Config::validate that cannot fund the allocations --- src/commands/start/usdfc_deploy/deployment.rs | 61 ++++++++++--- .../start/usdfc_deploy/usdfc_deploy_step.rs | 3 - src/commands/start/usdfc_funding/constants.rs | 72 ++++++++++++++- .../start/usdfc_funding/usdfc_funding_step.rs | 51 ++--------- src/config.rs | 58 +++++++++++++ src/constants.rs | 87 ++++++++++++++++++- 6 files changed, 272 insertions(+), 60 deletions(-) diff --git a/src/commands/start/usdfc_deploy/deployment.rs b/src/commands/start/usdfc_deploy/deployment.rs index fe1d9ef1..16f6efd0 100644 --- a/src/commands/start/usdfc_deploy/deployment.rs +++ b/src/commands/start/usdfc_deploy/deployment.rs @@ -13,6 +13,28 @@ use std::error::Error; use std::path::PathBuf; use tracing::{error, info}; +/// Build the forge deploy command. +/// +/// `INITIAL_SUPPLY` is passed explicitly from the Rust constant so the deployed +/// token always matches the supply that funding allocates against. Relying on +/// the Solidity script's fallback default would let the two values drift apart. +fn mock_usdfc_deploy_command(lotus_rpc_url: &str, private_key: &str) -> String { + format!( + "cd /workspace && \ + INITIAL_SUPPLY={} \ + forge script script/Deploy.s.sol:DeployMockUSDFC \ + --rpc-url {} \ + --private-key {} \ + --broadcast \ + --slow \ + --gas-estimate-multiplier 10000 \ + -vv", + crate::constants::MOCK_USDFC_INITIAL_SUPPLY, + lotus_rpc_url, + private_key + ) +} + /// Deploy MockUSDFC using the Foundry project pub fn deploy_mock_usdfc_foundry( context: &SetupContext, @@ -31,17 +53,7 @@ pub fn deploy_mock_usdfc_foundry( // Deploy using forge script with explicit gas limit for FEVM info!("Executing deployment script..."); - let deploy_cmd = format!( - "cd /workspace && \ - forge script script/Deploy.s.sol:DeployMockUSDFC \ - --rpc-url {} \ - --private-key {} \ - --broadcast \ - --slow \ - --gas-estimate-multiplier 10000 \ - -vv", - lotus_rpc_url, private_key - ); + let deploy_cmd = mock_usdfc_deploy_command(lotus_rpc_url, private_key); let key = format!("usdfc_deploy_{}", run_id); let contract_mount = bind_mount(&contract_dir, "/workspace")?; @@ -143,10 +155,33 @@ pub fn perform_token_deployment( info!("✓ MockUSDFC token deployed successfully!"); info!("Token Address: {}", mock_usdfc_address); info!( - "Initial Supply: {} tokens", - super::usdfc_deploy_step::MOCK_USDFC_INITIAL_SUPPLY + "Initial Supply: {} tokens (base units: {})", + crate::constants::MOCK_USDFC_INITIAL_SUPPLY_TOKENS, + crate::constants::MOCK_USDFC_INITIAL_SUPPLY ); info!("Decimals: 18"); Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn deploy_command_sets_initial_supply_from_shared_constant() { + let cmd = mock_usdfc_deploy_command("http://localhost:1234/rpc/v1", "0xabc"); + + assert!( + cmd.contains(&format!( + "INITIAL_SUPPLY={}", + crate::constants::MOCK_USDFC_INITIAL_SUPPLY + )), + "command must pass the shared supply constant: {}", + cmd + ); + assert!(cmd.contains("script/Deploy.s.sol:DeployMockUSDFC")); + assert!(cmd.contains("--rpc-url http://localhost:1234/rpc/v1")); + assert!(cmd.contains("--private-key 0xabc")); + } +} diff --git a/src/commands/start/usdfc_deploy/usdfc_deploy_step.rs b/src/commands/start/usdfc_deploy/usdfc_deploy_step.rs index 5774ff98..c77b1b0d 100644 --- a/src/commands/start/usdfc_deploy/usdfc_deploy_step.rs +++ b/src/commands/start/usdfc_deploy/usdfc_deploy_step.rs @@ -12,9 +12,6 @@ use std::error::Error; use std::path::PathBuf; use tracing::info; -// Token configuration -pub const MOCK_USDFC_INITIAL_SUPPLY: &str = "1000000000000000000000000"; // 1 million tokens (18 decimals) - /// Step for deploying MockUSDFC token pub struct USDFCDeployStep { volumes_dir: PathBuf, diff --git a/src/commands/start/usdfc_funding/constants.rs b/src/commands/start/usdfc_funding/constants.rs index 49e91124..aa2726b7 100644 --- a/src/commands/start/usdfc_funding/constants.rs +++ b/src/commands/start/usdfc_funding/constants.rs @@ -1,7 +1,10 @@ -//! Constants for MockUSDFC token distribution. +//! Constants and allocation planning for MockUSDFC token distribution. //! //! This module defines constants used in the MockUSDFC funding process. +use crate::constants::{ + mock_usdfc_sp_allocation_tokens, MOCK_USDFC_USER_ALLOCATION_TOKENS, USER_ACCOUNT_COUNT, +}; use ethers_core::types::U256; /// Convert token amount to wei (multiply by 10^18) @@ -9,5 +12,72 @@ pub fn token_amount_to_wei(tokens: u64) -> U256 { U256::from(tokens) * U256::exp10(18) } +/// Build the startup allocation plan as `(account name, whole tokens)` pairs. +/// +/// Balance checks, transfers, and post-transfer verification all derive from +/// this plan so they cannot drift apart. The plan never exceeds the MockUSDFC +/// initial supply; see [`mock_usdfc_sp_allocation_tokens`]. +pub fn distribution_plan(active_pdp_sp_count: usize) -> Vec<(String, u64)> { + let mut plan = Vec::with_capacity(USER_ACCOUNT_COUNT + active_pdp_sp_count); + + for user_num in 1..=USER_ACCOUNT_COUNT { + plan.push(( + format!("USER_{}", user_num), + MOCK_USDFC_USER_ALLOCATION_TOKENS, + )); + } + + let sp_amount = mock_usdfc_sp_allocation_tokens(active_pdp_sp_count); + for sp_num in 1..=active_pdp_sp_count { + plan.push((format!("PDP_SP_{}", sp_num), sp_amount)); + } + + plan +} + /// Transaction confirmation wait time in seconds pub const TRANSACTION_CONFIRMATION_WAIT_SECS: u64 = 5; + +#[cfg(test)] +mod tests { + use super::*; + use crate::constants::{ + mock_usdfc_distribution_total_tokens, MAX_PDP_SP_COUNT, MOCK_USDFC_INITIAL_SUPPLY_TOKENS, + MOCK_USDFC_SP_ALLOCATION_TOKENS, + }; + + #[test] + fn plan_lists_every_user_and_active_sp() { + let plan = distribution_plan(2); + let names: Vec<&str> = plan.iter().map(|(name, _)| name.as_str()).collect(); + assert_eq!( + names, + ["USER_1", "USER_2", "USER_3", "PDP_SP_1", "PDP_SP_2"] + ); + } + + #[test] + fn plan_ignores_inactive_sps() { + let plan = distribution_plan(0); + assert_eq!(plan.len(), USER_ACCOUNT_COUNT); + assert!(plan.iter().all(|(name, _)| name.starts_with("USER_"))); + } + + #[test] + fn plan_keeps_default_allocations() { + let plan = distribution_plan(2); + assert_eq!(plan[0].1, 100_000); + assert_eq!(plan[3].1, MOCK_USDFC_SP_ALLOCATION_TOKENS); + } + + #[test] + fn plan_fits_within_supply_at_max_sp_count() { + let plan = distribution_plan(MAX_PDP_SP_COUNT); + let total: u64 = plan.iter().map(|(_, tokens)| tokens).sum(); + assert!(total <= MOCK_USDFC_INITIAL_SUPPLY_TOKENS); + assert_eq!( + total, + mock_usdfc_distribution_total_tokens(MAX_PDP_SP_COUNT) + ); + } +} diff --git a/src/commands/start/usdfc_funding/usdfc_funding_step.rs b/src/commands/start/usdfc_funding/usdfc_funding_step.rs index 299e0f1c..3d6acb59 100644 --- a/src/commands/start/usdfc_funding/usdfc_funding_step.rs +++ b/src/commands/start/usdfc_funding/usdfc_funding_step.rs @@ -3,12 +3,13 @@ //! This module contains the main Step implementation for distributing MockUSDFC tokens //! to user and service provider addresses. -use super::constants::{token_amount_to_wei, TRANSACTION_CONFIRMATION_WAIT_SECS}; +use super::constants::{ + distribution_plan, token_amount_to_wei, TRANSACTION_CONFIRMATION_WAIT_SECS, +}; use super::funding_operations::{self, check_mock_usdfc_balance, transfer_mock_usdfc}; use super::key_operations::get_user_private_key; use crate::commands::start::step::{SetupContext, Step}; use crate::commands::start::usdfc_funding::key_operations::get_user_eth_address; -use crate::constants::USER_ACCOUNT_COUNT; use crate::docker::containers::lotus_container_name; use crate::docker::core::container_is_running; use std::error::Error; @@ -38,20 +39,8 @@ impl USDFCFundingStep { mockusdfc_address: &str, lotus_rpc_url: &str, ) -> Result> { - // Build list of accounts to check (same as what will be transferred) - let mut accounts_to_check = Vec::new(); - - // Add user accounts (base-1 numbering) - for user_num in 1..=USER_ACCOUNT_COUNT { - let account_name = format!("USER_{}", user_num); - accounts_to_check.push((account_name, 100_000u64)); - } - - // Add only active PDP SPs (base-1 numbering) - for sp_num in 1..=self.active_pdp_sp_count { - let account_name = format!("PDP_SP_{}", sp_num); - accounts_to_check.push((account_name, 200_000u64)); - } + // Build list of accounts to check (same plan as what will be transferred) + let accounts_to_check = distribution_plan(self.active_pdp_sp_count); // Check balances for all accounts for (account_name, amount_tokens) in accounts_to_check.iter() { @@ -247,23 +236,11 @@ impl Step for USDFCFundingStep { // Get deployer private key let deployer_private_key = get_user_private_key("DEPLOYER_MOCKUSDFC")?; - // Build list of transfers + // Build list of transfers from the shared allocation plan let mut token_transfers = Vec::new(); - // Add user accounts (base-1 numbering) - for user_num in 1..=USER_ACCOUNT_COUNT { - let account_name = format!("USER_{}", user_num); + for (account_name, amount_tokens) in distribution_plan(self.active_pdp_sp_count) { let eth_address = get_user_eth_address(&account_name)?; - let amount_tokens = 100_000u64; - let amount_wei = token_amount_to_wei(amount_tokens); - token_transfers.push((account_name, eth_address, amount_wei, amount_tokens)); - } - - // Add only active PDP SPs (base-1 numbering) - for sp_num in 1..=self.active_pdp_sp_count { - let account_name = format!("PDP_SP_{}", sp_num); - let eth_address = get_user_eth_address(&account_name)?; - let amount_tokens = 200_000u64; let amount_wei = token_amount_to_wei(amount_tokens); token_transfers.push((account_name, eth_address, amount_wei, amount_tokens)); } @@ -289,18 +266,8 @@ impl Step for USDFCFundingStep { // Get Lotus RPC URL let lotus_rpc_url = get_lotus_rpc_url(context)?; - // Build list of accounts to verify - let mut accounts_to_verify = Vec::new(); - - for user_num in 1..=USER_ACCOUNT_COUNT { - let account_name = format!("USER_{}", user_num); - accounts_to_verify.push((account_name, 100_000u64)); - } - - for sp_num in 1..=self.active_pdp_sp_count { - let account_name = format!("PDP_SP_{}", sp_num); - accounts_to_verify.push((account_name, 200_000u64)); - } + // Build list of accounts to verify (same plan as the transfers) + let accounts_to_verify = distribution_plan(self.active_pdp_sp_count); for (account_name, amount_tokens) in accounts_to_verify.iter() { let eth_address = get_user_eth_address(account_name)?; diff --git a/src/config.rs b/src/config.rs index 3101dd6a..c93c47bd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -311,6 +311,7 @@ impl Config { /// /// Ensures that: /// - ENDORSED_PDP_SP_COUNT <= APPROVED_PDP_SP_COUNT <= ACTIVE_PDP_SP_COUNT <= MAX_PDP_SP_COUNT + /// - the MockUSDFC startup distribution fits within the initial supply pub fn validate(&self) -> Result<(), String> { const MAX_PDP_SP_COUNT: usize = crate::constants::MAX_PDP_SP_COUNT; @@ -335,6 +336,30 @@ impl Config { )); } + // Funding allocates a fixed amount per user and splits what remains + // between the active PDP SPs. Reject topologies where either group can + // no longer be funded from the initial supply. + let user_allocation_total = crate::constants::USER_ACCOUNT_COUNT as u64 + * crate::constants::MOCK_USDFC_USER_ALLOCATION_TOKENS; + if user_allocation_total > crate::constants::MOCK_USDFC_INITIAL_SUPPLY_TOKENS { + return Err(format!( + "USER_ACCOUNT_COUNT ({}) * MockUSDFC user allocation ({} tokens) exceeds the initial supply ({} tokens)", + crate::constants::USER_ACCOUNT_COUNT, + crate::constants::MOCK_USDFC_USER_ALLOCATION_TOKENS, + crate::constants::MOCK_USDFC_INITIAL_SUPPLY_TOKENS + )); + } + + if self.active_pdp_sp_count > 0 + && crate::constants::mock_usdfc_sp_allocation_tokens(self.active_pdp_sp_count) == 0 + { + return Err(format!( + "active_pdp_sp_count ({}) leaves no MockUSDFC for PDP SPs after user allocations from a {} token supply", + self.active_pdp_sp_count, + crate::constants::MOCK_USDFC_INITIAL_SUPPLY_TOKENS + )); + } + Ok(()) } } @@ -492,4 +517,37 @@ mod tests { assert!(serialized.contains("pdp")); assert!(serialized.contains("https://github.com/FilOzone/pdp.git")); } + + fn config_with_active_sps(active: usize) -> Config { + Config { + active_pdp_sp_count: active, + approved_pdp_sp_count: active, + endorsed_pdp_sp_count: active.min(1), + ..Default::default() + } + } + + #[test] + fn validate_accepts_every_supported_sp_count() { + for active in 0..=crate::constants::MAX_PDP_SP_COUNT { + let config = config_with_active_sps(active); + assert!( + config.validate().is_ok(), + "{} active PDP SPs should be fundable: {:?}", + active, + config.validate() + ); + } + } + + #[test] + fn validate_rejects_more_sps_than_supported() { + let config = config_with_active_sps(crate::constants::MAX_PDP_SP_COUNT + 1); + let err = config.validate().unwrap_err(); + assert!( + err.contains("MAX_PDP_SP_COUNT"), + "unexpected error: {}", + err + ); + } } diff --git a/src/constants.rs b/src/constants.rs index 05a7bdfd..6a2fd362 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -100,11 +100,48 @@ pub const SERVICE_NAME: &str = "FOC DevNet Warm Storage"; pub const SERVICE_DESCRIPTION: &str = "Warm storage service for FOC local development network"; /// Token parameters -pub const MOCK_USDFC_INITIAL_SUPPLY: &str = "1000000000000000000000000"; // 1,000,000 tokens +/// +/// The whole-token value is the authoritative supply; [`MOCK_USDFC_INITIAL_SUPPLY`] +/// expresses the same amount in base units for callers that need a decimal string. +pub const MOCK_USDFC_INITIAL_SUPPLY_TOKENS: u64 = 1_000_000; +pub const MOCK_USDFC_INITIAL_SUPPLY: &str = "1000000000000000000000000"; // 1,000,000 tokens * 10^18 pub const MOCK_USDFC_DECIMALS: u8 = 18; pub const MOCK_USDFC_SYMBOL: &str = "USDFC"; pub const MOCK_USDFC_NAME: &str = "Mock USDFC"; +/// MockUSDFC granted to each user account at startup. +pub const MOCK_USDFC_USER_ALLOCATION_TOKENS: u64 = 100_000; + +/// Nominal MockUSDFC grant per active PDP SP. +/// +/// This is an upper bound: when the configured SP count would push the total +/// distribution past the initial supply, each SP receives an equal share of +/// what remains after the user allocations (see +/// [`mock_usdfc_sp_allocation_tokens`]). +pub const MOCK_USDFC_SP_ALLOCATION_TOKENS: u64 = 200_000; + +/// Per-SP MockUSDFC grant that keeps the whole distribution within +/// [`MOCK_USDFC_INITIAL_SUPPLY_TOKENS`]. +/// +/// With the default two active PDP SPs every SP gets the nominal +/// [`MOCK_USDFC_SP_ALLOCATION_TOKENS`]. With more SPs the remainder of the +/// supply is split evenly, so scheduling `MAX_PDP_SP_COUNT` providers can never +/// ask the deployer to transfer more tokens than it holds. +pub fn mock_usdfc_sp_allocation_tokens(active_pdp_sp_count: usize) -> u64 { + let user_total = USER_ACCOUNT_COUNT as u64 * MOCK_USDFC_USER_ALLOCATION_TOKENS; + let remaining = MOCK_USDFC_INITIAL_SUPPLY_TOKENS.saturating_sub(user_total); + if active_pdp_sp_count == 0 { + return 0; + } + (remaining / active_pdp_sp_count as u64).min(MOCK_USDFC_SP_ALLOCATION_TOKENS) +} + +/// Total MockUSDFC distributed for a given number of active PDP SPs. +pub fn mock_usdfc_distribution_total_tokens(active_pdp_sp_count: usize) -> u64 { + USER_ACCOUNT_COUNT as u64 * MOCK_USDFC_USER_ALLOCATION_TOKENS + + active_pdp_sp_count as u64 * mock_usdfc_sp_allocation_tokens(active_pdp_sp_count) +} + /// Network configuration pub const LOCAL_NETWORK_CHAIN_ID: u64 = 31415926; // Local network chain ID @@ -150,6 +187,54 @@ mod tests { } } + #[test] + fn test_initial_supply_string_matches_whole_token_constant() { + let expected = MOCK_USDFC_INITIAL_SUPPLY_TOKENS.to_string() + + &"0".repeat(MOCK_USDFC_DECIMALS as usize); + assert_eq!(MOCK_USDFC_INITIAL_SUPPLY, expected); + } + + #[test] + fn test_sp_allocation_uses_nominal_rate_when_supply_allows() { + // Default topology: 3 users + 2 SPs fits comfortably within the supply. + assert_eq!(mock_usdfc_sp_allocation_tokens(0), 0); + for sp_count in 1..=3 { + assert_eq!( + mock_usdfc_sp_allocation_tokens(sp_count), + MOCK_USDFC_SP_ALLOCATION_TOKENS + ); + } + } + + #[test] + fn test_sp_allocation_shrinks_to_fit_the_supply() { + // 3 users * 100k leaves 700k for SPs: four SPs get 175k, five get 140k. + assert_eq!(mock_usdfc_sp_allocation_tokens(4), 175_000); + assert_eq!(mock_usdfc_sp_allocation_tokens(MAX_PDP_SP_COUNT), 140_000); + } + + #[test] + fn test_distribution_never_exceeds_initial_supply() { + for sp_count in 0..=MAX_PDP_SP_COUNT { + let total = mock_usdfc_distribution_total_tokens(sp_count); + assert!( + total <= MOCK_USDFC_INITIAL_SUPPLY_TOKENS, + "{} SPs distribute {} tokens, supply is {}", + sp_count, + total, + MOCK_USDFC_INITIAL_SUPPLY_TOKENS + ); + } + } + + #[test] + fn test_distribution_with_default_topology_keeps_existing_grants() { + assert_eq!( + mock_usdfc_distribution_total_tokens(2), + 3 * MOCK_USDFC_USER_ALLOCATION_TOKENS + 2 * 200_000 + ); + } + #[test] fn test_is_foc_devnet_image_rejects_unrelated() { assert!(!is_foc_devnet_image("foc-observer-foc-observer"));