---
url: https://game-engine-io.github.io/enginex-frontend-sdk/igaming/bonus.md
---
# Bonuses and promo codes

The demo above uses `createIgaming(enginex)` on a client with `createMockFetch(withIgamingRoutes())`:
no call goes out to the network. See the public showcase, log in, join the welcome campaign (`optIn`
with the terms acceptance) and redeem the reward (`claim`); in the promo code scenario, resolve and
redeem `BEMVINDO`. The **Not eligible** scenario shows `BONUS_NOT_ELIGIBLE` arriving with HTTP 500:
identify it by the code, never by the status. In the **Under the hood** panel, the promo code appears
masked and the `idempotencyKey` values of `optIn`, `claim` and `redeemPromoCode` are visible.

The `bonus` namespace of [`@getenginex/sdk-igaming`](/igaming/) covers the operator's bonus
campaigns: the public showcase, the player's offers, joining (opt-in), reward redemption (claim) and
promo codes. Only `listPublicOffers` is public; the other methods require login. In tests,
`withIgamingRoutes` already answers all these routes (see [Testing](#tests)).

## Offers

```ts
// Showcase (no login): only describes the campaigns.
const showcase = await igaming.bonus.listPublicOffers()

// Logged in: the offers available to the player.
const { items, nextCursor } = await igaming.bonus.listOffers({ pageSize: 20 })
const offer = await igaming.bonus.getOffer({ campaignId: items[0].campaignId })
```

Bonus listings are paginated **by cursor** (unlike the casino catalog; see
[Pagination](/concepts/pagination#cursor-pagination)): they take `CursorPageInput` (`cursor`,
`pageSize`) and return `CursorPage` (`items`, `nextCursor`), core types. Pass the previous page's
`nextCursor` as `cursor`; with no `nextCursor`, you are done.

```ts
let cursor: string | undefined
do {
  const page = await igaming.bonus.listOffers({ cursor })
  render(page.items)
  cursor = page.nextCursor
} while (cursor)
```

An offer (`CampaignOffer`) tells you:

* **how to join** — `offer.entryPolicy?.code`: `automatic` (the player joins on their own once they meet
  the qualification), `opt_in` ("join" button, with `optIn`), `promo_code` (with `redeemPromoCode`) or
  `manual`;
* **how to receive the reward** — `offer.rewardClaimPolicy?.code`: `automatic` or `player_claim`
  ("redeem" button, with `claim`);
* **what is required** — `offer.qualification` (one of `immediate`, `depositSettled`, `userEvent`,
  `activityAggregate`);
* **the reward** — `offer.reward`: `rewardKind` says which detail is filled in (`balanceCredit`,
  `casinoFreeSpins`, `sportsBonusBet`, `sportsBetCoverage`), plus the wagering requirement
  (`wageringPolicy`) and where the bonus balance is valid (`usePolicy`);
* **the texts** — `offer.content.localizedContent`: name, description and terms per language.

```ts
import { formatMoney } from '@getenginex/sdk'
import type { CampaignOffer } from '@getenginex/sdk-igaming'

function texts(offer: CampaignOffer, locale: string) {
  const content = offer.content
  return (
    content?.localizedContent.find((c) => c.locale === locale) ??
    content?.localizedContent.find((c) => c.locale === content.defaultLocale)
  )
}

const credit = offer.reward?.balanceCredit?.fixedAmount?.amount // { amount: 5000, currency: 'BRL' }
if (credit) formatMoney(credit.amount, config.currency) // 'R$ 50,00'
```

::: tip Field format
The gateway writes campaigns in protobuf format. The SDK delivers them in camelCase, with enums
stripped of the prefix and in lowercase (`ENTRY_POLICY_CODE_OPT_IN` → `opt_in`), money as `number`
(minor units), durations in seconds and the zero value in place of what protobuf omits (`''`, `0`,
`[]`, `'unspecified'`). Objects (windows, policies, reward, texts) may be absent: use `?.`. A new enum
value is passed along in the same format — handle the default case.
:::

::: warning Stability (0.x)
The detail tree of the reward, the qualification and the policies (balance use, wagering requirement,
accumulation, odds, maximum bet, casino/sports cuts, execution profiles and the `version` fields)
mirrors the protobuf of the bonus service and **may change in 0.x minor versions** — these types are
marked `@beta` in the reference. The stable part is: the top-level fields of `CampaignOffer` and
`CampaignParticipation`, the participation `status`, the entry codes (`entryPolicy.code`) and
redemption codes (`rewardClaimPolicy.code`), `content` (texts), the inputs and the methods.
:::

## Join (opt-in) and redeem (claim)

`optIn` and `claim` are **idempotent**: the SDK sends an `Idempotency-Key` per call and keeps it on the
internal retry after refreshing the session. So that a second click, or a new attempt after a network
failure, does not duplicate the operation, generate the key once per intent and reuse it (as in the
[deposit](/flows/pix-deposit)):

```ts
import { isEnginexError } from '@getenginex/sdk'

const key = crypto.randomUUID() // one per click on "join"
const text = texts(offer, 'pt-BR')

try {
  const participation = await igaming.bonus.optIn(
    {
      campaignId: offer.campaignId,
      campaignVersionId: offer.campaignVersionId, // the version the player saw
      termsAcceptance: text && { locale: text.locale, termsRevision: text.termsRevision },
    },
    { idempotencyKey: key },
  )
  participation.status // 'enrolled' | 'qualifying' | 'qualified' | ...
} catch (e) {
  if (isEnginexError(e, 'BONUS_NOT_ELIGIBLE')) showNotEligible()
  else if (isEnginexError(e, 'BONUS_EXPIRED')) showExpired()
  else if (isEnginexError(e, 'KYC_REQUIRED')) goToKyc()
  else throw e
}
```

When the participation reaches `qualified` in a `player_claim` campaign, show the redeem button:

```ts
const { items } = await igaming.bonus.listParticipations()
for (const p of items.filter((p) => p.status === 'qualified')) {
  const done = await igaming.bonus.claim({ participationId: p.id }, { idempotencyKey: claimKeys.get(p.id) })
  done.status // 'completed' (or 'reward_pending' while the reward is being granted)
}
```

The participation (`CampaignParticipation`) carries `status`, the state timestamps (`qualifiedAt`,
`completedAt`, `expiredAt`) and, in `snapshot`, the reward, the texts and the terms acceptance as they
were when the player joined.

The responses of `optIn`, `claim` and `redeemPromoCode` are always validated in strict mode, even with
`validation: 'warn'` on the client. If `VALIDATION_ERROR` comes back, the operation may have happened:
check `listParticipations`/`getParticipation` before trying again (or repeat with the **same** key).

## Promo codes

First show the code's offer (name, description and terms in the requested language); then redeem:

```ts
const { offer, localizedContent } = await igaming.bonus.resolvePromoCode({ code: input.value, locale: 'pt-BR' })
showOffer(localizedContent.displayName, localizedContent.terms)

const participation = await igaming.bonus.redeemPromoCode(
  { code: input.value, termsAcceptance: { locale: localizedContent.locale, termsRevision: localizedContent.termsRevision } },
  { idempotencyKey: key },
)
```

* `resolvePromoCode` does not join the campaign; `redeemPromoCode` does (and is idempotent: the gateway
  requires the key).
* The code is a low-entropy secret: the SDK sends it only in the body (never in the URL or the hooks),
  and the gateway limits attempts per player (the same limit applies to `resolvePromoCode` and
  `redeemPromoCode`) — `RESOURCE_EXHAUSTED` (429): wait `e.retryAfter` seconds before letting the
  player try again. Do not log it.
* If the gateway's rate limiter is down, both routes **fail closed** for safety: `UNAVAILABLE` (503).
  Show "try again later", without retrying in a loop.

## Errors {#errors}

| Code                                     | When                                                                     |
| ---------------------------------------- | ------------------------------------------------------------------------ |
| `BONUS_NOT_FOUND` (404)                  | campaign, participation or promo code does not exist (or belongs to another player) |
| `BONUS_ALREADY_CLAIMED` (409)            | reward already redeemed; promo code already used                         |
| `ALREADY_EXISTS` (409)                   | the player already participates in the campaign                          |
| `BONUS_NOT_ELIGIBLE`                     | the player cannot join/redeem (e.g. has not qualified yet)               |
| `BONUS_EXPIRED`                          | outside the join or redemption window                                    |
| `KYC_REQUIRED`, `FAILED_PRECONDITION` (422) | bonus service precondition (KYC, terms, campaign version)             |
| `INVALID_ARGUMENT` (400)                 | id that is not a UUID, invalid `pageSize`, empty code                    |
| `KEY_IN_USE` (409), `PAYLOAD_MISMATCH` (422) | same `idempotencyKey` still processing, or already used with a different body |
| `RESOURCE_EXHAUSTED` (429)               | too many promo code attempts (see `e.retryAfter`)                        |
| `UNAVAILABLE` (503)                      | promo code with the gateway's attempt limiter down                       |
| `UNAUTHENTICATED` (401)                  | methods that require login, with no session                              |

::: warning HTTP status of `BONUS_NOT_ELIGIBLE` and `BONUS_EXPIRED`
The gateway does not yet map these two codes to a status of their own: they arrive with HTTP 500. The
code is correct — always identify them with `isEnginexError(error, code)`, never by `status`.
:::

## 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 { items } = await igaming.bonus.listOffers() // welcome (opt-in) and free spins (automatic)
const welcome = items.find((o) => o.entryPolicy?.code === 'opt_in')!
const p = await igaming.bonus.optIn({ campaignId: welcome.campaignId, campaignVersionId: welcome.campaignVersionId })
await igaming.bonus.claim({ participationId: p.id }) // status: 'completed'
await igaming.bonus.redeemPromoCode({ code: 'BEMVINDO' }) // status: 'enrolled'
```

The mock keeps state per instance, repeats the first response for the same `Idempotency-Key` and
returns the same errors as the gateway (`BONUS_ALREADY_CLAIMED` on the second redemption,
`ALREADY_EXISTS` on the second opt-in, `BONUS_NOT_ELIGIBLE` on the opt-in of an automatic campaign,
`BONUS_NOT_FOUND` for an unknown code).
