From ab94b5e4d4214a44190bddb1babdea929b0e3d9b Mon Sep 17 00:00:00 2001 From: Mike MacCana Date: Tue, 10 Nov 2026 15:26:09 +0000 Subject: [PATCH] Say "minor units", not "base units", for the smallest token denomination The solana-finance plugin's rule: an amount's smallest denomination, the raw integer a program works in, is a minor unit (cent, lamport); do not say "base units". In finance "base" already names the first asset of a pair, as in GOLD/USD, so "base units" read as units of the base asset. Doc comments, code comments, READMEs and CHANGELOGs across lending, managed fund, perpetual futures, token swap and betting market now say "minor unit(s)", including "sub-minor-unit" and phrases split across a line break. The order book README, where "base units" meant the BASE token's minor units, now says "BASE minor units" and "QUOTE minor units". "Base" where it names the base asset of a pair is unchanged. Only comments and documentation change; no code does. Claude-Session: https://claude.ai/code/session_01GZHin6BQpAqf7j2ucSZWkx --- finance/betting-market/kani-proofs/src/lib.rs | 4 +- finance/lending/anchor-v1/CHANGELOG.md | 2 +- finance/lending/anchor-v1/README.md | 2 +- .../anchor-v1/programs/lending/src/math.rs | 6 +-- .../programs/lending/src/state/reserve.rs | 2 +- .../lending/tests/test_deposit_redeem.rs | 4 +- .../lending/tests/test_liquidation.rs | 2 +- finance/lending/anchor/CHANGELOG.md | 2 +- finance/lending/anchor/README.md | 2 +- .../anchor/programs/lending/src/math.rs | 6 +-- .../programs/lending/src/state/reserve.rs | 2 +- .../lending/tests/test_deposit_redeem.rs | 4 +- .../lending/tests/test_liquidation.rs | 2 +- finance/lending/quasar/src/math.rs | 4 +- finance/lending/quasar/src/tests.rs | 4 +- .../mock-swap-router/src/state/asset_rate.rs | 2 +- .../mock-swap-router/src/state/asset_rate.rs | 2 +- .../quasar/mock-swap-router/src/state/mod.rs | 2 +- finance/order-book/anchor-v1/README.md | 8 ++-- finance/order-book/anchor/README.md | 8 ++-- .../perpetual-futures/anchor-v1/CHANGELOG.md | 20 +++++----- finance/perpetual-futures/anchor-v1/README.md | 8 ++-- .../src/instructions/add_liquidity.rs | 2 +- .../src/instructions/remove_liquidity.rs | 2 +- .../src/instructions/shared.rs | 16 ++++---- .../perpetual-futures/src/state/pool.rs | 6 +-- .../perpetual-futures/src/state/position.rs | 4 +- .../tests/test_perpetual_futures.rs | 40 +++++++++---------- finance/perpetual-futures/anchor/CHANGELOG.md | 20 +++++----- finance/perpetual-futures/anchor/README.md | 8 ++-- .../src/instructions/add_liquidity.rs | 2 +- .../src/instructions/remove_liquidity.rs | 2 +- .../src/instructions/shared.rs | 16 ++++---- .../perpetual-futures/src/state/pool.rs | 6 +-- .../perpetual-futures/src/state/position.rs | 4 +- .../tests/test_perpetual_futures.rs | 40 +++++++++---------- finance/perpetual-futures/quasar/CHANGELOG.md | 20 +++++----- finance/perpetual-futures/quasar/README.md | 2 +- .../quasar/src/instructions/add_liquidity.rs | 2 +- .../src/instructions/remove_liquidity.rs | 2 +- .../quasar/src/instructions/shared.rs | 12 +++--- finance/perpetual-futures/quasar/src/state.rs | 2 +- finance/perpetual-futures/quasar/src/tests.rs | 38 +++++++++--------- finance/token-swap/README.md | 16 ++++---- .../src/instructions/deposit_liquidity.rs | 6 +-- .../src/instructions/swap_tokens.rs | 4 +- .../src/instructions/withdraw_liquidity.rs | 2 +- .../programs/token-swap/tests/test_swap.rs | 6 +-- .../src/instructions/deposit_liquidity.rs | 6 +-- .../src/instructions/swap_tokens.rs | 4 +- .../src/instructions/withdraw_liquidity.rs | 2 +- .../programs/token-swap/tests/test_swap.rs | 6 +-- finance/token-swap/kani-proofs/src/lib.rs | 4 +- 53 files changed, 200 insertions(+), 200 deletions(-) diff --git a/finance/betting-market/kani-proofs/src/lib.rs b/finance/betting-market/kani-proofs/src/lib.rs index 6155222e..bb96b42a 100644 --- a/finance/betting-market/kani-proofs/src/lib.rs +++ b/finance/betting-market/kani-proofs/src/lib.rs @@ -60,7 +60,7 @@ pub fn winnings(stake: u64, distributable: u64, winning_pool: u64) -> Option= exact); assert!((fee as u128) * BPS_DENOMINATOR < exact + BPS_DENOMINATOR); diff --git a/finance/lending/anchor-v1/CHANGELOG.md b/finance/lending/anchor-v1/CHANGELOG.md index 71e71ae7..6e55563b 100644 --- a/finance/lending/anchor-v1/CHANGELOG.md +++ b/finance/lending/anchor-v1/CHANGELOG.md @@ -162,7 +162,7 @@ rather than bootstrapping it. Pricing shares against tracked `total_liquidity` stopped a vault donation, but `total_liquidity` includes interest owed on borrows. A lone supplier with one -share could borrow a single base unit from their own reserve, let one second of +share could borrow a single minor unit from their own reserve, let one second of interest round the debt up to two, and then ratchet the share price up about half again per round by depositing the most that still minted one share and redeeming it, leaving the rounding with their own share. On the default rate diff --git a/finance/lending/anchor-v1/README.md b/finance/lending/anchor-v1/README.md index aa5b1df4..353b15ec 100644 --- a/finance/lending/anchor-v1/README.md +++ b/finance/lending/anchor-v1/README.md @@ -63,7 +63,7 @@ so a token donated directly to the vault cannot inflate the rate. That alone does not close the empty-pool inflation attack, because `total_liquidity` also counts interest owed on borrows, and a supplier can -borrow. A lone supplier holding one share borrows a single base unit from their +borrow. A lone supplier holding one share borrows a single minor unit from their own reserve; debt rounds up, so a second later it reads as two, and the share is worth two units without anything having been minted. Deposits and redemptions round in the pool's favor, so depositing the most that still mints one share diff --git a/finance/lending/anchor-v1/programs/lending/src/math.rs b/finance/lending/anchor-v1/programs/lending/src/math.rs index 4ce26e2d..f2f00bd3 100644 --- a/finance/lending/anchor-v1/programs/lending/src/math.rs +++ b/finance/lending/anchor-v1/programs/lending/src/math.rs @@ -5,7 +5,7 @@ use crate::errors::LendingError; /// Which way to break ties when a division truncates. Deposits/redeems and /// collateral valuations round the user's favourable quantity DOWN; debt and -/// program-owed quantities round UP. The program never loses a base unit to +/// program-owed quantities round UP. The program never loses a minor unit to /// rounding, so dust cannot be extracted by repeated round-trips. #[derive(Clone, Copy, PartialEq, Eq)] pub enum Rounding { @@ -50,7 +50,7 @@ fn mul_div(a: u128, b: u128, denominator: u128, rounding: Rounding) -> Result Result Result 0, PerpError::PoolInsolvent); diff --git a/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/src/instructions/shared.rs b/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/src/instructions/shared.rs index 7cc78392..71848bd6 100644 --- a/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/src/instructions/shared.rs +++ b/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/src/instructions/shared.rs @@ -8,7 +8,7 @@ use crate::errors::PerpError; use crate::state::{Pool, Position, Side}; /// Result of removing a position from the pool's aggregates. All figures are in -/// collateral base units; `equity` is what the trader's position is worth +/// collateral minor units; `equity` is what the trader's position is worth /// before any close or liquidation fee. pub struct Settlement { pub profit_and_loss: i128, @@ -118,7 +118,7 @@ pub fn scale_size(size: u64, entry_price: u64) -> Result { .ok_or(PerpError::MathOverflow.into()) } -/// Signed profit/loss of one position at `price`, in collateral base units. +/// Signed profit/loss of one position at `price`, in collateral minor units. /// Longs profit when price rises, shorts when it falls. pub fn position_pnl(side: Side, size: u64, entry_price: u64, price: u64) -> Result { let size = size as i128; @@ -133,7 +133,7 @@ pub fn position_pnl(side: Side, size: u64, entry_price: u64, price: u64) -> Resu // Multiply before dividing to keep precision; `entry > 0` is guaranteed. // Floored toward negative infinity rather than truncated toward zero, so a - // loss that is not a whole base unit rounds up to the next one and a + // loss that is not a whole minor unit rounds up to the next one and a // profit rounds down: the trader's result is always the lower of the two. size.checked_mul(price_change) .ok_or(PerpError::MathOverflow)? @@ -141,7 +141,7 @@ pub fn position_pnl(side: Side, size: u64, entry_price: u64, price: u64) -> Resu .ok_or(PerpError::MathOverflow.into()) } -/// Which way a valuation's fractional base unit goes. +/// Which way a valuation's fractional minor unit goes. #[derive(Clone, Copy, PartialEq, Eq)] pub enum Rounding { Down, @@ -170,7 +170,7 @@ fn divide_rounding(numerator: i128, denominator: i128, rounding: Rounding) -> Re /// Positive means traders are collectively up (and the pool is down). /// /// `rounding` is the direction of the result: `Up` rounds the long side's -/// value up and the short side's value down, so a fraction of a base unit on +/// value up and the short side's value down, so a fraction of a minor unit on /// either side counts as owed to traders; `Down` does the opposite. Callers /// choose the direction that goes against whoever is being priced. /// @@ -252,7 +252,7 @@ pub fn liquidity_provider_aum(pool: &Pool, price: u64, rounding: Rounding) -> Re /// paid at most the pool's backing, and is never refused; when the liability is /// the larger, every other winner's fraction is unchanged. pub fn haircut_ratio(pool: &Pool, price: u64, closing_profit: i128) -> Result { - // Rounded up, so a fraction of a base unit counts as owed and can only + // Rounded up, so a fraction of a minor unit counts as owed and can only // lower `h`: no winner is paid more than the backing allows. let liability: u128 = traders_unrealized_pnl(pool, price, Rounding::Up)? .max(closing_profit) @@ -315,10 +315,10 @@ pub fn credit_fee(pool: &mut Pool, fee: u64) -> Result<()> { Ok(()) } -/// Funding a position owes since it opened, in collateral base units. Positive +/// Funding a position owes since it opened, in collateral minor units. Positive /// means the trader pays the pool; negative means the pool pays the trader. /// -/// Rounded up, toward positive infinity, so a fraction of a base unit always +/// Rounded up, toward positive infinity, so a fraction of a minor unit always /// goes to the pool: funding the trader pays rounds up to the next whole unit /// and funding the trader receives rounds down. The side's sign is applied /// before dividing, so a short is rounded the same way as a long. diff --git a/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/src/state/pool.rs b/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/src/state/pool.rs index 11eb751c..67604b2b 100644 --- a/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/src/state/pool.rs +++ b/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/src/state/pool.rs @@ -4,7 +4,7 @@ use anchor_lang::prelude::*; /// oracle feed. Liquidity providers fund the pool and are the counterparty to /// every trader; the pool absorbs trader profit and loss. /// -/// Money fields are raw base units of the collateral token. The pool never +/// Money fields are raw minor units of the collateral token. The pool never /// assumes decimals — `transfer_checked` carries them through every CPI. #[account] #[derive(InitSpace)] @@ -33,7 +33,7 @@ pub struct Pool { pub lp_mint: Pubkey, - /// Liquidity-provider-owned assets, in collateral base units. Grows with + /// Liquidity-provider-owned assets, in collateral minor units. Grows with /// deposits, trader losses, fees-to-LPs; shrinks with withdrawals and /// trader profits. Trader collateral is tracked separately in /// `total_collateral` and is not part of this figure. Together with @@ -57,7 +57,7 @@ pub struct Pool { pub insurance_fund: u64, /// Aggregate long open interest (sum of position `size`), in collateral - /// base units of notional. + /// minor units of notional. pub long_size: u128, pub short_size: u128, diff --git a/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/src/state/position.rs b/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/src/state/position.rs index 7dbd9d44..ce1ede7f 100644 --- a/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/src/state/position.rs +++ b/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/src/state/position.rs @@ -28,11 +28,11 @@ pub struct Position { pub side: Side, - /// Collateral the trader posted, in collateral base units. Part of the + /// Collateral the trader posted, in collateral minor units. Part of the /// pool's `total_collateral` while the position is open. pub collateral: u64, - /// Notional position size, in collateral base units. `size / collateral` is + /// Notional position size, in collateral minor units. `size / collateral` is /// the leverage. pub size: u64, diff --git a/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/tests/test_perpetual_futures.rs b/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/tests/test_perpetual_futures.rs index fddda692..e6b3f432 100644 --- a/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/tests/test_perpetual_futures.rs +++ b/finance/perpetual-futures/anchor-v1/programs/perpetual-futures/tests/test_perpetual_futures.rs @@ -41,7 +41,7 @@ const HAIRCUT_PRECISION: u64 = 1_000_000_000; // carried in, so a position's funding is `size * rate * seconds / this`. const FUNDING_PRECISION: u64 = 1_000_000_000; // Collateral token has 6 decimals (like USDC), so one whole unit is 1_000_000 -// base units. +// minor units. const ONE_USDC: u64 = 1_000_000; const DECIMALS: u8 = 6; @@ -711,7 +711,7 @@ fn test_add_liquidity_first_deposit_withholds_minimum() { assert_eq!(shares, deposit - 1_000); } -/// The first deposit must exceed the 1_000 withheld minimum: one base unit +/// The first deposit must exceed the 1_000 withheld minimum: one minor unit /// short is refused, and one over mints a single share. #[test] fn test_first_deposit_below_minimum_fails() { @@ -1832,12 +1832,12 @@ fn test_remove_liquidity_capped_at_liquidity() { market.assert_vault_matches_ledger(); } /// `add_liquidity` values the pool rounding up. A $5,000 short entered at -/// $100 and marked at $99.99999999 is worth 4,999,999,999.5 base units, so -/// traders are up half a base unit. Rounded against the depositor that half +/// $100 and marked at $99.99999999 is worth 4,999,999,999.5 minor units, so +/// traders are up half a minor unit. Rounded against the depositor that half /// counts as nothing owed, assets-under-management stays at the pool's /// 100,000 USDC of liquidity, and a 100,000 USDC deposit is minted exactly /// 100,000 USDC of shares. Valuing the short at 4,999,999,999 would read the -/// pool one base unit low and mint one share more. +/// pool one minor unit low and mint one share more. #[test] fn test_add_liquidity_values_the_pool_rounding_up() { let mut market = Market::default_market(); @@ -1870,8 +1870,8 @@ fn test_add_liquidity_values_the_pool_rounding_up() { } /// `remove_liquidity` values the pool rounding down. A $5,000 long entered at -/// $100 and marked at $100.00000001 is worth 5,000,000,000.5 base units, so -/// traders are up half a base unit. Rounded against the withdrawing provider +/// $100 and marked at $100.00000001 is worth 5,000,000,000.5 minor units, so +/// traders are up half a minor unit. Rounded against the withdrawing provider /// that half counts as a whole unit owed, assets-under-management reads /// 99,999,999,999, and the provider's 99,999,999,000 shares of 100,000,000,000 /// redeem 99,999,998,999.00000001, paid as 99,999,998,999. Valuing the long at @@ -2133,13 +2133,13 @@ fn test_liquidation_of_bankrupt_position_charges_insurance_before_liquidity() { } /// Every fee rounds up, and so does the maintenance requirement, so none is -/// a minor unit short in the trader's favour. A position one base unit over +/// a minor unit short in the trader's favour. A position one minor unit over /// $5,000 pays $5.000001 to open and the same to close: 0.1% of it is -/// 5,000,000.001 base units, rounded up to 5,000,001. The insurance fund's +/// 5,000,000.001 minor units, rounded up to 5,000,001. The insurance fund's /// half of a fee rounds down, and the program takes the odd unit. The same -/// position is liquidatable at an equity of 250,000,001 base units, the +/// position is liquidatable at an equity of 250,000,001 minor units, the /// maintenance requirement 250,000,000.05 rounded up, where a requirement -/// rounded down would have left it one base unit too healthy, and the +/// rounded down would have left it one minor unit too healthy, and the /// liquidation fee is 50,000,001. #[test] fn test_fees_and_maintenance_requirement_round_up() { @@ -2178,7 +2178,7 @@ fn test_fees_and_maintenance_requirement_round_up() { assert_eq!(pool.program_fees, 2 * 2_500_001); // The same position again, taken to an equity of exactly the rounded-up - // maintenance requirement: $85.10000005 loses it 744,999,997.65 base + // maintenance requirement: $85.10000005 loses it 744,999,997.65 minor // units, a loss of 744,999,998 once floored against the trader. // The open is byte-identical to the first, so it would carry the same // signature and be dropped as already processed without a new blockhash. @@ -2204,7 +2204,7 @@ fn test_fees_and_maintenance_requirement_round_up() { } /// `basis_points_of` rounds up, so an amount that is not an exact multiple -/// rounds to the next base unit and the smallest non-zero amount pays a whole +/// rounds to the next minor unit and the smallest non-zero amount pays a whole /// unit; an exact multiple is unchanged. `basis_points_of_rounded_down` /// splits a fee the pool already holds, so it rounds the other way. #[test] @@ -2226,8 +2226,8 @@ fn test_basis_points_of_rounds_up_and_the_insurance_split_rounds_down() { } /// `position_pnl` floors toward negative infinity rather than truncating -/// toward zero. A position of 1,000 base units entered at 3 and marked at 2 -/// has lost 333.33 base units: truncation would book a loss of 333, floor +/// toward zero. A position of 1,000 minor units entered at 3 and marked at 2 +/// has lost 333.33 minor units: truncation would book a loss of 333, floor /// books 334, so the fraction goes to the pool. A profit of 333.33 still /// books 333, the same as truncation, and a short is floored the same way. #[test] @@ -2236,14 +2236,14 @@ fn test_position_pnl_rounds_against_the_trader() { assert_eq!(position_pnl(Side::Long, 1_000, 3, 4).unwrap(), 333); assert_eq!(position_pnl(Side::Short, 1_000, 3, 4).unwrap(), -334); assert_eq!(position_pnl(Side::Short, 1_000, 3, 2).unwrap(), 333); - // A whole number of base units is unchanged. + // A whole number of minor units is unchanged. assert_eq!(position_pnl(Side::Long, 1_000, 4, 2).unwrap(), -500); } /// `position_funding` rounds up, toward positive infinity, so a fraction of a -/// base unit goes to the pool. A funding index that moves 1,500,000 (in -/// `FUNDING_PRECISION` units of 10^9) on a position of 1,000 base units is -/// 1.5 base units. A trader who pays is charged 2, where truncation would +/// minor unit goes to the pool. A funding index that moves 1,500,000 (in +/// `FUNDING_PRECISION` units of 10^9) on a position of 1,000 minor units is +/// 1.5 minor units. A trader who pays is charged 2, where truncation would /// charge 1; a trader who is paid receives 1, the same as truncation. A short /// is rounded the same way as a long. #[test] @@ -2266,7 +2266,7 @@ fn test_position_funding_rounds_against_the_trader() { position_funding(Side::Long, 1_000, 0, -1_500_000).unwrap(), -1 ); - // A whole number of base units is unchanged. + // A whole number of minor units is unchanged. assert_eq!( position_funding(Side::Long, 1_000, 0, 2_000_000).unwrap(), 2 diff --git a/finance/perpetual-futures/anchor/CHANGELOG.md b/finance/perpetual-futures/anchor/CHANGELOG.md index 050be932..26f8f301 100644 --- a/finance/perpetual-futures/anchor/CHANGELOG.md +++ b/finance/perpetual-futures/anchor/CHANGELOG.md @@ -5,24 +5,24 @@ Liquidity-provider shares are priced against the provider. `traders_unrealized_pnl` floored both sides' marked value, so the long side rounded traders' profit down and the short side rounded it up, and -`add_liquidity` or `remove_liquidity` could round a base unit in the +`add_liquidity` or `remove_liquidity` could round a minor unit in the provider's favour depending on the book. It now takes a `Rounding`, and `liquidity_provider_aum` takes the direction of the valuation: `add_liquidity` values the pool rounding up, so a deposit is minted no more shares than it pays for, and `remove_liquidity` rounds it down, so a withdrawal is paid no more than its shares are worth. `haircut_ratio` rounds -the traders' liability up, so a fraction of a base unit can only lower `h`. +the traders' liability up, so a fraction of a minor unit can only lower `h`. Tested by `test_add_liquidity_values_the_pool_rounding_up` (a 100,000 USDC -deposit against an open short marked half a base unit in profit mints +deposit against an open short marked half a minor unit in profit mints 100,000,000,000 shares, not 100,000,000,001) and `test_remove_liquidity_values_the_pool_rounding_down` (a provider -withdrawing against an open long marked half a base unit in profit is paid +withdrawing against an open long marked half a minor unit in profit is paid 99,999,998,999, not 99,999,999,000). No existing figure changes. Profit/loss and funding round against the trader. `position_pnl` and `position_funding` in `instructions/shared.rs` divided with truncation toward -zero, so a fractional loss was booked a base unit small, and funding a trader -owed was charged a base unit short. `position_pnl` now floors toward +zero, so a fractional loss was booked a minor unit small, and funding a trader +owed was charged a minor unit short. `position_pnl` now floors toward negative infinity, and `position_funding` applies the side's sign first and then rounds toward positive infinity, so funding the trader pays rounds up and funding the trader receives rounds down. The walkthrough's figures are exact and unchanged. @@ -30,12 +30,12 @@ Tested by `test_position_pnl_rounds_against_the_trader` and `test_position_funding_rounds_against_the_trader`. `test_fees_and_maintenance_requirement_round_up` now liquidates at $85.10000005 instead of $85.10000004: the old price's loss of 744,999,998.15 -base units floors to 744,999,999, and the new one's 744,999,997.65 floors to +minor units floors to 744,999,999, and the new one's 744,999,997.65 floors to 744,999,998, so the position is still liquidated at an equity of exactly 250,000,001. Every fee rounds up. `basis_points_of` in `instructions/shared.rs` rounds its -result up to the next base unit, so the open, close and liquidation fees and +result up to the next minor unit, so the open, close and liquidation fees and the maintenance requirement a position is liquidated at each round in the pool's favour: a fee is never a minor unit short, and a position is never a minor unit too healthy to liquidate. The insurance fund's cut of a fee the @@ -43,7 +43,7 @@ pool already holds is split by the new `basis_points_of_rounded_down`, and the program takes the remainder, so the two still add up to the whole fee. The walkthrough's figures are exact multiples and are unchanged. Tested by `test_fees_and_maintenance_requirement_round_up`, which opens, closes and -liquidates a position one base unit over $5,000 and checks the 5,000,001-unit +liquidates a position one minor unit over $5,000 and checks the 5,000,001-unit fees, the 2,500,000 / 2,500,001 insurance and program split, the liquidation at an equity of exactly 250,000,001 and the 50,000,001 liquidation fee, and by `test_basis_points_of_rounds_up_and_the_insurance_split_rounds_down` at the @@ -78,7 +78,7 @@ owner; `test_initialize_pool` checks the recorded program. `test_funding_charged_to_long` asserts the exact funding paid, `size * rate * seconds / FUNDING_PRECISION`, rather than that some was paid, and `test_first_deposit_below_minimum_fails` asserts `DepositTooSmall` by code one -base unit under the withheld minimum and a single share minted one over it. +minor unit under the withheld minimum and a single share minted one over it. ## 2026-10-01 diff --git a/finance/perpetual-futures/anchor/README.md b/finance/perpetual-futures/anchor/README.md index 091dd401..802f6e74 100644 --- a/finance/perpetual-futures/anchor/README.md +++ b/finance/perpetual-futures/anchor/README.md @@ -21,7 +21,7 @@ A [perpetual future](https://www.investopedia.com/terms/f/futurescontract.asp) ( - `perpetual-futures`: The exchange: pool creation, liquidity provision, opening/closing leveraged positions, funding, liquidation, and fee collection. - `mock-price-feed`: Test-only price feed. Stores a price, scale, last-update slot, and confidence band that tests write directly. Replaced in production by a Pyth `PriceUpdateV2` account, as read in [`basics/pyth`](../../../basics/pyth/). -All arithmetic is integer `u128` with `checked_*` operations, multiplying before dividing and rounding in the pool's favour: every fee and the maintenance requirement round up, and what is paid out rounds down. A position's profit/loss is floored toward negative infinity, so a fractional loss rounds up to the next base unit, and its funding rounds toward positive infinity, so funding the trader pays rounds up and funding the trader receives rounds down (`test_position_pnl_rounds_against_the_trader`, `test_position_funding_rounds_against_the_trader`). Provider shares are priced against a valuation rounded against the provider: `add_liquidity` values the pool rounding up, so a deposit is minted no more shares than it pays for, and `remove_liquidity` rounds it down, so a withdrawal is paid no more than its shares are worth (`test_add_liquidity_values_the_pool_rounding_up`, `test_remove_liquidity_values_the_pool_rounding_down`). The haircut's liability rounds up, so a fraction of a base unit can only lower `h`. No floats, no fixed-point library. +All arithmetic is integer `u128` with `checked_*` operations, multiplying before dividing and rounding in the pool's favour: every fee and the maintenance requirement round up, and what is paid out rounds down. A position's profit/loss is floored toward negative infinity, so a fractional loss rounds up to the next minor unit, and its funding rounds toward positive infinity, so funding the trader pays rounds up and funding the trader receives rounds down (`test_position_pnl_rounds_against_the_trader`, `test_position_funding_rounds_against_the_trader`). Provider shares are priced against a valuation rounded against the provider: `add_liquidity` values the pool rounding up, so a deposit is minted no more shares than it pays for, and `remove_liquidity` rounds it down, so a withdrawal is paid no more than its shares are worth (`test_add_liquidity_values_the_pool_rounding_up`, `test_remove_liquidity_values_the_pool_rounding_down`). The haircut's liability rounds up, so a fraction of a minor unit can only lower `h`. No floats, no fixed-point library. --- @@ -104,7 +104,7 @@ A single oracle print can be wrong while still being fresh, positive and confide ### Fees and slippage -Open and close fees are charged in [basis points](https://www.investopedia.com/terms/b/basispoint.asp) (1 bp = 0.01%) of notional. `basis_points_of` rounds each fee up to the next base unit, as it does the liquidation fee and the maintenance requirement, so a fee is never a minor unit short in the trader's favour; `insurance_fee_bps` of each fee, rounded down by `basis_points_of_rounded_down`, goes to the insurance fund and the program takes the rest. `test_fees_and_maintenance_requirement_round_up` opens, closes and liquidates a position one base unit over $5,000 and checks every rounded figure. Every state-changing handler takes a `minimum_*` / acceptable-price bound (protection against [slippage](https://www.investopedia.com/terms/s/slippage.asp), the gap between the expected and actual fill) and reverts if the bound is breached. Pass `0` to opt out. +Open and close fees are charged in [basis points](https://www.investopedia.com/terms/b/basispoint.asp) (1 bp = 0.01%) of notional. `basis_points_of` rounds each fee up to the next minor unit, as it does the liquidation fee and the maintenance requirement, so a fee is never a minor unit short in the trader's favour; `insurance_fee_bps` of each fee, rounded down by `basis_points_of_rounded_down`, goes to the insurance fund and the program takes the rest. `test_fees_and_maintenance_requirement_round_up` opens, closes and liquidates a position one minor unit over $5,000 and checks every rounded figure. Every state-changing handler takes a `minimum_*` / acceptable-price bound (protection against [slippage](https://www.investopedia.com/terms/s/slippage.asp), the gap between the expected and actual fill) and reverts if the bound is breached. Pass `0` to opt out. --- @@ -118,7 +118,7 @@ Open and close fees are charged in [basis points](https://www.investopedia.com/t - **Bob** (Short trader): He thinks NVDA will fall and wants to profit from the downside. - **Dave** (Liquidator): Runs a bot that closes under-margined positions to earn the liquidation fee. -Amounts below are shown in whole USDC; onchain they are base units (× 10⁶). The pool is configured with a 10% initial margin (10× leverage), 0.1% open/close fees with half of each paid into the insurance fund, a 5% maintenance margin, a 1% liquidation fee, a 1% maximum oracle confidence band, a 20% price band around its average price, and a 10-slot profit warm-up. +Amounts below are shown in whole USDC; onchain they are minor units (× 10⁶). The pool is configured with a 10% initial margin (10× leverage), 0.1% open/close fees with half of each paid into the insurance fund, a 5% maintenance margin, a 1% liquidation fee, a 1% maximum oracle confidence band, a 20% price band around its average price, and a 10-slot profit warm-up. --- @@ -272,7 +272,7 @@ The tests run in-process with [LiteSVM](https://www.anchor-lang.com/docs/testing - the profit warm-up on both sides of its boundary (`test_profit_blocked_before_maturation`, `test_profit_realized_after_maturation`), and a loss closing in the slot it opened (`test_loss_not_gated_by_maturation`) - the insurance fund: its exact share of each fee (`test_insurance_fund_funded_by_fees`), a bankrupt position's deficit paid by the fund (`test_insurance_absorbs_bankruptcy_deficit`), and a bankrupt position liquidated for no fee with the fund paying before the providers (`test_liquidation_of_bankrupt_position_charges_insurance_before_liquidity`) - withdrawals capped at `liquidity` while traders are down (`test_remove_liquidity_capped_at_liquidity`) -- the pool valued rounding up for a deposit and down for a withdrawal, each a base unit in the pool's favour against the old valuation (`test_add_liquidity_values_the_pool_rounding_up`, `test_remove_liquidity_values_the_pool_rounding_down`) +- the pool valued rounding up for a deposit and down for a withdrawal, each a minor unit in the pool's favour against the old valuation (`test_add_liquidity_values_the_pool_rounding_up`, `test_remove_liquidity_values_the_pool_rounding_down`) - `initialize_pool`'s parameter checks, including an initial margin at or below the maintenance margin, a close fee at or above it (`test_initialize_pool_rejects_close_fee_at_or_above_maintenance_margin`), a price band outside its range, and an insurance fee of 10,000 basis points or more - every fee and the maintenance requirement rounding up (`test_fees_and_maintenance_requirement_round_up`), and `basis_points_of` at its boundaries - fee collection, and its refusal to anyone but the pool's authority (`test_collect_fees_requires_authority`, which asserts the constraint's own error code) diff --git a/finance/perpetual-futures/anchor/programs/perpetual-futures/src/instructions/add_liquidity.rs b/finance/perpetual-futures/anchor/programs/perpetual-futures/src/instructions/add_liquidity.rs index bd69cd05..680e0180 100644 --- a/finance/perpetual-futures/anchor/programs/perpetual-futures/src/instructions/add_liquidity.rs +++ b/finance/perpetual-futures/anchor/programs/perpetual-futures/src/instructions/add_liquidity.rs @@ -47,7 +47,7 @@ pub fn handle_add_liquidity( // minimum's slice is still in `liquidity`, so the next deposit is // priced against it rather than bootstrapped. // - // The pool is valued rounding up, so a fraction of a base unit in the + // The pool is valued rounding up, so a fraction of a minor unit in the // traders' marked profit/loss raises the price of a share rather than // lowering it. let aum = liquidity_provider_aum(pool, price, Rounding::Up)?; diff --git a/finance/perpetual-futures/anchor/programs/perpetual-futures/src/instructions/remove_liquidity.rs b/finance/perpetual-futures/anchor/programs/perpetual-futures/src/instructions/remove_liquidity.rs index f6340548..1ece3370 100644 --- a/finance/perpetual-futures/anchor/programs/perpetual-futures/src/instructions/remove_liquidity.rs +++ b/finance/perpetual-futures/anchor/programs/perpetual-futures/src/instructions/remove_liquidity.rs @@ -24,7 +24,7 @@ pub fn handle_remove_liquidity( let price = refresh_price_and_funding_within_band(pool, &context.accounts.oracle_feed)?; let lp_supply = context.accounts.lp_mint.supply(); - // The pool is valued rounding down, so a fraction of a base unit in the + // The pool is valued rounding down, so a fraction of a minor unit in the // traders' marked profit/loss lowers what a share redeems for. let aum = liquidity_provider_aum(pool, price, Rounding::Down)?; require!(aum > 0, PerpError::PoolInsolvent); diff --git a/finance/perpetual-futures/anchor/programs/perpetual-futures/src/instructions/shared.rs b/finance/perpetual-futures/anchor/programs/perpetual-futures/src/instructions/shared.rs index 18dffb1a..80403d80 100644 --- a/finance/perpetual-futures/anchor/programs/perpetual-futures/src/instructions/shared.rs +++ b/finance/perpetual-futures/anchor/programs/perpetual-futures/src/instructions/shared.rs @@ -8,7 +8,7 @@ use crate::errors::PerpError; use crate::state::{Pool, Position, Side}; /// Result of removing a position from the pool's aggregates. All figures are in -/// collateral base units; `equity` is what the trader's position is worth +/// collateral minor units; `equity` is what the trader's position is worth /// before any close or liquidation fee. pub struct Settlement { pub profit_and_loss: i128, @@ -118,7 +118,7 @@ pub fn scale_size(size: u64, entry_price: u64) -> Result { .ok_or(PerpError::MathOverflow.into()) } -/// Signed profit/loss of one position at `price`, in collateral base units. +/// Signed profit/loss of one position at `price`, in collateral minor units. /// Longs profit when price rises, shorts when it falls. pub fn position_pnl(side: Side, size: u64, entry_price: u64, price: u64) -> Result { let size = size as i128; @@ -133,7 +133,7 @@ pub fn position_pnl(side: Side, size: u64, entry_price: u64, price: u64) -> Resu // Multiply before dividing to keep precision; `entry > 0` is guaranteed. // Floored toward negative infinity rather than truncated toward zero, so a - // loss that is not a whole base unit rounds up to the next one and a + // loss that is not a whole minor unit rounds up to the next one and a // profit rounds down: the trader's result is always the lower of the two. size.checked_mul(price_change) .ok_or(PerpError::MathOverflow)? @@ -141,7 +141,7 @@ pub fn position_pnl(side: Side, size: u64, entry_price: u64, price: u64) -> Resu .ok_or(PerpError::MathOverflow.into()) } -/// Which way a valuation's fractional base unit goes. +/// Which way a valuation's fractional minor unit goes. #[derive(Clone, Copy, PartialEq, Eq)] pub enum Rounding { Down, @@ -170,7 +170,7 @@ fn divide_rounding(numerator: i128, denominator: i128, rounding: Rounding) -> Re /// Positive means traders are collectively up (and the pool is down). /// /// `rounding` is the direction of the result: `Up` rounds the long side's -/// value up and the short side's value down, so a fraction of a base unit on +/// value up and the short side's value down, so a fraction of a minor unit on /// either side counts as owed to traders; `Down` does the opposite. Callers /// choose the direction that goes against whoever is being priced. /// @@ -252,7 +252,7 @@ pub fn liquidity_provider_aum(pool: &Pool, price: u64, rounding: Rounding) -> Re /// paid at most the pool's backing, and is never refused; when the liability is /// the larger, every other winner's fraction is unchanged. pub fn haircut_ratio(pool: &Pool, price: u64, closing_profit: i128) -> Result { - // Rounded up, so a fraction of a base unit counts as owed and can only + // Rounded up, so a fraction of a minor unit counts as owed and can only // lower `h`: no winner is paid more than the backing allows. let liability: u128 = traders_unrealized_pnl(pool, price, Rounding::Up)? .max(closing_profit) @@ -315,10 +315,10 @@ pub fn credit_fee(pool: &mut Pool, fee: u64) -> Result<()> { Ok(()) } -/// Funding a position owes since it opened, in collateral base units. Positive +/// Funding a position owes since it opened, in collateral minor units. Positive /// means the trader pays the pool; negative means the pool pays the trader. /// -/// Rounded up, toward positive infinity, so a fraction of a base unit always +/// Rounded up, toward positive infinity, so a fraction of a minor unit always /// goes to the pool: funding the trader pays rounds up to the next whole unit /// and funding the trader receives rounds down. The side's sign is applied /// before dividing, so a short is rounded the same way as a long. diff --git a/finance/perpetual-futures/anchor/programs/perpetual-futures/src/state/pool.rs b/finance/perpetual-futures/anchor/programs/perpetual-futures/src/state/pool.rs index 1c2d0587..1fbadc96 100644 --- a/finance/perpetual-futures/anchor/programs/perpetual-futures/src/state/pool.rs +++ b/finance/perpetual-futures/anchor/programs/perpetual-futures/src/state/pool.rs @@ -4,7 +4,7 @@ use anchor_lang::prelude::*; /// oracle feed. Liquidity providers fund the pool and are the counterparty to /// every trader; the pool absorbs trader profit and loss. /// -/// Money fields are raw base units of the collateral token. The pool never +/// Money fields are raw minor units of the collateral token. The pool never /// assumes decimals — `transfer_checked` carries them through every CPI. #[account(borsh)] #[derive(InitSpace)] @@ -33,7 +33,7 @@ pub struct Pool { pub lp_mint: Address, - /// Liquidity-provider-owned assets, in collateral base units. Grows with + /// Liquidity-provider-owned assets, in collateral minor units. Grows with /// deposits, trader losses, fees-to-LPs; shrinks with withdrawals and /// trader profits. Trader collateral is tracked separately in /// `total_collateral` and is not part of this figure. Together with @@ -57,7 +57,7 @@ pub struct Pool { pub insurance_fund: u64, /// Aggregate long open interest (sum of position `size`), in collateral - /// base units of notional. + /// minor units of notional. pub long_size: u128, pub short_size: u128, diff --git a/finance/perpetual-futures/anchor/programs/perpetual-futures/src/state/position.rs b/finance/perpetual-futures/anchor/programs/perpetual-futures/src/state/position.rs index db6774cb..98e512ca 100644 --- a/finance/perpetual-futures/anchor/programs/perpetual-futures/src/state/position.rs +++ b/finance/perpetual-futures/anchor/programs/perpetual-futures/src/state/position.rs @@ -30,11 +30,11 @@ pub struct Position { pub side: Side, - /// Collateral the trader posted, in collateral base units. Part of the + /// Collateral the trader posted, in collateral minor units. Part of the /// pool's `total_collateral` while the position is open. pub collateral: u64, - /// Notional position size, in collateral base units. `size / collateral` is + /// Notional position size, in collateral minor units. `size / collateral` is /// the leverage. pub size: u64, diff --git a/finance/perpetual-futures/anchor/programs/perpetual-futures/tests/test_perpetual_futures.rs b/finance/perpetual-futures/anchor/programs/perpetual-futures/tests/test_perpetual_futures.rs index e058c13e..9d342b0f 100644 --- a/finance/perpetual-futures/anchor/programs/perpetual-futures/tests/test_perpetual_futures.rs +++ b/finance/perpetual-futures/anchor/programs/perpetual-futures/tests/test_perpetual_futures.rs @@ -38,7 +38,7 @@ const HAIRCUT_PRECISION: u64 = 1_000_000_000; // carried in, so a position's funding is `size * rate * seconds / this`. const FUNDING_PRECISION: u64 = 1_000_000_000; // Collateral token has 6 decimals (like USDC), so one whole unit is 1_000_000 -// base units. +// minor units. const ONE_USDC: u64 = 1_000_000; const DECIMALS: u8 = 6; @@ -711,7 +711,7 @@ fn test_add_liquidity_first_deposit_withholds_minimum() { assert_eq!(shares, deposit - 1_000); } -/// The first deposit must exceed the 1_000 withheld minimum: one base unit +/// The first deposit must exceed the 1_000 withheld minimum: one minor unit /// short is refused, and one over mints a single share. #[test] fn test_first_deposit_below_minimum_fails() { @@ -1832,12 +1832,12 @@ fn test_remove_liquidity_capped_at_liquidity() { market.assert_vault_matches_ledger(); } /// `add_liquidity` values the pool rounding up. A $5,000 short entered at -/// $100 and marked at $99.99999999 is worth 4,999,999,999.5 base units, so -/// traders are up half a base unit. Rounded against the depositor that half +/// $100 and marked at $99.99999999 is worth 4,999,999,999.5 minor units, so +/// traders are up half a minor unit. Rounded against the depositor that half /// counts as nothing owed, assets-under-management stays at the pool's /// 100,000 USDC of liquidity, and a 100,000 USDC deposit is minted exactly /// 100,000 USDC of shares. Valuing the short at 4,999,999,999 would read the -/// pool one base unit low and mint one share more. +/// pool one minor unit low and mint one share more. #[test] fn test_add_liquidity_values_the_pool_rounding_up() { let mut market = Market::default_market(); @@ -1870,8 +1870,8 @@ fn test_add_liquidity_values_the_pool_rounding_up() { } /// `remove_liquidity` values the pool rounding down. A $5,000 long entered at -/// $100 and marked at $100.00000001 is worth 5,000,000,000.5 base units, so -/// traders are up half a base unit. Rounded against the withdrawing provider +/// $100 and marked at $100.00000001 is worth 5,000,000,000.5 minor units, so +/// traders are up half a minor unit. Rounded against the withdrawing provider /// that half counts as a whole unit owed, assets-under-management reads /// 99,999,999,999, and the provider's 99,999,999,000 shares of 100,000,000,000 /// redeem 99,999,998,999.00000001, paid as 99,999,998,999. Valuing the long at @@ -2133,13 +2133,13 @@ fn test_liquidation_of_bankrupt_position_charges_insurance_before_liquidity() { } /// Every fee rounds up, and so does the maintenance requirement, so none is -/// a minor unit short in the trader's favour. A position one base unit over +/// a minor unit short in the trader's favour. A position one minor unit over /// $5,000 pays $5.000001 to open and the same to close: 0.1% of it is -/// 5,000,000.001 base units, rounded up to 5,000,001. The insurance fund's +/// 5,000,000.001 minor units, rounded up to 5,000,001. The insurance fund's /// half of a fee rounds down, and the program takes the odd unit. The same -/// position is liquidatable at an equity of 250,000,001 base units, the +/// position is liquidatable at an equity of 250,000,001 minor units, the /// maintenance requirement 250,000,000.05 rounded up, where a requirement -/// rounded down would have left it one base unit too healthy, and the +/// rounded down would have left it one minor unit too healthy, and the /// liquidation fee is 50,000,001. #[test] fn test_fees_and_maintenance_requirement_round_up() { @@ -2178,7 +2178,7 @@ fn test_fees_and_maintenance_requirement_round_up() { assert_eq!(pool.program_fees, 2 * 2_500_001); // The same position again, taken to an equity of exactly the rounded-up - // maintenance requirement: $85.10000005 loses it 744,999,997.65 base + // maintenance requirement: $85.10000005 loses it 744,999,997.65 minor // units, a loss of 744,999,998 once floored against the trader. // The open is byte-identical to the first, so it would carry the same // signature and be dropped as already processed without a new blockhash. @@ -2204,7 +2204,7 @@ fn test_fees_and_maintenance_requirement_round_up() { } /// `basis_points_of` rounds up, so an amount that is not an exact multiple -/// rounds to the next base unit and the smallest non-zero amount pays a whole +/// rounds to the next minor unit and the smallest non-zero amount pays a whole /// unit; an exact multiple is unchanged. `basis_points_of_rounded_down` /// splits a fee the pool already holds, so it rounds the other way. #[test] @@ -2226,8 +2226,8 @@ fn test_basis_points_of_rounds_up_and_the_insurance_split_rounds_down() { } /// `position_pnl` floors toward negative infinity rather than truncating -/// toward zero. A position of 1,000 base units entered at 3 and marked at 2 -/// has lost 333.33 base units: truncation would book a loss of 333, floor +/// toward zero. A position of 1,000 minor units entered at 3 and marked at 2 +/// has lost 333.33 minor units: truncation would book a loss of 333, floor /// books 334, so the fraction goes to the pool. A profit of 333.33 still /// books 333, the same as truncation, and a short is floored the same way. #[test] @@ -2236,14 +2236,14 @@ fn test_position_pnl_rounds_against_the_trader() { assert_eq!(position_pnl(Side::Long, 1_000, 3, 4).unwrap(), 333); assert_eq!(position_pnl(Side::Short, 1_000, 3, 4).unwrap(), -334); assert_eq!(position_pnl(Side::Short, 1_000, 3, 2).unwrap(), 333); - // A whole number of base units is unchanged. + // A whole number of minor units is unchanged. assert_eq!(position_pnl(Side::Long, 1_000, 4, 2).unwrap(), -500); } /// `position_funding` rounds up, toward positive infinity, so a fraction of a -/// base unit goes to the pool. A funding index that moves 1,500,000 (in -/// `FUNDING_PRECISION` units of 10^9) on a position of 1,000 base units is -/// 1.5 base units. A trader who pays is charged 2, where truncation would +/// minor unit goes to the pool. A funding index that moves 1,500,000 (in +/// `FUNDING_PRECISION` units of 10^9) on a position of 1,000 minor units is +/// 1.5 minor units. A trader who pays is charged 2, where truncation would /// charge 1; a trader who is paid receives 1, the same as truncation. A short /// is rounded the same way as a long. #[test] @@ -2266,7 +2266,7 @@ fn test_position_funding_rounds_against_the_trader() { position_funding(Side::Long, 1_000, 0, -1_500_000).unwrap(), -1 ); - // A whole number of base units is unchanged. + // A whole number of minor units is unchanged. assert_eq!( position_funding(Side::Long, 1_000, 0, 2_000_000).unwrap(), 2 diff --git a/finance/perpetual-futures/quasar/CHANGELOG.md b/finance/perpetual-futures/quasar/CHANGELOG.md index 01db41e4..ff86cdbd 100644 --- a/finance/perpetual-futures/quasar/CHANGELOG.md +++ b/finance/perpetual-futures/quasar/CHANGELOG.md @@ -5,24 +5,24 @@ Liquidity-provider shares are priced against the provider. `traders_unrealized_pnl` floored both sides' marked value, so the long side rounded traders' profit down and the short side rounded it up, and -`add_liquidity` or `remove_liquidity` could round a base unit in the +`add_liquidity` or `remove_liquidity` could round a minor unit in the provider's favour depending on the book. It now takes a `Rounding`: `add_liquidity` rounds traders' profit down and so values the pool rounding up, so a deposit is minted no more shares than it pays for, and `remove_liquidity` rounds the pool down, so a withdrawal is paid no more than its shares are worth. `haircut_ratio` rounds the traders' liability up, -so a fraction of a base unit can only lower `h`. Tested by +so a fraction of a minor unit can only lower `h`. Tested by `add_liquidity_values_the_pool_rounding_up` (a 100,000 USDC deposit against -an open short marked half a base unit in profit mints 100,000,000,000 +an open short marked half a minor unit in profit mints 100,000,000,000 shares, not 100,000,000,001) and `remove_liquidity_values_the_pool_rounding_down` (a provider withdrawing -against an open long marked half a base unit in profit is paid +against an open long marked half a minor unit in profit is paid 99,999,998,999, not 99,999,999,000). No existing figure changes. Profit/loss and funding round against the trader. `position_pnl` and `position_funding` in `instructions/shared.rs` divided with truncation toward -zero, so a fractional loss was booked a base unit small, and funding a trader -owed was charged a base unit short. `position_pnl` now floors toward +zero, so a fractional loss was booked a minor unit small, and funding a trader +owed was charged a minor unit short. `position_pnl` now floors toward negative infinity, and `position_funding` applies the side's sign first and then rounds toward positive infinity, so funding the trader pays rounds up and funding the trader receives rounds down. The walkthrough's figures are exact and unchanged. @@ -30,19 +30,19 @@ Tested by `position_pnl_rounds_against_the_trader` and `position_funding_rounds_against_the_trader`. `fees_and_maintenance_requirement_round_up` now liquidates at $85.10000005 instead of $85.10000004: the old price's loss of 744,999,998.15 -base units floors to 744,999,999, and the new one's 744,999,997.65 floors to +minor units floors to 744,999,999, and the new one's 744,999,997.65 floors to 744,999,998, so the position is still liquidated at an equity of exactly 250,000,001. Every fee rounds up. `basis_points_of` in `instructions/shared.rs` rounds its -result up to the next base unit, so the open, close and liquidation fees and +result up to the next minor unit, so the open, close and liquidation fees and the maintenance requirement a position is liquidated at each round in the pool's favour: a fee is never a minor unit short, and a position is never a minor unit too healthy to liquidate. The insurance fund's cut of a fee the pool already holds is split by the new `basis_points_of_rounded_down`, and the program takes the remainder, so the two still add up to the whole fee. Tested by `fees_and_maintenance_requirement_round_up`, which opens, closes and -liquidates a position one base unit over $5,000 and checks the 5,000,001-unit +liquidates a position one minor unit over $5,000 and checks the 5,000,001-unit fees, the 2,500,000 / 2,500,001 insurance and program split, the liquidation at an equity of exactly 250,000,001 and the 50,000,001 liquidation fee, and by `basis_points_of_rounds_up_and_the_insurance_split_rounds_down` at the @@ -71,7 +71,7 @@ recorded program. `funding_follows_seconds_not_slots` asserts the exact funding paid, `size * rate * seconds / FUNDING_PRECISION`, rather than that some was paid, and the new `first_deposit_below_minimum_fails` asserts `DEPOSIT_TOO_SMALL` by code one -base unit under the withheld minimum and a single share minted one over it. +minor unit under the withheld minimum and a single share minted one over it. ## 2026-10-01 diff --git a/finance/perpetual-futures/quasar/README.md b/finance/perpetual-futures/quasar/README.md index 416b27a6..0c3c9008 100644 --- a/finance/perpetual-futures/quasar/README.md +++ b/finance/perpetual-futures/quasar/README.md @@ -66,7 +66,7 @@ wallets, then exercise: (`fees_and_maintenance_requirement_round_up`), and `basis_points_of` at its boundaries - profit/loss floored toward negative infinity and funding rounded toward - positive infinity, so a fraction of a base unit always goes to the pool + positive infinity, so a fraction of a minor unit always goes to the pool (`position_pnl_rounds_against_the_trader`, `position_funding_rounds_against_the_trader`) - the pool valued rounding up for a deposit and down for a withdrawal, so diff --git a/finance/perpetual-futures/quasar/src/instructions/add_liquidity.rs b/finance/perpetual-futures/quasar/src/instructions/add_liquidity.rs index dfebd24d..8e5d3798 100644 --- a/finance/perpetual-futures/quasar/src/instructions/add_liquidity.rs +++ b/finance/perpetual-futures/quasar/src/instructions/add_liquidity.rs @@ -79,7 +79,7 @@ pub fn handle_add_liquidity( accounts.pool.short_size_scaled.get(), price, // Rounded down, so the pool is valued high and a fraction of a - // base unit raises the price of a share rather than lowering it. + // minor unit raises the price of a share rather than lowering it. Rounding::Down, )?; let aum = (accounts.pool.liquidity.get() as i128) diff --git a/finance/perpetual-futures/quasar/src/instructions/remove_liquidity.rs b/finance/perpetual-futures/quasar/src/instructions/remove_liquidity.rs index b9c950ce..d162ee6c 100644 --- a/finance/perpetual-futures/quasar/src/instructions/remove_liquidity.rs +++ b/finance/perpetual-futures/quasar/src/instructions/remove_liquidity.rs @@ -70,7 +70,7 @@ pub fn handle_remove_liquidity( accounts.pool.short_size.get(), accounts.pool.short_size_scaled.get(), price, - // Rounded up, so the pool is valued low and a fraction of a base + // Rounded up, so the pool is valued low and a fraction of a minor // unit lowers what a share redeems for. Rounding::Up, )?; diff --git a/finance/perpetual-futures/quasar/src/instructions/shared.rs b/finance/perpetual-futures/quasar/src/instructions/shared.rs index dfc4c89c..5fb2ea3c 100644 --- a/finance/perpetual-futures/quasar/src/instructions/shared.rs +++ b/finance/perpetual-futures/quasar/src/instructions/shared.rs @@ -211,7 +211,7 @@ pub fn position_pnl( .ok_or_else(overflow)?; // Multiply before dividing to keep precision; `entry > 0` is guaranteed. // Floored toward negative infinity rather than truncated toward zero, so a - // loss that is not a whole base unit rounds up to the next one and a + // loss that is not a whole minor unit rounds up to the next one and a // profit rounds down: the trader's result is always the lower of the two. size.checked_mul(price_change) .ok_or_else(overflow)? @@ -219,7 +219,7 @@ pub fn position_pnl( .ok_or_else(overflow) } -/// Which way a valuation's fractional base unit goes. +/// Which way a valuation's fractional minor unit goes. #[derive(Clone, Copy, PartialEq, Eq)] pub enum Rounding { Down, @@ -245,7 +245,7 @@ fn divide_rounding( /// pool's per-side accumulators. Positive means traders are collectively up. /// /// `rounding` is the direction of the result: `Up` rounds the long side's -/// value up and the short side's value down, so a fraction of a base unit on +/// value up and the short side's value down, so a fraction of a minor unit on /// either side counts as owed to traders; `Down` does the opposite. Callers /// choose the direction that goes against whoever is being priced: /// `add_liquidity` rounds this `Down` (the pool is valued high, so a deposit @@ -321,7 +321,7 @@ pub fn haircut_ratio( pool.short_size.get(), pool.short_size_scaled.get(), price, - // Rounded up, so a fraction of a base unit counts as owed and can + // Rounded up, so a fraction of a minor unit counts as owed and can // only lower `h`. Rounding::Up, )?; @@ -383,10 +383,10 @@ pub fn credit_fee(pool: &mut Account, fee: u64) -> Result<(), ProgramError Ok(()) } -/// Funding a position owes since it opened, in collateral base units. Positive +/// Funding a position owes since it opened, in collateral minor units. Positive /// means the trader pays the pool; negative means the pool pays the trader. /// -/// Rounded up, toward positive infinity, so a fraction of a base unit always +/// Rounded up, toward positive infinity, so a fraction of a minor unit always /// goes to the pool: funding the trader pays rounds up to the next whole unit /// and funding the trader receives rounds down. The side's sign is applied /// before dividing, so a short is rounded the same way as a long. diff --git a/finance/perpetual-futures/quasar/src/state.rs b/finance/perpetual-futures/quasar/src/state.rs index fe16be4c..b1e11cb9 100644 --- a/finance/perpetual-futures/quasar/src/state.rs +++ b/finance/perpetual-futures/quasar/src/state.rs @@ -2,7 +2,7 @@ use quasar_lang::prelude::*; /// One perpetual-futures market. Mirrors the Anchor `Pool` field-for-field; see /// the Anchor sibling's README for what each field means. Money fields are raw -/// base units of the collateral token. +/// minor units of the collateral token. /// The pool account owns the custody vault and is the liquidity-provider /// mint's authority; it signs vault transfers and mint/burn CPIs with its own /// seeds. There is no separate signing PDA. diff --git a/finance/perpetual-futures/quasar/src/tests.rs b/finance/perpetual-futures/quasar/src/tests.rs index 1013bb94..46163fe5 100644 --- a/finance/perpetual-futures/quasar/src/tests.rs +++ b/finance/perpetual-futures/quasar/src/tests.rs @@ -423,7 +423,7 @@ fn add_liquidity_deposits_and_mints_shares(test: &mut Test) { .has_tokens(PROVIDER_LP, 10_000 * ONE_USDC - 1_000); } -/// The first deposit must exceed the 1_000 withheld minimum: one base unit +/// The first deposit must exceed the 1_000 withheld minimum: one minor unit /// short is refused, and one over mints a single share. #[quasar_test] fn first_deposit_below_minimum_fails(test: &mut Test) { @@ -1096,12 +1096,12 @@ fn remove_liquidity_capped_at_liquidity(test: &mut Test) { } /// `add_liquidity` values the pool rounding up. A $5,000 short entered at -/// $100 and marked at $99.99999999 is worth 4,999,999,999.5 base units, so -/// traders are up half a base unit. Rounded against the depositor that half +/// $100 and marked at $99.99999999 is worth 4,999,999,999.5 minor units, so +/// traders are up half a minor unit. Rounded against the depositor that half /// counts as nothing owed, assets-under-management stays at the pool's /// 100,000 USDC of liquidity, and a 100,000 USDC deposit is minted exactly /// 100,000 USDC of shares. Valuing the short at 4,999,999,999 would read the -/// pool one base unit low and mint one share more. +/// pool one minor unit low and mint one share more. #[quasar_test] fn add_liquidity_values_the_pool_rounding_up(test: &mut Test) { let env = setup(test); @@ -1124,8 +1124,8 @@ fn add_liquidity_values_the_pool_rounding_up(test: &mut Test) { } /// `remove_liquidity` values the pool rounding down. A $5,000 long entered at -/// $100 and marked at $100.00000001 is worth 5,000,000,000.5 base units, so -/// traders are up half a base unit. Rounded against the withdrawing provider +/// $100 and marked at $100.00000001 is worth 5,000,000,000.5 minor units, so +/// traders are up half a minor unit. Rounded against the withdrawing provider /// that half counts as a whole unit owed, assets-under-management reads /// 99,999,999,999, and the provider's 99,999,999,000 shares of 100,000,000,000 /// redeem 99,999,998,999.00000001, paid as 99,999,998,999. Valuing the long at @@ -1331,13 +1331,13 @@ fn liquidation_of_bankrupt_position_charges_insurance_before_liquidity(test: &mu } /// Every fee rounds up, and so does the maintenance requirement, so none is -/// a minor unit short in the trader's favour. A position one base unit over +/// a minor unit short in the trader's favour. A position one minor unit over /// $5,000 pays $5.000001 to open and the same to close: 0.1% of it is -/// 5,000,000.001 base units, rounded up to 5,000,001. The insurance fund's +/// 5,000,000.001 minor units, rounded up to 5,000,001. The insurance fund's /// half of a fee rounds down, and the program takes the odd unit. The same -/// position is liquidatable at an equity of 250,000,001 base units, the +/// position is liquidatable at an equity of 250,000,001 minor units, the /// maintenance requirement 250,000,000.05 rounded up, where a requirement -/// rounded down would have left it one base unit too healthy, and the +/// rounded down would have left it one minor unit too healthy, and the /// liquidation fee is 50,000,001. #[quasar_test] fn fees_and_maintenance_requirement_round_up(test: &mut Test) { @@ -1367,7 +1367,7 @@ fn fees_and_maintenance_requirement_round_up(test: &mut Test) { assert_eq!(u64::from(pool.program_fees), 2 * 2_500_001); // The same position again, taken to an equity of exactly the rounded-up - // maintenance requirement: $85.10000005 loses it 744,999,997.65 base + // maintenance requirement: $85.10000005 loses it 744,999,997.65 minor // units, a loss of 744,999,998 once floored against the trader. open_position(test, &env, SIDE_LONG, collateral, size).succeeds(); set_feed(test, 8_510_000_005, 0); @@ -1383,7 +1383,7 @@ fn fees_and_maintenance_requirement_round_up(test: &mut Test) { } /// `basis_points_of` rounds up, so an amount that is not an exact multiple -/// rounds to the next base unit and the smallest non-zero amount pays a whole +/// rounds to the next minor unit and the smallest non-zero amount pays a whole /// unit; an exact multiple is unchanged. `basis_points_of_rounded_down` /// splits a fee the pool already holds, so it rounds the other way. #[test] @@ -1405,8 +1405,8 @@ fn basis_points_of_rounds_up_and_the_insurance_split_rounds_down() { } /// `position_pnl` floors toward negative infinity rather than truncating -/// toward zero. A position of 1,000 base units entered at 3 and marked at 2 -/// has lost 333.33 base units: truncation would book a loss of 333, floor +/// toward zero. A position of 1,000 minor units entered at 3 and marked at 2 +/// has lost 333.33 minor units: truncation would book a loss of 333, floor /// books 334, so the fraction goes to the pool. A profit of 333.33 still /// books 333, the same as truncation, and a short is floored the same way. #[test] @@ -1415,14 +1415,14 @@ fn position_pnl_rounds_against_the_trader() { assert_eq!(position_pnl(SIDE_LONG, 1_000, 3, 4).unwrap(), 333); assert_eq!(position_pnl(SIDE_SHORT, 1_000, 3, 4).unwrap(), -334); assert_eq!(position_pnl(SIDE_SHORT, 1_000, 3, 2).unwrap(), 333); - // A whole number of base units is unchanged. + // A whole number of minor units is unchanged. assert_eq!(position_pnl(SIDE_LONG, 1_000, 4, 2).unwrap(), -500); } /// `position_funding` rounds up, toward positive infinity, so a fraction of a -/// base unit goes to the pool. A funding index that moves 1,500,000 (in -/// `FUNDING_PRECISION` units of 10^9) on a position of 1,000 base units is -/// 1.5 base units. A trader who pays is charged 2, where truncation would +/// minor unit goes to the pool. A funding index that moves 1,500,000 (in +/// `FUNDING_PRECISION` units of 10^9) on a position of 1,000 minor units is +/// 1.5 minor units. A trader who pays is charged 2, where truncation would /// charge 1; a trader who is paid receives 1, the same as truncation. A short /// is rounded the same way as a long. #[test] @@ -1442,7 +1442,7 @@ fn position_funding_rounds_against_the_trader() { position_funding(SIDE_LONG, 1_000, 0, -1_500_000).unwrap(), -1 ); - // A whole number of base units is unchanged. + // A whole number of minor units is unchanged. assert_eq!(position_funding(SIDE_LONG, 1_000, 0, 2_000_000).unwrap(), 2); assert_eq!( position_funding(SIDE_SHORT, 1_000, 0, 2_000_000).unwrap(), diff --git a/finance/token-swap/README.md b/finance/token-swap/README.md index cd6225a6..19bca77e 100644 --- a/finance/token-swap/README.md +++ b/finance/token-swap/README.md @@ -88,7 +88,7 @@ Per-pool configuration / identity record. Identifies a single pool by which `Con - `config: Pubkey` - the parent `Config` account. - `mint_a: Pubkey` - mint of token A. - `mint_b: Pubkey` - mint of token B. -- `admin_fees_owed_a: u64` - admin's accumulated fee claim on token A, in base units. Sits physically in `pool_a` but is excluded from the LP curve and from LP-withdrawable amounts. Swept by `claim_admin_fees`. +- `admin_fees_owed_a: u64` - admin's accumulated fee claim on token A, in minor units. Sits physically in `pool_a` but is excluded from the LP curve and from LP-withdrawable amounts. Swept by `claim_admin_fees`. - `admin_fees_owed_b: u64` - same for token B. The admin's fees are tracked as *virtual* claims on the existing `pool_a` / `pool_b` reserves rather than as separate vaults. LP-facing math uses **effective reserves** = `pool_X.amount - admin_fees_owed_X` so the admin's owed slice doesn't grow LP [yield](https://www.investopedia.com/terms/y/yield.asp). @@ -118,9 +118,9 @@ Transfers token A and token B from the depositor to the pool, then mints LP toke 2. If `amount_b_required ≤ amount_b`, use `(amount_a, amount_b_required)` - the depositor offered enough B, so we take the full A and clamp B down. 3. Otherwise, compute `amount_a_required = amount_b * effective_pool_a / effective_pool_b` and use `(amount_a_required, amount_b)` - B is the binding side, so we take the full B and clamp A down. - The LP amount is `min(amount_a * total / effective_pool_a, amount_b * total / effective_pool_b)` with `total = liquidity_provider_mint.supply + MINIMUM_LIQUIDITY`: the unminted floor counts as supply, exactly as it does in `withdraw_liquidity`, so a deposit is minted the share of the pool it can later redeem. Counting the floor on both sides is also what makes the donation (inflation) attack cost the attacker: to round a later deposit down to zero LP tokens, the attacker has to donate at least `MINIMUM_LIQUIDITY + 1` times that deposit, and the floor keeps its share of the donation. -- All ratio math runs in `u128` with checked arithmetic. No floats are used for money; rounding is always toward the pool (the depositor never gets a sub-base-unit advantage). +- All ratio math runs in `u128` with checked arithmetic. No floats are used for money; rounding is always toward the pool (the depositor never gets a sub-minor-unit advantage). - The ratio is computed on the **effective reserves** (`pool_X.amount - admin_fees_owed_X`). The admin's owed slice isn't LP-claimable capital, so it doesn't shift the deposit ratio. -- If the clamp rounds one of the amounts down to zero (e.g. a depositor offering a sub-base-unit fraction against a thick pool), the handler reverts with `DepositAmountTooSmall` rather than minting LP shares against a zero contribution. +- If the clamp rounds one of the amounts down to zero (e.g. a depositor offering a sub-minor-unit fraction against a thick pool), the handler reverts with `DepositAmountTooSmall` rather than minting LP shares against a zero contribution. - If either effective reserve is zero, the handler reverts with `EmptyPoolReserve` rather than let the depositor set the price. The state is not reachable (every pool opens with both reserves positive, a withdrawal leaves the floor's share behind, and a swap's output is always less than the reserve it comes from); the check is there so the ratio math never divides by zero if that ever stopped being true. - If the computed LP-token amount falls below `minimum_lp_tokens_out`, the handler reverts with `DepositBelowMinimum`. This is the depositor's slippage guard for cases where the pool ratio shifted between offchain quote time and tx landing. @@ -140,7 +140,7 @@ Swaps a fixed `input_amount` of one token for as much of the other as possible ( ### `withdraw_liquidity` -Burns LP tokens and returns a proportional share of the **effective reserves** (`pool_X.amount - admin_fees_owed_X`) to the LP. The proportion is `amount / (liquidity_provider_mint.supply + MINIMUM_LIQUIDITY)`. The admin's owed slice physically remains in the vaults but is not distributed to exiting LPs - it's claimed separately via `claim_admin_fees`. All math is `u128` with checked arithmetic, multiplying before dividing; floor rounding leaves sub-base-unit dust with the pool (grows LP value for everyone still in). +Burns LP tokens and returns a proportional share of the **effective reserves** (`pool_X.amount - admin_fees_owed_X`) to the LP. The proportion is `amount / (liquidity_provider_mint.supply + MINIMUM_LIQUIDITY)`. The admin's owed slice physically remains in the vaults but is not distributed to exiting LPs - it's claimed separately via `claim_admin_fees`. All math is `u128` with checked arithmetic, multiplying before dividing; floor rounding leaves sub-minor-unit dust with the pool (grows LP value for everyone still in). - `minimum_token_a_out` and `minimum_token_b_out` are the LP's per-side slippage floors. If either computed amount falls below its floor, the handler reverts with `WithdrawalBelowMinimum` *before* any tokens move. Pass `0` on either side to opt out. This protects LPs from withdrawing during a pool imbalance (e.g. a large swap landed just before this tx and skewed the mix). @@ -202,8 +202,8 @@ Alice picks a 1:5 ratio so the NVDAx/USDC pool launches at ~5 USDC per NVDAx. Sh Math: - 20 NVDAx move from Alice's NVDAx account into `pool_a`, and 100 USDC from her USDC account into `pool_b`. -- LP tokens minted to Alice: `sqrt(20 × 100) = sqrt(2000) ≈ 44.72`, minus the withheld `MINIMUM_LIQUIDITY = 100` floor (base units - negligible at major-unit scale). -- Alice receives ~44.72 LP tokens. The 100 base-unit floor is never minted to anyone; its share of the reserves stays in the pool. Alice pays that cost as the price of opening the pool. +- LP tokens minted to Alice: `sqrt(20 × 100) = sqrt(2000) ≈ 44.72`, minus the withheld `MINIMUM_LIQUIDITY = 100` floor (minor units - negligible at major-unit scale). +- Alice receives ~44.72 LP tokens. The 100 minor-unit floor is never minted to anyone; its share of the reserves stays in the pool. Alice pays that cost as the price of opening the pool. NVDAx/USDC pool state: **20 NVDAx, 100 USDC**. Mid-price = 5. Alice owns 100% of withdrawable LP supply on this pool. Trading can start. @@ -243,9 +243,9 @@ At the current 1:5 ratio, Bob deposits **100 NVDAx and 500 USDC**. - `token_a` - Bob's NVDAx ATA, `token_b` - Bob's USDC ATA - `payer` = Bob - token, ATA, system programs -- **Args:** `amount_a = 100`, `amount_b = 500`, `minimum_lp_tokens_out = 223_000_000` (Bob quoted ~223.6 LP offchain and is unwilling to accept less than ~223.0 if the pool shifts before his tx lands; units here are LP base units at the LP mint's decimals) +- **Args:** `amount_a = 100`, `amount_b = 500`, `minimum_lp_tokens_out = 223_000_000` (Bob quoted ~223.6 LP offchain and is unwilling to accept less than ~223.0 if the pool shifts before his tx lands; units here are LP minor units at the LP mint's decimals) -Math: subsequent deposits get `min(amount_a / pool_a, amount_b / pool_b) × (current_lp_supply + MINIMUM_LIQUIDITY) = min(100/20, 500/100) × 44.72 ≈ 223.6` LP tokens (the 100 base-unit floor is too small to show at this precision). +Math: subsequent deposits get `min(amount_a / pool_a, amount_b / pool_b) × (current_lp_supply + MINIMUM_LIQUIDITY) = min(100/20, 500/100) × 44.72 ≈ 223.6` LP tokens (the 100 minor-unit floor is too small to show at this precision). NVDAx/USDC pool state: **120 NVDAx, 600 USDC**. LP supply ~268.32. Bob owns ~83%, Alice ~17%. diff --git a/finance/token-swap/anchor-v1/programs/token-swap/src/instructions/deposit_liquidity.rs b/finance/token-swap/anchor-v1/programs/token-swap/src/instructions/deposit_liquidity.rs index 61961b68..0b50e0be 100644 --- a/finance/token-swap/anchor-v1/programs/token-swap/src/instructions/deposit_liquidity.rs +++ b/finance/token-swap/anchor-v1/programs/token-swap/src/instructions/deposit_liquidity.rs @@ -71,7 +71,7 @@ pub fn handle_deposit_liquidity( // amount_b_required = amount_a * effective_pool_b / effective_pool_a. // Round down: this can only ever ask the depositor for *less* token B - // than perfect-ratio, which favours the pool by a sub-base-unit and + // than perfect-ratio, which favours the pool by a sub-minor-unit and // matches Uniswap V2. let amount_b_required = (amount_a as u128) .checked_mul(effective_pool_b as u128) @@ -99,8 +99,8 @@ pub fn handle_deposit_liquidity( // After clamping, both sides must contribute something. If either side // rounds to zero the deposit is too small to register at the current - // ratio (e.g. a depositor offering 1 base unit of A against a pool where - // 1 A is worth less than 1 base unit of B). Fail rather than letting an + // ratio (e.g. a depositor offering 1 minor unit of A against a pool where + // 1 A is worth less than 1 minor unit of B). Fail rather than letting an // LP mint zero-priced shares. if amount_a == 0 || amount_b == 0 { return err!(AmmError::DepositAmountTooSmall); diff --git a/finance/token-swap/anchor-v1/programs/token-swap/src/instructions/swap_tokens.rs b/finance/token-swap/anchor-v1/programs/token-swap/src/instructions/swap_tokens.rs index d9027fbf..140ee593 100644 --- a/finance/token-swap/anchor-v1/programs/token-swap/src/instructions/swap_tokens.rs +++ b/finance/token-swap/anchor-v1/programs/token-swap/src/instructions/swap_tokens.rs @@ -104,7 +104,7 @@ pub fn handle_swap_tokens( // u128 + checked: the numerator `taxed_input * reserve` can fill the // full u128 (both factors are u64). Multiply before divide to keep // precision. Floor on the divide is program-favouring (the pool keeps - // sub-base-unit rounding, the trader gets slightly less output) - same + // sub-minor-unit rounding, the trader gets slightly less output) - same // direction as Uniswap V2. let (this_reserve, other_reserve) = if input_is_token_a { (effective_pool_a, effective_pool_b) @@ -134,7 +134,7 @@ pub fn handle_swap_tokens( // trivially even when the LP-claimable reserves shrunk. // // u128 + checked: each side is u64, so the product can fill the full - // u128. Raw `*` on u64 would overflow at ~1.8e19 base units. + // u128. Raw `*` on u64 would overflow at ~1.8e19 minor units. let invariant = (effective_pool_a as u128) .checked_mul(effective_pool_b as u128) .ok_or(AmmError::MathOverflow)?; diff --git a/finance/token-swap/anchor-v1/programs/token-swap/src/instructions/withdraw_liquidity.rs b/finance/token-swap/anchor-v1/programs/token-swap/src/instructions/withdraw_liquidity.rs index 16f28f41..83bc62bf 100644 --- a/finance/token-swap/anchor-v1/programs/token-swap/src/instructions/withdraw_liquidity.rs +++ b/finance/token-swap/anchor-v1/programs/token-swap/src/instructions/withdraw_liquidity.rs @@ -59,7 +59,7 @@ pub fn handle_withdraw_liquidity( // // u128 + checked: `lp_amount * reserve` can fill the full u128 (both // factors are u64). Multiply before divide to preserve precision; floor - // is program-favouring (sub-base-unit rounding stays with the pool, + // is program-favouring (sub-minor-unit rounding stays with the pool, // grows LP value for everyone still in). // // Both amounts are computed up-front (before the slippage checks) so diff --git a/finance/token-swap/anchor-v1/programs/token-swap/tests/test_swap.rs b/finance/token-swap/anchor-v1/programs/token-swap/tests/test_swap.rs index 507cb39a..41b45d5d 100644 --- a/finance/token-swap/anchor-v1/programs/token-swap/tests/test_swap.rs +++ b/finance/token-swap/anchor-v1/programs/token-swap/tests/test_swap.rs @@ -1160,7 +1160,7 @@ fn test_deposit_after_swap_uses_shifted_effective_ratio() { let holder_b_after = get_token_account_balance(&ts.svm, &ts.holder_account_b).unwrap(); // The contract should have pulled exactly deposit_a (or deposit_a ± 1 - // base unit because of integer division rounding) and the full deposit_b. + // minor unit because of integer division rounding) and the full deposit_b. let used_a = holder_a_before - holder_a_after; let used_b = holder_b_before - holder_b_after; assert_eq!(used_b, deposit_b, "amount_b should be fully used"); @@ -1183,8 +1183,8 @@ fn test_deposit_too_small_for_ratio_reverts() { let mut ts = setup_pool(4_000_000, 1_000_000); // Opened at 4M:1M (A is "cheaper" - 4 A per 1 B). To force amount_b to - // round down to zero, the depositor must offer < 4 base units of A - // (so amount_b_required = amount_a * 1M / 4M = 0). We offer 1 base unit + // round down to zero, the depositor must offer < 4 minor units of A + // (so amount_b_required = amount_a * 1M / 4M = 0). We offer 1 minor unit // of A and a large amount_b. assert_error_code(send_deposit(&mut ts, 1, 1_000_000), "DepositAmountTooSmall"); } diff --git a/finance/token-swap/anchor/programs/token-swap/src/instructions/deposit_liquidity.rs b/finance/token-swap/anchor/programs/token-swap/src/instructions/deposit_liquidity.rs index eb92e7fc..8fa29c01 100644 --- a/finance/token-swap/anchor/programs/token-swap/src/instructions/deposit_liquidity.rs +++ b/finance/token-swap/anchor/programs/token-swap/src/instructions/deposit_liquidity.rs @@ -72,7 +72,7 @@ pub fn handle_deposit_liquidity( // amount_b_required = amount_a * effective_pool_b / effective_pool_a. // Round down: this can only ever ask the depositor for *less* token B - // than perfect-ratio, which favours the pool by a sub-base-unit and + // than perfect-ratio, which favours the pool by a sub-minor-unit and // matches Uniswap V2. let amount_b_required = (amount_a as u128) .checked_mul(effective_pool_b as u128) @@ -100,8 +100,8 @@ pub fn handle_deposit_liquidity( // After clamping, both sides must contribute something. If either side // rounds to zero the deposit is too small to register at the current - // ratio (e.g. a depositor offering 1 base unit of A against a pool where - // 1 A is worth less than 1 base unit of B). Fail rather than letting an + // ratio (e.g. a depositor offering 1 minor unit of A against a pool where + // 1 A is worth less than 1 minor unit of B). Fail rather than letting an // LP mint zero-priced shares. if amount_a == 0 || amount_b == 0 { return err!(AmmError::DepositAmountTooSmall); diff --git a/finance/token-swap/anchor/programs/token-swap/src/instructions/swap_tokens.rs b/finance/token-swap/anchor/programs/token-swap/src/instructions/swap_tokens.rs index eafff18d..ea34e42c 100644 --- a/finance/token-swap/anchor/programs/token-swap/src/instructions/swap_tokens.rs +++ b/finance/token-swap/anchor/programs/token-swap/src/instructions/swap_tokens.rs @@ -104,7 +104,7 @@ pub fn handle_swap_tokens( // u128 + checked: the numerator `taxed_input * reserve` can fill the // full u128 (both factors are u64). Multiply before divide to keep // precision. Floor on the divide is program-favouring (the pool keeps - // sub-base-unit rounding, the trader gets slightly less output) - same + // sub-minor-unit rounding, the trader gets slightly less output) - same // direction as Uniswap V2. let (this_reserve, other_reserve) = if input_is_token_a { (effective_pool_a, effective_pool_b) @@ -134,7 +134,7 @@ pub fn handle_swap_tokens( // trivially even when the LP-claimable reserves shrunk. // // u128 + checked: each side is u64, so the product can fill the full - // u128. Raw `*` on u64 would overflow at ~1.8e19 base units. + // u128. Raw `*` on u64 would overflow at ~1.8e19 minor units. let invariant = (effective_pool_a as u128) .checked_mul(effective_pool_b as u128) .ok_or(AmmError::MathOverflow)?; diff --git a/finance/token-swap/anchor/programs/token-swap/src/instructions/withdraw_liquidity.rs b/finance/token-swap/anchor/programs/token-swap/src/instructions/withdraw_liquidity.rs index fcefa0a4..c2d42779 100644 --- a/finance/token-swap/anchor/programs/token-swap/src/instructions/withdraw_liquidity.rs +++ b/finance/token-swap/anchor/programs/token-swap/src/instructions/withdraw_liquidity.rs @@ -59,7 +59,7 @@ pub fn handle_withdraw_liquidity( // // u128 + checked: `lp_amount * reserve` can fill the full u128 (both // factors are u64). Multiply before divide to preserve precision; floor - // is program-favouring (sub-base-unit rounding stays with the pool, + // is program-favouring (sub-minor-unit rounding stays with the pool, // grows LP value for everyone still in). // // Both amounts are computed up-front (before the slippage checks) so diff --git a/finance/token-swap/anchor/programs/token-swap/tests/test_swap.rs b/finance/token-swap/anchor/programs/token-swap/tests/test_swap.rs index 4bc3d969..f49eefef 100644 --- a/finance/token-swap/anchor/programs/token-swap/tests/test_swap.rs +++ b/finance/token-swap/anchor/programs/token-swap/tests/test_swap.rs @@ -1174,7 +1174,7 @@ fn test_deposit_after_swap_uses_shifted_effective_ratio() { let holder_b_after = get_token_account_balance(&ts.svm, &ts.holder_account_b).unwrap(); // The contract should have pulled exactly deposit_a (or deposit_a ± 1 - // base unit because of integer division rounding) and the full deposit_b. + // minor unit because of integer division rounding) and the full deposit_b. let used_a = holder_a_before - holder_a_after; let used_b = holder_b_before - holder_b_after; assert_eq!(used_b, deposit_b, "amount_b should be fully used"); @@ -1197,8 +1197,8 @@ fn test_deposit_too_small_for_ratio_reverts() { let mut ts = setup_pool(4_000_000, 1_000_000); // Opened at 4M:1M (A is "cheaper" - 4 A per 1 B). To force amount_b to - // round down to zero, the depositor must offer < 4 base units of A - // (so amount_b_required = amount_a * 1M / 4M = 0). We offer 1 base unit + // round down to zero, the depositor must offer < 4 minor units of A + // (so amount_b_required = amount_a * 1M / 4M = 0). We offer 1 minor unit // of A and a large amount_b. assert_error_code( send_deposit(&mut ts, 1, 1_000_000), diff --git a/finance/token-swap/kani-proofs/src/lib.rs b/finance/token-swap/kani-proofs/src/lib.rs index d3c665d2..316a0a36 100644 --- a/finance/token-swap/kani-proofs/src/lib.rs +++ b/finance/token-swap/kani-proofs/src/lib.rs @@ -331,7 +331,7 @@ pub fn deposit_lp_amount(amount: u64, effective_reserve: u64, lp_supply: u64) -> } /// A deposit followed at once by a withdrawal of the LP tokens it minted -/// returns at most what was deposited, and less than one base unit plus one +/// returns at most what was deposited, and less than one minor unit plus one /// LP token's worth short of it. The upper bound means no round trip creates /// value; the lower bound means the depositor is minted the share they paid /// for. The lower bound holds only because deposit and withdraw divide by the @@ -365,7 +365,7 @@ fn proof_deposit_withdraw_round_trip_is_fair() { // Never more than was put in. assert!(out <= amount); - // Short by less than one base unit plus one LP token's worth of reserve: + // Short by less than one minor unit plus one LP token's worth of reserve: // (out + 1) * (total + minted) + reserve > amount * (total + minted). let total_after = new_supply as u128 + MINIMUM_LIQUIDITY; assert!((out as u128 + 1) * total_after + reserve as u128 > amount as u128 * total_after);