@vllnt/convex-wallet 0.1.0-canary.3a56ec7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +144 -0
  3. package/dist/client/index.d.ts +109 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +105 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +45 -0
  8. package/dist/client/types.d.ts.map +1 -0
  9. package/dist/client/types.js +3 -0
  10. package/dist/client/types.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +42 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +31 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/component.d.ts +105 -0
  16. package/dist/component/_generated/component.d.ts.map +1 -0
  17. package/dist/component/_generated/component.js +11 -0
  18. package/dist/component/_generated/component.js.map +1 -0
  19. package/dist/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/component/_generated/dataModel.js +11 -0
  22. package/dist/component/_generated/dataModel.js.map +1 -0
  23. package/dist/component/_generated/server.d.ts +121 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +78 -0
  26. package/dist/component/_generated/server.js.map +1 -0
  27. package/dist/component/convex.config.d.ts +3 -0
  28. package/dist/component/convex.config.d.ts.map +1 -0
  29. package/dist/component/convex.config.js +7 -0
  30. package/dist/component/convex.config.js.map +1 -0
  31. package/dist/component/crons.d.ts +12 -0
  32. package/dist/component/crons.d.ts.map +1 -0
  33. package/dist/component/crons.js +19 -0
  34. package/dist/component/crons.js.map +1 -0
  35. package/dist/component/internal_mutations.d.ts +20 -0
  36. package/dist/component/internal_mutations.d.ts.map +1 -0
  37. package/dist/component/internal_mutations.js +52 -0
  38. package/dist/component/internal_mutations.js.map +1 -0
  39. package/dist/component/mutations.d.ts +79 -0
  40. package/dist/component/mutations.d.ts.map +1 -0
  41. package/dist/component/mutations.js +243 -0
  42. package/dist/component/mutations.js.map +1 -0
  43. package/dist/component/queries.d.ts +43 -0
  44. package/dist/component/queries.d.ts.map +1 -0
  45. package/dist/component/queries.js +70 -0
  46. package/dist/component/queries.js.map +1 -0
  47. package/dist/component/schema.d.ts +45 -0
  48. package/dist/component/schema.d.ts.map +1 -0
  49. package/dist/component/schema.js +33 -0
  50. package/dist/component/schema.js.map +1 -0
  51. package/dist/component/validators.d.ts +73 -0
  52. package/dist/component/validators.d.ts.map +1 -0
  53. package/dist/component/validators.js +45 -0
  54. package/dist/component/validators.js.map +1 -0
  55. package/dist/react/index.d.ts +37 -0
  56. package/dist/react/index.d.ts.map +1 -0
  57. package/dist/react/index.js +30 -0
  58. package/dist/react/index.js.map +1 -0
  59. package/dist/shared.d.ts +84 -0
  60. package/dist/shared.d.ts.map +1 -0
  61. package/dist/shared.js +91 -0
  62. package/dist/shared.js.map +1 -0
  63. package/package.json +112 -0
  64. package/src/client/index.ts +257 -0
  65. package/src/client/types.ts +51 -0
  66. package/src/component/_generated/api.ts +58 -0
  67. package/src/component/_generated/component.ts +118 -0
  68. package/src/component/_generated/dataModel.ts +60 -0
  69. package/src/component/_generated/server.ts +156 -0
  70. package/src/component/convex.config.ts +9 -0
  71. package/src/component/crons.ts +29 -0
  72. package/src/component/internal_mutations.ts +58 -0
  73. package/src/component/mutations.ts +279 -0
  74. package/src/component/queries.ts +76 -0
  75. package/src/component/schema.ts +33 -0
  76. package/src/component/validators.ts +58 -0
  77. package/src/react/index.test.tsx +61 -0
  78. package/src/react/index.tsx +50 -0
  79. package/src/shared.ts +123 -0
  80. package/src/test.ts +12 -0
@@ -0,0 +1,279 @@
1
+ import { v } from "convex/values";
2
+ import type { DataModel } from "./_generated/dataModel";
3
+ import type { GenericMutationCtx } from "convex/server";
4
+ import { mutation } from "./_generated/server";
5
+ import { applyRegen, assertPositiveAmount } from "../shared";
6
+ import { maxArg, regenArg, spendResult } from "./validators";
7
+
8
+ const balanceObject = v.object({ balance: v.number() });
9
+
10
+ type MutCtx = GenericMutationCtx<DataModel>;
11
+
12
+ /**
13
+ * Find the prior ledger row for a replayed `idempotencyKey`, scoped to this
14
+ * exact `(subjectRef, currency)`. A key reused across different subjects or
15
+ * currencies is independent — so a legitimate grant is never dropped.
16
+ */
17
+ async function findIdempotent(
18
+ ctx: MutCtx,
19
+ subjectRef: string,
20
+ currency: string,
21
+ idempotencyKey: string,
22
+ ) {
23
+ return ctx.db
24
+ .query("ledger")
25
+ .withIndex("by_idem", (q) =>
26
+ q
27
+ .eq("subjectRef", subjectRef)
28
+ .eq("currency", currency)
29
+ .eq("idempotencyKey", idempotencyKey),
30
+ )
31
+ .first();
32
+ }
33
+
34
+ /** Clamp a post-credit balance to an optional per-currency `max` ceiling. */
35
+ function clampToMax(balance: number, max: number | undefined): number {
36
+ return max === undefined ? balance : Math.min(balance, max);
37
+ }
38
+
39
+ /**
40
+ * Credit `amount` of `currency` to `subjectRef`. When `idempotencyKey` is
41
+ * supplied and already recorded for this `(subjectRef, currency)`, this is a
42
+ * no-op replay — the current (regen-aware) balance is returned without
43
+ * double-crediting. A credit that would exceed `max` is clamped to `max`.
44
+ */
45
+ export const earn = mutation({
46
+ args: {
47
+ subjectRef: v.string(),
48
+ currency: v.string(),
49
+ amount: v.number(),
50
+ reason: v.string(),
51
+ idempotencyKey: v.optional(v.string()),
52
+ regen: regenArg,
53
+ max: maxArg,
54
+ },
55
+ returns: balanceObject,
56
+ handler: async (ctx, args) => {
57
+ assertPositiveAmount(args.amount);
58
+ const now = Date.now();
59
+ const row = await ctx.db
60
+ .query("balances")
61
+ .withIndex("by_subject_currency", (q) =>
62
+ q.eq("subjectRef", args.subjectRef).eq("currency", args.currency),
63
+ )
64
+ .unique();
65
+
66
+ let balance: number;
67
+ let delta: number;
68
+ if (row === null) {
69
+ // No balance row → no recorded key for it can exist, so the idempotency
70
+ // check is unnecessary: this is always a first credit.
71
+ balance = clampToMax(args.amount, args.max);
72
+ delta = balance;
73
+ await ctx.db.insert("balances", {
74
+ subjectRef: args.subjectRef,
75
+ currency: args.currency,
76
+ amount: balance,
77
+ lastRegenAt: now,
78
+ lifetimeEarned: balance,
79
+ lifetimeSpent: 0,
80
+ });
81
+ } else {
82
+ if (args.idempotencyKey !== undefined) {
83
+ const seen = await findIdempotent(
84
+ ctx,
85
+ args.subjectRef,
86
+ args.currency,
87
+ args.idempotencyKey,
88
+ );
89
+ if (seen !== null) {
90
+ // Replay: return the current (regen-aware) balance, no double-credit.
91
+ return {
92
+ balance: applyRegen(row.amount, row.lastRegenAt, now, args.regen).amount,
93
+ };
94
+ }
95
+ }
96
+ const r = applyRegen(row.amount, row.lastRegenAt, now, args.regen);
97
+ balance = clampToMax(r.amount + args.amount, args.max);
98
+ delta = balance - r.amount;
99
+ await ctx.db.patch(row._id, {
100
+ amount: balance,
101
+ lastRegenAt: r.lastRegenAt,
102
+ lifetimeEarned: row.lifetimeEarned + delta,
103
+ });
104
+ }
105
+
106
+ await ctx.db.insert("ledger", {
107
+ subjectRef: args.subjectRef,
108
+ currency: args.currency,
109
+ delta,
110
+ reason: args.reason,
111
+ idempotencyKey: args.idempotencyKey,
112
+ createdAt: now,
113
+ });
114
+ return { balance };
115
+ },
116
+ });
117
+
118
+ /**
119
+ * Debit `amount` of `currency` from `subjectRef`. Never goes negative — when
120
+ * the (regen-aware) balance is short, returns `{ ok: false, code:
121
+ * "INSUFFICIENT" }` while still persisting any regen that accrued.
122
+ */
123
+ export const spend = mutation({
124
+ args: {
125
+ subjectRef: v.string(),
126
+ currency: v.string(),
127
+ amount: v.number(),
128
+ reason: v.string(),
129
+ idempotencyKey: v.optional(v.string()),
130
+ regen: regenArg,
131
+ },
132
+ returns: spendResult,
133
+ handler: async (ctx, args) => {
134
+ assertPositiveAmount(args.amount);
135
+ const now = Date.now();
136
+ const row = await ctx.db
137
+ .query("balances")
138
+ .withIndex("by_subject_currency", (q) =>
139
+ q.eq("subjectRef", args.subjectRef).eq("currency", args.currency),
140
+ )
141
+ .unique();
142
+ if (row === null) {
143
+ return { ok: false, balance: 0, code: "INSUFFICIENT" as const };
144
+ }
145
+ if (args.idempotencyKey !== undefined) {
146
+ const seen = await findIdempotent(
147
+ ctx,
148
+ args.subjectRef,
149
+ args.currency,
150
+ args.idempotencyKey,
151
+ );
152
+ if (seen !== null) {
153
+ // Replay: return the current (regen-aware) balance, no double-debit.
154
+ return {
155
+ ok: true,
156
+ balance: applyRegen(row.amount, row.lastRegenAt, now, args.regen).amount,
157
+ };
158
+ }
159
+ }
160
+ const r = applyRegen(row.amount, row.lastRegenAt, now, args.regen);
161
+ if (r.amount < args.amount) {
162
+ await ctx.db.patch(row._id, { amount: r.amount, lastRegenAt: r.lastRegenAt });
163
+ return { ok: false, balance: r.amount, code: "INSUFFICIENT" as const };
164
+ }
165
+ const balance = r.amount - args.amount;
166
+ await ctx.db.patch(row._id, {
167
+ amount: balance,
168
+ lastRegenAt: r.lastRegenAt,
169
+ lifetimeSpent: row.lifetimeSpent + args.amount,
170
+ });
171
+ await ctx.db.insert("ledger", {
172
+ subjectRef: args.subjectRef,
173
+ currency: args.currency,
174
+ delta: -args.amount,
175
+ reason: args.reason,
176
+ idempotencyKey: args.idempotencyKey,
177
+ createdAt: now,
178
+ });
179
+ return { ok: true, balance };
180
+ },
181
+ });
182
+
183
+ /**
184
+ * Move `amount` of `currency` from `fromRef` to `toRef` in one transaction.
185
+ * Debits the sender (with the same insufficiency guard as {@link spend}); on
186
+ * success credits the receiver (clamped to `max`) and ledgers both legs.
187
+ * `fromRef === toRef` is rejected with `SELF_TRANSFER` (never double-touches one
188
+ * row). Returns the sender's new balance.
189
+ */
190
+ export const transfer = mutation({
191
+ args: {
192
+ fromRef: v.string(),
193
+ toRef: v.string(),
194
+ currency: v.string(),
195
+ amount: v.number(),
196
+ reason: v.string(),
197
+ regen: regenArg,
198
+ max: maxArg,
199
+ },
200
+ returns: spendResult,
201
+ handler: async (ctx, args) => {
202
+ assertPositiveAmount(args.amount);
203
+ const now = Date.now();
204
+ const fromRow = await ctx.db
205
+ .query("balances")
206
+ .withIndex("by_subject_currency", (q) =>
207
+ q.eq("subjectRef", args.fromRef).eq("currency", args.currency),
208
+ )
209
+ .unique();
210
+ if (args.fromRef === args.toRef) {
211
+ const current =
212
+ fromRow === null
213
+ ? 0
214
+ : applyRegen(fromRow.amount, fromRow.lastRegenAt, now, args.regen).amount;
215
+ return { ok: false, balance: current, code: "SELF_TRANSFER" as const };
216
+ }
217
+ if (fromRow === null) {
218
+ return { ok: false, balance: 0, code: "INSUFFICIENT" as const };
219
+ }
220
+ const fromR = applyRegen(fromRow.amount, fromRow.lastRegenAt, now, args.regen);
221
+ if (fromR.amount < args.amount) {
222
+ await ctx.db.patch(fromRow._id, {
223
+ amount: fromR.amount,
224
+ lastRegenAt: fromR.lastRegenAt,
225
+ });
226
+ return { ok: false, balance: fromR.amount, code: "INSUFFICIENT" as const };
227
+ }
228
+ const fromBalance = fromR.amount - args.amount;
229
+ await ctx.db.patch(fromRow._id, {
230
+ amount: fromBalance,
231
+ lastRegenAt: fromR.lastRegenAt,
232
+ lifetimeSpent: fromRow.lifetimeSpent + args.amount,
233
+ });
234
+ await ctx.db.insert("ledger", {
235
+ subjectRef: args.fromRef,
236
+ currency: args.currency,
237
+ delta: -args.amount,
238
+ reason: args.reason,
239
+ createdAt: now,
240
+ });
241
+
242
+ const toRow = await ctx.db
243
+ .query("balances")
244
+ .withIndex("by_subject_currency", (q) =>
245
+ q.eq("subjectRef", args.toRef).eq("currency", args.currency),
246
+ )
247
+ .unique();
248
+ let receiverDelta: number;
249
+ if (toRow === null) {
250
+ const credited = clampToMax(args.amount, args.max);
251
+ receiverDelta = credited;
252
+ await ctx.db.insert("balances", {
253
+ subjectRef: args.toRef,
254
+ currency: args.currency,
255
+ amount: credited,
256
+ lastRegenAt: now,
257
+ lifetimeEarned: credited,
258
+ lifetimeSpent: 0,
259
+ });
260
+ } else {
261
+ const toR = applyRegen(toRow.amount, toRow.lastRegenAt, now, args.regen);
262
+ const credited = clampToMax(toR.amount + args.amount, args.max);
263
+ receiverDelta = credited - toR.amount;
264
+ await ctx.db.patch(toRow._id, {
265
+ amount: credited,
266
+ lastRegenAt: toR.lastRegenAt,
267
+ lifetimeEarned: toRow.lifetimeEarned + receiverDelta,
268
+ });
269
+ }
270
+ await ctx.db.insert("ledger", {
271
+ subjectRef: args.toRef,
272
+ currency: args.currency,
273
+ delta: receiverDelta,
274
+ reason: args.reason,
275
+ createdAt: now,
276
+ });
277
+ return { ok: true, balance: fromBalance };
278
+ },
279
+ });
@@ -0,0 +1,76 @@
1
+ import { v } from "convex/values";
2
+ import { query } from "./_generated/server";
3
+ import { applyRegen } from "../shared";
4
+ import { balanceEntry, ledgerDoc, regenArg, regenMapArg } from "./validators";
5
+
6
+ /**
7
+ * Regen-aware single-currency read. Projects the stored balance forward to the
8
+ * server clock under the per-currency `regen` (compute-only — queries cannot
9
+ * write, so the regen is reflected in the result but not persisted). Missing → 0.
10
+ */
11
+ export const balance = query({
12
+ args: {
13
+ subjectRef: v.string(),
14
+ currency: v.string(),
15
+ regen: regenArg,
16
+ },
17
+ returns: v.number(),
18
+ handler: async (ctx, args) => {
19
+ const now = Date.now();
20
+ const row = await ctx.db
21
+ .query("balances")
22
+ .withIndex("by_subject_currency", (q) =>
23
+ q.eq("subjectRef", args.subjectRef).eq("currency", args.currency),
24
+ )
25
+ .unique();
26
+ if (row === null) {
27
+ return 0;
28
+ }
29
+ return applyRegen(row.amount, row.lastRegenAt, now, args.regen).amount;
30
+ },
31
+ });
32
+
33
+ /**
34
+ * Multi-currency overview for `subjectRef`, regen-aware. The client passes its
35
+ * per-currency `regen` map so each row is projected exactly as {@link balance}
36
+ * would — no stale divergence. A currency absent from the map is static.
37
+ */
38
+ export const balances = query({
39
+ args: { subjectRef: v.string(), regen: regenMapArg },
40
+ returns: v.array(balanceEntry),
41
+ handler: async (ctx, args) => {
42
+ const now = Date.now();
43
+ const regenMap = args.regen ?? {};
44
+ const rows = await ctx.db
45
+ .query("balances")
46
+ .withIndex("by_subject_currency", (q) => q.eq("subjectRef", args.subjectRef))
47
+ .collect();
48
+ return rows.map((row) => ({
49
+ currency: row.currency,
50
+ amount: applyRegen(row.amount, row.lastRegenAt, now, regenMap[row.currency])
51
+ .amount,
52
+ }));
53
+ },
54
+ });
55
+
56
+ /** Newest-first ledger entries for one currency, capped at `limit`. */
57
+ export const history = query({
58
+ args: { subjectRef: v.string(), currency: v.string(), limit: v.number() },
59
+ returns: v.array(ledgerDoc),
60
+ handler: async (ctx, args) => {
61
+ const rows = await ctx.db
62
+ .query("ledger")
63
+ .withIndex("by_subject_currency", (q) =>
64
+ q.eq("subjectRef", args.subjectRef).eq("currency", args.currency),
65
+ )
66
+ .order("desc")
67
+ .take(args.limit);
68
+ return rows.map((row) => ({
69
+ currency: row.currency,
70
+ delta: row.delta,
71
+ reason: row.reason,
72
+ idempotencyKey: row.idempotencyKey,
73
+ createdAt: row.createdAt,
74
+ }));
75
+ },
76
+ });
@@ -0,0 +1,33 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+
4
+ /**
5
+ * Sandboxed tables — the wallet's own concern. `subjectRef` is an opaque
6
+ * host-owned reference (never assume it is a user id or its shape); `currency`
7
+ * is an opaque host-chosen string (coins, energy, gems, credits).
8
+ */
9
+ export default defineSchema({
10
+ balances: defineTable({
11
+ subjectRef: v.string(),
12
+ currency: v.string(),
13
+ amount: v.number(),
14
+ lastRegenAt: v.number(),
15
+ lifetimeEarned: v.number(),
16
+ lifetimeSpent: v.number(),
17
+ }).index("by_subject_currency", ["subjectRef", "currency"]),
18
+ ledger: defineTable({
19
+ subjectRef: v.string(),
20
+ currency: v.string(),
21
+ delta: v.number(),
22
+ reason: v.string(),
23
+ idempotencyKey: v.optional(v.string()),
24
+ createdAt: v.number(),
25
+ })
26
+ .index("by_subject_currency", ["subjectRef", "currency", "createdAt"])
27
+ // Idempotency is scoped per (subject, currency): the same key reused across
28
+ // different subjects/currencies is independent, so a legitimate grant is
29
+ // never silently dropped by a key collision.
30
+ .index("by_idem", ["subjectRef", "currency", "idempotencyKey"])
31
+ // Drives the retention/idempotency prune cron (oldest-first by createdAt).
32
+ .index("by_created", ["createdAt"]),
33
+ });
@@ -0,0 +1,58 @@
1
+ import { v } from "convex/values";
2
+
3
+ /**
4
+ * Optional per-call time-regen rule, injected by the client from its
5
+ * per-currency config. The component itself is config-less. `max`, when set,
6
+ * is the hard ceiling on stored balance for the currency — credits are clamped
7
+ * to it (see {@link mutations}).
8
+ */
9
+ export const regenArg = v.optional(
10
+ v.object({
11
+ amount: v.number(),
12
+ intervalMs: v.number(),
13
+ cap: v.number(),
14
+ }),
15
+ );
16
+
17
+ /**
18
+ * Optional per-currency hard ceiling on the stored balance. A credit that would
19
+ * carry the balance above `max` is clamped to `max`; an `earn`/`grant`/receive
20
+ * leg that is ALREADY at or above `max` is a no-op credit (idempotent ceiling).
21
+ */
22
+ export const maxArg = v.optional(v.number());
23
+
24
+ /** Per-currency regen map for the multi-currency {@link queries.balances} read. */
25
+ export const regenMapArg = v.optional(
26
+ v.record(
27
+ v.string(),
28
+ v.object({ amount: v.number(), intervalMs: v.number(), cap: v.number() }),
29
+ ),
30
+ );
31
+
32
+ /** Stable, code-tagged failure reasons. `reason` (free text) is the ledger note. */
33
+ export const errorCode = v.union(v.literal("INSUFFICIENT"), v.literal("SELF_TRANSFER"));
34
+
35
+ /**
36
+ * Result of a spend/transfer that may be rejected. `code` carries a stable
37
+ * machine-readable tag when `ok` is false; it is absent on success.
38
+ */
39
+ export const spendResult = v.object({
40
+ ok: v.boolean(),
41
+ balance: v.number(),
42
+ code: v.optional(errorCode),
43
+ });
44
+
45
+ /** A single currency balance in the multi-currency overview. */
46
+ export const balanceEntry = v.object({
47
+ currency: v.string(),
48
+ amount: v.number(),
49
+ });
50
+
51
+ /** A ledger row projected for history reads (sandbox fields omitted). */
52
+ export const ledgerDoc = v.object({
53
+ currency: v.string(),
54
+ delta: v.number(),
55
+ reason: v.string(),
56
+ idempotencyKey: v.optional(v.string()),
57
+ createdAt: v.number(),
58
+ });
@@ -0,0 +1,61 @@
1
+ // @vitest-environment jsdom
2
+ import { renderHook } from "@testing-library/react";
3
+ import { expect, test, vi } from "vitest";
4
+ import * as cr from "convex/react";
5
+ import type { FunctionReference } from "convex/server";
6
+ import type { BalanceEntry } from "../client/types.js";
7
+ import { useBalance, useBalances } from "./index.js";
8
+
9
+ vi.mock("convex/react", () => ({
10
+ useQuery: vi.fn(),
11
+ usePaginatedQuery: vi.fn(),
12
+ }));
13
+
14
+ const mockedUseQuery = cr.useQuery as unknown as ReturnType<typeof vi.fn>;
15
+
16
+ const balanceRef = {} as FunctionReference<
17
+ "query",
18
+ "public",
19
+ { subjectRef: string; currency: string },
20
+ number
21
+ >;
22
+
23
+ const balancesRef = {} as FunctionReference<
24
+ "query",
25
+ "public",
26
+ { subjectRef: string },
27
+ BalanceEntry[]
28
+ >;
29
+
30
+ test("useBalance passes ref + args and returns the loaded value", () => {
31
+ mockedUseQuery.mockReturnValue(42);
32
+ const args = { subjectRef: "s", currency: "coins" };
33
+ const { result } = renderHook(() => useBalance(balanceRef, args));
34
+ expect(mockedUseQuery).toHaveBeenCalledWith(balanceRef, args);
35
+ expect(result.current).toBe(42);
36
+ });
37
+
38
+ test("useBalance returns undefined while loading", () => {
39
+ mockedUseQuery.mockReturnValue(undefined);
40
+ const { result } = renderHook(() =>
41
+ useBalance(balanceRef, { subjectRef: "s", currency: "coins" }),
42
+ );
43
+ expect(result.current).toBeUndefined();
44
+ });
45
+
46
+ test("useBalances passes ref + args and returns the loaded value", () => {
47
+ const balances: BalanceEntry[] = [{ currency: "coins", amount: 7 }];
48
+ mockedUseQuery.mockReturnValue(balances);
49
+ const args = { subjectRef: "s" };
50
+ const { result } = renderHook(() => useBalances(balancesRef, args));
51
+ expect(mockedUseQuery).toHaveBeenCalledWith(balancesRef, args);
52
+ expect(result.current).toBe(balances);
53
+ });
54
+
55
+ test("useBalances returns undefined while loading", () => {
56
+ mockedUseQuery.mockReturnValue(undefined);
57
+ const { result } = renderHook(() =>
58
+ useBalances(balancesRef, { subjectRef: "s" }),
59
+ );
60
+ expect(result.current).toBeUndefined();
61
+ });
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Optional, tree-shakeable React front-tooling for `@vllnt/convex-wallet`.
3
+ *
4
+ * Thin reactive hooks over `useQuery` from `convex/react`. Each hook takes the
5
+ * HOST's re-exported wallet function reference plus its args — the component
6
+ * never imports the host `api`. `react` and `convex/react` are optional peer
7
+ * deps: a backend-only consumer pulls none of this code.
8
+ */
9
+
10
+ import type { FunctionReference } from "convex/server";
11
+ import { useQuery } from "convex/react";
12
+ import type { BalanceEntry } from "../client/types.js";
13
+
14
+ /**
15
+ * Reactive single-currency balance for `subjectRef`.
16
+ *
17
+ * @param balanceRef - The host's re-exported `wallet.balance` query reference.
18
+ * @param args - `{ subjectRef, currency }` opaque identity + currency string.
19
+ * @returns The current balance, or `undefined` while the query loads.
20
+ */
21
+ export function useBalance(
22
+ balanceRef: FunctionReference<
23
+ "query",
24
+ "public",
25
+ { subjectRef: string; currency: string },
26
+ number
27
+ >,
28
+ args: { subjectRef: string; currency: string },
29
+ ): number | undefined {
30
+ return useQuery(balanceRef, args);
31
+ }
32
+
33
+ /**
34
+ * Reactive multi-currency overview for `subjectRef`.
35
+ *
36
+ * @param balancesRef - The host's re-exported `wallet.balances` query reference.
37
+ * @param args - `{ subjectRef }` opaque identity.
38
+ * @returns The balances array, or `undefined` while the query loads.
39
+ */
40
+ export function useBalances(
41
+ balancesRef: FunctionReference<
42
+ "query",
43
+ "public",
44
+ { subjectRef: string },
45
+ BalanceEntry[]
46
+ >,
47
+ args: { subjectRef: string },
48
+ ): BalanceEntry[] | undefined {
49
+ return useQuery(balancesRef, args);
50
+ }
package/src/shared.ts ADDED
@@ -0,0 +1,123 @@
1
+ /** Shared constants + pure utilities used by both `client/` and `component/`. */
2
+
3
+ export const COMPONENT_NAME = "wallet";
4
+
5
+ /** Default newest-first page size for {@link history} when the caller omits one. */
6
+ export const DEFAULT_HISTORY_LIMIT = 50;
7
+
8
+ /**
9
+ * Default ledger retention: rows older than this are pruned by the internal
10
+ * cron. 90 days. Override per mount via {@link WalletOptions.ledgerRetentionMs}.
11
+ */
12
+ export const DEFAULT_LEDGER_RETENTION_MS = 90 * 24 * 60 * 60 * 1000;
13
+
14
+ /**
15
+ * Default idempotency window: a recorded `idempotencyKey` is honored (replays
16
+ * are no-ops) for this long; afterwards the cron forgets it so the key can be
17
+ * reused. 7 days. Override via {@link WalletOptions.idempotencyTtlMs}.
18
+ */
19
+ export const DEFAULT_IDEMPOTENCY_TTL_MS = 7 * 24 * 60 * 60 * 1000;
20
+
21
+ /** Default cron cadence for the ledger/idempotency prune sweep. 1 hour. */
22
+ export const DEFAULT_PRUNE_INTERVAL_MS = 60 * 60 * 1000;
23
+
24
+ /** Stable, code-tagged failure reasons returned on the `code` field of a result. */
25
+ export const ERROR_CODES = {
26
+ /** A spend/transfer was short of funds. */
27
+ INSUFFICIENT: "INSUFFICIENT",
28
+ /** A transfer named the same subject as sender and receiver. */
29
+ SELF_TRANSFER: "SELF_TRANSFER",
30
+ } as const;
31
+
32
+ /**
33
+ * Thrown by {@link applyRegen} when a regen config has a non-finite or
34
+ * non-positive field. Carries the stable `INVALID_REGEN` code so hosts can
35
+ * branch without string-matching prose.
36
+ */
37
+ export const INVALID_REGEN = "INVALID_REGEN";
38
+
39
+ /** A non-throwing result failure tag. */
40
+ export type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
41
+
42
+ /**
43
+ * Thrown by {@link assertPositiveAmount} when an amount is non-finite or not
44
+ * strictly positive. Carries the stable `INVALID_AMOUNT` code so hosts can
45
+ * branch on `error.message` without string-matching prose.
46
+ */
47
+ export const INVALID_AMOUNT = "INVALID_AMOUNT";
48
+
49
+ /** Opaque host-supplied subject reference. Never assume its shape or source. */
50
+ export type SubjectRef = string;
51
+
52
+ /**
53
+ * Time-regen rule for an energy-style currency: gain `amount` units every
54
+ * `intervalMs`, never exceeding `cap`. Coin/gem-style currencies omit it.
55
+ */
56
+ export interface RegenConfig {
57
+ amount: number;
58
+ intervalMs: number;
59
+ cap: number;
60
+ }
61
+
62
+ /**
63
+ * Guard every value-moving entry point. Rejects non-finite (`NaN`, `Infinity`)
64
+ * and non-positive (`0`, negative) amounts — a negative `spend` would otherwise
65
+ * MINT funds, and `NaN` would corrupt a balance. Throws `INVALID_AMOUNT`.
66
+ *
67
+ * @param amount - the caller-supplied amount to credit or debit.
68
+ * @throws when `amount` is not a finite number `> 0`.
69
+ */
70
+ export function assertPositiveAmount(amount: number): void {
71
+ if (!Number.isFinite(amount) || amount <= 0) {
72
+ throw new Error(INVALID_AMOUNT);
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Pure, deterministic lazy regen. Given a `stored` balance last touched at
78
+ * `lastRegenAt`, project it forward to `now` under `regen`.
79
+ *
80
+ * - No `regen` → unchanged `{ amount: stored, lastRegenAt }`.
81
+ * - Backwards/equal clock (`now <= lastRegenAt`) → unchanged: the pointer is
82
+ * never moved backward and never advanced past `now`, so a host that supplies
83
+ * a stale/rewound clock can never over-regen or rewind accrual.
84
+ * - `ticks = floor((now - lastRegenAt) / intervalMs)`; zero ticks → unchanged
85
+ * (the clock pointer does not advance until a whole tick elapses).
86
+ * - Otherwise grant `ticks * amount`, clamped to `cap` (never above `cap`,
87
+ * never below `stored`), and advance `lastRegenAt` by exactly the ticks
88
+ * consumed so partial-interval progress is preserved. Because
89
+ * `lastRegenAt + ticks * intervalMs <= now`, the pointer never passes `now`.
90
+ *
91
+ * @param stored - the persisted balance.
92
+ * @param lastRegenAt - epoch ms the balance was last reconciled.
93
+ * @param now - current epoch ms (read server-side via `Date.now()`).
94
+ * @param regen - optional regen rule; when absent the balance is static.
95
+ * @returns the projected `{ amount, lastRegenAt }`.
96
+ */
97
+ export function applyRegen(
98
+ stored: number,
99
+ lastRegenAt: number,
100
+ now: number,
101
+ regen?: RegenConfig,
102
+ ): { amount: number; lastRegenAt: number } {
103
+ if (regen === undefined || now <= lastRegenAt) {
104
+ return { amount: stored, lastRegenAt };
105
+ }
106
+ if (
107
+ !Number.isFinite(regen.intervalMs) ||
108
+ regen.intervalMs <= 0 ||
109
+ !Number.isFinite(regen.amount) ||
110
+ regen.amount <= 0 ||
111
+ !Number.isFinite(regen.cap) ||
112
+ regen.cap <= 0
113
+ ) {
114
+ throw new Error(INVALID_REGEN);
115
+ }
116
+ const ticks = Math.floor((now - lastRegenAt) / regen.intervalMs);
117
+ return ticks === 0
118
+ ? { amount: stored, lastRegenAt }
119
+ : {
120
+ amount: Math.max(stored, Math.min(regen.cap, stored + ticks * regen.amount)),
121
+ lastRegenAt: lastRegenAt + ticks * regen.intervalMs,
122
+ };
123
+ }
package/src/test.ts ADDED
@@ -0,0 +1,12 @@
1
+ import type { TestConvex } from "convex-test";
2
+ import schema from "./component/schema";
3
+
4
+ const modules = import.meta.glob("./component/**/*.ts");
5
+
6
+ /**
7
+ * Register this component with a `convex-test` instance so consuming apps can
8
+ * test integration: `import { register } from "@vllnt/convex-wallet/test"`.
9
+ */
10
+ export function register(t: TestConvex<typeof schema>, name = "wallet"): void {
11
+ t.registerComponent(name, schema, modules);
12
+ }