Skip to content

refactor(predict): migrate buy flow to single-route architecture with controller state machine#27761

Merged
caieu merged 87 commits into
mainfrom
predict/stay-on-preview
Mar 30, 2026
Merged

refactor(predict): migrate buy flow to single-route architecture with controller state machine#27761
caieu merged 87 commits into
mainfrom
predict/stay-on-preview

Conversation

@caieu

@caieu caieu commented Mar 20, 2026

Copy link
Copy Markdown
Contributor

Description

The Predict buy/order flow previously navigated between separate screens for preview, token selection, and deposit confirmation. This caused visible screen flicker and complex navigation state synchronization that led to multiple UX bugs (header flicker, input delay, stale deposit amounts, broken back-swipe behavior).

This PR migrates the entire buy flow to a single-route architecture where all order states (preview, token selection, deposit, order placement) are managed by PredictController and rendered inline within PredictBuyWithAnyToken. Key changes:

  • Controller state machine: Added ActiveOrderState enum (PREVIEW → PAY_WITH_ANY_TOKEN → DEPOSITING → PLACE_ORDER → PLACING_ORDER → SUCCESS) with dedicated controller methods for each transition (initializeOrder, onConfirmOrder, onDepositOrder, onDepositOrderSuccess, onDepositOrderFailed, onOrderError, onOrderCancelled, onPlaceOrderEnd, onBuyPaymentTokenChange).
  • Headless confirmation component: PredictPayWithAnyTokenInfo is now a headless component that syncs deposit amounts and payment tokens via effects, rather than living on a separate navigation screen.
  • Removed navigation-driven flows: Eliminated usePredictBuyBackSwipe, usePredictPayWithAnyToken, usePredictOrderTracking, usePredictPayWithAnyTokenTracking, and redirect/confirmation logic that drove screen transitions.
  • Simplified hooks: Streamlined usePredictBuyPreviewActions (reacts to activeOrder.state changes via effects), usePredictPaymentToken, usePredictActiveOrder, usePredictBuyInputState, and usePredictBuyConditions.
  • Feature flag: Gated pay-with-any-token logic behind a feature flag.
  • Transaction event handling: PredictController now handles predictDepositAndOrder transaction status events directly (confirmed → place order, failed → retry, rejected → cancel).

Net result: ~800 lines removed, eliminated screen flicker, and centralized order lifecycle in the controller instead of distributed across navigation hooks.

Changelog

CHANGELOG entry: null

Related issues

Fixes:

Manual testing steps

Feature: my feature name

  Scenario: user [verb for user action]
    Given [describe expected initial app state]

    When user [verb for user action]
    Then [describe expected outcome]

Screenshots/Recordings

Before

After

Pre-merge author checklist

Pre-merge reviewer checklist

  • I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed).
  • I confirm that this PR addresses all acceptance criteria described in the ticket it closes and includes the necessary testing evidence such as recordings and or screenshots.

Note

Low Risk
Mostly documentation and test-mock adjustments, plus a new error code mapping; low likelihood of runtime impact aside from any new code paths relying on the added error constant/i18n key.

Overview
Updates Predict/README.md with detailed documentation of the new PredictBuyWithAnyToken single-route buy flow, including its controller-driven active order state machine, component breakdown, and hook responsibilities.

Adjusts several Predict component tests to mock usePredictActiveOrder as returning only activeOrder (removing now-unused mocked methods), and extends PREDICT_ERROR_CODES/getPredictErrorMessages with PREVIEW_NOT_AVAILABLE.

Written by Cursor Bugbot for commit 8c2e6fc. This will update automatically on new commits. Configure here.

@github-actions

Copy link
Copy Markdown
Contributor

CLA Signature Action: All authors have signed the CLA. You may need to manually re-run the blocking PR check if it doesn't pass in a few minutes.

@metamaskbot metamaskbot added the team-predict Predict team label Mar 20, 2026
@caieu caieu force-pushed the predict/stay-on-preview branch from a06f3b8 to 6c18385 Compare March 23, 2026 17:40
@caieu caieu marked this pull request as ready for review March 23, 2026 19:32
@caieu caieu requested a review from a team as a code owner March 23, 2026 19:32
Comment thread app/components/UI/Predict/controllers/PredictController.ts Outdated
Comment thread app/components/UI/Predict/controllers/PredictController.ts Outdated
Comment thread app/components/UI/Predict/controllers/PredictController.ts Outdated
@github-actions github-actions Bot added risk-high Extensive testing required · High bug introduction risk and removed risk-high Extensive testing required · High bug introduction risk labels Mar 23, 2026
Comment thread app/components/UI/Predict/controllers/PredictController.ts Outdated
Comment thread app/components/UI/Predict/controllers/PredictController.ts
@github-actions github-actions Bot added risk-high Extensive testing required · High bug introduction risk and removed risk-high Extensive testing required · High bug introduction risk labels Mar 24, 2026
@github-actions github-actions Bot added risk-high Extensive testing required · High bug introduction risk and removed risk-high Extensive testing required · High bug introduction risk labels Mar 25, 2026
Comment thread app/components/UI/Predict/controllers/PredictController.ts Outdated
Comment thread app/components/UI/Predict/controllers/PredictController.ts Outdated
Comment thread app/components/UI/Predict/hooks/usePredictActiveOrder.ts
@github-actions github-actions Bot added risk-high Extensive testing required · High bug introduction risk and removed risk-high Extensive testing required · High bug introduction risk labels Mar 25, 2026
Comment thread app/components/UI/Predict/hooks/usePredictNavigation.ts
Comment thread app/components/UI/Predict/controllers/PredictController.ts
@github-actions github-actions Bot added risk-high Extensive testing required · High bug introduction risk and removed risk-high Extensive testing required · High bug introduction risk labels Mar 26, 2026
@github-actions github-actions Bot removed the risk-high Extensive testing required · High bug introduction risk label Mar 26, 2026
@github-actions github-actions Bot added the risk-high Extensive testing required · High bug introduction risk label Mar 28, 2026
Comment thread app/components/UI/Predict/controllers/PredictController.ts
Comment thread app/components/UI/Predict/controllers/PredictController.ts Outdated
caieu added 3 commits March 28, 2026 14:18
Replace direct ToastService calls with messenger.publish using the
existing ControllerEventToastBridge pattern. Add 'order' type to
PredictTransactionEventType and handle confirmed/failed statuses in
usePredictToastRegistrations. Also publish order failed event when
depositAndOrder fails and the user is not on the buy screen. Delete
utils/toasts.ts since all toast rendering now goes through the bridge.
Guard the order confirmed messenger event with !activeBuyOrder so it
only fires when the buy screen is unmounted. When the user is on screen,
usePredictBuyActions shows the toast directly via showOrderPlacedToast
from usePredictPlaceOrder on the SUCCESS state transition.
Comment thread app/components/UI/Predict/controllers/PredictController.ts
@github-actions github-actions Bot added risk-high Extensive testing required · High bug introduction risk and removed risk-high Extensive testing required · High bug introduction risk labels Mar 28, 2026
@github-actions github-actions Bot added risk-medium Moderate testing recommended · Possible bug introduction risk and removed risk-high Extensive testing required · High bug introduction risk labels Mar 28, 2026
Comment thread app/components/UI/Predict/controllers/PredictController.ts
Move order-related query invalidation out of PredictController.
Reuse invalidation from usePredictPlaceOrder for on-screen success,
and rely on transactionStatusChanged handling for background updates.
Update tests and docs to match the new ownership.
@github-actions github-actions Bot added risk-high Extensive testing required · High bug introduction risk and removed risk-medium Moderate testing recommended · Possible bug introduction risk labels Mar 29, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 2 potential issues.

There are 3 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Comment thread app/components/UI/Predict/controllers/PredictController.ts
Comment thread app/components/UI/Predict/controllers/PredictController.ts
caieu added 2 commits March 29, 2026 21:18
When the user places a bet via predictWithAnyToken and navigates away,
background deposit/order results now show actionable toasts:
- Order success → "View" button navigates to market details
- Deposit/order failure → "Try Again" button navigates to market details
The controller event payload is extended with an optional `marketId` so
the toast handler can route to the correct market. Buttons degrade
gracefully when marketId is absent.
When a deposit-and-order completes in the background while the user is
configuring a new bet, the background placeOrder call incorrectly updates
the new bet's activeBuyOrder state — causing loading spinners, false
success toasts, and auto-dismissal of the screen.
Root cause: isCurrentActiveBuyOrder returned true when
activeBuyOrder.transactionId was undefined, matching any incoming
transactionId. Fix: return false instead, since an active order without
a transactionId was never part of a deposit-order flow.
Additional guards:
- Only pass transactionId from handleConfirm for PAY_WITH_ANY_TOKEN flow
- Use isExistingPendingOrder to prevent background re-entry into PAT branch
- Defer pendingOrderPreviews cleanup to placeOrder finally block
- Publish events via messenger when background order completes without
  matching the active order
@github-actions github-actions Bot added risk-high Extensive testing required · High bug introduction risk and removed risk-high Extensive testing required · High bug introduction risk labels Mar 30, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔍 Smart E2E Test Selection

  • Selected E2E tags: SmokePredictions, SmokeWalletPlatform, SmokeConfirmations
  • Selected Performance tags: @PerformancePredict
  • Risk Level: high
  • AI Confidence: 88%
click to see 🤖 AI reasoning details

E2E Test Selection:
The PR introduces substantial changes to the Predictions (Polymarket) feature:

  1. PredictController.ts (CRITICAL): Major refactoring including:

    • State key rename: activeOrderactiveBuyOrder (breaking change in state shape)
    • New ActiveOrderState values: SUCCESS added, REDIRECTING removed
    • New transaction event types: depositAndOrder and order
    • New pendingOrderPreviews map for tracking pending orders
    • payWithAnyTokenConfirmation() renamed to initPayWithAnyToken() with different behavior
    • New methods: selectPaymentToken(), clearOrderError(), onPlaceOrderEnd()
    • Significant placeOrder() flow changes for "pay with any token" feature
    • Feature flag predictWithAnyTokenEnabled now controls new deposit+order flow
  2. Selectors: selectPredictActiveOrderselectPredictActiveBuyOrder (breaking rename)

  3. Hooks: Multiple hooks refactored - usePredictActiveOrder simplified, usePredictTrading updated

  4. PredictBuyWithAnyToken.tsx: Major UI refactoring - new component structure, feature flag integration, removed isConfirmation prop handling

  5. initial-background-state.json: activeOrderactiveBuyOrder rename affects test fixtures used across tests

  6. locales/en.json: New strings for prediction failure messages

Tag Selection Rationale:

  • SmokePredictions: Primary tag - all Predictions E2E tests must run to validate the new buy flow, deposit+order flow, error handling, and state management changes
  • SmokeWalletPlatform: Required per SmokePredictions description - Predictions is a section inside the Trending tab, and changes to Predictions views affect Trending
  • SmokeConfirmations: Required per SmokePredictions description - opening/closing positions are on-chain transactions that go through the confirmation flow; the new predictDepositAndOrder transaction type and initPayWithAnyToken flow directly interact with transaction confirmations

The initial-background-state.json change (activeOrder → activeBuyOrder) is a test fixture change that could affect any test using this state, but since it's scoped to the PredictController state key, only Predictions-related tests are impacted.

Performance Test Selection:
The PredictController has significant state management changes including new pendingOrderPreviews map, new transaction flow for deposit+order, and new feature flag resolution logic. The PredictBuyWithAnyToken view has been substantially refactored with new hooks and components. These changes could impact the rendering performance of the Predictions market screens and the deposit/order flow timing. @PerformancePredict covers prediction market list loading, market details, deposit flows, and balance display - all of which are affected by these controller and view changes.

View GitHub Actions results

@github-actions

Copy link
Copy Markdown
Contributor

E2E Fixture Validation — Schema is up to date
17 value mismatches detected (expected — fixture represents an existing user).
View details

@sonarqubecloud

Copy link
Copy Markdown

@caieu caieu enabled auto-merge March 30, 2026 17:47
@caieu caieu added this pull request to the merge queue Mar 30, 2026
Merged via the queue into main with commit daf5499 Mar 30, 2026
106 of 108 checks passed
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

release-7.73.0 Issue or pull request that will be included in release 7.73.0 risk-high Extensive testing required · High bug introduction risk size-XL team-predict Predict team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants