@suluk/credits - v0.1.0
    Preparing search index...

    Function debitOnceIfCovers

    @suluk/credits — a metered credit ledger (C046, extracted verbatim). The package OWNS the schema (credit_transaction

    • the credit_amount/credit_key sidecars); the app injects a Drizzle handle (D1 in prod, bun:sqlite in tests). The money-correctness core: the ATOMIC debitIfCovers (a conditional INSERT that can't drive the ledger negative under concurrency) + the idempotent debitOnceIfCovers (the partial-refund double-spend guard) + per-key spend + the activity-log query. App-specific payment-alert kinds + the user-table count stay in the app.
    • Idempotent atomic debit: debit amount ONLY if the balance covers it AND this exact logical operation (identified by idemKey) hasn't already been debited. The row id is DERIVED from the key (${reason}:${idemKey}), so a retry/duplicate collides on the primary key and is IGNORED — it can never mint a second debit. The money-OUT double-spend guard a per-call random nonce lacks for PARTIAL refunds. One statement (INSERT OR IGNORE … WHERE SUM(delta) >= amount), atomic on both engines. Returns debited (fresh — nonce anchors the downstream Stripe idempotency key), replayed (already debited — caller MUST NOT move money again), or insufficient (balance no longer covers it).

      Parameters

      • db: CreditsDB
      • userId: string
      • amount: number
      • reason: string
      • idemKey: string

      Returns Promise<DebitOutcome>