---
url: https://game-engine-io.github.io/enginex-frontend-sdk/predictions.md
---
# Predictions

`@getenginex/sdk-predictions` provides the EngineX prediction markets, built on top of the core client
(`@getenginex/sdk`). The operator installs only the product they have: whoever doesn't use predictions
doesn't load any predictions code.

The namespaces are [`markets`](/predictions/markets), [`comments`](/predictions/comments),
[`orders`](/predictions/orders) and [`portfolio`](/predictions/portfolio). Realtime lives in the
`@getenginex/sdk-predictions/realtime` entry ([Live orderbook](/predictions/live-orderbook)) and the mock
routes in `/testing`.

## Installation

```bash
npm i @getenginex/sdk @getenginex/sdk-predictions
# or
pnpm add @getenginex/sdk @getenginex/sdk-predictions
```

The core is a *peer dependency* of the predictions package: the app installs the core once and every
product package uses that same copy. The requirements are the core's (see
[Installation](/guide/installation)).

* **Core versions**: `@getenginex/sdk-predictions` declares the core as a peer `>=0.6.0 <1.0.0` (0.6.0
  brings the strict money handling and the per-attempt idempotency that the packages use; 0.5.0 was the
  first with `registerProductClient`, which connects Predictions to the
  [`/query`](/frameworks/) factories; up to Predictions 0.1.x, `>=0.3.0`). This range guides the package
  manager; the runtime guarantee is the core's **transport contract**: if the client comes from a copy of
  the core with an incompatible contract (e.g. two core versions installed), `createPredictions` throws
  `CONFIGURATION_ERROR` right away, instead of working halfway.
* **`zod`**: it is a regular dependency of both core and predictions (not a *peer*), deduplicated into a
  single copy when the ranges match. Install a single `zod` 4 at the top of the project (see
  [Installation](/guide/installation#single-zod-copy)).

## Create the predictions client

Create the core client as in [Getting started](/guide/getting-started) and pass it to
`createPredictions`:

```ts
// enginex.ts
import { createEnginexClient, localStorageTokenStore } from '@getenginex/sdk'
import { createPredictions } from '@getenginex/sdk-predictions'

export const enginex = createEnginexClient({
  locale: 'pt-BR',
  tokenStore: localStorageTokenStore(),
})

export const predictions = createPredictions(enginex)
```

`createPredictions` doesn't create its own session, tenant or transport and makes no request. Every
predictions method goes through the app's client:

* the same session and token refresh (a login done with `enginex.auth.login` also applies to predictions);
* the same tenant (`X-Original-Host`), `locale`, `timeout`, [`hooks`](/concepts/extensibility) and
  [validation](/concepts/validation);
* the same [errors](/concepts/errors) (`isEnginexError(error, code)`);
* `enginex.dispose()` shuts down predictions too: after it, every method rejects with
  `CONFIGURATION_ERROR`.

Create one predictions client per core client: in the browser, one per app; on the server, one per request,
together with the client. A value that isn't a client created by `createEnginexClient` (for example, a
`{ ...enginex }` copy) is rejected with `CONFIGURATION_ERROR`.

## Realtime

`predictionsTopics` (`@getenginex/sdk-predictions/realtime`) are the topics for the core's
`realtime.subscribe`. They live in a separate entry: importing `@getenginex/sdk-predictions` loads no
WebSocket code.

| Topic                                       | Message             | Access                  |
| ------------------------------------------- | ------------------- | ----------------------- |
| `predictionsTopics.orderbook({ marketId })` | `OrderbookUpdate`   | public                  |
| `predictionsTopics.trades({ marketId })`    | `TradeUpdate`       | public                  |
| `predictionsTopics.market({ marketId })`    | `MarketUpdate`      | public                  |
| `predictionsTopics.orders()`                | `OrderStatusUpdate` | private (requires login) |

Enums arrive in lowercase, as in REST. A `marketId` that is empty or has characters outside
`[a-zA-Z0-9_:.-]` throws `CONFIGURATION_ERROR` when the topic is created. Details and a full example in
[Live orderbook](/predictions/live-orderbook).

## Queries

`@getenginex/sdk-predictions/query` brings the Predictions factories for TanStack Query v5, with the
conventions of the [queries layer](/frameworks/#queries-layer): `createPredictionsQueries(predictions)`
returns one query factory per read method and `createPredictionsMutations(predictions)` one mutation per
write method, with the same names and inputs as the namespaces. They are plain objects: the package does
not depend on TanStack.

```ts
import { createPredictionsMutations, createPredictionsQueries } from '@getenginex/sdk-predictions/query'

const pq = createPredictionsQueries(predictions)
pq.markets.getMarket({ marketId: 'mkt-1' }) // { queryKey: ['enginex', 'public', 'markets', 'getMarket', { marketId: 'mkt-1' }], queryFn }
pq.portfolio.get() // { queryKey: ['enginex', 'user', userId, 'portfolio', 'get'], queryFn }

const pm = createPredictionsMutations(predictions)
pm.orders.place() // { mutationKey: ['enginex', 'orders', 'place'], mutationFn, invalidates }
```

| Kind | Factories |
| --- | --- |
| public reads (key `['enginex', 'public', ...]`, no login) | `markets.listCategories/listEvents/getEvent/listMarkets/getMarket/getOrderbook/getPriceHistory`, `comments.list` |
| player reads (key `['enginex', 'user', userId, ...]`) | `comments.listMine`, `orders.list/get`, `portfolio.listPositions/getPosition/get` |
| mutations | `orders.place/placeBatch/cancel/amend`, `comments.create/like/unlike` |

* `orders.*` invalidate `orders`, `portfolio` and the core's `wallet` (the balance); `comments.*` invalidate
  `comments.list` (of any market) and `comments.listMine`.
* `orders.place` is idempotent and accepts `{ idempotencyKey }` on the factory; `orders.placeBatch` keeps one
  key per order on the result of `createPredictionsMutations` (see [Orders](/predictions/orders)).
* Pass the object returned by `createPredictions` itself: a `{ ...predictions }` copy throws
  `CONFIGURATION_ERROR`.

In **React** (and Next.js), `useEnginexQueries` and `useEnginexMutations` take the product factory and the
predictions client, and memoize the result:

```tsx
import { createPredictionsMutations, createPredictionsQueries } from '@getenginex/sdk-predictions/query'
import { useEnginexMutation, useEnginexMutations, useEnginexQueries, useEnginexQuery } from '@getenginex/sdk-react'
import { predictions } from './enginex'

function BuyYes({ marketId }: { marketId: string }) {
  const pq = useEnginexQueries(createPredictionsQueries, predictions)
  const pm = useEnginexMutations(createPredictionsMutations, predictions)
  const market = useEnginexQuery(pq.markets.getMarket({ marketId }))
  const place = useEnginexMutation(pm.orders.place())
  return (
    <button
      disabled={place.isPending}
      onClick={() => place.mutate({ marketId, side: 'yes', direction: 'buy', price: 40, quantity: 10 })}
    >
      Buy YES on {market.data?.title}
    </button>
  )
}
```

In **Vue**, the same pair comes from `@getenginex/sdk-vue`; `useEnginexQuery` takes a getter, so the query
follows `props.marketId`:

```vue
<script setup lang="ts">
import { createPredictionsQueries } from '@getenginex/sdk-predictions/query'
import { useEnginexQueries, useEnginexQuery } from '@getenginex/sdk-vue'
import { predictions } from './enginex'

const props = defineProps<{ marketId: string }>()
const pq = useEnginexQueries(createPredictionsQueries, predictions)
const market = useEnginexQuery(() => pq.markets.getMarket({ marketId: props.marketId }))
</script>

<template>
  <h1>{{ market.data.value?.title }}</h1>
</template>
```

To keep the orderbook and the orders fresh without polling, feed `useRealtimeSync` with
`predictionsTopics` and these factories' keys (see [React](/frameworks/react) and [Vue](/frameworks/vue)).

## Testing

`@getenginex/sdk-predictions/testing` adds the predictions mock routes to the core's `createMockFetch`
(see [Testing and mocks](/guide/testing)). The core routes still apply, and yours (`routes`) win over the
predictions ones:

```ts
import { createEnginexClient } from '@getenginex/sdk'
import { createMockFetch } from '@getenginex/sdk/testing'
import { createPredictions } from '@getenginex/sdk-predictions'
import { withPredictionsRoutes } from '@getenginex/sdk-predictions/testing'

const enginex = createEnginexClient({
  baseUrl: 'https://gateway.test', // in Node: absolute baseUrl + tenantHost (optional in the browser)
  tenantHost: 'casino.test',
  fetch: createMockFetch(withPredictionsRoutes()),
})
const predictions = createPredictions(enginex)
```

To build the routes object by hand, use `createPredictionsRoutes()`, which returns fresh routes (with their
own state) on every call.
