Skip to content

#599 Fixed-Point-Math | Constant Product Invariants via U256 High-Precision Engine - #3

Open
oraimoitel wants to merge 50 commits into
mainfrom
feature/fixed-point-math-599
Open

#599 Fixed-Point-Math | Constant Product Invariants via U256 High-Precision Engine#3
oraimoitel wants to merge 50 commits into
mainfrom
feature/fixed-point-math-599

Conversation

@oraimoitel

Copy link
Copy Markdown
Owner

Description

Core AMM swap module maintaining constant product (x * y = k) invariants without precision loss or rounding vulnerabilities.

Changes

  • Created src/amm/invariant.rs with U256 struct (two u128 words) for 256-bit intermediate products
  • compute_swap_out: out = reserve_out * amount_in / (reserve_in + amount_in) with floor rounding
  • compute_lp_shares: min(a * total / reserve_a, b * total / reserve_b) with floor rounding
  • compute_remove_liquidity: proportional withdrawals with floor rounding
  • assert_invariant_stable: verifies k is non-decreasing after swaps
  • All rounding directional bias favors pool reserves (floor division)
  • Unit tests covering basic ops, max bounds, high-volume scenarios

Closes StellarFlow-Network#599

AliceTenni and others added 30 commits July 24, 2026 20:26
Exposes advanced administrative operations on public test networks before
full audit completion poses unmitigated configuration security risks. This
change adds a conditional access layer that restricts execution of admin
write pathways to an explicit tester allowlist whenever staging mode is
active.

Changes:
- src/staging.rs (new): StagingConfig struct, set_staging_mode,
  add_tester, remove_tester, is_staging_active, get_staging_config,
  and check_staging_access — the core gate function. Includes unit
  tests covering all allowlist lifecycle scenarios.
- src/lib.rs: add StagingNotAuthorized (error code 37), STAGING_KEY
  constant, pub mod staging declaration, and wire check_staging_access
  into propose_upgrade, execute_upgrade, cancel_upgrade, set_value,
  set_heartbeat_interval, and upsert_node_profile. Expose staging
  management as public contract functions (set_staging_mode,
  add_staging_tester, remove_staging_tester, is_staging_active,
  get_staging_config).
- src/admin.rs: wire check_staging_access into propose_admin_change
  and propose_ownership_transfer.
- src/test.rs: add 7 integration tests covering: staging off (no-op),
  management restricted to admin, unauthorized callers blocked on all
  pathways, authorized testers clearing the gate, admin always passing,
  disabling staging unblocking callers, and add/remove lifecycle.

Access decision table:
  staging off            -> pass (no-op, existing rules apply)
  staging on + is admin  -> pass
  staging on + in list   -> pass
  staging on + neither   -> StagingNotAuthorized

The check fires before the NotAdmin guard so unauthorized callers are
rejected at the earliest possible point without leaking information
through downstream error differences.
…rFlow-Network#595)

Add N-of-M multi-sig authorization for WASM bytecode upgrades:

- GovernanceConfig with configurable quorum_threshold stored in instance storage
- verify_upgrade_quorum() checks collected signature weight against threshold
- propose_upgrade() validates quorum at proposal time, stores signer list
- execute_upgrade() re-verifies quorum at execution time (prevents signer-removal race)
- Emit GV_UPG_PROPOSED event on proposal registration
- Clean up governance proposal record on cancel/execute
…imitives

- Migrate CooldownStage.description from soroban_sdk::String to Symbol
- Replace verbose String::from_str stage descriptions with symbol_short!
  macros: INIT, REVIEW, APPROVE for stages 1-3 respectively
- Update configure_cooldown_stage parameter from String to Symbol
- Update tests to use symbol_short! instead of String::from_str

CooldownAction.data remains String (holds bech32 address payload for
the UpdateToken action path via Address::from_string).

Closes: memory-sanitization asset key lookup task
ethnum 1.5.0 has a mem::transmute bug (E0512) on newer Rust stable
builds. The lockfile already pins ethnum to 1.5.1 (fixed), but CI
rolling dtolnay/rust-toolchain@stable onto a newer Rust was causing
the crates.io cache to resolve 1.5.0 in some dependency paths.

Pinning the toolchain to 1.81.0 (the stable release this SDK was
developed against) makes CI deterministic and eliminates the drift.
base64ct 1.8.3 (pulled by the dependency tree) declares edition = 2024
which requires Cargo >= 1.85. Rust 1.81 predates edition2024
stabilisation (landed in 1.85.0, 2025-02-20), causing the build to
fail with 'feature edition2024 is required'.

Bumping the pin to 1.85.0 satisfies base64ct and all other transitive
deps without introducing nightly instability.
…nction bodies

Multiple functions had their old implementation left inline without a
closing brace before the refactored version was inserted, causing the
compiler to report cascading unclosed delimiter errors:

- get_last_update_timestamp: removed stale Symbol-keyed body
- is_data_fresh: removed stale HEARTBEAT_KEY map-based body
- add_corridor_fees: added missing closing brace on old Symbol body
- _resolve_feed_metrics: restored missing body preamble and closing brace
- update_validator_profile: removed duplicate one-liner signature
- get_feed_stake: removed orphaned Symbol-keyed variant
- get_corridor_fee_pool: removed orphaned Symbol-keyed variant
- remove_signer/vote_revocation: added missing closing brace
- _load_data: removed duplicate private function definition
- stake_and_register_for_feed: removed duplicate feed_key declaration
- FeedStakeRecord return: removed stray comma/whitespace tokens
Resolves all compilation errors caused by accumulated merge conflicts:

- Removed duplicate pub mod admin declaration
- Deduplicated all use/import statements (governance, validation, staking_tiers)
- Fixed ContractError enum: unique discriminants 1-37, removed all
  duplicate variants (InvalidVarianceConfig=28 x3, StaleTelemetryPayload
  x3, StaleSequence collision with InvalidVarianceConfig=28)
- Removed duplicate const SIGNERS_KEY definition
- Removed broken vote_revocation first body (wrong proposer.require_auth,
  undefined variables target/replacement/proposer)
- Removed duplicate update_heartbeat (old Symbol-based body)
- Fixed get_stake: removed duplicate Map-based body, kept StakeKey path
- Removed duplicate _resolve_feed_metrics (kept final corridor-aware version)
- Removed duplicate _revocation_threshold (kept signer_count-based version)
- Removed duplicate _get_signers/_get_node_profiles definitions
- Removed duplicate execute_upgrade pending lookup block
- Fixed set_asset_feed_metrics: removed duplicate .set() call with wrong key
- Fixed add_corridor_fees: unified to AssetId-based signature
- Removed all orphaned stray code fragments between function bodies
- upsert_node_profile: removed duplicate Map-based profiles block
Add atomic multi-token route execution (e.g., XLM -> USDC -> EURT)
within a single transaction frame.

- HopStep/Route/HopResult/RouteResult types with contracttype derives
- validate_route() pre-flight checks (empty route, hop limit, zero
  amounts, asset chain continuity, pool liveness)
- execute_route() sequential hop engine with slippage enforcement and
  snapshot-based rollback tracking
- estimate_route() read-only quoting
- execute_single_hop() constant-product AMM pricing via CorridorFeePool
- 7 new ContractError variants (EmptyRoute through SlippageExceeded)
- Module tests for validation, types, and error paths
Add tick index infrastructure for stable fiat corridor pools to maximize
capital efficiency via concentrated liquidity positions.

- TickIndexMeta / TickData types with contracttype derives
- Sorted Vec<i32> tick list with O(log n) binary search lookup
- initialize_tick_index() pool setup with configurable tick spacing
- place_liquidity() atomic gross + net liquidity updates
- find_next_initialized_tick() sub-linear traversal for swap execution
- simulate_swap_across_ticks() multi-tick swap with fee deduction
- tick_to_price() iterative (10001/10000)^i approximation
- integer_sqrt() Babylonian method for price math
- compute_step_input / compute_step_output for concentrated liquidity AMM
- range_efficiency_bps() capital efficiency calculator
- Stable (1) and volatile (60) tick spacing presets
- 6 new ContractError variants (InvalidTickSpacing through TooManyTicks)
- 25+ unit tests covering search, placement, traversal, and math
…and time-lock refund

Add hash time-locked contract settlement for trustless cross-border
settlement, unlocked via secret pre-image verification or refunded
upon deadline ledger sequence expiration.

- Htlc struct with depositor, beneficiary, hash_lock, deadline_sequence,
  amount, and Active/Claimed/Refunded state machine
- create_htlc() locks funds with SHA-256 hash and ledger-sequence deadline
- claim() verifies sha256(pre_image) == hash_lock before deadline
- refund() returns funds to depositor after deadline_sequence expires
- Per-depositor active HTLC counter with MAX_ACTIVE_HTLCS cap (64)
- Deadline bounds enforcement (MIN_DEADLINE_OFFSET=10, MAX=6.3M sequences)
- Query helpers: get_htlc, active_htlc_count, is_expired, is_claimable
- 8 new ContractError variants (HtlcNotFound through TooManyActiveHtlcs)
- 20+ unit tests covering create/claim/refund lifecycle, auth, edge cases
Centralize event publishing behind a validated helper that enforces a
maximum of 4 indexed Symbol topics per event, ensuring all contract
events are filterable via soroban RPC getEvents topic vectors.

- MAX_EVENT_TOPICS = 4 constant with validate_topics() guard
- emit_event() core publisher builds Vec<Symbol> topic list and rejects
  over-limit calls with EventTopicLimitExceeded error
- emit_simple2/3/4() convenience publishers for 2/3/4-topic patterns
- 33 standardized EV_* Symbol constants (snake_case, ≤9 bytes) covering
  oracle, HTLC, router, admin, staking, slashing, and governance events
- Uniqueness test ensures no two constants collide
- Migrated 6 existing event sites across htlc.rs, multihop.rs,
  consensus.rs, and lib.rs to use the new API
- 1 new ContractError variant: EventTopicLimitExceeded (discriminant 58)
…interface

Standardize cross-contract operations for native XLM, classic Stellar asset
wrappers, and native Soroban tokens via a unified SAClient that wraps
soroban_sdk::token::Client. All token types share the identical host-function
execution path, confirmed by unit tests.
…igh-precision engine

Core AMM swap math maintaining x*y=k without precision loss:
- U256 struct for 256-bit intermediate products of two u128 values
- mul_div with full precision, always rounding down (favors pool reserves)
- compute_swap_out, compute_lp_shares, compute_remove_liquidity
- assert_invariant_stable checks k is non-decreasing
- Unit tests covering basic ops, max bounds, high volume scenarios
…maximum-slippage-tolerance-601

feat: maximum slippage tolerance enforcement
…vent-telemetry-swap-executed

feat(events): add SwapExecuted event publisher (StellarFlow-Network#609)
…overy

State-Recovery | Automated Instance-Level State Auto-Restoration Helper
…set-standardization-605

feat: StellarFlow-Network#605 - Unified Stellar Asset Contract (SAC) interface
ayandipe and others added 20 commits July 27, 2026 12:58
…oop/feat/memory-sanitization-symbol-asset-keys

refactor(reward-splitter): replace String descriptions with Symbol primitive
…ng-tester-allowlist-v2

feat(security): add staging-phase tester allowlist for admin pathways
…589-ttl-renewal

feat(storage): automate ledger TTL renewal for persistent entries
…isig-quorum-upgrade

🏛️ Multi-Sig Governance: Quorum Threshold Checker for WASM Upgrades (Issue StellarFlow-Network#595)
…cked-math-safeguards

Enforce checked math safeguards
Fix issue StellarFlow-Network#607: anchor verification for off-ramp callback attestation
…ultihop-router

feat(router): implement multi-hop cross-border settlement router
…vent-topic-standardization

Feat/event topic standardization
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🧮 Fixed-Point-Math | Constant Product Invariants via U256 High-Precision Engine