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

The referral history, with the email masked, appears in the [Loyalty](/igaming/loyalty) demo
(**Referrals** scenario).

The `referrals` namespace of [`@getenginex/sdk-igaming`](/igaming/) shows the player's referral code and
link, the referral history, and registers another player's code. All three methods require login. In
tests, `withIgamingRoutes` already answers all three routes (see [Testing](#tests)).

## Code and link

```ts
const referral = await igaming.referrals.get()
console.log(referral.code, referral.link)
console.log(referral.totalReferrals, referral.completedReferrals, referral.pendingReferrals)
console.log(referral.totalEarned, referral.bonusPerReferral, referral.minDeposit)
```

`ReferralInfo` carries:

| Field | What it is |
| --- | --- |
| `code`, `link` | the player's referral code and link; `null` when the gateway sends empty |
| `totalReferrals`, `completedReferrals`, `pendingReferrals` | counters (integers) |
| `totalEarned` | total earned from referrals, in minor units |
| `bonusPerReferral` | bonus per referral, in minor units |
| `minDeposit` | the referee's minimum deposit, in minor units |

The contract (`bonus.proto`) does not say when a referral counts as `completed` (for example, whether
it requires a minimum deposit) nor whether `totalEarned` includes bonuses still pending. Describing the
`minDeposit` field as "the referee's minimum deposit" is an **assumption**, not confirmed by the
contract. Confirm the rule with the operator before promising it on screen.

## Values in minor units

The gateway writes referral money as a **float in the major unit** (cents divided by 100, e.g.
`19.99`). The SDK converts everything back to whole minor units, like the rest of the SDK (see
[Money](/concepts/money)): `Math.round(value * 100)`, with halves rounded away from zero.

| The gateway sends | The SDK returns |
| --- | --- |
| `19.99` | `1999` |
| `0.1 + 0.2` (`0.30000000000000004`) | `30` |
| `1e-7` | `0` |
| `-19.99` | `-1999` (the sign is preserved) |
| `-0.005` | `-1` (symmetric to `0.005` → `1`; never `-0`) |

The conversion applies to `totalEarned`, `bonusPerReferral` and `minDeposit` of `get`, `referrerBonus`
and `refereeBonus` of each referral, `totalEarned` of the history and `refereeBonus` of the
registration. A value that is not a finite number, or that does not fit in a safe integer after ×100,
rejects with `VALIDATION_ERROR` under `validation: 'strict'` (under `'warn'` the field arrives raw and
`onValidationIssue` is notified, without the value). Exception in the history: under `'warn'`, a
referral whose `referrerBonus` or `refereeBonus` does not become minor units is **dropped** from `items`
(and reported), so a major unit is never shown in a minor-units field. The currency does not come
along: use the operator's.

## History

```ts
const history = await igaming.referrals.listHistory({ page: 1, perPage: 20 })
for (const r of history.items) {
  console.log(r.refereeName, r.refereeEmailMasked, r.status, r.referrerBonus, r.createdAt)
}
console.log(history.totalItems, history.totalPages, history.completedCount, history.totalEarned)
```

`listHistory` returns `Page<Referral>` (`items`, `page`, `perPage`, `totalItems`, `totalPages`; see
[Pagination](/concepts/pagination)) plus `completedCount` and `totalEarned`, which apply to all pages.
`page` is an integer ≥ 1 and `perPage` an integer from 1 to 100; otherwise it rejects with
`CONFIGURATION_ERROR`, with no request.

Unlike missions, the gateway sends the pagination **inside `data`** (`pagination.page`, `page_size`,
`total_items`, `total_pages`), not in the envelope's `meta`. The SDK builds the `Page` from it and
hardens it: `page_size` becomes `perPage`, `totalPages` is computed (`0` with no items) and
`totalItems` never falls below the items already seen. Negative or fractional counters reject with
`VALIDATION_ERROR` under `strict`. A page past the end returns `items: []`. If the gateway does not
send the pagination, the requested page and size apply.

`Referral`:

| Field | What it is |
| --- | --- |
| `id`, `code` | the referral id and the code used |
| `refereeName` | the referee's name; `null` when empty |
| `refereeEmailMasked` | the referee's masked email (see below); `null` if empty or invalid |
| `status` | `pending`, `qualified`, `completed` or `expired` (open union) |
| `referrerBonus`, `refereeBonus` | the referrer's and the referee's bonus, in minor units |
| `createdAt`, `completedAt`, `expiresAt` | ISO 8601 (UTC); `completedAt`/`expiresAt` are `null` when the gateway does not send them |

`status` comes from the gateway's `REFERRAL_STATUS_*`, in lowercase and without the prefix. The four
values come from `bonus.proto`; the gateway may still send `unspecified` (the enum's zero). It is an open
union: handle the default case. The contract **does not describe** what takes a referral from `pending`
to `qualified` and to `completed`, nor what causes `expired`; the bonus service decides.

### Masked email and why

The gateway returns the referee's `referee_email` **unmasked**. It is another person's personal data,
and a "my referrals" screen does not need it in full. That is why the SDK never exposes it: it delivers
only `refereeEmailMasked`, with the first character of the local part and one `*` per remaining
character, and the whole domain:

| Gateway | `refereeEmailMasked` |
| --- | --- |
| `ana@exemplo.com` | `a**@exemplo.com` |
| `maria.silva@exemplo.com.br` | `m**********@exemplo.com.br` |
| `a@exemplo.com` | `*@exemplo.com` (1-character local part: shows nothing of it) |
| empty, no `@`, no local part or no domain | `null` |

The gateway's `referee_id` is not exposed either. The raw email and the `referee_id` do not appear in
the result, in the `issues` of `onValidationIssue` or in the SDK's errors, also under
`validation: 'warn'`: when a history item fails entirely (e.g. `null`), the core returns the raw list
and the SDK rebuilds each referral with the same rules (mask, lowercase status, money in minor units),
dropping what is not an object.

::: warning The referee's name is personal data
`refereeName` is the name as the gateway sends it. Show it only on the player's own screen and do not
log it or send it to analytics.
:::

::: warning The issue's `raw`
In `onValidationIssue`, the `raw` property carries the whole response body, with sensitive keys masked
by the core. Today the mask covers the `referee_email` and `referee_name` keys (the key name contains
`email` or `name`), but **not** `referee_id`, and `raw` belongs to the core and is outside what this
package controls: if your hook sends the issue to an external service, discard `raw`.
:::

## Register a code

For someone who **is signing up**, the code goes straight into the sign-up, with the core's
[`auth.register({ referralCode })`](/flows/sign-up) (optional field). `referrals.register` is for
someone who **already has an account** and enters the code later:

```ts
async function useCode(code: string) {
  try {
    const result = await igaming.referrals.register({ code })
    console.log(result.id, result.status, result.refereeBonus, result.createdAt)
  } catch (error) {
    if (isEnginexError(error, 'UNAUTHENTICATED')) goToLogin()
    else showMessage('Could not use this code') // the contract does not list the refusal codes
  }
}
```

* **Input:** `code` is a non-empty string (only spaces is also refused; surrounding spaces are removed).
  Otherwise the call rejects with `CONFIGURATION_ERROR`, with no request, and the message does not carry
  the received value.
* **Result:** `{ id, code, status, refereeBonus, createdAt }`; the gateway answers HTTP 201.
  `refereeBonus` in minor units; `createdAt` is `null` when the gateway sends an empty date.
* **Idempotency:** this route does not go through the gateway's idempotency middleware and the SDK does
  not send `Idempotency-Key`. Lock the button while the call is in flight.

## Errors

| Code | When |
| --- | --- |
| `UNAUTHENTICATED` (401) | no session |
| `CONFIGURATION_ERROR` | invalid `page`/`perPage` or `code` (no request) or client already disposed |
| `VALIDATION_ERROR` | under `validation: 'strict'`: unknown status, money that is not a finite number or a malformed field; under `'warn'` only when the response root does not have the expected shape (e.g. text instead of an object) |

When the service refuses the code (nonexistent, already used, the player's own code, past the deadline),
the error arrives with whatever `code` the service returns. **The contract does not list these codes**:
always decide by `error.code` and use a generic message for what you do not recognize. Do not assume a
specific code (for example `NOT_FOUND`) is the one used in each case.

## What the gateway does not offer yet

* **Validate a code before using it**: there is no route that says whether a code exists and whose it is;
  only `register` answers, and it already registers.
* **Unmasked referee email**: the gateway sends another person's full email to whoever lists the
  history. The SDK masks it on the client, but the data has already traveled; ideally the gateway would
  mask it.
* **Referral rules**: minimum deposit, validity period, when it becomes `completed` and when the bonus is
  paid are not in the contract; confirm with the operator.
* **Realtime notification**: no realtime topic for referrals; query again.

## 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 info = await igaming.referrals.get() // code MOCK123
const { items, totalItems } = await igaming.referrals.listHistory({ perPage: 2 }) // 2 of 3 referrals
await igaming.referrals.register({ code: 'BEMVINDO' }) // HTTP 201; other codes: NOT_FOUND
```

The mock returns three fixed referrals in the gateway's format (pagination inside `data`, money as a
major-unit float, unmasked email) and keeps no state. To simulate other errors or values (such as
`0.1 + 0.2`), override the route in `routes`.
