Skip to content

Wallets and real-money safety

A wallet lets a game hold, spend and pay out chips or money without ever double-charging. You give createServer a Wallet, and game code uses it through ctx.wallet. For development, new MemoryWallet({ startingBalance: 1000 }) implements the whole contract in memory. It is exported from shoehive/server and is never suitable for real money.

Amounts are non-negative safe integers in the smallest unit (chips, cents). Never floats.

ctx.wallet call When it runs
reserve(seat, amount, key) Now, awaited. Resolves false if refused (not enough funds).
balance(seat) Now, awaited. Available funds, excluding reservations.
commit(key) After the entry commits and is stored. A reservation becomes a debit.
release(key) After the entry commits and is stored. The reservation is cancelled.
credit(seat, amount, key) After the entry commits and is stored. Pays the seat's player.

So money never moves for a state change that did not happen. If the action rejects, throws or times out, the engine releases every key it tried to reserve. A reservation that a committed action keeps stays held until a later action commits or releases it, and reservations still open when a table closes are released.

Reserve a bet
betting: {
rounds: {
durationMs: BET_MS,
closeWhen: 'all-submitted',
onOpen: ({ state }) => {
state.handNumber += 1;
state.dealer = [];
state.hands = state.hands.map(() => null);
},
onClose: ({ state, ctx }) => {
if (state.hands.some((h) => h !== null)) ctx.phase.go('play');
else ctx.round.next(); // nobody bet: open betting again
},
},
actions: {
bet: {
once: true,
input: z.object({ amount: z.number().int().positive() }),
async run({ state, seat, input, ctx }) {
const { minBet, maxBet } = ctx.options;
if (input.amount < minBet || input.amount > maxBet)
reject('BET_OUT_OF_RANGE', { minBet, maxBet });
if (!(await ctx.wallet.reserve(seat, input.amount, betKey(state.handNumber, seat))))
reject('INSUFFICIENT_FUNDS');
state.bankroll[seat]! -= input.amount;
state.hands[seat] = {
bet: input.amount,
doubled: false,
cards: [],
done: false,
outcome: null,
};
},
},
},
},

Blackjack reserves the bet here, then commits it and credits the payout when the hand settles:

Settle a hand
onEnter: ({ state, ctx }) => {
const anyLive = state.hands.some((h) => {
const value = h && blackjackValue(h.cards);
return value && !value.bust && !value.blackjack;
});
// Dealer draws to 17 and stands on all 17s.
while (anyLive && blackjackValue(state.dealer).total < 17)
state.dealer.push(state.shoe.pop()!);
const dealer = blackjackValue(state.dealer);
state.hands.forEach((hand, seat) => {
if (!hand) return;
const value = blackjackValue(hand.cards);
let outcome: Outcome;
if (value.bust) outcome = 'bust';
else if (value.blackjack) outcome = dealer.blackjack ? 'push' : 'blackjack';
else if (dealer.blackjack) outcome = 'lose';
else if (dealer.bust || value.total > dealer.total) outcome = 'win';
else if (value.total === dealer.total) outcome = 'push';
else outcome = 'lose';
hand.outcome = outcome;
ctx.wallet.commit(betKey(state.handNumber, seat));
if (hand.doubled) ctx.wallet.commit(doubleKey(state.handNumber, seat));
const payout = Math.floor(hand.bet * PAYOUT[outcome]);
if (payout > 0) ctx.wallet.credit(seat, payout, payKey(state.handNumber, seat));
state.bankroll[seat]! += payout;
});
ctx.timers.after('nextHand', NEXT_HAND_MS, 'nextHand');
},

Pass a key that is unique within the table and stable for the thing you are paying for, such as bet:12:3 for hand 12, seat 3. The engine prefixes it with the table id. For reserve it also adds a random id per attempt, so a game can reuse a key after a rolled-back attempt. commit and release take your original key.

credit keys are used as given and must be unique for good: a retry of the same payout must reuse the key, and a different payout must not. Build it from a counter in state, like the hand number above.

Calls time out after walletTimeoutMs (5 seconds) and throw WALLET_UNAVAILABLE. If your game does not catch it, the action rolls back and the client gets that code. Without a wallet, ctx.wallet throws WALLET_NOT_CONFIGURED.

Your database is the source of truth for money. Implement the five Wallet methods so that every key is a small state machine: reserved, then exactly one of committed or released.

  • Repeating a call with the same arguments does nothing and returns the original result.
  • A conflicting call throws: commit after release, release after commit, or reserve with a different amount or player.
  • release of an unknown key records a tombstone, so a late reserve with that key returns { ok: false, reason: 'RELEASED' }.
  • reserve refuses with INSUFFICIENT_FUNDS or UNKNOWN_PLAYER rather than throwing.
  • credit is idempotent by key.
  • Do each call in one database transaction with a unique constraint on the key.
src/ledger-wallet.ts
export function ledgerWallet(ledger: Ledger): Wallet {
return {
reserve: (playerId, amount, key) =>
ledger.transaction(async (tx) => {
const held = await tx.hold(key);
if (held) {
if (held.state === 'released') return { ok: false, reason: 'RELEASED' };
if (held.playerId !== playerId || held.amount !== amount) {
throw new Error(`reserve ${key}: same key, different arguments`);
}
return { ok: true }; // a retry: report the original result
}
const available = await tx.available(playerId);
if (available === undefined) return { ok: false, reason: 'UNKNOWN_PLAYER' };
if (available < amount) return { ok: false, reason: 'INSUFFICIENT_FUNDS' };
await tx.adjust(playerId, -amount);
await tx.putHold(key, { playerId, amount, state: 'held' });
return { ok: true };
}),
commit: (key) =>
ledger.transaction(async (tx) => {
const held = await tx.hold(key);
if (!held || held.state === 'released') throw new Error(`commit ${key}: not reserved`);
if (held.state === 'held') await tx.putHold(key, { ...held, state: 'committed' });
}),
release: (key) =>
ledger.transaction(async (tx) => {
const held = await tx.hold(key);
if (!held) {
// Unknown key: leave a tombstone so a late reserve with this key is refused.
await tx.putHold(key, { playerId: '', amount: 0, state: 'released' });
} else if (held.state === 'committed') {
throw new Error(`release ${key}: already committed`);
} else if (held.state === 'held') {
await tx.adjust(held.playerId, held.amount);
await tx.putHold(key, { ...held, state: 'released' });
}
}),
balance: (playerId) => ledger.transaction(async (tx) => (await tx.available(playerId)) ?? 0),
credit: (playerId, amount, key) =>
ledger.transaction(async (tx) => {
const done = await tx.credited(key);
if (done) {
if (done.playerId !== playerId || done.amount !== amount) {
throw new Error(`credit ${key}: same key, different arguments`);
}
return; // already paid
}
await tx.adjust(playerId, amount);
await tx.putCredit(key, { playerId, amount });
}),
};
}

Ledger stands for your database. Your SQL goes inside transaction.

runWalletConformance from shoehive/testing checks idempotency, conflicts, tombstones and concurrent keys. It hands your factory the starting funds for each test.

test/ledger-wallet.test.ts
runWalletConformance((funds) => ledgerWallet(memoryLedger(funds)), { describe, it, expect });

commit, release and credit run after the table state is committed and broadcast. If one fails, the server retries it (5 attempts over about 3 seconds). If it still fails, the table is not rolled back. The server logs an error and emits wallet:error with the table, the operation and the error. Page someone and reconcile by hand.

src/server.ts
const shoehive = createServer({
games: [ticTacToe],
wallet: ledgerWallet(ledger),
// Real money needs real identities: guest ids are bearer tokens.
auth: async (request) => {
const token = new URL(request.url ?? '/', 'http://x').searchParams.get('token');
if (!token) return null; // refused with HTTP 401
const claims = await verifyJwt(token);
return { id: claims.sub, name: claims.name };
},
});
// A deferred commit, release or credit that still failed after retries.
shoehive.on('wallet:error', ({ table, op, error }) => {
console.error('RECONCILE', { table, op, error });
});

Operations that were in flight when the server stopped are kept in snapshots and the log, and are sent again after a restart. Idempotent keys make the repeats harmless. To reconcile, keep an audit log in your ledger (key, player, amount, state, time).

Without an auth hook, every connection is a guest, and the guest resume token is a bearer token: whoever holds it is that player. The server warns when you configure a wallet without auth in production. Authenticate with your own accounts, return their stable ids from auth, and use those ids as the wallet's player ids.

Shoehive gives you idempotent, commit-tied bookkeeping. Licensing, age and identity checks, certified randomness, responsible gambling tools, tax and audited payouts are yours.