Wallet & Bonuses

Last Updated: November 2026 · Plugin API: 1.1 (transfers: 1.2) · Capabilities: wallet:credit-virtual, wallet:credit-real, wallet:credit-tickets, wallet:debit-virtual, wallet:transfer-virtual, wallet:transfer-real, bonus

registry.wallet moves money for your plugin, and registry.bonus credits bonuses that carry wagering requirements. Both run through the engine’s own services (balance.service.ts, bonus-trigger.service.ts), so every check those services apply still applies. Every call is idempotent, counts against a daily cap, is written to the ledger and is recorded in the admin audit log.

Wallet API

registry.wallet.creditVirtual(userId, amount, { reason, idempotencyKey })   // wallet:credit-virtual
registry.wallet.creditReal(userId, amount, { reason, idempotencyKey })      // wallet:credit-real
registry.wallet.creditTickets(userId, count, { reason, idempotencyKey })    // wallet:credit-tickets
registry.wallet.debitVirtual(userId, amount, { reason, idempotencyKey })    // wallet:debit-virtual
registry.wallet.getBalance(userId)                                          // any wallet:* capability
registry.wallet.transfer({ fromUserId, toUserId, amount, balanceType, reason, idempotencyKey, message? })
                                                    // wallet:transfer-virtual / wallet:transfer-real (API 1.2)

transfer is described in Transfers between players.

Each mutation resolves to:

{
  userId: string;
  operation: 'plugin_credit' | 'plugin_debit';
  balanceType: 'real' | 'virtual' | 'tickets';
  amount: string;            // decimal string
  balanceBefore: string;
  balanceAfter: string;
  transactionId: string;     // ledger row id
  createdAt: string;         // ISO timestamp
  replayed: boolean;         // true when the idempotency key was already used
}

getBalance resolves to { userId, real: string, virtual: string, tickets: number }.

Example

registry.registerRoute('POST', '/spin', async (req, res) => {
  const userId = req.user.sub;
  const day = new Date().toISOString().slice(0, 10);
  const result = await registry.wallet.creditVirtual(userId, 500, {
    reason: 'daily-wheel',
    idempotencyKey: `spin:${userId}:${day}`,
  });
  res.json({ success: true, data: { won: result.amount, alreadySpun: result.replayed } });
});

Input rules

FieldRule
amountPositive number or decimal string, at most 2 decimal places, at most 1,000,000,000
count (tickets)Positive integer, at most 1,000,000
reason1-100 characters of letters, digits, space, _ . : -. Written to the ledger as plugin:<providerType>:<reason>
idempotencyKeyRequired. ^[a-z0-9:_-]{1,120}$, unique per plugin. Build it from the business event, e.g. mission:<id>:<period>:<userId>

Invalid input throws ValidationError and moves nothing.

Guarantees

Wraps the core services. Each method calls the core balance service: creditVirtualChips, creditBalance(…, 'real'), creditTournamentTickets or debitVirtualChips. The feature toggles still apply: virtual chips must be enabled for virtual operations, and real money must be enabled for creditReal. Insufficient funds throws InsufficientFundsError. The wallet also refuses blocked and frozen accounts.

Atomic. The balance change, the ledger row, the idempotency record and the daily-cap counter commit in one serializable transaction. If any step fails, none of them is applied.

Idempotent. The first successful call stores its result under the reserved plugin_data key idem:<idempotencyKey> for your plugin. Repeating the call returns that result with replayed: true and moves nothing. Reusing a key for a different operation, user or amount throws ConflictError (409).

Ledger. Each call writes a transactions row with status: COMPLETED and description: plugin:<providerType>:<reason>. Credits use type BONUS, the same as the core daily virtual-chips bonus. Virtual debits use type ADJUSTMENT. Ticket credits record the ticket counts in amount, balanceBefore and balanceAfter. The result’s operation field uses the BalanceOperationType values plugin_credit and plugin_debit.

Audited. Each applied call writes an admin-audit record (admin_actions, category user, action update). The actor is plugin:<providerType> (email <providerType>@plugin.internal). The details hold the operation, amount, reason, idempotency key, ledger id and balances. A replayed call writes nothing.

Daily caps

Credits count against a per-plugin daily cap for each balance type. The day is the UTC day. Debits are not capped.

BalanceDefaultWho can change it
real0 (blocked)Admin only (Extensions › Plugins → View details → Wallet daily caps)
virtualUnlimitedAdmin, or the plugin manifest
ticketsUnlimitedAdmin, or the plugin manifest

Each balance’s cap is resolved in this order, first match wins:

  1. Admin cap: Plugin.walletCaps.dailyCap.<balance>, set in the admin panel or with PUT /api/v1/admin/plugins/:providerType/wallet-caps (super-admin). Stored as a decimal string ({ "dailyCap": { "real": "100", "tickets": null } }); numbers written by older versions are read too. null means unlimited.
  2. Manifest cap: pokerEnginePlugin.wallet.dailyCap.virtual and .tickets. A manifest can’t set the real-money cap, so a plugin can’t authorise its own real-money credits.
  3. Default: real 0, virtual and tickets unlimited.

An admin cap is at most 1,000,000,000 a day for real and 1,000,000,000,000 a day for virtual and tickets (the same limits apply to the transfer caps below: real 1,000,000,000, virtual 1,000,000,000,000); larger values are refused with 400 VALIDATION_ERROR (<balance> cap cannot exceed …). Caps and usage are decimal strings compared as decimals, so they are exact to the cent. A cap of 0 refuses every credit of that balance. The admin can only set caps for balances the plugin can credit: wallet:credit-<balance>, or any balance when it declares bonus (bonuses count against the cap of their balance type). See Admin: Plugins.

  • Going over the cap throws PluginWalletCapError (code PLUGIN_WALLET_DAILY_CAP, 403) and moves nothing. Today’s usage is stored in the reserved key sys:wallet:daily:<YYYY-MM-DD>.

A plugin with wallet:credit-real can’t credit real money until the real-money feature is enabled and an admin sets a real cap above 0.

Transfers between players

API 1.2. registry.wallet.transfer moves real money or virtual chips from one player to another, for example a gift between friends. It runs through the same core function as the cashier’s player-to-player transfer (transferBetweenUsers in src/services/transfer.service.ts), so a plugin gets exactly the checks a player gets in the cashier, plus its own daily cap.

const result = await registry.wallet.transfer({
  fromUserId: sender.id,
  toUserId: friend.id,
  amount: 500,                    // positive, at most 2 decimals
  balanceType: 'virtual',         // 'virtual' needs wallet:transfer-virtual, 'real' needs wallet:transfer-real
  reason: 'gift',                 // same rule as the other wallet calls
  idempotencyKey: `gift:${giftId}`,
  message: 'Good luck tonight!',  // optional, at most 200 characters, shown in both players' ledgers
});

It resolves to:

{
  transferId: string;        // the player_transfers row id
  fromUserId: string;
  toUserId: string;
  balanceType: 'real' | 'virtual';
  amount: string;            // decimal string
  fee: string;               // charged to the sender on top of amount (real money only)
  fromBalanceAfter: string;
  toBalanceAfter: string;
  createdAt: string;         // ISO timestamp
  replayed: boolean;
}

Either transfer capability also unlocks getBalance and the balance:changed figures.

Checks

CheckVirtualReal
Sender and recipient differ, exist, and are not blocked, frozen or botsYesYes
Feature toggle on (virtualChips / realMoney) and the balance type enabled in the transfer settingsYesYes
Transfer limits from Money › Payment Providers → Player transfers (min and max per transfer, daily and monthly per sender, daily per recipient, UTC days)YesYes
Sender not seated at a tableNo: play chips can be sent while seatedYes
Sender and recipient at or above the minimum KYC tier (default TIER_1)NoYes
Sender has no real-money bonus whose wagering is unmetNoYes
AML check (checkTransactionForAml) on the sender and on the recipientNoYes
Fee (real.feePercentage, clamped to the fee minimum and maximum)NeverAs configured
The plugin’s daily transfer cap for the balance typeYesYes

A virtual transfer only ever changes User.virtualBalance. Chips in play at a table belong to the table stack, which a transfer never touches.

Daily transfer caps

Transfers count against their own per-plugin daily cap, separate from the credit caps. They resolve like the credit caps (admin, then manifest, then default):

BalanceDefaultWho can change it
real0 (blocked)Admin only: Extensions › Plugins → View details → Wallet daily caps → Transfers, or PUT /api/v1/admin/plugins/:providerType/wallet-caps with { "transfers": { "real": "250" } }
virtualUnlimitedAdmin, or the manifest’s pokerEnginePlugin.wallet.dailyTransferCap.virtual

The admin values are stored in Plugin.walletCaps.dailyTransferCap. A manifest can’t set the real transfer cap. Today’s usage is in the reserved key sys:wallet:transfer-daily:<YYYY-MM-DD>. So a plugin with wallet:transfer-real can’t move real money until the real-money feature is on and an admin sets a real transfer cap above 0.

Errors

ErrorCodeStatusWhen
PluginCapabilityErrorPLUGIN_CAPABILITY_DENIED403The plugin lacks the capability for balanceType
ValidationErrorVALIDATION_ERROR400Bad input, or fromUserId === toUserId
NotFoundErrorNOT_FOUND404Unknown sender or recipient
PluginTransferCapErrorPLUGIN_TRANSFER_DAILY_CAP403The plugin’s daily transfer cap would be exceeded (checked before any other rule, and again inside the transaction)
TransferErrorTRANSFER_DISABLED403Feature toggle off or the balance type disabled; details.reason is realMoney, virtualChips, balanceType or cashier
TransferErrorTRANSFER_ACCOUNT_RESTRICTED403A party is blocked, frozen or a bot; details: { party, restriction }
TransferErrorTRANSFER_SEATED409Real money while the sender is seated
WageringRequirementsErrorWAGERING_REQUIREMENTS_NOT_MET400Real money while the sender has a real-money bonus whose wagering is unmet; wagering: { required, completed, remaining } (site currency, two decimals)
TransferErrorTRANSFER_KYC_REQUIRED403Real money below the minimum tier; details: { party, requiredTier, tier }
TransferErrorTRANSFER_AML_REVIEW403The AML check flagged the transfer; nothing moved, the review is in Risk & Compliance › AML Reviews
TransferErrorTRANSFER_LIMIT_EXCEEDED400details.limit is min, max, dailySend, monthlySend or dailyReceive
InsufficientFundsErrorINSUFFICIENT_FUNDS400The sender can’t pay the amount plus the fee
ConflictErrorCONFLICT409The idempotency key was used for a different operation

Map these to clear messages for your players; code and details are stable.

Guarantees

  • Atomic. The debit, the credit, the TRANSFER_OUT and TRANSFER_IN ledger rows, the player_transfers record, the chip-flow edge, the plugin’s cap counter and the idempotency record commit in one serializable transaction.
  • Idempotent. Same rules as the other wallet calls: the result is stored under idem:<idempotencyKey> and a repeat returns it with replayed: true. The core also records the key on the transfer (plugin:<providerType>:<idempotencyKey>), so two concurrent calls with the same key move the money once.
  • Ledger. The ledger rows’ description is your message, or Transfer to <username> / Transfer from <username>. Virtual transfers start with [Play chips] .
  • Fraud data. Every transfer adds to the day’s ChipFlowEdge from sender to recipient (evidence.source: 'player-transfer'), which the chip-flow fraud detectors read. A real transfer at or above the fraud alert threshold (default 1,000) raises a CHIP_DUMPING fraud alert (detector player-transfer) for review.
  • Audited. Each applied transfer writes an admin-audit record with actor plugin:<providerType>, and fires balance:changed for both players (operation: 'transfer_out' / 'transfer_in', source: 'plugin').

Bonus bridge

registry.bonus.credit(userId, {
  amount: 500,
  type: 'VIRTUAL' | 'USD' | 'TICKETS',
  description: 'Level 10 reward',     // 1-120 plain characters
  wageringMultiplier?: 5,             // 0-999.99; USD only: wagering required = amount × multiplier
  wageringDeadlineDays?: 7,           // 1-3650
  idempotencyKey: 'level:10:user-1',
})
registry.bonus.listForUser(userId)    // this plugin's credits for the user, newest first (max 200)
  • The bridge finds or creates a Bonus row owned by the plugin. The row has event: PLUGIN and description: plugin:<providerType>:<description>, and one row stands for one bonus of your plugin: the description, type and amount. A later call with other wagering settings for the same bonus updates that row’s wageringMultiplier and wageringDeadlineDays (they apply to credits from then on; earlier credits keep theirs) instead of creating a second row. Then it calls applyBonus from bonus-trigger.service.ts. Balance, BonusCredit, wagering requirement and deadline, and the BONUS ledger row for USD all work exactly as for admin bonuses.
  • Wagering counts only on USD bonuses: play at real-money cash tables counts towards it, and until it is met the player cannot withdraw, send real money to another player or be cashed out by an agent. On a VIRTUAL or TICKETS bonus wageringMultiplier has no effect: it is still accepted, so existing plugins keep working, but it is dropped (the bonus row and the credit have no wagering, and wageringRequired is "0"), and the first call that sends one for a type logs a warning naming your plugin. Leave it out for those types. wageringDeadlineDays sets wageringDeadline on the credit for you to show; passing it does not forfeit the bonus or lift the requirement, and play keeps counting towards it.
  • An admin can switch a plugin’s bonus off in the Bonuses page by setting the row inactive. Further credits for that bonus then throw AuthorizationError, whatever wagering settings the call sends.
  • Bonuses respect the bonuses feature toggle. USD bonuses also require the real-money toggle and count against the real daily cap. VIRTUAL bonuses count against the virtual cap and TICKETS against tickets.
  • Idempotency works as in the wallet. The key is claimed first, and the claim and the cap reservation are released if applyBonus fails, so a retry can succeed.
  • The result is { creditId, bonusId, userId, type, amount, balanceBefore, balanceAfter, wageringRequired, wageringDeadline, createdAt, replayed }.
  • listForUser returns { creditId, bonusId, description, type, amount, wageringRequired, wageringCompleted, wageringDeadline, createdAt }[], with the plugin:<providerType>: prefix removed from description.

Purchases (API 1.4)

Capability: cashier:purchase (high trust). registry.purchases lets a plugin sell goods for real money (for example packs of play chips) through the payment providers, without any balance moving in core. The plugin delivers the goods itself once the provider has confirmed the payment.

registry.purchases.methods()                       // [{ paymentSystemId, type, name }]: empty when no provider can take purchases
registry.purchases.create({
  userId, paymentSystemId,
  amount: 4.99, currency: 'USD',                   // price, at most 2 decimals
  reference: orderId,                              // your order id, ^[A-Za-z0-9:_-]{1,100}$; the same reference returns the same purchase
  description: '600,000 chips',                    // 1-200 characters, shown by the provider and in the ledger
  returnUrl: '/cashier',                           // optional, where the provider sends the player back
})                                                 // { transactionId, status, paymentUrl, instructions, expiresAt, replayed }
registry.purchases.get(transactionId)              // { transactionId, userId, reference, status, amount, currency, ... } | null
registry.purchases.reverse(transactionId, reason)  // mark a completed purchase refunded (an admin refunded it at the provider)

status is pending, completed, canceled, failed, reversed or needs_review (a late confirmation an admin has to check, below). A plugin only sees and reverses purchases it created.

What core does. create refuses a blocked or frozen account, an active self-exclusion or core cool-off, and whatever a player:eligibility plugin refuses for the action cashier:purchase; then it writes one PURCHASE ledger row (status PENDING, amount the price, paymentCurrency the currency, idempotencyKey plugin:<providerType>:<reference>, balances unchanged) and asks the provider for a payment page. The provider’s webhook or a status sync settles the row, each transition once however often the provider retries, and core fires:

HookWhen
cashier:purchase:confirmedPENDING → COMPLETED: the money arrived. Deliver now.
cashier:purchase:failedPENDING → CANCELED: failed, abandoned or expired at the provider.
cashier:purchase:reversedCOMPLETED → CANCELED ([Reversed] in the description): refunded or charged back. Take back what you delivered.
cashier:purchase:confirmed (late)CANCELED → COMPLETED: the provider confirmed a payment after the purchase had failed or expired, with the same amount and currency, within the economy setting purchaseLateConfirmationHours (default 72) and not reversed. Deliver now, even for an order you already marked failed.
cashier:purchase:needs-reviewAny other late confirmation (after a reversal, an amount or currency mismatch, or later than the window): the row stays CANCELED, its status reads needs_review, and an admin resolves it in Money › Transactions (status Needs review) (deliver: cashier:purchase:confirmed fires; or close the review after refunding the player). Payload adds reason. Do not deliver anything yet; tell the player the payment is being checked.

Payload: { transactionId, userId, plugin, reference, amount, currency, paymentSystemId, externalId } (needs-review adds reason). The hooks reach only plugins holding cashier:purchase; check plugin is your providerType.

Late confirmations are never dropped. The player paid, so a provider confirmation that arrives after the purchase was failed or expired is recorded in the admin audit log and then either delivered (the late confirmed row above) or flagged for review; a duplicate changes nothing. Your cashier:purchase:confirmed handler must accept a confirmation for an order it already failed.

Delivering safely. Before crediting, read the purchase back with get and check status: 'completed', the player, the amount and your reference. Credit with an idempotency key built from your order and the purchase’s id (creditVirtual(userId, chips, { reason: 'purchase:<orderId>', idempotencyKey: '<you>:order:<orderId>', purchaseTransactionId: transactionId })), so a retried webhook, a second node or your own reconcile job never credit twice. Hooks are fire-and-forget: run a scheduler job that re-reads open orders with get, so a missed hook (restart, crash) is settled.

Daily caps never hold a paid order back. A creditVirtual or creditTickets that names purchaseTransactionId does not count against the plugin’s daily cap when core finds that transaction is your own PURCHASE of that player with status COMPLETED; each purchase is exempt once (a second credit naming it counts as usual), and anything else is refused with PLUGIN_PURCHASE_CREDIT_INVALID (400). Not accepted by creditReal. If a delivery still fails (a frozen account, the database), keep the order pending and let your reconcile job retry it, and log it as an error.

Ledger and reconciliation. A PURCHASE row records money received; it is never a deposit, never credits a Gold or Diamond wallet, and is left out of wallet reconciliation (NON_WALLET_TRANSACTION_TYPES), deposit push notifications and partner deposit.* events. The goods you deliver are your own ledger rows (for chips the BONUS row of creditVirtual). The core personal deposit limit does not apply to purchases; a plugin that sells to players should offer its own spending limit (the first-party store plugin does).

For payment provider plugins

A provider takes purchases when its class implements the optional createPurchase(params: CreatePurchaseParams): Promise<PurchaseResult> (src/services/payment-gateway.service.ts):

  • Core has already created the pending PURCHASE row: do not create a transaction (no createPendingDeposit). Send params.transactionId to the provider as the order or merchant reference, charge params.amount in params.currency, and return { status: 'pending', paymentUrl?, instructions?, externalId?, expiresAt? }. params.callbackUrl is the core webhook URL of the payment system.
  • Settle only through parseWebhook (or checkPaymentStatus for a sync): direction: 'deposit', the exact amount and currency, and params.transactionId or the returned externalId among externalId / lookupExternalIds. A refund or chargeback of a completed payment is status: 'canceled'. A completed status returned by createPurchase itself is not trusted.
  • A provider that implements createPurchase parses its own webhooks (it takes the provider-parsed path in processPaymentWebhook).
  • Own webhook route (API 1.4). A provider whose notifications need the raw request body (a signature over the exact bytes) or map one provider event to several payment changes can receive them on its own registerRoute('POST', '/webhook', { access: 'webhook' }, …): req.rawBody is the unparsed body (a Buffer; the engine keeps it for JSON and form bodies). After verifying, it hands each result to core with registry.cashier.applyProviderPayment({ paymentSystemId, status, amount, currency, externalId, lookupExternalIds?, direction?, eventType?, occurredAt? }) (amount as a decimal string, not minor units). Core runs it through the same settlement as a parseWebhook result (lookup by the ids within the payment system, provider, direction, amount, currency and status-transition checks, each transition once) and returns { processed, transactionId } (processed: false when no transaction matched). A refusal throws ValidationError (400); a payment system whose provider type the plugin did not register throws AuthorizationError (403). Replay protection of the provider’s event ids is the plugin’s job; core’s transitions are idempotent anyway.
  • Purchases only. listPurchaseMethods passes { purpose: 'purchase' } as the second argument of cashier:deposit:methods; a provider that takes no deposits removes its method when the purpose is 'deposit' (or missing) and keeps it for 'purchase'. The payment system must still be active for deposits.
  • A paid amount that differs. processWebhook refuses a confirmation of a pending purchase with another amount or currency. To put such a payment in front of an admin instead of only refusing it, report failed with the purchase’s own amount first and then completed with the amount actually paid: the late-confirmation rule then flags the purchase for review.

Tests: src/services/purchase.service.test.ts runs the whole flow against a mock provider; src/core/plugins/__tests__/stripe-store.integration.test.ts runs the store and Stripe plugin builds against PostgreSQL with a Stripe double. In plugin tests, createTestRegistry({ purchaseMethods: [{ paymentSystemId, type, name }] }) gives an in-memory registry.purchases; registry.test.confirmPurchase(id), failPurchase(id) and reversePurchase(id) play the provider and fire the hooks.

Core and tests

pluginWalletFor(providerType) and pluginBonusFor(providerType) (exported from src/core/plugins) are the same APIs without the capability guard, for core code and tests. Unit tests with the balance and bonus services mocked are in src/core/plugins/__tests__/plugin-wallet.test.ts. The DB-backed tests are in plugin-wallet.integration.test.ts.

Transfer tests: src/core/plugins/__tests__/plugin-wallet-transfer.test.ts (caps, capabilities, idempotency), src/services/transfer.service.test.ts (every core rule), and plugin-transfer.integration.test.ts (PostgreSQL: concurrency, KYC, AML, seated sender, GOLD wallet, fraud alert).

In plugin tests, createTestRegistry({ balances: { u1: { virtual: 100 } } }) from @poker-engine/plugin-sdk/testing provides an in-memory wallet and bonus double (see SDK: Testing). registry.wallet.transfer moves money between the test balances, replays a repeated key and records each transfer in registry.test.transfers. The double does not apply caps, capabilities, limits, fees, KYC or AML.

See Also

Try the live demo Pricing

Have questions about Poker Engine? We reply fast.