Skip to content

fix(bets): route vote and place_bet through one validated stake ledger - #1478

Merged
greatest0fallt1me merged 5 commits into
Predictify-org:masterfrom
AnnieIj:fix/unify-stake-ledger
Oct 24, 2026
Merged

greatest0fallt1me merged 5 commits into
Predictify-org:masterfrom
AnnieIj:fix/unify-stake-ledger

Conversation

@AnnieIj

@AnnieIj AnnieIj commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

Closes #1454

Summary

vote and place_bet are the two exported ways to put tokens into a market. They wrote overlapping state (market.votes, market.stakes, market.total_staked) but checked different things: a vote followed by a bet silently overwrote the first stake (stranding those tokens — no claim path could reach them), and vote skipped the circuit breaker, stake validation, min/max bet limits, the max-participants accounting used by bets, and the per-ledger bet cap.

Both entrypoints now delegate to one validated stake ledger, bets::BetManager::record_stake(env, user, market_id, outcome, amount, source: StakeSource).

What changed

  • record_stake (bets.rs) runs, in this exact order: circuit breaker ("betting") → global per-ledger bet cap → market state (Active) → bet deadline → outcome validity → amount bounds (BetValidator, incl. per-market cap) → duplicate stake across both ledgers → max_participants capacity → per-user cap → checked total_staked (Error::Overflow, no trap) → lock_funds → state writes. No state is written before the transfer succeeds.
  • vote (lib.rs) keeps a single require_auth(), its voting rate limit, and now calls record_stake; the unchecked market.total_staked += stake is gone (grep -n 'total_staked +=' contracts/predictify-hybrid/src/lib.rs returns nothing).
  • place_bet_inner delegates to record_stake for validation/ledger writes and only stores bet-specific state after lock_funds succeeds. The batch place_bets loop also rejects vote-ledger stakes.
  • Duplicates: repeat vote → AlreadyVoted; repeat bet → AlreadyBet; cross-entrypoint stake (vote → bet or bet → vote) → AlreadyBet (single documented unified-ledger error, documented on Error::AlreadyBet in err.rs). The first stake is never overwritten.
  • cancel_bet only removes ledger entries the bet created (its exact mirror in market.stakes); a mismatched entry (pre-unification vote residue) is left claimable.

Regression proof (master, d806a26)

Replayed row 1 on master: vote(1_000_000) then place_bet(2_000_000) by the same user succeeds — stakes[user] is overwritten to 2_000_000, total_staked becomes 3_000_000, and 1_000_000 stroops are stranded (locked in the contract, unreachable by any claim or cancel path). Under this fix the second call is rejected atomically and the stranded amount can no longer be created.

Legacy (pre-fix) markets — storage compatibility

No Market layout change. Existing markets where one user already has both a vote and a bet (the master bug state) remain claimable: the bet-side mirror in market.stakes is authoritative for claims and cancels — exactly what claim_winnings/cancel_bet have always paid from. Tested in test_legacy_dual_entry_market_remains_claimable (legacy claim pays out; the master residue inflates the pool and accrues to claimants instead of being stranded) and test_legacy_cancel_only_removes_bet_owned_entries (cancel refunds the bet amount; residue stays in totals for admin remediation).

Test output

cargo test -p predictify-hybrid --lib
test result: ok. 739 passed; 0 failed; 203 ignored

New module contracts/predictify-hybrid/src/stake_ledger_unification_tests.rs (13 tests) covers all 9 issue rows: vote-then-bet rejection, bet-then-vote same error, circuit breaker parity (CBOpen, no token transfer), identical amount-bound errors for both entrypoints, participant capacity, typed overflow near i128::MAX, cancel/refund/restore, conservation (balance minus fees == outstanding claimable), and pinned error precedence for both entrypoints — plus legacy compatibility and the vote rate-limit path.

Coverage (cargo-llvm-cov, --lib)

Function Coverage
vote (lib.rs) 96.3%
place_bet_inner (bets.rs) 96.4%
record_stake (bets.rs) 100%
require_no_existing_stake (bets.rs) 100%

WASM size delta (slim build, scripts/build_testnet_wasm.sh)

Build Size
master 129,898 bytes
this PR 129,567 bytes
delta −331 bytes

Limit 131,072 bytes (128 KiB) — within budget. cargo check -p predictify-hybrid --no-default-features passes.

vote and place_bet maintained overlapping stake ledgers: a bet overwrote
a prior vote stake, permanently stranding those tokens, and vote skipped
the circuit breaker, stake validation, min/max limits, the
max-participants accounting used by bets, and the per-ledger bet cap.

Both entrypoints now delegate to a single validated record_stake that
runs, in order: circuit breaker, per-ledger cap, market state, bet
deadline, outcome, amount bounds, duplicate stake across both ledgers,
participant capacity, per-user cap, and checked total_staked - then
locks funds and writes the shared ledger. No state is written before
lock_funds succeeds. Cross-entrypoint duplicates return AlreadyBet; the
first stake is never overwritten or stranded. cancel_bet only removes
ledger entries that the bet itself created.

Covered by contracts/predictify-hybrid/src/stake_ledger_unification_tests.rs
(all 9 issue rows plus legacy pre-fix market compatibility).

Closes Predictify-org#1454
Predictify-org#1466 added predictify-analytics to the workspace (via the contracts/*
glob) but never committed its src/, so every cargo command failed to
load the workspace ("can't find library predictify_analytics") and the
Soroban CI build job has been red on master since.

Also fix the crate's Cargo.toml: the [depdevelopment-dependencies]
section name was a typo cargo silently ignored, and the dev-dependency
requested a `testutils` feature on predictify-hybrid that does not
exist (available: default, full), which broke version resolution for
the whole workspace.

Commit a placeholder lib so CI is green until the real analytics
contract sources land. Verified locally with the exact CI commands:
cargo build -p predictify-hybrid, cargo test -p hello-world -p oracles,
cargo test -p predictify-hybrid --lib (739 passed), and
cargo test -p predictify-analytics.
AnnieIj and others added 3 commits October 22, 2026 01:28
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	Cargo.lock
#	contracts/predictify-analytics/Cargo.toml
#	contracts/predictify-analytics/src/lib.rs
#	contracts/predictify-hybrid/src/bets.rs
#	contracts/predictify-hybrid/src/lib.rs
@greatest0fallt1me
greatest0fallt1me merged commit bf167bb into Predictify-org:master Oct 24, 2026
1 check failed
greatest0fallt1me added a commit that referenced this pull request Oct 24, 2026
* fix(ci): restore green master build after #1471/#1476/#1478

- rate_limit_enforcement_tests (from #1476) never compiled: it imported a
  non-existent crate::test_utils, called CircuitBreaker::set_state and
  CircuitBreakerState::Open which do not exist, and lacked the testutils
  Ledger trait import. Its tests also registered a second, uninitialised
  contract after setup, so they could not pass. Drop the module; the
  rate-limiter enforcement changes from #1476 are kept.
- BudgetGuard::check compared *consumed* instructions against the
  "minimum remaining" threshold, so distribute_payouts aborted with
  OperationWouldExceedBudget after 100k instructions. This was hidden
  while resolution auto-distributed with `let _ =`; #1471 made
  distribution an explicit call and its payout gating tests exposed it.
  Compute remaining headroom against a per-transaction ceiling instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(rate-limiter): align test_different_markets with per-user voting limit

#1476 changed the voting bucket key from (user, market) to user, making
the voting limit global per user. The old test still expected a fresh
budget on a second market.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(conservation): distribute payouts explicitly after the dispute window

#1471 removed the automatic distribution from resolve_market_manual, so
the conservation test must wait out the post-resolution dispute window
and call distribute_payouts before checking credited balances.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: greatest0fallt1me <greatest0fallt1me@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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.

vote() and place_bet() keep divergent stake ledgers (a vote then a bet strands funds, and vote() skips circuit breaker and bet limits)

2 participants