# Build on Stacked

Page: https://buildon.stacked.xyz/docs

Stacked runs **offers**, **live ops events** and **leaderboards** for your game. Your game sends events as players play. Stacked decides what each player sees, keeps their progress and scores, and tells your backend what to grant when they claim a reward.

- [Offers](https://buildon.stacked.xyz/docs/offers): Rewarded tasks shown to the players who match, completed by playing, and claimed for a reward.
- [Live Ops](https://buildon.stacked.xyz/docs/live-ops): Time-limited events with milestone tracks, daily rewards and event-only offers.
- [Leaderboards](https://buildon.stacked.xyz/docs/leaderboards): Rankings scored live from game events, repeating or split into shards, with prizes by rank.

## How it works

One loop drives all three features. Your game reports what players do, and never has to know which offer, event or leaderboard is listening.

1. **Send events.** Sign-ins, purchases, currency changes and any action of your own, sent through an SDK as players play.
2. **Track and score.** Each event updates the player's snapshot, moves offer progress, and adds points to live ops tracks and leaderboards.
3. **See and claim.** Your game asks Stacked what to show a player: their offers, their event progress, their rank. What is complete, they claim.
4. **Grant the reward.** Stacked sends a signed webhook that says what to grant. Your backend verifies it and gives the items or currency.

You set everything up in the dashboard, or let an [AI agent](https://buildon.stacked.xyz/docs/mcp) do it. Launching an offer, an event or a leaderboard needs no game update.

## What you integrate

| Piece | Runs in | What it does |
| --- | --- | --- |
| A server SDK (Node.js, Go) | Your backend | Sends [events](https://buildon.stacked.xyz/docs/events) and signs player tokens |
| A client SDK (JavaScript, Unity) | Your game | Shows a player their offers and events, claims rewards, and gets live updates |
| A [reward webhook](https://buildon.stacked.xyz/docs/webhooks) | Your backend | Grants what a player claimed |
| The [dashboard](https://buildon.stacked.xyz) | Your browser | Where you build offers, events and leaderboards, and watch them run |

The [Quickstart](https://buildon.stacked.xyz/docs/quickstart) connects all four for one offer.

## Quick reference

| What | Value |
| --- | --- |
| Dashboard | [https://buildon.stacked.xyz](https://buildon.stacked.xyz) |
| Live API | `https://api.stacked.xyz` |
| Test API | `https://api.sandbox.stacked.xyz` |
| Backend authentication | `x-api-key` and `x-client-id` headers |
| Game client authentication | `Authorization: Bearer <player token>` |
| Reward webhook event | `user.gain_rewards` |
| MCP server | `https://api.stacked.xyz/mcp` |

## For AI agents

Building with a coding agent? Point it at [`/docs/llms-full.txt`](https://buildon.stacked.xyz/docs/llms-full.txt), every page of these docs as plain markdown, or the short index at [`/docs/llms.txt`](https://buildon.stacked.xyz/docs/llms.txt).

To let an agent run your Stacked setup itself, connect it to the [MCP server](https://buildon.stacked.xyz/docs/mcp).

## All pages

**Get started.** What Stacked is, how the pieces fit, and a first integration.

- [Overview](https://buildon.stacked.xyz/docs): What Stacked does for a game, its three features, and how an integration works end to end.
- [Core concepts](https://buildon.stacked.xyz/docs/concepts): Games, Test and Live, players and their snapshot, events, conditions, rewards and claims.
- [Quickstart](https://buildon.stacked.xyz/docs/quickstart): Send events, show a player their offers, let them claim, and grant the reward from a webhook.

**Features.** The three things you run with Stacked.

- [Offers](https://buildon.stacked.xyz/docs/offers): Rewarded tasks shown to the players who match, completed by playing, and claimed for a reward.
- [Live Ops](https://buildon.stacked.xyz/docs/live-ops): Time-limited events with milestone tracks, daily rewards and event-only offers.
- [Leaderboards](https://buildon.stacked.xyz/docs/leaderboards): Rankings scored live from game events, repeating or split into shards, with prizes by rank.

**Building blocks.** What every feature is made of.

- [Events](https://buildon.stacked.xyz/docs/events): The events a game sends, and what each one does to snapshots, offer progress and scores.
- [Scoring rules](https://buildon.stacked.xyz/docs/scoring-rules): How events become points: triggers, points, criteria and intervals. Shared by Live Ops and Leaderboards.
- [Rewards](https://buildon.stacked.xyz/docs/rewards): Reward kinds, the asset library, USD-anchored amounts, reward rules and spend limits.

**Integrate.** Connect your game, your backend and your tools.

- [Reward webhooks](https://buildon.stacked.xyz/docs/webhooks): How your backend is told to grant rewards: the payload, verifying it, retries and idempotency.
- [SDKs and API](https://buildon.stacked.xyz/docs/api): The SDKs, authentication, base URLs, the endpoints a game calls, realtime events and errors.
- [MCP server](https://buildon.stacked.xyz/docs/mcp): Let an AI agent manage offers, live ops and leaderboards with the permissions of one team member.

---

# Core concepts

Page: https://buildon.stacked.xyz/docs/concepts

Stacked is built from a few ideas. Offers, live ops events and leaderboards are the same loop seen three ways, so once these are clear, each feature is a short read.

## The loop

1. Your game sends **events** as players play.
2. Each event updates what Stacked knows about the **player**, and counts toward whatever is listening: an offer's progress, a milestone track, a leaderboard.
3. Your game asks Stacked what to show a player.
4. The player **claims** what they have earned.
5. Stacked tells your backend with a **reward webhook**, and your backend grants it.

Your game reports and grants. Stacked decides and keeps count. Nothing in your game's code names a specific offer, so you can change what runs from the dashboard at any time.

## Game, Test and Live

A **game** is one organization in the dashboard, with its own team and roles.

Every game has two environments, switched at the top of the dashboard:

| | Test | Live |
| --- | --- | --- |
| For | Building and trying things out | Real players |
| Credentials | Its own client id and API key | Its own client id and API key |
| Data | Its own players, offers, events and leaderboards | Its own |
| Webhooks | Its own endpoints and secrets | Its own |

Nothing moves from Test to Live by itself. See [environments](https://buildon.stacked.xyz/docs/api#environments) for the URLs.

## Players

A player is whoever your game says it is. You choose the id (up to 250 characters), and Stacked creates the player the first time it sees that id.

What Stacked knows about a player is their **snapshot**. Your [events](https://buildon.stacked.xyz/docs/events) keep it current, and [conditions](https://buildon.stacked.xyz/docs/offers#surfacing-conditions) read it.

| Part of the snapshot | Kept current by |
| --- | --- |
| Username, sign-up date | `signIn`, `signUp` |
| Days in game, login streak | `signIn` |
| Levels | `levelUp` |
| Currency balances | `earnCurrency`, `spendCurrency` |
| Dynamic fields: values of your own | `setField`, `incField` |
| Tags | `addTags`, `removeTags`, or the dashboard |
| Trust score | `trustScore`, or the dashboard |
| Achievements, quests, memberships | Their own events |
| Country and network | The address the player's game client calls from |
| Entity kind and links | `playerSnapshot`, `linkUser` |

**Entities and links.** A "player" does not have to be a person. It can be a pet, a guild or a character: give its snapshot an **entity kind**. Entities can be **linked**, a pet to its owners, a member to a guild. Links are what let an offer be [shared by a team](https://buildon.stacked.xyz/docs/offers#team-offers), let a milestone track [count by group](https://buildon.stacked.xyz/docs/live-ops#milestone-tracks), and let a signed-in player act for an entity linked to them (`targetId` on the API).

## Events

An event says one thing happened: a sign-in, a purchase, a level gained, a value of your own changed. Your backend sends events with a [server SDK](https://buildon.stacked.xyz/docs/api#sdks).

Two kinds of event are worth knowing by name, because you define them yourself:

- A **dynamic field** is a named value on a player, such as `boss_kills`. Conditions and scoring rules can read it and count changes to it.
- A **context** is a named moment, such as `enter_arena`. Calling it can surface offers on the spot.

[Events](https://buildon.stacked.xyz/docs/events) lists them all.

## Conditions

A condition is a test on a player. The same tests are used everywhere a feature needs to pick players:

| Used as | Answers |
| --- | --- |
| A surfacing condition on an offer | Who gets this offer? |
| A completion condition on an offer | Has the player done it? |
| A bucket of a sharded leaderboard | Which shard does this player belong in? |
| A reward rule, a spend limit, a prize boost | Which players does this apply to? |

[Offers](https://buildon.stacked.xyz/docs/offers#surfacing-conditions) has the full list.

## Scoring rules

A scoring rule turns an event into points: "1 point per gold coin spent", "50 points for each boss kill, once a day". Live ops milestone tracks and leaderboards both score with them. See [Scoring rules](https://buildon.stacked.xyz/docs/scoring-rules).

## Rewards and claims

A [reward](https://buildon.stacked.xyz/docs/rewards) is what a player gets: an item, currency, experience. Rewards are **claimed**, by the player in your game or by your backend for them.

Stacked never changes anything inside your game. A claim makes Stacked send a signed [reward webhook](https://buildon.stacked.xyz/docs/webhooks) to your backend with the player and the rewards, and your backend does the granting.

## The three features

| | [Offers](https://buildon.stacked.xyz/docs/offers) | [Live Ops](https://buildon.stacked.xyz/docs/live-ops) | [Leaderboards](https://buildon.stacked.xyz/docs/leaderboards) |
| --- | --- | --- | --- |
| What a player sees | Tasks with rewards | A timed event: milestones, dailies, event offers | A ranking, and their own place in it |
| Who gets it | Players who meet the surfacing conditions | Everyone, or players who reach a context | Everyone, optionally split into shards |
| Progress comes from | Completion conditions | Scoring rules, and showing up each day | Scoring rules |
| Paid when | The player claims | The player claims a milestone or a daily | You generate rewards after it ends |

## Words used in these docs

| Word | Meaning |
| --- | --- |
| Surface | To give an offer or an event to a player. Before that, the player does not have it |
| Instance | One player's copy of an offer, with its own progress, status and `instanceId` |
| Snapshot | What Stacked knows about a player |
| Dynamic field | A named value of your own on a player |
| Context | A named moment in your game |
| Track | A line of milestones in a live ops event, with its own points |
| Threshold | A point value on a track that unlocks rewards |
| Shard | A group of players who compete on their own copy of a leaderboard |
| Claim | The call that turns earned rewards into a reward webhook |

---

# Quickstart

Page: https://buildon.stacked.xyz/docs/quickstart

This walks one player through one offer on Test: your backend sends an event, the player sees the offer in your game, completes it, claims it, and your backend grants the reward. Examples use the Node.js and JavaScript SDKs. The [other SDKs](https://buildon.stacked.xyz/docs/api#sdks) work the same way.

## 1. Get your credentials

Sign in to the [dashboard](https://buildon.stacked.xyz) and switch to **Test** at the top. Open **Credentials** and copy the **Client ID** and the **API Key**.

Test and Live are separate: each has its own credentials, data and webhooks. Build on Test.

## 2. Describe what your game gives away

Open **Asset Library** and add the currencies and items your game can grant, each with an id your backend knows, such as `gold`. Offers reward these, and conditions refer to them, by id.

## 3. Send events from your backend

```bash
npm install @pixels-online/pixels-analytics-node-sdk
```

```ts
import PixelsAnalytics from '@pixels-online/pixels-analytics-node-sdk';

const analytics = new PixelsAnalytics({
  apiKey: process.env.STACKED_API_KEY,
  clientId: process.env.STACKED_CLIENT_ID,
  env: 'test',
});

// When a player signs in
analytics.signIn('player-1', { username: 'ada' });

// When a player spends currency
analytics.spendCurrency('player-1', {
  currency_id: 'gold',
  currency_amount: 100,
  to_kind: 'store',
  to_id: 'starter-shop',
});
```

Calls return at once. The SDK sends events in batches every two seconds, so call `await analytics.flush()` before a short script exits. [Events](https://buildon.stacked.xyz/docs/events) lists everything you can send.

## 4. Create an offer

Open **Offers** and create one:

- **Surfacing conditions**: none, so every player gets it.
- **Completion condition**: spend 100 `gold`.
- **Reward**: something from your asset library.

Save it, then switch it on: a new offer starts disabled. [Offers](https://buildon.stacked.xyz/docs/offers) explains every part.

## 5. Receive the reward webhook

Open **Webhooks**, add your backend's URL and subscribe it to `user.gain_rewards`. Copy the signing secret into your backend, and grant what the webhook says:

```ts
app.post('/stacked/rewards', express.raw({ type: 'application/json' }), async (req, res) => {
  const reward = webhook.verify(req.body, {
    'svix-id': req.header('svix-id'),
    'svix-timestamp': req.header('svix-timestamp'),
    'svix-signature': req.header('svix-signature'),
  });
  await grantOnce(reward.dedupeId, () => giveRewards(reward.playerId, reward.rewards));
  res.status(204).end();
});
```

[Reward webhooks](https://buildon.stacked.xyz/docs/webhooks#verify-and-grant) has the full handler. Do this before the first claim: a claim fails while webhooks are not set up.

## 6. Show offers in your game

A game client never holds the API key. Add an endpoint to your backend that signs a token for the signed-in player:

```ts
app.post('/api/stacked-token', async (req, res) => {
  const token = await analytics.signJwt({ playerId: req.user.id });
  res.json({ token });
});
```

Then start the client SDK with it:

```bash
npm install @pixels-online/pixels-client-js-sdk
```

```ts
import { OfferwallClient } from '@pixels-online/pixels-client-js-sdk';

const client = new OfferwallClient({
  env: 'test',
  tokenProvider: async () => {
    const response = await fetch('/api/stacked-token', { method: 'POST' });
    return (await response.json()).token;
  },
  fallbackRewardImage: 'https://your-game.example/reward.png',
});

await client.initialize();
const offers = client.getOffers();
```

`initialize` fetches the player's offers and opens the [realtime connection](https://buildon.stacked.xyz/docs/api#realtime-events). Draw `offers` however suits your game: each has a `name`, `description`, `image`, `rewards`, `status` and progress.

## 7. Complete and claim

The offer counts progress from the moment it surfaced for the player, so spend the gold after step 6. Send the `spendCurrency` event from step 3 again, then refresh:

```ts
await client.refreshOffersAndPlayer();

const offer = client.getOffers().find((o) => o.status === 'claimable');
if (offer) await client.claimReward(offer.instanceId);
```

Stacked marks the offer claimed and sends the webhook. Your backend grants the reward.

## 8. Go live

- Switch to **Live** in the dashboard and copy the Live credentials. Set `env: 'live'` in both SDKs.
- Add your Live webhook endpoint. It has its own signing secret.
- Create your offers on Live. Nothing carries over from Test by itself.

## Where next

| To | Read |
| --- | --- |
| Understand the pieces before building more | [Core concepts](https://buildon.stacked.xyz/docs/concepts) |
| Target offers and track different actions | [Offers](https://buildon.stacked.xyz/docs/offers) |
| Run a timed event with milestones and dailies | [Live Ops](https://buildon.stacked.xyz/docs/live-ops) |
| Rank players and pay the winners | [Leaderboards](https://buildon.stacked.xyz/docs/leaderboards) |
| Let an AI agent set all of this up | [MCP server](https://buildon.stacked.xyz/docs/mcp) |

---

# Offers

Page: https://buildon.stacked.xyz/docs/offers

An offer is a task with a reward. Stacked gives it to the players who match, counts what they do toward it, and lets them claim the reward when it is done. You build offers in the dashboard. Your game shows them and grants the rewards.

## Anatomy of an offer

| Part | What it decides |
| --- | --- |
| [Surfacing conditions](#surfacing-conditions) | Who gets the offer |
| [Completion conditions](#completion-conditions) | What the player has to do. With none, the offer can be claimed as soon as the player gets it |
| [Rewards](https://buildon.stacked.xyz/docs/rewards) | What the player gets |
| [Timing](#repeat-expire-and-limit) | When it runs, how long a player has, and whether it comes back |
| Display | A name, description, image and labels for your game to draw it with |

You build offers on the **Offers** page of the [dashboard](https://buildon.stacked.xyz/offers). A new offer starts switched off, so you can review it before players see it.

## Lifecycle

When an offer surfaces for a player, that player gets their own copy of it, with its own progress and status. The docs call the copy an **instance**. Its id is the `instanceId` you claim with.

| Status | Meaning |
| --- | --- |
| `surfaced` | The player has the offer, and has not been shown it yet |
| `viewed` | The player has been shown it |
| `completed` | The player did their part, and is waiting on others (see [team offers](#team-offers)) |
| `claimable` | The reward can be claimed |
| `claimed` | The reward was claimed |
| `expired` | Time ran out |
| `declined` | The player, or your backend, turned it down |

Four rules explain most of what you will see:

- **Progress counts from the moment an offer surfaces.** What a player did before they had the offer does not count.
- **Events move progress. Fetches move status.** An instance becomes `claimable` or `expired` the next time Stacked looks at the player: an offers fetch, a live ops call or a claim.
- **A claimable offer does not expire.** An offer completed in time can be claimed later.
- **The rewards are fixed at surfacing.** The amounts a player sees are the amounts they get, whatever changes on the offer afterwards.

## When offers surface

Stacked looks for new offers for a player when your game [fetches their offers](https://buildon.stacked.xyz/docs/api#offers), and when it loads their live ops events.

- **On Live, a player is checked for new offers at most once every 5 to 15 minutes.** On Test, every fetch checks. Between checks a fetch still updates and returns the offers the player has.
- An offer surfaces when it is switched on, inside its start and end dates, the player meets every surfacing condition, and the player does not already hold it.
- There is no cap on how many offers a player holds. Use exclusive [groups](#groups-and-ab-tests) to show one of several.
- `priority` only orders the list your game gets back. It never decides which offers surface.

## Surfacing conditions

Surfacing conditions say who gets an offer. They read the player's [snapshot](https://buildon.stacked.xyz/docs/concepts#players). A player must meet all of them, and you can nest them in groups with `AND`, `OR` and `NOT`.

| Condition | The player... |
| --- | --- |
| `level` | has a skill level in a range |
| `currency` | has a balance in a range, or has deposited or withdrawn at least an amount |
| `achievement`, `quest`, `membership` | has an achievement, a completed quest or a membership |
| `dynamic` | has [dynamic fields](https://buildon.stacked.xyz/docs/events#dynamic-fields) that pass comparisons |
| `tags` | has all, any or none of a list of tags |
| `trustScore` | has a trust score in a range |
| `daysInGame` | has signed in on a number of days |
| `loginStreak`, `currentLoginStreak` | has signed in a number of days in a row |
| `lastSeen` | last signed in a number of days ago: lapsed, or recently active |
| `dateSignedUp`, `daysSinceSignUp` | signed up in a date range, or a number of days ago |
| `completedOffers` | has completed other offers: all of a list, or any |
| `geo` | is in an allowed country, or not in a restricted one |
| `networkRestriction` | is not on a VPN, proxy, Tor or relay |
| `surfacingContext` | has just reached a [context](https://buildon.stacked.xyz/docs/events#contexts) your game called |
| `entityLink` | has a number of [linked entities](https://buildon.stacked.xyz/docs/concepts#players) of a kind |
| `targetEntityType` | is an entity of a certain kind |
| `linkedEntityOffer` | has linked entities that hold an offer or meet conditions |
| `stackedAccount`, `identifiers` | has linked a Stacked account, or connected certain sign-in methods |
| `programmatic` | Never surfaces by itself. Such an offer is given to players by another offer or a referral |

- **Country and network come from the game client.** Stacked reads them from the address a player's client fetches offers from. A player whose offers are only ever fetched by your backend has no country, and fails `geo` and `networkRestriction` conditions.
- **Defaults for every offer.** The **Rules** page holds country and network rules that apply to every offer without its own `geo` or `networkRestriction` condition. On **Settings** you can stop treating trusted players as VPN users, by trust score.
- On-chain conditions exist too, for token balances and staked tokens.

## Completion conditions

Completion conditions say what the player has to do. There are two kinds.

**Trackers count events** your game sends after the offer surfaced:

| Condition | Done when the player has... | Counts |
| --- | --- | --- |
| `spendCurrency` | spent an amount of a currency | [`spendCurrency`](https://buildon.stacked.xyz/docs/events#currency-and-items) events |
| `depositCurrency` | deposited an amount of a currency | `depositCurrency` events |
| `buyItem` | bought a number of an item | `gainItem` events that carry a currency |
| `completionContext` | reached a context | [`callContext`](https://buildon.stacked.xyz/docs/events#contexts) events |
| `dynamicTracker` | changed [dynamic fields](https://buildon.stacked.xyz/docs/events#dynamic-fields) enough to pass comparisons | `setField`, `incField`, `maxField` and `minField` events |
| `linkedCompletions` | had a number of linked players complete their offer, as in a referral | Other players' completions |
| `contractInteraction` | made on-chain transactions that match | On-chain events |

**Checks read the player** as they are when Stacked looks:

| Condition | Done when |
| --- | --- |
| `level`, `currency`, `achievement`, `quest`, `membership`, `dynamic`, `trustScore`, `daysInGame` | The same test as for surfacing passes now. "Reach level 10" is a `level` condition |
| `loginStreak` | The player has signed in a number of days in a row since the offer surfaced |
| `login` | The player has been active since the offer surfaced |
| `timeWindow` | Stacked looks at the player inside a set window of time. This is what makes a [daily reward](https://buildon.stacked.xyz/docs/live-ops#daily-rewards) claimable on its day only |
| `social`, `twitterVerification` | Stacked has verified a post, or an action on X |

- A `dynamicTracker` can count a field **at most once per interval** (`intervalHr`): 24 counts it once per UTC day, however often it changes.
- **Keep trackers at the top level.** A tracker inside an `AND` / `OR` / `NOT` group does not count.
- **One of each.** An offer counts one `spendCurrency`, one `depositCurrency`, one `buyItem` and one `completionContext` condition. For more, use `dynamicTracker`, which can follow several fields.
- Every condition can carry a `template`, the text to show for it, and a `goToUrl`, where the player can go to do it.

## Repeat, expire and limit

| Setting | Effect |
| --- | --- |
| Start and end date | The offer surfaces only between them. Instances a player already has stay |
| Expiry | How long a player has, counted from surfacing. Without it, the offer stays until it is claimed |
| Cooldown | Lets the offer come back. A new instance can surface once the last one is finished and the cooldown has passed since that one surfaced. Without a cooldown, a player gets an offer once, ever |
| Max receive count | With a cooldown: the most times a player gets the offer |
| Max claim count | How many times one instance can be claimed. Above 1, the player claims, keeps going and claims again, and the goal grows with each claim |

Your backend can also step in: [`POST /v1/player/offer/status`](https://buildon.stacked.xyz/docs/api#offers) reopens an expired instance or closes one, and a decline endpoint turns an offer down for a player.

## Groups and A/B tests

| Tool | What it does |
| --- | --- |
| Exclusive group | Surfaces one offer of the group at a time, picked at random among the ones the player can get |
| Campaign group | An A/B test across offers: each player gets one offer of the group, split by the weights you set |
| Reward variants | An A/B test on one offer: each player is assigned a variant, and the reward amounts are multiplied by its factors |
| Normal and milestone groups | Sort offers for display. They do not change what surfaces |

Compare variants on the **Stats** page: how many players each one surfaced for, and how many completed and claimed.

## Team offers

An offer can involve more than one player, through [entity links](https://buildon.stacked.xyz/docs/concepts#players).

- **Shared goals.** An offer can surface for every player linked to an entity, such as both owners of a pet. Each gets an instance, and none can claim until all have completed. Until then a finished player's instance is `completed`.
- **Referrals.** A referrer's offer can count how many referred players completed theirs.

## What your game gets

A fetch returns the player's offers, each with:

| Field | Holds |
| --- | --- |
| `instanceId` | The player's copy of the offer. Claim with this |
| `offerId` | The offer it is a copy of |
| `name`, `description`, `image` | What to show |
| `status` | See [Lifecycle](#lifecycle) |
| `rewards` | What this player gets: `kind`, `rewardId`, `amount`, `name`, `image` |
| `completionConditions`, `completionTrackers` | The conditions, and the player's progress on the trackers |
| `createdAt`, `expiresAt`, `claimedAt` | When it surfaced, when it expires, when it was claimed |
| `labels` | Your labels, plus ones Stacked adds: `daily`, `weekly`, `team_offer`, `login_streak`, `event:daily` |

Surfacing conditions are never sent to a game. The client SDKs add helpers to each offer, such as `getProgressPercent()` and `getCompletionConditions()`.

---

# Live Ops

Page: https://buildon.stacked.xyz/docs/live-ops

A live ops event is something that runs for a set time: a season, a holiday, a weekend challenge. While it runs, players earn points by playing, reach milestones that unlock rewards, pick up a reward each day, and get offers that exist only for the event.

## What an event is made of

| Part | What it is |
| --- | --- |
| Dates | A start and an end, in UTC. The event is live between them, unless it is switched off |
| [Milestone tracks](#milestone-tracks) | Points that unlock rewards at thresholds: for each player, for everyone together, or for groups |
| [Daily rewards](#daily-rewards) | One reward per day of the event |
| [Event offers](#event-offers) | Offers that only surface while the event is live |
| Content | A name, caption, description, image, wallpaper, icon, and any extra images and texts by key, for your game to draw the event with |

You build events on the **Live Ops** page of the [dashboard](https://buildon.stacked.xyz/live-ops). Each event also has a readable id of your choosing, such as `summer-2026`, that your game can look it up by.

## Milestone tracks

A track turns play into points, and points into rewards. It has:

- **Scoring rules**, which say which events earn points. They are [scoring rules](https://buildon.stacked.xyz/docs/scoring-rules), the same ones leaderboards use.
- **Thresholds**, the milestones: point values that each unlock a set of [rewards](https://buildon.stacked.xyz/docs/rewards).

An event can have one track of each kind. Every track has its own rules and its own points.

| Track | Points counted | Who can claim a threshold |
| --- | --- | --- |
| `individual` | The player's own | The player |
| `community` | Everyone's, added together | Players who added points. You can open it to every player |
| `grouped` | Each group's | The group's members |

**Groups** form in one of two ways. By default they come from [entity links](https://buildon.stacked.xyz/docs/concepts#players): the players linked to one entity, such as the owners of one pet, are a group. Or your backend forms groups itself with `POST /v1/player/liveops/group/upsert`. A group's points are the sum of its members' points. You can instead require every member to keep up, so the group moves at the pace of its slowest member.

An offer can also pay into a track: give it a `milestone_points` [reward](https://buildon.stacked.xyz/docs/rewards#reward-kinds).

## Daily rewards

Daily rewards give players a reason to come back each day of an event.

- Each day of the event has its own reward. Day 1 starts when the event starts, and each day lasts 24 hours.
- A day's reward can be claimed only during that day. A missed day stays missed.
- You create them on the event's **Dailies** tab with **Generate dailies**: set the rewards once, then adjust any day.

Every daily is an offer underneath, so it is claimed like one: `kind: "offer"` with the daily's `instanceId`. For each day your game gets a `status`:

| Status | Meaning |
| --- | --- |
| `locked` | The day has not started |
| `available` | The day is open, and the player has not yet done what it asks |
| `claimable` | The player can claim it now |
| `claimed` | Claimed |
| `missed` | The day ended unclaimed |

## Event offers

An offer tied to an event surfaces only while the event is live. It is a normal [offer](https://buildon.stacked.xyz/docs/offers) in every other way: same conditions, same rewards, same claim.

Event offers and dailies are set up on the Live Ops page. They come back from the live ops call below, not from the ordinary offers fetch, so your game can show them inside the event.

## Gate an event behind a context

By default every player gets a live event. To show it only to players who reach a certain place in your game, give the event one or more **surfacing contexts**.

A player then gets the event once your game [calls one of those contexts](https://buildon.stacked.xyz/docs/events#contexts) for them while it is live, and keeps it from then on. Until that moment the event is not returned for them, its offers do not surface, and they earn no points in it.

## Show an event in your game

One call returns everything a player needs: the events live now, their progress on each track, their dailies and the event offers.

| From | Call |
| --- | --- |
| A game client | `client.initializeLiveOpsEvents()`, or `POST /v2/client/liveops/initialize` |
| Your backend | `analytics.initializeLiveOpsEvents(playerId)`, or `POST /v1/player/liveops/initialize` |

```ts
await client.initialize();
await client.initializeLiveOpsEvents();

const event = client.getLiveOpsEvent('summer-2026');
const tracks = client.getMilestoneTracks(event.id);
const dailies = client.getEventDailies(event.id);
```

The answer has `events` and `offers`. Each event carries:

| Field | Holds |
| --- | --- |
| `id`, `readableId`, `name`, `caption`, `description` | What the event is |
| `image`, `wallpaper`, `icon`, `images`, `texts` | Its art and copy. `images` and `texts` are lists of `key` and value |
| `startDate`, `endDate` | When it runs |
| `milestones` | `individual`, `community` and `grouped`: the tracks it has |
| `eventDailies` | One entry per day: `day`, `status`, `rewards`, `instanceId`, `opensAt`, `closesAt` |

Each track carries its `id`, its `thresholds` (`id`, `value`, `name`, `rewards`), its `scoring` rules to show players how to earn, and the player's `progress`:

| Track | `progress` |
| --- | --- |
| `individual` | `points`, `claims`, `claimable` |
| `community` | `points` (the total), `contributorCount`, `myPoints`, `claims`, `claimable` |
| `grouped` | `groups`: each with its `points`, its `members`, and the player's own `membership` |

`claimable` lists the threshold values the player can claim now. Call this once per session, and again when you want fresh numbers.

## Claim milestone rewards

A milestone claim is the ordinary [claim call](https://buildon.stacked.xyz/docs/api#claim-rewards) with `kind: "milestone"`.

| Track | `instanceId` to send |
| --- | --- |
| `individual`, `community` | The track's `id` |
| `grouped` | The player's `membership.id` in the group |

```ts
// One track
await client.claimMilestoneRewards(track.id);

// Everything the player can claim, across events
await client.claimAllMilestoneRewards();
```

- One claim pays every threshold the track has reached and the player has not claimed yet.
- Your backend is told with a [reward webhook](https://buildon.stacked.xyz/docs/webhooks) whose `source` is `milestone`.
- A threshold is paid once per player. Changing its value later does not open it again.
- Rewards of an event that has ended can still be claimed. Rewards of an event that is switched off cannot.

## Live progress

A connected game client is told when a player's points change, with no need to ask again. The [`milestone_progress`](https://buildon.stacked.xyz/docs/api#realtime-events) event carries the track's whole `progress`, so replace what you hold with it. It is sent for individual and community tracks.

## Rules to rely on

- Points are earned only while the event is live. An event that is switched off earns none.
- Points never move between tracks.
- [Points are fixed when they are earned](https://buildon.stacked.xyz/docs/scoring-rules#points-and-intervals): editing a scoring rule changes later events only.
- A track can be limited to certain kinds of player, such as pets only. Other players still score for the community and for their groups, but do not see or claim that track.

---

# Leaderboards

Page: https://buildon.stacked.xyz/docs/leaderboards

A leaderboard ranks players by a score built from the events your game already sends. Scores move as players play, with no batch job to wait for, and when the leaderboard ends you pay the winners by rank.

## How a leaderboard scores

A leaderboard has [scoring rules](https://buildon.stacked.xyz/docs/scoring-rules), the same rules live ops tracks use: which events earn points, and how many. Two settings say what the points do to a player's score.

| Setting | Options |
| --- | --- |
| Score | `sum` (default) adds up every rule's points. `max` keeps the most points one event gave: a high score. `min` keeps the fewest and ranks the lowest first: a best time |
| Tiebreaker | `first-to-score` (default) or `last-to-score`, for players on the same score |

To rank players by a number your game computes, such as a lap time, send it as a [dynamic field](https://buildon.stacked.xyz/docs/events#dynamic-fields) and score it with a `dynamicTracker` rule in `perAmount` mode with 1 point.

A leaderboard also has a **start** and an **end**. Events score only between them. Either can be left open.

You build leaderboards on the **Leaderboards** page of the [dashboard](https://buildon.stacked.xyz/leaderboards).

## Kinds of leaderboard

| Kind | What it does |
| --- | --- |
| Single | One ranking, over one window |
| Repeating | Starts a fresh leaderboard every period: daily, weekly, any interval, or whenever you start the next one by hand. Your game keeps using one id, which always points at the current period |
| Sharded | Splits players into shards of a size you set. A player competes within their shard |
| Repeating and sharded | Every period has fresh shards |

**Shards** fill from buckets. A bucket is a set of [conditions](https://buildon.stacked.xyz/docs/offers#surfacing-conditions) on the player, such as a level range or a country, and a player goes to the first bucket they match. So you can keep beginners with beginners. A player is placed in a shard on their first scoring event, or, if you choose, only when your game [joins](#join-a-leaderboard) them.

**Periods** of a repeating leaderboard run on a schedule you set, or are **started by hand**: then a period runs until you press **Start next period** in the dashboard, or until the leaderboard's own end date. The period that ended can be paid at once.

## Show a leaderboard

The JavaScript and Unity SDKs have leaderboard methods, and send the player's token for you. From anything else, call the API: the `/v2/client/...` paths with a [player token](https://buildon.stacked.xyz/docs/api#authentication) from a game client, or the API-key paths from your backend.

**With an SDK**

```ts
// after the player signs in, and again whenever their rewards should be fresh: it loads
// the rewards the player can claim (see "Claim leaderboard rewards").
// The reads below prepare themselves if you skip it.
await client.initLeaderboards();

// the live leaderboards: prizes, the player's points and the first five ranks
const leaderboards = await client.listLeaderboards({ labels: { $in: ['weekly'] } });

// one leaderboard: every rank with what it is paid, and the player's own row
const standings = await client.getLeaderboard(leaderboards[0].id);
for (const row of standings.entries) {
  console.log(row.rank, row.username ?? row.playerId, row.score, row.rewards);
}
```

In Unity the same methods are `InitLeaderboardsAsync`, `ListLeaderboardsAsync`, `GetLeaderboardAsync` and `JoinLeaderboardAsync`, and for rewards `ClaimableLeaderboardRewards`, `ClaimLeaderboardRewardAsync` and `ClaimAllLeaderboardRewardsAsync`.

Every reward an SDK returns has the `amount` that would be paid: rounded down to the reward's unit, as it is when [rewards are generated](#rewards). Over HTTP the amounts are not rounded yet: see [Amounts over HTTP](#amounts-over-http). The fields below are the same either way.

**List the game's leaderboards**

`POST /v2/client/leaderboards`

With an empty body the answer has the leaderboards that are live now. Send any of these to narrow it, or to list others:

| Field | Meaning |
| --- | --- |
| `labels` | `{ "$in": [...] }` for the ones with any of these labels, `{ "$nin": [...] }` for the ones with none of them, or both. Labels are compared exactly |
| `startDate`, `endDate` | `{ "$gt": date, "$lt": date }`, one bound or both: the ones that start (or end) after `$gt` and before `$lt`. A date is an ISO string or milliseconds. Sending either one replaces the live-only default |
| `targetId` | Read as a linked entity of the player, such as a pet, as the standings do |

A leaderboard with no start counts as having always started, and one with no end as never ending. A field or operator the API does not know is refused with a 400, so a typo never returns the wrong list. From your backend, `POST /v1/sdk/leaderboards` takes the same fields, with `playerId` in place of `targetId`.

```bash
curl -X POST https://api.sandbox.stacked.xyz/v1/sdk/leaderboards \
  -H "x-api-key: your_api_key" \
  -H "x-client-id: your_client_id" \
  -H "Content-Type: application/json" \
  -d '{ "playerId": "player-1", "labels": { "$in": ["weekly"] }, "endDate": { "$gt": "2026-12-01T00:00:00Z" } }'
```

Each one has `id`, `name`, `description`, `labels`, `startDate`, `endDate`, `status` (`upcoming`, `live` or `ended`), `sharded`, `repeating`, its `scoring` rules to show players how to score, and its `prizes`. The list has the game's leaderboards themselves, each with its own dates, which are the dates the filters look at. It never has a period of a repeating leaderboard or a shard of a sharded one: read the standings of a leaderboard (below) by its `id` to get the one that stands for it now, the current period and the player's shard. A repeating leaderboard is live while it repeats. At most 100 are listed, newest first.

Each one also has the player's points on it now: `viewer` is `{ playerId, username, score }`, or `null` when they have none yet. The list does not have the player's rank: read the standings for that.

Each one comes with its first five ranks, to show the leaders without a call per leaderboard: `top` is `[{ rank, playerId, username, score, rewards }]`, with the `rewards` that rank would be paid now (but for a share in proportion to points, which the standings have). A repeating leaderboard has its current period's, and a sharded one the shard of the player. It is empty for a sharded leaderboard when there is no player, or the player is in no shard yet, or their shard still waits for players (see the standings below). The rows can be a few seconds old. A leaderboard with a [prize pool that grows](#a-prize-pool-that-grows-with-play) has it as `pool`, as the standings do.

**Read the standings**

`POST /v2/client/leaderboard`

| Field | Meaning |
| --- | --- |
| `leaderboardId` | The leaderboard's `id` |
| `page`, `limit` | Which page, from 1, and how many rows: 100 by default, 200 at most |
| `repeater` | Repeating only. `0` or absent is the current period, `1` the one before, `2` the one before that, `-1` the next to come |
| `shardId` | Sharded only. The `id` of the shard to read, when it is not the player's own |
| `global` | Sharded only. `true` ranks the players of every shard together, instead of one shard: see [one ranking across all shards](#one-ranking-across-all-shards) |

```bash
curl -X POST https://api.sandbox.stacked.xyz/v1/player/leaderboard \
  -H "x-api-key: your_api_key" \
  -H "x-client-id: your_client_id" \
  -H "Content-Type: application/json" \
  -d '{ "leaderboardId": "68a1f3c2e4b0a1d2c3f4a5b6", "playerId": "player-1" }'
```

The answer holds:

| Field | Holds |
| --- | --- |
| `leaderboard` | The leaderboard the rows are from. For a repeating one that is a period, and `templateId` is the id that stays the same |
| `entries` | The rows of this page: `rank` (1 is first), `playerId`, `username`, `score`, and the `rewards` that rank would be paid |
| `viewer` | The player's own row, wherever they rank, or `null` when they have no score |
| `prizes` | What each rank is paid, ready to draw: `byRank` (`fromRank`, `toRank`, `rewards`), `byScore`, `byShare` for rewards shared [in proportion to points](#rewards), and `pools`: the whole prize pool of each reward that shares one |
| `pool` | Only with a [prize pool that grows](#a-prize-pool-that-grows-with-play): `count`, `rewards` and `rules` |
| `repeat` | Repeating only: `repeater`, `hasPrevious`, `hasNext` |
| `shard` | Sharded only: the shard shown, with its `id`, its `bucket`, its number of `players`, and `waiting` while it waits for players |
| `global` | `true` when the rows are a sharded leaderboard's ranking across all its shards |
| `total`, `page`, `limit`, `hasMore` | Paging |

- A sharded leaderboard returns the player's own shard. To read another shard, send its `id` as `shardId`, or as the `leaderboardId` itself.
- **A new shard waits for players.** While a shard is new and has few players, `shard.waiting` is `true` and `entries` is empty: show "waiting for more players", not a board of two. The player's own row (`viewer`) is still there. Waiting ends when the shard has 10 players, or is full if your shards are smaller, or has been open for 4 hours (or a sixth of the leaderboard's length, if that is shorter). It never waits once the leaderboard has ended.
- Rows stop at the number of ranks you set for the leaderboard (1,000 by default). The player's own row is always returned.
- **Every row has the player's name.** `username` is the name your game sent for that player with a `sign_in`, `sign_up` or `player_snapshot` [event](https://buildon.stacked.xyz/docs/events), and a new name shows within seconds. A player you sent no name for has no `username`: show `playerId`, your game's id for them. To search by name, filter the rows you have read.

### One ranking across all shards

A sharded leaderboard normally shows a player their own shard. To show everyone together, ask for the standings with `global: true`:

```ts
const everyone = await client.getLeaderboard(leaderboard.id, { global: true });
```

- The answer has `global: true` and no `shard`. Its ranks are across all shards.
- It has the first ranks only: the number of ranks you set for the leaderboard (1,000 by default). `viewer` is the player's own row when it is among them, and `null` otherwise. Their points, and their rank in their shard, are on the standings without `global`.
- Its rows have no `rewards`: a sharded leaderboard [pays by rank within each shard](#rewards). `prizes` is still there, and says what each shard pays.
- It is read from saved scores, so it can be up to 15 minutes behind a shard's own standings, which are live.
- `repeater`, `page` and `limit` work as for any standings. For a leaderboard that is not sharded, `global` changes nothing.

### Amounts over HTTP

The API answers with amounts that are not rounded. When rewards are generated, each amount is [rounded down](#rewards) to its reward's unit. To show what will be paid, round the same way (the SDKs do this for you):

- `POST /v2/client/leaderboards/init`, or `GET /v1/sdk/leaderboards/init` from your backend, answers `currencies`: `[{ kind, rewardId, name, roundDecimalPlaces }]`. These are your game's currencies (`coins`) and the Stacked currencies (`loyalty_currency`). (The same answer has the player's [rewards to claim](#claim-leaderboard-rewards), which are rounded already.)
- Round a currency reward down to its `roundDecimalPlaces`, and every other reward down to a whole number. Leave a `discount` as it is.
- A reward that rounds down to nothing is not paid: do not show it.
- In `prizes`, a reward with `parts` adds up several rewards of one currency. Round each part down, then add them.

A pool (`prizes.pools`, `prizes.byShare`, `pool`) is a figure to show, not a payout.

## Join a leaderboard

Most leaderboards need no joining: a player is on the board as soon as they score. Joining matters for a sharded leaderboard that places players only on request.

`POST /v2/client/leaderboard/join`

Send `leaderboardId`. The answer has `joined` and, for a sharded leaderboard, the `shard` the player was given.

A leaderboard cannot be joined before it starts (`leaderboard-not-started`) or after it ends (`leaderboard-ended`). Join a player once the list shows it as `live`.

## Rewards

Prizes come from **reward templates**, which belong to your game and can be attached to any number of leaderboards. A template pays:

- **by rank**: rank 1 gets this, ranks 4 to 10 get that;
- **by score band**: everyone above a score gets something;
- **in proportion to points**: every player with points gets a share of a prize pool, the pool × their points ÷ everyone's points;
- as **fixed amounts**, or as **shares of a prize pool**;
- with an optional **boost** for players who match conditions you set.

**Nothing is paid automatically.** When a leaderboard has ended, open its standings in the dashboard and press **Generate rewards**. For a repeating leaderboard, do it for each period. It can be done once.

When rewards are generated:

- **Blacklisted players are left out**, and everyone below them moves up a rank. So a rank's prize goes to the next player in line.
- **On a sharded leaderboard every pool is split evenly over the shards.** Each shard with players gets the same slice, and pays from it as a leaderboard without shards would: its ranks by their percents, its score bands among its own players, and a share in proportion to points by its own players' points. So rank 1 of a small shard wins as much as rank 1 of a big one, and a point is worth more in a small shard. A shard where nobody can be paid keeps its slice unpaid. A reward that only pays some buckets is split over those buckets' shards.
- **Amounts are rounded down to the reward's unit**: an in-game currency by the decimal places you set for it in the asset library, a Stacked currency by its own, and whole numbers when none is set and for items and everything else. An amount that rounds down to nothing pays nothing: there is no minimum, so a pool is never paid more than it holds.

A reward shared **in proportion to points** is shared by the leaderboard's players, or on a sharded leaderboard by the players of each shard, each shard sharing its slice. Only points above zero share, and it cannot be used on a leaderboard that ranks the lowest score first. Each share is rounded down to the reward's unit, and a player whose share rounds down to nothing gets nothing, so the pool is never paid more than it holds. Games see it in `prizes.byShare`, with the `pool` being shared: on a sharded leaderboard, one shard's slice. What one player would get is in their row's `rewards` only once the leaderboard has ended.

**Generating grants nothing yet.** Each winner's rewards are kept with their place on the leaderboard, waiting to be claimed. Nothing reaches your backend until a player [claims theirs](#claim-leaderboard-rewards). A reward that is not claimed does not expire.

The dashboard's **Payouts** tab then shows where each winner's reward stands: waiting to be claimed, or claimed and when.

### Claim leaderboard rewards

A player claims a leaderboard reward the way they claim any other: one [claim](https://buildon.stacked.xyz/docs/api#claim-rewards), from your game client or from your backend.

**With an SDK**

```ts
// initLeaderboards() loaded them. Every call of it asks the server again, so call it
// when the player opens their leaderboards to pick up rewards generated since
const rewards = client.claimableLeaderboardRewards();
for (const reward of rewards) {
  console.log(reward.name, `rank ${reward.rank}`, reward.rewards);
}

// claim one, or everything at once
await client.claimLeaderboardReward(rewards[0].id);
await client.claimAllLeaderboardRewards();
```

A connected client is also sent new rewards the moment they are generated ("In realtime" below has the details):

```ts
import { OfferEvent } from '@pixels-online/pixels-client-js-sdk';

// claimableLeaderboardRewards() already has the new entry when this runs
client.events.on(OfferEvent.LEADERBOARD_ENTRY_UPDATED, ({ entry }) => {
  if (entry.rewardsStatus === 'claimable') {
    showRewardsBadge(client.claimableLeaderboardRewards().length);
  }
});
```

**Over HTTP**

1. `POST /v2/client/leaderboards/init` (player token) answers `claimableRewards` for that player. From your backend, `GET /v1/sdk/leaderboards/init?playerId=player-1` does the same for the player you name.
2. Claim with `kind: "leaderboard"` and the reward's `id` as the `instanceId`: `POST /v1/client/reward/claim` with the player token, or `POST /v1/reward/sdk/claim` with your API key and `playerId`.

Each item of `claimableRewards` is the player's entry on a leaderboard, with the rewards on it:

| Field | Meaning |
| --- | --- |
| `id` | What to claim it with |
| `leaderboardId` | The leaderboard it was won on. For a repeating leaderboard this is the period: read its standings by this id |
| `templateId` | Only for a period: the repeating leaderboard, which is the id your list has |
| `shardId` | Only on a sharded leaderboard: the shard the player was on |
| `name`, `description`, `startDate`, `endDate` | The leaderboard's, or the period's |
| `playerId` | Whose entry it is |
| `rank`, `score` | The rank and the score the reward was won with. Rank 1 is first, within the player's shard on a sharded leaderboard |
| `rewards` | What the claim grants: `[{ kind, rewardId, name, amount, image }]`. The amounts are final: they were rounded down when the rewards were generated |
| `rewardsStatus` | `claimable` on every item of this list. It becomes `claimed` once the player claims |
| `rewardsGeneratedAt` | When the rewards were generated |

The list has the newest first and at most 100. A player with more gets the rest as they claim.

**In realtime**

A game client that is [connected](https://buildon.stacked.xyz/docs/api#realtime-events) is sent the entry the moment the leaderboard's rewards are generated: a `leaderboard_entry_updated` event whose data has the fields of an item above. The SDKs put it in the player's claimable rewards before your listener runs (`OfferEvent.LEADERBOARD_ENTRY_UPDATED`, `OfferEvent.LeaderboardEntryUpdated` in Unity), so the player can claim without another fetch.

- The event only reaches players who are connected right then: one who connects later never gets it. Keep calling `initLeaderboards()` when the player signs in or opens their leaderboards.
- The event is about the entry, not only about rewards, and may be sent for other changes of an entry later. Read `rewardsStatus` before you treat one as a reward: it is absent on an entry that has none.

When a claim goes through, the player is granted the rewards once: Stacked currencies are credited, and your backend gets one `user.gain_rewards` [reward webhook](https://buildon.stacked.xyz/docs/webhooks#payload), the same one every other claim sends, with `source: "leaderboard"`, the player's `rank` and `score`, the leaderboard's id as `campaignId` and the reward's `id` as `instanceId`. A claim that fails changes nothing, so it can be tried again.

| Error | Meaning |
| --- | --- |
| `leaderboard-reward-not-found` | No reward with that id for this player |
| `already-claimed` | It was claimed before |
| `player-blacklisted` | The player is on your [blacklist](#keep-it-fair). A reward generated before you blacklisted them cannot be claimed while they are on it |
| `claim-failed` | The rewards could not be granted. The usual cause: [webhooks](https://buildon.stacked.xyz/docs/webhooks#set-up-an-endpoint) are not set up for this environment yet |

### A prize pool that grows with play

A reward template that pays shares of a prize pool can have that pool grow as players play: "every coin spent adds 1 to the pot". You set it on the leaderboard's **Rewards** tab:

- **What counts**: [scoring rules](https://buildon.stacked.xyz/docs/scoring-rules), like the ones that score the leaderboard. Every event that matches adds the rule's points to one count for the leaderboard, whoever the player is, on the board or not. A blacklisted player's events do not count.
- **What the count is worth**, for each reward template the pool pays:

| Curve | The pool is |
| --- | --- |
| Linear (default) | count × k, up to the limit |
| Exponential | limit × (1 − e^(−k × count)): it rises fast at first and nears the limit without passing it |

k is the curve's constant, 1 when you leave it empty. An exponential pool needs a limit.

Until something is counted, the template's own pool applies. A pool you set by hand on a leaderboard or a period always wins. Every period of a repeating leaderboard counts from zero. A sharded leaderboard has one count for all its shards, and the pool it comes to is split evenly over them like any other pool. `pool` shows what the whole count is worth.

A template the pool pays has one reward that shares a pool, with a percent on every rank and score band. To split one count over two rewards, use two templates, each with its own curve.

Games read it as `pool` in the standings and in the list:

| Field | Holds |
| --- | --- |
| `count` | What has been counted so far |
| `rewards` | One item per reward the pool pays: `templateId`, `kind`, `rewardId`, `name`, `image`, the pool's `amount` right now, and its `limit` when it has one |
| `rules` | The rules that grow it, to tell players how: `description`, `trigger`, `points`, `pointsMode`, `intervalMs` |

`prizes` and each row's `rewards` already share the pool out, so a rank's prize grows with it. The numbers can be up to 15 seconds behind play.

## Keep it fair

- **Blacklist a player** to stop their events from scoring on every leaderboard of your game, periods and shards included. The blacklist belongs to your game, not to one leaderboard. The score they already have is kept, but they are not shown: the standings, the list's `top` and the player's own `viewer` leave them out, everyone below them moves up a rank, and they are left out when rewards are generated. A reward that was generated for them before cannot be claimed while they are blacklisted. Taking them off the blacklist shows them again, and lets them claim.
- **Hide a leaderboard** while you test it. It scores, but your game does not get it.
- **Pause a leaderboard** to stop it scoring.
- [Points are fixed when they are earned](https://buildon.stacked.xyz/docs/scoring-rules#points-and-intervals). Changing a rule changes later events only, and scores are never worked out again from old events.

---

# Events

Page: https://buildon.stacked.xyz/docs/events

Events are how Stacked knows what players do. Your backend sends them with a server SDK as things happen in your game. One event can update the player's [snapshot](https://buildon.stacked.xyz/docs/concepts#players), move their offers forward, and score points in live ops and on leaderboards, all at once.

## Send an event

```ts
analytics.levelUp('player-1', { skill_id: 'farming', level_value: 12 });
```

Every method takes the player's id first, then the event's parameters.

- **Events are sent in the background.** The SDK batches them and sends every two seconds. Call `await analytics.flush()` before your process exits.
- **They are applied within seconds**, not at once. Fetch a player's offers again a moment after an event to see its effect.
- **Send what happens, not what it is for.** An event is not tied to an offer. Whatever is listening for it picks it up: this week's offer, next month's leaderboard.
- **Ids you send appear in the dashboard.** Items, currencies, skills and contexts seen in events are added to your [asset library](https://buildon.stacked.xyz/docs/rewards#the-asset-library), ready to pick when you build a condition.

The Go SDK has the same methods, in Go style (`analytics.LevelUp`).

## What each event does

| SDK method | Send it when | Updates on the player | Counts toward |
| --- | --- | --- | --- |
| `signIn` | A player starts a session | Username, days in game, login streak | |
| `signUp` | A player is created | Username, sign-up date | |
| `playerSnapshot` | You want to set a player's state in one go | Levels, currencies, memberships, quests, achievements, trust score, entity kind and links | |
| `levelUp` | A skill reaches a level | That level | |
| `earnCurrency` | A player gains currency | The balance | |
| `spendCurrency` | A player spends currency | The balance | `spendCurrency` |
| `depositCurrency` | Currency comes into your game from outside | The total deposited | `depositCurrency` |
| `withdrawCurrency` | Currency leaves your game | The total withdrawn | |
| `gainItem`, `loseItem` | A player gains or loses an item | | `buyItem`, when the item was gained for a currency |
| `setField`, `incField`, `maxField`, `minField` | A value of your own changes | That [dynamic field](#dynamic-fields) | `dynamicTracker` |
| `delField` | A value of your own goes away | Removes the field | |
| `callContext` | A player reaches a moment you named | | `completionContext`, and [surfacing](#contexts) |
| `addTags`, `removeTags` | You sort players into segments | Tags | |
| `trustScore` | Your own measure of a player's trust changes | Trust score | |
| `gainAchievement`, `loseAchievement` | An achievement changes | Achievements | |
| `gainMembership`, `renewMembership`, `loseMembership` | A subscription or pass changes | Memberships | |
| `questStart`, `questProgression`, `questEnd` | A player moves through a quest | Quest completions | |
| `linkUser`, `unlinkUser` | Two players or entities are linked, such as a pet and its owner | Entity links | |
| `identifierLink` | A player connects an email, a social account or a wallet | Identifiers | |
| `custom` | Anything else worth recording | | |

The last column names the [completion conditions](https://buildon.stacked.xyz/docs/offers#completion-conditions) and [scoring triggers](https://buildon.stacked.xyz/docs/scoring-rules#triggers) the event feeds. An event with nothing there still matters: [surfacing conditions](https://buildon.stacked.xyz/docs/offers#surfacing-conditions) read the snapshot it keeps up to date.

A `custom` event is recorded with the player's other events and can be inspected in the dashboard. It does not move offers or scores. To track something of your own, use a dynamic field or a context.

## Currency and items

```ts
// 100 gold spent at a shop
analytics.spendCurrency('player-1', {
  currency_id: 'gold',
  currency_amount: 100,
  to_kind: 'store',
  to_id: 'starter-shop',
});

// A sword bought for 250 gold: counts as buying an item
analytics.gainItem('player-1', {
  item_id: 'sword',
  item_amount: 1,
  from_kind: 'store',
  from_id: 'starter-shop',
  currency_id: 'gold',
  currency_amount: 250,
});
```

- `from_kind` and `to_kind` say where the currency or item came from or went: `store`, `marketplace`, `auction`, `player`, or a word of your own.
- A trade between two players (`from_kind` and `to_kind` both `player`) updates nothing and scores nothing.
- Send `in_game_balance` with a currency event to set the balance outright. Without it, the amount is added or taken off.

## Dynamic fields

A dynamic field is a named value you keep on a player: `boss_kills`, `best_lap_ms`, `favourite_class`. It can be a number, a text or a boolean.

```ts
analytics.setField('player-1', { key: 'favourite_class', value: 'mage' });
analytics.incField('player-1', { key: 'boss_kills', value: 1 });
analytics.minField('player-1', { key: 'best_lap_ms', value: 83450 });
```

| Method | Does |
| --- | --- |
| `setField` | Sets the value |
| `incField` | Adds to a number |
| `maxField` | Keeps the larger of the stored and the sent number |
| `minField` | Keeps the smaller |
| `delField` | Removes the field |

Dynamic fields are the general-purpose tool. A surfacing condition can read one ("players with 10 boss kills or more"), a completion condition can count changes to one ("kill 5 more bosses"), and a scoring rule can turn one into points.

## Contexts

A context is a named moment in your game: `open_shop`, `enter_arena`, `finish_tutorial`.

```ts
analytics.callContext('player-1', { context: 'enter_arena' });
```

Calling a context does three things:

- **Surfaces offers.** An offer with a `surfacingContext` condition surfaces only when your game calls one of its contexts, and a connected game client is told at once ([`offer_surfaced`](https://buildon.stacked.xyz/docs/api#realtime-events)). On Live, the [interval between checks for new offers](https://buildon.stacked.xyz/docs/offers#when-offers-surface) applies to context calls too.
- **Completes conditions.** A `completionContext` condition counts the call.
- **Opens gated live ops events.** An event [gated behind a context](https://buildon.stacked.xyz/docs/live-ops#gate-an-event-behind-a-context) starts for the player.

## The snapshot in one call

`playerSnapshot` sets many parts of a player at once. Use it to bring existing players into Stacked, or to correct drift.

```ts
analytics.playerSnapshot('player-1', {
  username: 'ada',
  levels: [{ skill_id: 'farming', level_value: 12 }],
  currencies: [{ id: 'gold', balance: 4200 }],
  trust_score: 80,
});
```

- Each entry you send is set. Entries you leave out of a list are kept, and an empty list clears it.
- A player with an [entity kind](https://buildon.stacked.xyz/docs/concepts#players) needs `entity_kind` on every call. Leaving it out makes them a regular player again.

---

# Scoring rules

Page: https://buildon.stacked.xyz/docs/scoring-rules

A scoring rule turns one kind of game event into points. [Live ops milestone tracks](https://buildon.stacked.xyz/docs/live-ops#milestone-tracks) and [leaderboards](https://buildon.stacked.xyz/docs/leaderboards) both score with the same rules, built in the same editor, so you learn them once.

## Anatomy of a rule

| Field | Meaning |
| --- | --- |
| `trigger` | Which event earns points |
| `criteria` | Optional. Extra checks on the event's parameters |
| `points` | Points for each matching event |
| `pointsMode` | `flat` (default): `points` per event. `perAmount`: `points` times the event's amount |
| `intervalMs` | Optional. A player scores from this rule at most once per interval |
| `description` | Optional. Text for players that says how to earn these points |

```json
{
  "description": "Spend gold in the event shop",
  "trigger": { "kind": "spendCurrency", "id": "currency_gold", "amount": 100 },
  "points": 1,
  "pointsMode": "perAmount",
  "intervalMs": 86400000
}
```

This rule gives one point per gold coin spent, for a spend of at least 100 in one go, once per day.

## Triggers

A trigger names the event that counts. Each one is fed by [events your game sends](https://buildon.stacked.xyz/docs/events).

| Trigger | Counts | Set on the trigger | The event's amount |
| --- | --- | --- | --- |
| `buyItem` | An item the player gained and paid for with a currency | The item's id | Items gained |
| `spendCurrency` | Currency the player spent | The currency's id | Amount spent |
| `depositCurrency` | Currency the player deposited | The currency's id | Amount deposited |
| `completionContext` | A [context](https://buildon.stacked.xyz/docs/events#contexts) your game called | The context's name | 1 |
| `dynamicTracker` | A [dynamic field](https://buildon.stacked.xyz/docs/events#dynamic-fields) your game set or changed | The field's key | The value sent, when it is a number. Otherwise 1 |
| `contractInteraction` | An on-chain event on a contract Stacked listens to | The contract and event | The on-chain amount |

- On `buyItem`, `spendCurrency` and `depositCurrency`, `amount` is the least a single event must carry to count.
- A `dynamicTracker` trigger can also compare the value: `==`, `!=`, `>`, `>=`, `<`, `<=`, `has`, `not_has`, `is_truthy`, `is_falsy` or `is_defined`. Its key can hold a wildcard: `care_action_{{x}}` matches `care_action_feed` and `care_action_wash`.
- Transfers from one player to another never score.

## Criteria

Criteria look inside the event that fired. Use them when the trigger alone is too broad: only purchases in one region, only an outfit that includes one item.

A check names a parameter, an operator and a value. Checks combine in groups with `AND`, `OR` and `NOT`.

```json
{
  "kind": "group",
  "operator": "AND",
  "conditions": [
    { "kind": "param", "param": "extra.region", "operator": "==", "value": "eu" },
    { "kind": "param", "param": "extra.clothes", "operator": "contains", "value": "itm_hat5" }
  ]
}
```

| Operator | Passes when |
| --- | --- |
| `==`, `!=` | The parameter equals, or does not equal, the value |
| `>`, `>=`, `<`, `<=` | The parameter compares to the value as a number |
| `in`, `not_in` | The parameter is, or is not, one of the listed values |
| `contains`, `not_contains` | A text holds the value, or a list holds it. With a list of values: all of them, or none |
| `contains_any` | The parameter holds any of the listed values |
| `matches` | The parameter matches a regular expression |
| `exists`, `not_exists` | The parameter is there, or is not |

`param` is a path into the event's parameters: `extra.region`, `extra.clothes[0]`, `extra.clothes.length`. The SDK's own parameters are in snake case (`item_id`, `currency_amount`). What you put in `extra` keeps the names you gave it. `event_name` and `user_id` can be checked too.

> **Criteria stay on the server.** Your game gets each rule's `description`, `trigger`, `points`, `pointsMode` and `intervalMs` to show players how to score. It never gets the criteria.

## Points and intervals

- **`flat`** gives `points` for each matching event. **`perAmount`** multiplies `points` by the event's amount: one point per coin spent, or a score equal to the value of a field.
- **`intervalMs`** lets a player score from the rule once per window. Windows are counted in UTC from a fixed origin, so `86400000` is once per UTC day, not once per 24 hours since the last score.
- **Points are fixed when they are earned.** Changing a rule changes what later events earn. Points a player already has are not worked out again.
- **Scoring takes a moment.** Events are processed in the background, usually within a few seconds.

## Where rules are used

| Used by | What the points do |
| --- | --- |
| A live ops [milestone track](https://buildon.stacked.xyz/docs/live-ops#milestone-tracks) | Add up toward the track's thresholds. Each track has its own rules, and points never move between tracks |
| A [leaderboard](https://buildon.stacked.xyz/docs/leaderboards#how-a-leaderboard-scores) | Become the player's score: added up, or the best or lowest single event |

---

# Rewards

Page: https://buildon.stacked.xyz/docs/rewards

A reward is what a player gets from an offer, a milestone, a daily, a leaderboard or the shop. Stacked decides who has earned what. For most kinds of reward, your game is the one that hands it over.

## Reward kinds

Every reward has a `kind`, an `amount` and a `name`. Most also have a `rewardId`, the id of the thing in your game.

```json
{ "kind": "coins", "rewardId": "currency_gold", "amount": 5000, "name": "Gold Coins" }
```

| Kind | What it is | Who gives it to the player |
| --- | --- | --- |
| `item` | An item in your game | Your game, from the [reward webhook](https://buildon.stacked.xyz/docs/webhooks) |
| `coins` | A currency of your game | Your game |
| `exp` | Experience in one of your skills | Your game |
| `trust_points` | Trust points | Your game |
| `discount` | A discount for your game to apply. `amount` is a fraction: `0.2` is 20% | Your game |
| `loyalty_currency` | A Stacked currency, held by Stacked across games | Stacked credits the player's Stacked balance |
| `milestone_points` | Points on a [live ops track](https://buildon.stacked.xyz/docs/live-ops#milestone-tracks). Offers only | Stacked adds them to the track |

Stacked never changes anything inside your game. For the first five kinds it tells your backend what to grant, and your backend does it. That is the whole of the [reward webhook](https://buildon.stacked.xyz/docs/webhooks).

## The asset library

The asset library is the list of things your game has: currencies, items, skills, and the names you use for contexts, dynamic fields and entity kinds. Rewards and conditions refer to them by id.

- Add assets on the **Asset Library** page of the [dashboard](https://buildon.stacked.xyz/asset-library), with a name and an image for your game to show.
- Ids seen in the [events](https://buildon.stacked.xyz/docs/events) your game sends are added by themselves.
- An id must not contain a dot.
- A currency carries two settings that shape reward amounts: its **decimal places** and, optionally, its **USD price**.

## Amounts

**Decimals.** A `coins` amount is cut down to the currency's decimal places, never rounded up: 12.349 of a two-decimal currency is 12.34. Items, experience and trust points are whole numbers.

**Amounts fixed in dollars.** A `coins` or `loyalty_currency` reward can be worth a set value instead of a set number of units: "$1.00 of gold". The amount is worked out from the currency's price when the offer surfaces for a player, or when a milestone is claimed, so the reward keeps its value as the price moves.

```json
{
  "kind": "coins",
  "rewardId": "currency_gold",
  "name": "Gold Coins",
  "amount": 400,
  "anchor": { "currency": "USD", "amount": 1 }
}
```

For this, a currency of your game needs a USD price in the asset library. `amount` is what was worked out when the reward was last saved, and is what is paid if no price is available.

## Reward rules

A reward rule multiplies a reward for the players who match it: double gold for new players, 20% less for players in one region.

| Part | Meaning |
| --- | --- |
| Scope | Every offer of the game, or one offer |
| Rewards | Which rewards it changes, by kind and id |
| Conditions | Which players it applies to. They are [surfacing conditions](https://buildon.stacked.xyz/docs/offers#surfacing-conditions) |
| Multiplier | What the amount is multiplied by |
| Priority | Which rule wins when several match |

- A rule is applied when an offer surfaces for a player, so the player sees the adjusted amount from the start.
- When several rules match one reward, only those with the highest priority apply.
- A single reward can opt out of rules.

Rules are on the **Rules** page of the dashboard.

## Spend limits

A spend limit caps how much of a reward your game gives away in a window of time. It is your budget control.

| Part | Meaning |
| --- | --- |
| Scope | The whole game, the offers that carry certain labels, or one offer |
| Rewards | Which rewards it counts, by kind and id |
| Windows | A cap per window: `minute`, `hourly`, `daily`, `weekly`, `monthly`, or `allTime`. Add a count for longer windows: `daily:7` is every seven days |

- **A limit acts at surfacing.** When an offer is about to surface, its reward is set aside from the budget. If there is no room left, the offer does not surface for that player. Nobody is shown a reward that cannot be paid.
- Windows are counted in UTC.
- A limit can give budget back when an offer expires or is declined. That is a setting per window.

Limits are on the **Spend Limits** page of the dashboard, which also shows how much of each window is used.

## Claiming

A reward is paid when it is claimed, and a claim is always one call: from your game client for the signed-in player, or from your backend for any player.

| What | How it is claimed |
| --- | --- |
| An offer, a daily reward | [Claim](https://buildon.stacked.xyz/docs/api#claim-rewards) with `kind: "offer"` and the `instanceId` |
| A leaderboard reward | [Claim](https://buildon.stacked.xyz/docs/leaderboards#claim-leaderboard-rewards) with `kind: "leaderboard"` and the reward's `id` |
| A live ops milestone | [Claim](https://buildon.stacked.xyz/docs/live-ops#claim-milestone-rewards) with `kind: "milestone"` |
| A shop item | A [purchase](https://buildon.stacked.xyz/docs/api#shop) |

Every claim that succeeds reaches your backend as a [reward webhook](https://buildon.stacked.xyz/docs/webhooks). Claiming the same thing a second time is refused.

---

# Reward webhooks

Page: https://buildon.stacked.xyz/docs/webhooks

Stacked decides what a player has earned. Your game decides how to hand it over. When a player claims a reward, Stacked sends a signed webhook to your backend that says who to give what, and your backend grants it.

## Set up an endpoint

1. Write an HTTPS handler in your game backend (see [Verify and grant](#verify-and-grant)).
2. Open **Webhooks** in the [dashboard](https://buildon.stacked.xyz/webhooks), on **Test** or **Live**, and add the handler's URL.
3. Subscribe it to `user.gain_rewards`.
4. Copy the endpoint's signing secret (it starts with `whsec_`) into your backend's configuration.
5. Send a test event from the page and check the delivery.

Test and Live have separate endpoints and secrets. An [AI agent](https://buildon.stacked.xyz/docs/mcp) can do all of this with the webhook tools.

## Event types

| Event type | Sent when |
| --- | --- |
| `user.gain_rewards` | A player is granted rewards: an offer claim, a shop purchase, a live ops milestone claim or a leaderboard reward claim. **Subscribe to this one.** |
| `claim.reward` | An offer claim only. Legacy: same claims and same payload as `user.gain_rewards`. |
| `claim.offer` | An offer claim only. Legacy: same payload. |

> **Subscribe to one event type.** An offer claim sends all three. An endpoint subscribed to all of them is told to grant the same reward three times.

## Payload

Every reward webhook has the same JSON body.

| Field | Type | Meaning |
| --- | --- | --- |
| `source` | string | What paid out: `offer`, `shop`, `milestone` or `leaderboard` |
| `campaignId` | string | The id of the offer, shop item, milestone track or leaderboard |
| `instanceId` | string | What was claimed: the player's offer, the shop purchase, the milestone claim or the leaderboard reward (the `id` it was claimed with) |
| `campaignKind` | string, optional | `offer`, `referral`, `shop`, `milestone` or `leaderboard` |
| `entityKind` | string, optional | The player's [entity kind](https://buildon.stacked.xyz/docs/concepts#players), when it has one |
| `playerId` | string | Your game's id for the player, as your game sent it |
| `extra` | object, optional | The string values your game sent as `extra` with the [claim](https://buildon.stacked.xyz/docs/api#claim-rewards), unchanged |
| `rank`, `score` | number, optional | Leaderboard payouts only: the player's final rank (1 is first) and score |
| `name` | string | The name of what was claimed |
| `description` | string, optional | Its description |
| `rewards` | array | What to grant. Each entry is a [reward](https://buildon.stacked.xyz/docs/rewards#reward-kinds): `kind`, `rewardId`, `amount`, `name` |
| `dedupeId` | string | Unique per message. It differs between the three event types of one claim |

```json
{
  "source": "offer",
  "campaignId": "6844c430e3db6fb7612cc126",
  "campaignKind": "offer",
  "instanceId": "68a1f3c2e4b0a1d2c3f4a5b6",
  "playerId": "playerId_from_your_game",
  "name": "Welcome back",
  "description": "Sign in three days in a row",
  "rewards": [
    { "kind": "coins", "rewardId": "currency_gold", "amount": 5000, "name": "Gold Coins" },
    { "kind": "item", "rewardId": "item_popberry", "amount": 12, "name": "Popberry Fruit" },
    { "kind": "exp", "rewardId": "skill_ranger", "amount": 69, "name": "Ranger EXP" }
  ],
  "dedupeId": "68a1f3c2e4b0a1d2c3f4a5b7"
}
```

Two reward kinds never need your game to act: Stacked credits `loyalty_currency` rewards to the player's Stacked balance itself and leaves them out of `rewards`, and it adds `milestone_points` to the live ops track itself (they are listed so your game can show them).

> **`extra` from a game client is the player's word.** When the claim came from your game client, `extra` holds whatever that client sent. Check it before you act on it.

## Verify and grant

Each delivery is signed with the endpoint's secret, following the [Standard Webhooks](https://www.standardwebhooks.com) scheme. The `svix` libraries verify it in most languages.

| Header | Value |
| --- | --- |
| `svix-id` | The message id. The same on every retry of one message |
| `svix-timestamp` | When this attempt was sent, in seconds |
| `svix-signature` | `v1,` and the signature. More than one, separated by spaces, while a secret is being rotated |

The same three values are also sent as `webhook-id`, `webhook-timestamp` and `webhook-signature`.

```ts
import express from 'express';
import { Webhook } from 'svix';

const app = express();
const webhook = new Webhook(process.env.STACKED_WEBHOOK_SECRET); // whsec_...

// The signature covers the raw body, so read it before any JSON parsing.
app.post('/stacked/rewards', express.raw({ type: 'application/json' }), async (req, res) => {
  let reward;
  try {
    reward = webhook.verify(req.body, {
      'svix-id': req.header('svix-id'),
      'svix-timestamp': req.header('svix-timestamp'),
      'svix-signature': req.header('svix-signature'),
    });
  } catch {
    return res.status(400).end();
  }

  // Grant once per message, however many times it is delivered.
  await grantOnce(reward.dedupeId, () => giveRewards(reward.playerId, reward.rewards));
  res.status(204).end();
});
```

`grantOnce` and `giveRewards` are yours: record the key and grant in one transaction, and do nothing when the key is already there.

To verify without a library: the signed content is `<svix-id>.<svix-timestamp>.<raw body>`, the key is the secret without `whsec_`, decoded from base64, and the signature is the base64 HMAC-SHA256 of the content. Accept the request if any signature in the header matches, and reject a timestamp more than five minutes from your clock.

## Grant each reward once

A webhook can reach you more than once: a retry after a slow answer, or a resend from the dashboard. Make granting idempotent.

- **Key on `dedupeId`.** Record it when you grant, and do nothing when you have seen it before. A retry or a resend of a message carries the same `dedupeId` and the same `svix-id`.
- **Subscribe to one event type.** The three messages of one offer claim have three different `dedupeId`s.
- `source` and `instanceId` say what was claimed, which is useful in your own records. They identify one grant in every case but one: an offer a player can claim several times keeps the same `instanceId` for each claim.

## Delivery and retries

Answer with a `2xx` status within 30 seconds. Anything else, a redirect included, is a failed attempt and is retried:

| Attempt | Sent |
| --- | --- |
| 1 | At once |
| 2 | 5 seconds later |
| 3 | 5 minutes later |
| 4 | 30 minutes later |
| 5 | 2 hours later |
| 6 | 5 hours later |
| 7 and 8 | 10 hours later, each |

After the eighth attempt the message is failed. You can send it again from the dashboard: one message, or every message that failed since a time you choose.

- **Stop the retries of one message** by answering with the header `webhook-delivery: abort-message`. Answer `webhook-delivery: disable` to disable the endpoint.
- **An endpoint that only fails for five and a half days is disabled.** Enable it again on the Webhooks page.
- **Rotating a secret** keeps the old one valid for 24 hours. Deliveries carry a signature for both, so switch at any time in that window.
- Messages and their delivery logs are kept for 30 days.

## Limits

| Limit | Value |
| --- | --- |
| Endpoints per game | 50 |
| Extra request headers per endpoint | 20 |
| URL | `https://`, on a public address |
| Response time | 30 seconds |

---

# SDKs and API

Page: https://buildon.stacked.xyz/docs/api

Your game talks to Stacked through an SDK, or through the HTTP API the SDKs wrap. This page lists the SDKs, how to authenticate, and every endpoint a game calls.

## SDKs

| SDK | Runs in | Install |
| --- | --- | --- |
| Node.js | Your game backend | `npm install @pixels-online/pixels-analytics-node-sdk` |
| Go | Your game backend | `go get gitlab.com/pixels-online-oss/pixels-analytics-go-sdk` |
| JavaScript | A web game client | `npm install @pixels-online/pixels-client-js-sdk` |
| Unity and .NET | A Unity or C# game client | `dotnet add package PixelsOnline.Client.SDK` |

What each side does:

| Task | Server SDKs (Node.js, Go) | Client SDKs (JavaScript, Unity) |
| --- | --- | --- |
| Send [events](https://buildon.stacked.xyz/docs/events) | Yes | No |
| Sign player tokens | `signJwt` / `SignJwt` | No |
| Fetch a player's offers | `fetchPlayerCampaigns` / `FetchPlayerCampaigns` | `refreshOffersAndPlayer` / `RefreshOffersAndPlayerAsync` |
| Claim an offer | Go: `ClaimRewards`. Node.js: [over HTTP](#claim-rewards) | `claimReward` / `ClaimRewardAsync` |
| Live ops | `initializeLiveOpsEvents`, `claimMilestoneRewards` | `initializeLiveOpsEvents`, `claimMilestoneRewards` |
| Leaderboards | [Over HTTP](#leaderboards) | `initLeaderboards`, `listLeaderboards`, `getLeaderboard`, `joinLeaderboard`, `claimableLeaderboardRewards`, `claimLeaderboardReward` |
| Realtime updates | No | `client.events.on(...)` |

The Go and Unity SDKs name the same methods in their own style (`InitializeLiveOpsEvents`, `ClaimMilestoneRewardsAsync`, `ListLeaderboardsAsync`).

## Environments

Every game has two environments with separate data, credentials and webhooks.

| | Test | Live |
| --- | --- | --- |
| Use it for | Building and trying things out | Real players |
| API | `https://api.sandbox.stacked.xyz` | `https://api.stacked.xyz` |
| SDK option | `env: 'test'` | `env: 'live'` |

## Authentication

There are two credentials, for the two places your game runs.

### API key: your backend

Send your game's API key and client id as headers. Both are on the **Credentials** page of the [dashboard](https://buildon.stacked.xyz/credentials), one pair for Test and one for Live.

```bash
curl -X POST https://api.sandbox.stacked.xyz/v1/player/campaigns/refresh \
  -H "x-api-key: your_api_key" \
  -H "x-client-id: your_client_id" \
  -H "Content-Type: application/json" \
  -d '{ "playerId": "player-1" }'
```

> **The API key stays on your server.** It can read and claim for any player of your game.

### Player token: your game client

A game client never holds the API key. Your backend signs a short-lived token for one player, and the client sends it as `Authorization: Bearer <token>`.

```ts
// On your backend, with the Node.js SDK
const token = await analytics.signJwt({ playerId: 'player-1' });
```

The client SDKs ask for a token through the `tokenProvider` you give them, and ask again shortly before it expires. A token lasts one hour unless you set `jwtExpirySeconds`.

Without a server SDK, sign it yourself. It is a JWT signed with HS256, keyed with your API key:

| Part | Field | Value |
| --- | --- | --- |
| Header | `alg`, `typ` | `HS256`, `JWT` |
| Header | `kid` | Your client id |
| Payload | `iss` | Your game id (`gameId` in the answer of `POST /v1/player/campaigns/refresh`) |
| Payload | `sub` | The player's id |
| Payload | `exp` | When it expires, in seconds |
| Payload | `iat`, `nbf` | When it was issued, and the earliest it is valid, in seconds |

## Endpoints

Paths are relative to the API of the environment. **Key** means the API key headers, **Player** a player token. Bodies and answers are JSON. Send `{}` when a `POST` needs no fields.

Where a path exists under both `/v1` and `/v2`, use `/v2`: the two differ only in how an offer's conditions are laid out, and `/v2` is the current layout.

### Offers

| Endpoint | Auth | What it does |
| --- | --- | --- |
| `POST /v1/player/campaigns/refresh` | Key | Looks for new offers for `playerId`, updates the ones they have, and returns them all |
| `POST /v2/client/player/campaigns` | Player | The same, for the signed-in player |
| `POST /v2/client/offers/finished` | Player | The player's past offers by `status` (`claimed`, `expired` or `declined`), in pages |
| `POST /v1/player/offer/status` | Key | Sets the status of one offer instance, for example to reopen an expired one. Never to `claimed` |
| `POST /v1/reward/sdk/decline` | Key | Declines an offer for `playerId` |
| `POST /v1/client/offer/decline` | Player | Declines an offer, when your game's settings allow players to |

Send `viewingCampaigns: true` with a fetch when the player is looking at the offers: it marks the surfaced ones as `viewed`. The answer holds `offers`, `offerGroups` and the player's snapshot. An [offer](https://buildon.stacked.xyz/docs/offers#what-your-game-gets) carries its `instanceId`, `status`, `rewards` and progress.

### Claim rewards

| Endpoint | Auth |
| --- | --- |
| `POST /v1/reward/sdk/claim` | Key |
| `POST /v1/client/reward/claim` | Player |

| Field | Meaning |
| --- | --- |
| `kind` | `offer`, `milestone` for a [live ops milestone](https://buildon.stacked.xyz/docs/live-ops#claim-milestone-rewards), or `leaderboard` for a [leaderboard reward](https://buildon.stacked.xyz/docs/leaderboards#claim-leaderboard-rewards) |
| `instanceId` | What to claim: an offer's `instanceId`, a milestone claim id, or a leaderboard reward's `id` |
| `instanceIds` | Up to 25 of them, to claim in one call, in place of `instanceId` |
| `playerId` | Key only: the player to claim for |
| `targetId` | Player only: claim for a [linked entity](https://buildon.stacked.xyz/docs/concepts#players) |
| `extra` | Optional. Up to 10 string values that are passed to your [reward webhook](https://buildon.stacked.xyz/docs/webhooks#payload) unchanged |
| `skipWebhook` | Key only. Sends no reward webhook: grant from the answer's `rewards` instead |

```bash
curl -X POST https://api.sandbox.stacked.xyz/v1/reward/sdk/claim \
  -H "x-api-key: your_api_key" \
  -H "x-client-id: your_client_id" \
  -H "Content-Type: application/json" \
  -d '{ "kind": "offer", "playerId": "player-1", "instanceId": "68a1f3c2e4b0a1d2c3f4a5b6" }'
```

A claim with one `instanceId` answers `{ "message": "success" }` (with `rewards` on the Key endpoint), or an error. A claim with `instanceIds` always answers `200` with one result per id, each with `claimed` and, when it failed, `error`.

A reward is claimed at most once. Claiming it again answers `player-offer-not-found` (for a leaderboard reward, `already-claimed`), not a second success.

### Live ops

| Endpoint | Auth | What it does |
| --- | --- | --- |
| `POST /v2/client/liveops/initialize` | Player | The events live now, with the player's progress, daily rewards and event offers |
| `POST /v1/player/liveops/initialize` | Key | The same, for `playerId` |
| `GET /v1/sdk/liveops/events` | Key | The events live now, without a player |
| `POST /v1/player/liveops/group/upsert` | Key | Creates or changes a group of players for a [grouped track](https://buildon.stacked.xyz/docs/live-ops#milestone-tracks) |
| `POST /v1/player/liveops/group/delete` | Key | Removes a group |

### Leaderboards

| Endpoint | Auth | What it does |
| --- | --- | --- |
| `POST /v2/client/leaderboards/init` | Player | The decimal places each currency a leaderboard can pay is rounded down to, and the player's [leaderboard rewards to claim](https://buildon.stacked.xyz/docs/leaderboards#claim-leaderboard-rewards) |
| `POST /v2/client/leaderboards` | Player | The game's leaderboards, with status, prizes and first ranks |
| `POST /v2/client/leaderboard` | Player | One page of standings, and the player's own row |
| `POST /v2/client/leaderboard/join` | Player | Enters the player in a leaderboard that needs joining |
| `GET /v1/sdk/leaderboards/init` | Key | The same decimal places, for a backend. With `playerId`, that player's leaderboard rewards to claim too |
| `GET /v1/sdk/leaderboards` | Key | The game's leaderboards |
| `POST /v1/player/leaderboard` | Key | One page of standings, with `playerId`'s row when given |
| `POST /v1/player/leaderboard/join` | Key | Enters `playerId` |

The fields are on the [Leaderboards](https://buildon.stacked.xyz/docs/leaderboards#show-a-leaderboard) page.

### Shop

| Endpoint | Auth | What it does |
| --- | --- | --- |
| `GET /v1/client/shop/items` | Player | The items your game sells in its Stacked shop |
| `POST /v1/client/shop/purchase` | Player | Buys `quantity` of `shopItemId` with `currencyId` |

The shop is switched on per game.

An item can be limited to some players with conditions, the same ones offers use. The list only has the items the player meets the conditions of, and buying any other item is refused with `shop-item-conditions-not-met`.

## Realtime events

A game client can hold one connection open and be told when something changes, instead of asking again.

`GET /v2/sse/connect`

It is a server-sent event stream, authenticated with a player token. The client SDKs open it, keep it alive and reconnect for you.

| Event | Sent when | Data |
| --- | --- | --- |
| `offer_surfaced` | An offer surfaces outside a fetch: one surfaced by a [context](https://buildon.stacked.xyz/docs/events#contexts) your game called | The offer |
| `offer_completed` | Such an offer becomes complete or claimable | The offer |
| `player_delta` | The player's offer progress or snapshot changes | The changes. The SDKs apply them to what they hold |
| `milestone_progress` | The player's points change on an individual or community [milestone track](https://buildon.stacked.xyz/docs/live-ops#milestone-tracks), or they claim on one | `liveOpsEventId`, `track`, `trackId`, and the track's whole `progress` |
| `leaderboard_entry_updated` | A player's entry on a leaderboard changes. Today that is when its rewards become [claimable](https://buildon.stacked.xyz/docs/leaderboards#claim-leaderboard-rewards): the leaderboard's rewards were generated and the player won some | The entry as it is now: `id`, `leaderboardId`, `playerId`, `score`, `rank`, and its `rewards` with `rewardsStatus`. The SDKs add it to the player's claimable rewards |

```ts
import { OfferEvent } from '@pixels-online/pixels-client-js-sdk';

client.events.on(OfferEvent.MILESTONE_PROGRESS, ({ liveOpsEventId, track, progress }) =>
  redrawTrack(liveOpsEventId, track, progress),
);
```

An event only reaches the clients that are connected at that moment: one that connects later never gets it. Use events to update what is on screen sooner, and the fetches for what is true: they always answer the current state.

## Errors

An error answers with a status and one code:

```json
{ "error": "invalid-api-key" }
```

A request with a missing or malformed field answers `400` with `"error": "Validation failed"` and `details`, a list of `path` and `message`.

| Status | Code | Meaning |
| --- | --- | --- |
| 401 | `invalid-api-key` | The API key is unknown, or the client id is not the key's |
| 400 | `jwt-expired`, `jwt-invalid` | The player token is no good. Sign a new one |
| 403 | `cannot-impersonate-target-player` | `targetId` is not an entity linked to the player |
| 400 | `player-offer-not-found` | No such offer instance for this player, or it is already claimed, expired or declined |
| 400 | `completion-conditions-not-met`, `claimable-conditions-not-met` | The offer cannot be claimed yet |
| 400 | `claim-failed` | The claim could not be made. The usual cause: [webhooks](https://buildon.stacked.xyz/docs/webhooks#set-up-an-endpoint) are not set up for this environment yet |
| 400 | `nothing-to-claim` | A milestone claim with no reward waiting |
| 400 | `leaderboard-reward-not-found`, `already-claimed`, `player-blacklisted` | A [leaderboard reward](https://buildon.stacked.xyz/docs/leaderboards#claim-leaderboard-rewards) that is not this player's, was claimed before, or belongs to a blacklisted player |
| 404 | `leaderboard-not-found` | No such leaderboard for this game |
| 400 | `leaderboard-not-started`, `leaderboard-ended` | A join outside the leaderboard's dates |
| 429 | | Too many requests. The body is the text `too-many-requests` |

## Limits

| Limit | Value |
| --- | --- |
| Requests | 10 a second and 50 in 30 seconds, per IP address |
| Request body | 100 KB |
| Ids in one claim | 25 |
| A player id | 250 characters |

A backend that calls from one address shares one allowance across all its players, so let game clients fetch their own offers with a player token.

---

# MCP server

Page: https://buildon.stacked.xyz/docs/mcp

Stacked has a [Model Context Protocol](https://modelcontextprotocol.io) server. Connect an AI agent such as Claude Code, Cursor or VS Code to it, and the agent can run your game's Stacked setup for you: offers, live ops events, leaderboards, rules, players, the shop and webhooks. It acts as one member of your team and can do exactly what that member can do in the dashboard.

## Connect an agent

1. Open the **MCP** page in the [dashboard](https://buildon.stacked.xyz/mcp) and choose **Test** or **Live** at the top.
2. Create a token. It starts with `ota_` and is shown once, so copy it.
3. Add the server to your agent. The page gives you the snippet with your token filled in.

| Environment | MCP URL |
| --- | --- |
| Live | `https://api.stacked.xyz/mcp` |
| Test | `https://api.sandbox.stacked.xyz/mcp` |

A token works on one environment only. Create one on each if your agent should reach both.

**Claude Code.** Run in a terminal:

```bash
claude mcp add --transport http --scope user stacked https://api.stacked.xyz/mcp \
  --header "Authorization: Bearer ota_your_token"
```

**Cursor.** Add to `~/.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "stacked": {
      "url": "https://api.stacked.xyz/mcp",
      "headers": { "Authorization": "Bearer ota_your_token" }
    }
  }
}
```

**VS Code.** Add to `.vscode/mcp.json`, or to your user MCP configuration:

```json
{
  "servers": {
    "stacked": {
      "type": "http",
      "url": "https://api.stacked.xyz/mcp",
      "headers": { "Authorization": "Bearer ota_your_token" }
    }
  }
}
```

**Any other client.** The server speaks Streamable HTTP and is stateless. Your client must be able to send an `Authorization: Bearer` header. There is no OAuth sign-in.

Then ask your agent something like "list my Stacked offers".

## What the agent may do

- **It is you.** The agent acts as the member who created the token, in that member's organization. It cannot reach another organization.
- **Same permissions, always current.** The agent can do what the member's role allows, nothing more. If the role changes, the agent's access changes with it. A call the member may not make answers `insufficient-permissions`.
- **Every tool is listed to every agent.** Whether a call is allowed is decided when it is made.
- **Tokens do not expire on a date.** A token lapses after 90 days without use, and you can revoke it on the MCP page at any time. Team admins see and can revoke every member's tokens.

> **A token is a password.** Anyone who holds it can act as you. Keep it out of git and out of shared configuration files.

## Tools

Your agent gets the current list from the server, with each tool's inputs. This is what it covers.

| Area | Tools |
| --- | --- |
| Start here | `get_context`, `get_reference`, `get_api_credentials`, `list_reward_currencies` |
| Offers | `list_offers`, `get_offers`, `create_offers`, `update_offers`, `archive_offers`, `get_offer_stats`, `estimate_offer_reach`, `save_offer_groups`, `reorder_offer_groups`, `link_cross_game_offer`, `unlink_cross_game_offer`, `get_upload_url` |
| Live ops | `list_liveops_events`, `upsert_liveops_event`, `bulk_upsert_liveops_events`, `generate_liveops_event_dailies`, `archive_liveops_event`, `get_milestone_progress` |
| Leaderboards | `list_leaderboards`, `upsert_leaderboard`, `archive_leaderboard`, `get_leaderboard_standings`, `list_leaderboard_periods`, `list_leaderboard_shards`, `list_leaderboard_rewards`, `upsert_leaderboard_reward`, `archive_leaderboard_reward`, `set_leaderboard_reward_overrides`, `generate_leaderboard_rewards`, `retry_leaderboard_payouts`, `list_leaderboard_payouts`, `list_leaderboard_blacklist`, `blacklist_leaderboard_player`, `unblacklist_leaderboard_player` |
| Rules and settings | `list_reward_rules`, `upsert_reward_rules`, `delete_reward_rule`, `get_offer_rules`, `update_offer_rules`, `list_spend_limits`, `upsert_spend_limit`, `delete_spend_limit`, `get_settings`, `update_settings`, `update_game_profile`, `get_gift_card_limits`, `get_billing_summary` |
| Assets and shop | `get_asset_library`, `upsert_assets`, `delete_assets`, `list_shop_items`, `upsert_shop_item`, `archive_shop_item`, `list_token_contracts`, `list_chain_listeners` |
| Players | `search_players`, `get_player`, `get_player_events`, `list_player_offers`, `set_player_offer_status`, `delete_player_offers`, `update_player_tags` |
| Testing | `qa_upsert_test_player`, `qa_send_events`, `qa_get_player_offers`, `qa_claim_offer`, `qa_liveops_initialize`, `qa_generate_player_jwt` |
| Webhooks | `list_webhook_event_types`, `list_webhook_endpoints`, `create_webhook_endpoint`, `update_webhook_endpoint`, `delete_webhook_endpoint`, `get_webhook_secret`, `rotate_webhook_secret`, `send_test_webhook`, `list_webhook_deliveries`, `list_webhook_messages`, `resend_webhook`, `recover_failed_webhooks`, `get_webhook_portal_url` |

Two tools matter most:

- **`get_context`** says which organization the agent acts in, which member it acts as, and that member's roles and permissions. Agents are told to call it first.
- **`get_reference`** returns a how-to guide and the exact types the server validates, for one topic: `offers`, `conditions`, `offer_groups`, `ab_testing`, `player_offers`, `offer_rules`, `reward_rules`, `spend_limits`, `liveops`, `leaderboards`, `shop`, `asset_library`, `players`, `qa` or `webhooks`. Agents are told to read the topic before they write a document of that kind.

## How it behaves

The tools run the same operations as the dashboard, with the same checks. A few rules keep an agent's changes safe to review:

- **New offers are created disabled.** Enable one with `update_offers` once you have looked at it.
- **Deleting is archiving.** Offers, live ops events, leaderboards and shop items are archived, and can be restored.
- **Updates replace lists whole.** `update_offers` merges your changes into the stored offer at the top level, so a list such as `rewards` is replaced, not appended to.
- **Leaderboard rewards are generated once**, and only when asked: `generate_leaderboard_rewards`. Generating grants nothing: each winner claims theirs in the game. `list_leaderboard_payouts` shows who has, and `qa_claim_offer` with `kind: "leaderboard"` claims one as a test player.

## Test an offer end to end

The testing tools let an agent prove an offer works before any real player sees it. Use them on **Test**, with a made-up player id such as `qa-alex`.

1. `qa_upsert_test_player` creates the player and shapes it (levels, currencies, tags) to match the offer's conditions.
2. `qa_get_player_offers` runs surfacing exactly as your game client would, and returns the player's offers.
3. `qa_send_events` sends game events for the player to move the offer's progress. Events are processed in the background, so give it a few seconds.
4. `qa_get_player_offers` again: the offer should be claimable.
5. `qa_claim_offer` claims it.

> **A test claim is a real claim.** `qa_claim_offer` pays the rewards and sends your reward webhooks. Point your Test webhook endpoint at a backend that expects it.

`qa_liveops_initialize` shows what a player gets from [Live Ops](https://buildon.stacked.xyz/docs/live-ops), and `qa_generate_player_jwt` gives a 15-minute player token for calling the [client endpoints](https://buildon.stacked.xyz/docs/api#authentication) by hand.

## Limits and errors

| Limit | Value |
| --- | --- |
| Requests | 300 a minute per token |
| Request body | 5 MB |
| One tool result | 200,000 characters. A longer one is cut: narrow it with filters or pages |

A request the server rejects before running a tool answers with an HTTP status and `{ "error": "<code>" }`:

| Status | Meaning |
| --- | --- |
| 401 | The token is missing (`missing-agent-token`) or not valid on this server: wrong, revoked, lapsed, or created for the other environment |
| 429 | `too-many-requests`: over the rate limit |
| 503 | `auth-unavailable`: the token could not be checked just now. Try again |

A tool that fails returns an error result your agent can read: `{ "error": "<code>", "status": <http status>, "details": ... }`. The common ones are `invalid-input` (400, with the fields at fault) and `insufficient-permissions` (403).

## Read these docs from an agent

The docs themselves are plain markdown for agents:

- [`/docs/llms-full.txt`](https://buildon.stacked.xyz/docs/llms-full.txt) is every page in one file.
- [`/docs/llms.txt`](https://buildon.stacked.xyz/docs/llms.txt) is the index: each page with one line about it.
