---
url: https://game-engine-io.github.io/enginex-frontend-sdk/igaming/loyalty.md
---
# Loyalty

The demo above uses `createIgaming(enginex)` on a client with `createMockFetch(withIgamingRoutes())`:
no call goes out to the network. See the points and the tier, redeem points (the button stays locked
while the request is in flight; asking for more than the balance returns `INSUFFICIENT_BALANCE`) and,
in the other scenarios, the progress of the [missions](/igaming/missions) and the history of
[referrals](/igaming/referrals) (only the masked email; the referee's name is hidden in the panel).

The `loyalty` namespace of [`@getenginex/sdk-igaming`](/igaming/) shows the player's points and tier
and redeems points. Both methods require login. In tests, `withIgamingRoutes` already answers both
routes (see [Testing](#tests)).

## Balance and tier

```ts
const loyalty = await igaming.loyalty.get()
console.log(loyalty.currentPoints, loyalty.currentTier, loyalty.tierExpiresAt)
```

`LoyaltyStatus` carries:

| Field | What it is |
| --- | --- |
| `totalPointsEarned`, `currentPoints`, `pointsRedeemed` | points earned in total, available and already redeemed (integers) |
| `currentTier` | current tier; `null` if the gateway does not report it (empty or absent) |
| `tierPoints` | points that count toward the tier (integer) |
| `lifetimeWagered`, `lifetimeDeposited` | total wagered and deposited over the player's lifetime, in minor units (the contract field is named `*_cents`; the currency does not come with it) |
| `tierBenefits` | benefits of the current tier, as an object; `null` if empty or invalid |
| `tierExpiresAt` | ISO 8601 (UTC); `null` when the gateway does not send it |

The contract (`bonus.proto`) does not list the possible tiers, does not say how `tierPoints` is
calculated and has no field for "points missing to the next tier". Show what the gateway returns; the
rest is operator rules, **not confirmed by the contract**.

## Tier benefits

The gateway passes `tier_benefits_json` along as **JSON text**; the SDK runs `JSON.parse` and delivers
an object in `tierBenefits`:

```ts
const { tierBenefits } = await igaming.loyalty.get()
if (tierBenefits) {
  console.log(Object.keys(tierBenefits)) // the keys are defined by the operator
}
```

* Empty or absent text: `tierBenefits` is `null`, with no warning.
* Text that is not valid JSON, or that is JSON but not an object (array, string, number, `null`):
  `tierBenefits` is `null` and `onValidationIssue` is notified under `validation: 'warn'`. The warning
  carries only the field path (`tier_benefits_json`) and the message, never the text. Under `'strict'`
  the call rejects with `VALIDATION_ERROR`.
* The shape of the object (which keys and values) **is not defined by the contract**: the proto only
  says "benefits of the current tier". Agree on it with the operator before displaying any key, and
  handle missing keys and types.

::: warning The issue's `raw`
In `onValidationIssue`, the `raw` property carries the whole response body (with sensitive keys
masked), and `tier_benefits_json` is not one of them. If your hook sends the issue to an external
service, discard `raw` or mask that field.
:::

## Redeem points

```ts
async function redeem(points: number) {
  setBusy(true) // lock the button: see below
  try {
    const result = await igaming.loyalty.redeem({ points, redemptionType: 'bonus' })
    console.log(result.redeemedPoints, result.value, result.currency, result.bonusId)
    await igaming.loyalty.get() // refresh the balance
  } catch (error) {
    if (isEnginexError(error, 'INSUFFICIENT_BALANCE')) showMessage('Insufficient points')
    else throw error
  } finally {
    setBusy(false)
  }
}
```

* **Input:** `points` is an integer greater than 0 and `redemptionType` a non-empty string (only spaces
  is also refused); otherwise the call rejects with `CONFIGURATION_ERROR`, with no request (and the
  message does not carry the received value).
* **`redemptionType`:** `bonus.proto` comments `bonus`, `cash` and `free_bet`, but the field is free text
  and the contract does not say which ones the operator enables. The SDK sends the value as received and
  does not validate the list (`'bonus' | 'cash' | 'free_bet' | (string & {})`).
* **Result:** `redeemedPoints` (integer); `value` (minor units of `currency`) and `currency` only come
  when the service returns the value, otherwise `null`; `bonusId` only when the redemption generated a
  bonus (the proto comments "if redeemed into a bonus"), otherwise `null`. The gateway answers HTTP 200.
* **The `success` field** that the gateway returns is not exposed: the SDK only delivers the result when
  it is `true`. With HTTP 200 and `success: false` (or absent, or malformed, even under
  `validation: 'warn'`) the call rejects with `UNKNOWN` (`status` 200), with the gateway's message when
  there is one (otherwise the SDK's), and fires `onError` once; check `get()` before trying again
  ([unconfirmed operation](/concepts/compliance-errors#unconfirmed-operation)).

### Idempotency and double click

`redeem` is marked as idempotent: it sends the `Idempotency-Key` header (generated per call or the one
from `options.idempotencyKey`) and keeps the same key on the retry after refreshing the session (see
[Idempotency](/concepts/idempotency)).

::: warning The gateway does not protect this route yet
The key is sent **for future compatibility**: today the gateway does not apply the idempotency
middleware to `POST /loyalty/redeem`. In practice, **a double click can redeem twice**. Lock the button
while the call is in flight and only release it when it finishes. After a `NETWORK_ERROR` or `TIMEOUT`,
do not retry blindly: check `get()` and confirm whether the points were deducted.
:::

## Errors

| Code | When |
| --- | --- |
| `UNAUTHENTICATED` (401) | no session |
| `CONFIGURATION_ERROR` | invalid `points` or `redemptionType` (no request) or client already disposed |
| `INSUFFICIENT_BALANCE`, `FAILED_PRECONDITION` | the service refuses the redemption (points balance, minimum, type not enabled). **The contract does not confirm** which code the service uses in each case: decide by `error.code` and show a generic message for the rest |
| `UNKNOWN` (status 200) | the gateway answered without confirming the redemption (`success` different from `true`) |
| `VALIDATION_ERROR` | only under `validation: 'strict'`: `tier_benefits_json` that is not a JSON object, or a malformed response |

## What the gateway does not offer yet

* **List of tiers and program rules**: the service has a program (`LoyaltyProgram`, with point value,
  redemption minimum, points expiry and the list of tiers), but the gateway does not expose a route for
  it. Point value, redemption minimum and tiers must come from the operator (or from your backend).
* **Idempotency on redemption**: there is no middleware on `POST /loyalty/redeem`; lock the button.
* **History of points and redemptions**: no route.
* **Available redemption types**: no route lists which ones the operator enables.

## Testing {#tests}

```ts
import { createEnginexClient } from '@getenginex/sdk'
import { createMockFetch } from '@getenginex/sdk/testing'
import { createIgaming } from '@getenginex/sdk-igaming'
import { withIgamingRoutes } from '@getenginex/sdk-igaming/testing'

const enginex = createEnginexClient({
  baseUrl: 'https://gateway.test', // in Node: absolute baseUrl + tenantHost (optional in the browser)
  tenantHost: 'casino.test',
  fetch: createMockFetch(withIgamingRoutes()),
})
const igaming = createIgaming(enginex)
await enginex.auth.login({ email: 'ana@exemplo.com', password: 'Senha@123' })

const loyalty = await igaming.loyalty.get() // tier "gold", 1500 points
await igaming.loyalty.redeem({ points: 500, redemptionType: 'bonus' }) // deducted from the balance
```

The mock keeps the balance in memory (create one per test), answers HTTP 200 on redemption and returns
`INSUFFICIENT_BALANCE` (422) when points are missing. To simulate other errors, override the route in
`routes`.
