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
| Field | Rule |
|---|---|
amount | Positive number or decimal string, at most 2 decimal places, at most 1,000,000,000 |
count (tickets) | Positive integer, at most 1,000,000 |
reason | 1-100 characters of letters, digits, space, _ . : -. Written to the ledger as plugin:<providerType>:<reason> |
idempotencyKey | Required. ^[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.
| Balance | Default | Who can change it |
|---|---|---|
real | 0 (blocked) | Admin only (Extensions › Plugins → View details → Wallet daily caps) |
virtual | Unlimited | Admin, or the plugin manifest |
tickets | Unlimited | Admin, or the plugin manifest |
Each balance’s cap is resolved in this order, first match wins:
- Admin cap:
Plugin.walletCaps.dailyCap.<balance>, set in the admin panel or withPUT /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.nullmeans unlimited. - Manifest cap:
pokerEnginePlugin.wallet.dailyCap.virtualand.tickets. A manifest can’t set the real-money cap, so a plugin can’t authorise its own real-money credits. - Default:
real0,virtualandticketsunlimited.
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(codePLUGIN_WALLET_DAILY_CAP, 403) and moves nothing. Today’s usage is stored in the reserved keysys: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
| Check | Virtual | Real |
|---|---|---|
| Sender and recipient differ, exist, and are not blocked, frozen or bots | Yes | Yes |
Feature toggle on (virtualChips / realMoney) and the balance type enabled in the transfer settings | Yes | Yes |
| Transfer limits from Money › Payment Providers → Player transfers (min and max per transfer, daily and monthly per sender, daily per recipient, UTC days) | Yes | Yes |
| Sender not seated at a table | No: play chips can be sent while seated | Yes |
Sender and recipient at or above the minimum KYC tier (default TIER_1) | No | Yes |
| Sender has no real-money bonus whose wagering is unmet | No | Yes |
AML check (checkTransactionForAml) on the sender and on the recipient | No | Yes |
Fee (real.feePercentage, clamped to the fee minimum and maximum) | Never | As configured |
| The plugin’s daily transfer cap for the balance type | Yes | Yes |
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):
| Balance | Default | Who can change it |
|---|---|---|
real | 0 (blocked) | Admin only: Extensions › Plugins → View details → Wallet daily caps → Transfers, or PUT /api/v1/admin/plugins/:providerType/wallet-caps with { "transfers": { "real": "250" } } |
virtual | Unlimited | Admin, 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
| Error | Code | Status | When |
|---|---|---|---|
PluginCapabilityError | PLUGIN_CAPABILITY_DENIED | 403 | The plugin lacks the capability for balanceType |
ValidationError | VALIDATION_ERROR | 400 | Bad input, or fromUserId === toUserId |
NotFoundError | NOT_FOUND | 404 | Unknown sender or recipient |
PluginTransferCapError | PLUGIN_TRANSFER_DAILY_CAP | 403 | The plugin’s daily transfer cap would be exceeded (checked before any other rule, and again inside the transaction) |
TransferError | TRANSFER_DISABLED | 403 | Feature toggle off or the balance type disabled; details.reason is realMoney, virtualChips, balanceType or cashier |
TransferError | TRANSFER_ACCOUNT_RESTRICTED | 403 | A party is blocked, frozen or a bot; details: { party, restriction } |
TransferError | TRANSFER_SEATED | 409 | Real money while the sender is seated |
WageringRequirementsError | WAGERING_REQUIREMENTS_NOT_MET | 400 | Real money while the sender has a real-money bonus whose wagering is unmet; wagering: { required, completed, remaining } (site currency, two decimals) |
TransferError | TRANSFER_KYC_REQUIRED | 403 | Real money below the minimum tier; details: { party, requiredTier, tier } |
TransferError | TRANSFER_AML_REVIEW | 403 | The AML check flagged the transfer; nothing moved, the review is in Risk & Compliance › AML Reviews |
TransferError | TRANSFER_LIMIT_EXCEEDED | 400 | details.limit is min, max, dailySend, monthlySend or dailyReceive |
InsufficientFundsError | INSUFFICIENT_FUNDS | 400 | The sender can’t pay the amount plus the fee |
ConflictError | CONFLICT | 409 | The 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_OUTandTRANSFER_INledger rows, theplayer_transfersrecord, 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 withreplayed: 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, orTransfer to <username>/Transfer from <username>. Virtual transfers start with[Play chips]. - Fraud data. Every transfer adds to the day’s
ChipFlowEdgefrom 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 aCHIP_DUMPINGfraud alert (detectorplayer-transfer) for review. - Audited. Each applied transfer writes an admin-audit record with actor
plugin:<providerType>, and firesbalance:changedfor 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
Bonusrow owned by the plugin. The row hasevent: PLUGINanddescription: 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’swageringMultiplierandwageringDeadlineDays(they apply to credits from then on; earlier credits keep theirs) instead of creating a second row. Then it callsapplyBonusfrombonus-trigger.service.ts. Balance,BonusCredit, wagering requirement and deadline, and theBONUSledger row for USD all work exactly as for admin bonuses. - Wagering counts only on
USDbonuses: 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 aVIRTUALorTICKETSbonuswageringMultiplierhas no effect: it is still accepted, so existing plugins keep working, but it is dropped (the bonus row and the credit have no wagering, andwageringRequiredis"0"), and the first call that sends one for a type logs a warning naming your plugin. Leave it out for those types.wageringDeadlineDayssetswageringDeadlineon 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.
USDbonuses also require the real-money toggle and count against therealdaily cap.VIRTUALbonuses count against thevirtualcap andTICKETSagainsttickets. - Idempotency works as in the wallet. The key is claimed first, and the claim and the cap reservation are released if
applyBonusfails, so a retry can succeed. - The result is
{ creditId, bonusId, userId, type, amount, balanceBefore, balanceAfter, wageringRequired, wageringDeadline, createdAt, replayed }. listForUserreturns{ creditId, bonusId, description, type, amount, wageringRequired, wageringCompleted, wageringDeadline, createdAt }[], with theplugin:<providerType>:prefix removed fromdescription.
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:
| Hook | When |
|---|---|
cashier:purchase:confirmed | PENDING → COMPLETED: the money arrived. Deliver now. |
cashier:purchase:failed | PENDING → CANCELED: failed, abandoned or expired at the provider. |
cashier:purchase:reversed | COMPLETED → 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-review | Any 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
PURCHASErow: do not create a transaction (nocreatePendingDeposit). Sendparams.transactionIdto the provider as the order or merchant reference, chargeparams.amountinparams.currency, and return{ status: 'pending', paymentUrl?, instructions?, externalId?, expiresAt? }.params.callbackUrlis the core webhook URL of the payment system. - Settle only through
parseWebhook(orcheckPaymentStatusfor a sync):direction: 'deposit', the exactamountandcurrency, andparams.transactionIdor the returnedexternalIdamongexternalId/lookupExternalIds. A refund or chargeback of a completed payment isstatus: 'canceled'. Acompletedstatus returned bycreatePurchaseitself is not trusted. - A provider that implements
createPurchaseparses its own webhooks (it takes the provider-parsed path inprocessPaymentWebhook). - 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.rawBodyis the unparsed body (aBuffer; the engine keeps it for JSON and form bodies). After verifying, it hands each result to core withregistry.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 aparseWebhookresult (lookup by the ids within the payment system, provider, direction, amount, currency and status-transition checks, each transition once) and returns{ processed, transactionId }(processed: falsewhen no transaction matched). A refusal throwsValidationError(400); a payment system whose provider type the plugin did not register throwsAuthorizationError(403). Replay protection of the provider’s event ids is the plugin’s job; core’s transitions are idempotent anyway. - Purchases only.
listPurchaseMethodspasses{ purpose: 'purchase' }as the second argument ofcashier: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.
processWebhookrefuses 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, reportfailedwith the purchase’s own amount first and thencompletedwith 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
- Capabilities — declaring and granting
wallet:*andbonus - Admin: Cashier and payments — the transfer limits an admin sets
- Server Hooks:
balance:changed— fires withsource: 'plugin'for wallet calls - Plugin Development Guide