Skip to content

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

Closed

Description

@greatest0fallt1me

Summary

The slim build exports two ways to put tokens into a market: vote and place_bet. They write overlapping state (market.votes, market.stakes and market.total_staked) but check different things.

  • A user who votes and then bets has their first stake silently overwritten. Those tokens stay in the contract, but no claim path can ever reach them.
  • vote also skips the circuit breaker, stake validation, min/max bet limits, the max-participants accounting used by bets, and the per-ledger cap.

This issue makes the two paths share one validated stake ledger.

Background and evidence

  • vote (lib.rs around line 1051, exported in the slim build):
    • There is no CircuitBreaker::require_write_allowed call. place_bet calls it with "betting", so vote keeps accepting funds while betting is paused.
    • There is no validation that stake > 0, and no BetValidator::validate_bet_parameters (min/max limits, per-market cap). A zero stake registers a vote and takes a max_participants slot.
    • market.total_staked += stake is unchecked. With overflow-checks = true in the release profile this traps instead of returning a typed error.
    • It rejects a repeat only via market.votes (AlreadyVoted), and never looks at BetStorage.
  • BetManager::place_bet_inner (bets.rs around line 387):
    • It rejects a repeat only via BetStorage (AlreadyBet), and never looks at market.votes.
    • It then writes market.votes.set(user, outcome) and market.stakes.set(user, amount), overwriting any earlier vote and stake, while total_staked adds both.
  • Where the first stake goes.
    • claim_winnings (lib.rs around line 1857) and distribute_payouts pay from market.stakes[user], so only the second amount is ever paid out.
    • BetManager::cancel_bet (bets.rs around line 997) refunds bet.amount and then removes market.votes[user] and market.stakes[user]. The first stake is then permanently orphaned, and total_staked stays inflated by it.
  • Totals disagree. get_market_bet_stats (outcome_totals) counts only bets, while ResolutionOutcomeCache uses market totals. The odds that integrators show therefore ignore vote stakes.

Scope

In scope

  1. One stake-entry function.
    • Extract an internal fn record_stake(env, user, market_id, outcome, amount, source: StakeSource) -> Result<(), Error>.
    • It runs, in order: circuit breaker, market active and before the deadline, outcome valid, amount bounds via BetValidator, the max-participants check, a duplicate check across both market.votes and BetStorage, a checked total_staked, lock_funds, then the state writes.
    • Both vote and place_bet call it. user.require_auth() stays once, in the entrypoint or in place_bet_inner, never in both.
  2. No overwrites. A user who has voted cannot then place_bet on the same market, and vice versa. Return a single error (AlreadyBet, or a new AlreadyStaked) and document it in err.rs.
  3. Typed errors in vote. Use checked arithmetic and return typed errors instead of panicking on overflow.
  4. Consistent cancellation. cancel_bet must only remove ledger entries that it created.
  5. Docs. Document the unified rules in docs/bet/ (or the bets.rs module docs) and list the new error code.

Out of scope

  • Removing vote from the API (a separate deprecation decision).
  • Changing payout math.

Design constraints

  • Error precedence, the same for both entrypoints: circuit breaker, then market state, then deadline, then outcome, then amount, then duplicate, then capacity, then overflow. Pin this with a test.
  • Atomicity. No state is written before lock_funds succeeds, matching the existing "atomic commit" contract in place_bet_inner.
  • Storage compatibility. No layout change to Market. Existing markets where both entries already exist must still be claimable: document how they are handled, and test it.
  • WASM size. The slim build stays at or below 131,072 bytes. Report the delta.

Test plan

Add contracts/predictify-hybrid/src/stake_ledger_unification_tests.rs.

# Scenario Expected
1 vote(S1) then place_bet(S2) by the same user the second call fails; stakes[user] == S1; total_staked == S1
2 place_bet(S2) then vote(S1) the second call fails with the same error
3 vote while the circuit breaker has betting paused CBOpen (or the same error place_bet returns); no token transfer
4 vote with stake 0 / negative / below min / above the market cap the matching typed error, identical to place_bet
5 vote filling max_participants, then place_bet from a new user MaxParticipantsReached
6 total_staked near i128::MAX typed overflow error, no trap
7 cancel_bet after a bet-only stake refund equals the amount; votes and stakes are cleared; total_staked restored
8 Conservation after mixed vote and bet activity, resolution and claims: the contract token balance minus fees equals the outstanding claimable amount
9 Error precedence inputs violating several rules return the first error in the documented order, for both entrypoints

Regression proof. Row 1 succeeds on current master, which overwrites the stake and strands S1. Show the stranded amount in the PR.

Acceptance criteria

  • vote and place_bet both delegate to one validated stake function.
  • grep -n 'total_staked +=' contracts/predictify-hybrid/src/lib.rs returns nothing.
  • cargo test -p predictify-hybrid --lib passes, and every row above is covered.
  • cargo check -p predictify-hybrid --no-default-features passes; slim WASM size reported.
  • Coverage is at least 95% on vote, place_bet_inner and the new function.

Getting started

git checkout -b fix/unify-stake-ledger
cargo test -p predictify-hybrid --lib bets
cargo test -p predictify-hybrid --lib voting

Read these first:

  • lib.rs: vote, claim_winnings
  • bets.rs: place_bet_inner, cancel_bet, BetValidator::validate_bet_parameters, BetUtils::lock_funds

PR requirements

  • Link this issue (Closes #<n>).
  • Explain how markets that already have both a vote and a bet for a user are handled.
  • Paste the test output, the coverage and the WASM size delta.
  • Example commit: fix(bets): route vote and place_bet through one validated stake ledger.

Priority rationale

High. Users can lose funds through normal use of two exported entrypoints, and vote bypasses the emergency pause. A correct fix touches the betting, voting, cancellation and claim paths, and needs careful thought about atomicity and backwards compatibility.

Activity

  1. added
    smart-contract
    Stellar Wave
    security
    priority:high
    on Oct 18, 2026
  2. AnnieIj commented on Oct 18, 2026

    @AnnieIj
    Contributor

    @AnnieIj has applied to work on this issue as part of the Stellar Wave Program's 10th wave.

    Hi maintainer, I would love to work on this issue.

    ℹ️ Repo Maintainers: To accept this application, review their application or assign @AnnieIj to this issue.

  3. drips-wave commented on Oct 19, 2026

    @drips-wave

    Congratulations, @AnnieIj! 🎉 Your application was accepted by the repo's maintainers, and the issue is due on October 22, 2026.

    🧑‍💻 @AnnieIj: Please resolve the issue such that the repo's maintainers have enough time to review your contribution before the due date. You'll earn Points for completing the issue on-time, which will make you eligible for a share of the Stellar Wave Program's reward pool.

    Warning

    When opening a PR, please link it to this issue to ensure it gets tracked accurately. Points are awarded when this issue is marked as completed by the maintainer.

    🤠 Repo maintainers: Please keep an eye on the contributor's progress and review their work before the due date. You can manage this issue, including adjusting its complexity and points, here.

    🌊 Happy Wave 🌊

  4. drips-wave commented on Oct 24, 2026

    @drips-wave

    This issue has been completed by @AnnieIj as part of the Stellar Wave Program's 10th Wave 🥳

    😎 @AnnieIj: You earned 100 Points for completing this issue! Once the Wave's rewards are finalized, you'll be eligible for a percentage of the Wave's reward pool based on the percentage of total points you've earned. Learn more here. You can also Leave a review to share your experience working on this issue.

    🧑‍💻 Repo maintainers: How'd the contributor do? Leave a review to share your experience working with them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Stellar Wavebetspriority:highsecuritysmart-contract

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions