> ## Documentation Index
> Fetch the complete documentation index at: https://docs.prizerail.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Pay your winners

When prizes go to your payout wallet, Prizerail sends you the money and you pay each winner. This page is the loop to build for that. It handles every case the same way: small prizes, large prizes, prizes held for [winner publicity](https://docs.prizerail.com/campaigns/winner-publicity.md) and [guarantee draws](https://docs.prizerail.com/api/guarantees.md).

> [!TIP]
>
> **Building with an AI assistant?** Give it this prompt: *"Read [https://www.prizerail.com/skills/prizerail-payouts/SKILL.md](https://www.prizerail.com/skills/prizerail-payouts/SKILL.md) and build the payout job in this repo, with our database and our way of paying users."*

## The rule

**Pay a winner when the transfer that carries their prize is `confirmed`. Never before, and never twice.**

A draw's prizes don't always arrive together. Read the drawing's `payouts[]` to see each transfer:

| Transfer `kind` | Carries | Arrives |
| - | - | - |
| `lump_sum` | Every prize that isn't held, in one transfer. | A few minutes after the draw. |
| `large_prize` | One prize, for a winner whose prizes in the draw reach your large-prize threshold (\$600 unless set otherwise). | After Prizerail staff review it, and after the winner's publicity is approved if they were asked. |
| `publicity_prize` | One prize, for a winner under that threshold who was asked for publicity. | After the winner's publicity is approved. |

A transfer for one prize names its winner in `winnerPosition`. The lump sum has `winnerPosition: null`.

## Steps

**1. Read recent drawings**

Every few minutes, list your `settled` and `paid` drawings. Each has `winners[]` and `payouts[]`. See [Drawings](https://docs.prizerail.com/api/drawings.md). Also read again any earlier drawing that still has a prize you haven't been sent. A held prize can be released days later, after the drawing has dropped off the first page of the list.

**2. Find each win's transfer**

For each winner, look for a `payouts[]` row whose `winnerPosition` is that winner's `position`. If there is one, that's their transfer. If not, their prize is in the `lump_sum`. If there's no row at all, nothing has been sent yet.

**3. Wait for confirmed**

Skip the win unless its transfer's `status` is `confirmed`. A held prize reads `held_manual` or `held_publicity` until it's released.

**4. Record it, then pay**

Insert a row keyed by the drawing's `id` and the winner's `position`, with a unique constraint. If the insert fails, that win is already handled. If it succeeds, pay the winner, then save your transaction hash or credit id on the row.

## Code

Reads `PRIZERAIL_API_KEY` and `PRIZERAIL_CAMPAIGN`. You supply `store`, your database, and `pay`, however your app pays a user: a transfer, in-app credit or anything else. `store` keeps two things: one row per win, so nobody is paid twice, and the drawings that still have a win to pay, so a late one isn't missed.

```ts SDK theme={null}
import { type Drawing, Prizerail } from "prizerail";

const campaign = new Prizerail({ apiKey: process.env.PRIZERAIL_API_KEY }).campaign(
  process.env.PRIZERAIL_CAMPAIGN!
);

type Win = { drawingId: string; position: number; entrantId: string; amountCents: number };

/** Your database. */
export type Store = {
  /**
   * Inserts the win as "sending", unique on (drawingId, position), and returns
   * "claimed". If the row already exists, returns its status instead.
   */
  claim(win: Win): Promise<"claimed" | "sending" | "paid">;
  /** Marks the win paid, with your transaction hash or credit id. */
  markPaid(win: Win, reference: string): Promise<void>;
  /** Remembers a drawing, and whether every win in it has been paid. */
  track(drawingId: string, finished: boolean): Promise<void>;
  /** The ids of tracked drawings that aren't finished. */
  unfinished(): Promise<string[]>;
};

/** The transfer that carries a win: its own row if it has one, else the lump sum. */
export function transferFor(drawing: Drawing, position: number) {
  return (
    drawing.payouts.find(p => p.winnerPosition === position) ??
    drawing.payouts.find(p => p.kind === "lump_sum") ??
    null
  );
}

/**
 * Pays every win in a drawing whose money has reached your wallet. Safe to run
 * again. Returns true once every win in it has been paid.
 */
export async function payDrawing(
  drawing: Drawing,
  store: Store,
  pay: (win: Win) => Promise<string>
) {
  // Prizerail pays these winners itself. There is nothing for you to send.
  if (drawing.payoutMode === "direct_winner") return true;
  let finished = true;
  for (const w of drawing.winners) {
    // Not in your wallet yet: a held prize, or a transfer still on its way.
    if (transferFor(drawing, w.position)?.status !== "confirmed") {
      finished = false;
      continue;
    }
    if (!w.amountCents) throw new Error(`No prize amount for ${drawing.id}/${w.position}`);
    const win = {
      drawingId: drawing.id,
      position: w.position,
      entrantId: w.winner,
      amountCents: w.amountCents,
    };
    const state = await store.claim(win);
    if (state === "paid") continue;
    if (state === "sending") {
      // Being paid by another run, or stuck. Never paid again automatically.
      finished = false;
      continue;
    }
    try {
      await store.markPaid(win, await pay(win));
    } catch (err) {
      // The row stays "sending". Check whether it went out before paying it again.
      finished = false;
      console.error(`Payment for ${win.drawingId}/${win.position} needs checking`, err);
    }
  }
  return finished;
}

/** Run this every few minutes. */
export async function payWinners(store: Store, pay: (win: Win) => Promise<string>) {
  const drawings = new Map<string, Drawing>();
  for (const status of ["settled", "paid"] as const) {
    const page = await campaign.drawings.list({ status, limit: 50 });
    for (const drawing of page.drawings) drawings.set(drawing.id, drawing);
  }
  // An older drawing with a win still to pay: it has dropped off the lists above.
  for (const id of await store.unfinished()) {
    if (!drawings.has(id)) drawings.set(id, await campaign.drawings.get(id));
  }
  for (const drawing of drawings.values()) {
    await store.track(drawing.id, await payDrawing(drawing, store, pay));
  }
}
```

## Mistakes to avoid

* **Don't wait for the drawing to be `paid`.** A drawing stays `settled` until every transfer has confirmed, held prizes included. If you wait for `paid`, one held prize delays everyone else in that draw.
* **Don't split the lump sum across every winner.** It carries only the prizes that aren't held. Pay each winner their own `amountCents`.
* **Don't pay from a wallet balance.** Decide from each transfer's `status`, not from what's in the wallet.
* **Don't look only at recent drawings.** Keep every drawing that still has a win to pay and read it again each run, as the code does. Otherwise a prize released a week later is never paid on.
* **Don't retry a win stuck at "sending" automatically.** If a run stops between recording a win and saving its hash, or `pay` fails part-way, check whether that payment went out before sending it again. If you're sure nothing was sent, delete the row and the next run pays it. The drawing stays on the list to read again until every win in it is paid. Alert on any row that stays at "sending" for more than a few minutes. If you pay onchain, sign the transaction and save its hash before you broadcast it. Then a restart can send the same signed transaction again, which can't pay twice.

## Good to know

* **Guarantee draws** are drawings with `kind: "guarantee"` and are paid the same way. A guaranteed prize under your large-prize threshold arrives in a lump sum. One at or above it arrives as one `large_prize` transfer, with no lump sum.
* **Amounts** are in cents. Transfers are USDC on Base, to the wallet in the transfer's `to`. One cent is 10,000 USDC base units.
* **Entrant ids** are the ids you sent with entries. Map each back to your user in your own database.
* **A `failed` transfer** needs nothing from you. Prizerail is alerted and sends it again.
* **A winner who never sends their publicity** isn't paid, and their transfer stays held. See [Winner publicity](https://docs.prizerail.com/campaigns/winner-publicity.md#when-the-prize-is-paid).
* **Repeat winners:** one person can fill several slots in a draw. Each slot is its own win, with its own `position`.
* **Direct payouts:** if Prizerail pays your winners directly (a drawing's `payoutMode` is `direct_winner`), don't build this job. The code skips those drawings.
* **Starting on a campaign that's already running, or after the job has been off for a while:** the code reads the 50 newest drawings of each status, so anything older that it has never seen is missed. Page back once with `nextBefore`, or `campaign.drawings.all({ status })` in the SDK, to pick those up.

## Try it in the sandbox

Run a draw with [draw now](https://docs.prizerail.com/api/drawings.md#draw-now-sandbox-only), then run your loop twice. The first run should pay each winner once. The second should pay nobody. Sandbox transfers aren't real money, so check your loop against each transfer's `status`, not your wallet.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.