@wopr-network/platform-core 1.42.3 → 1.43.0

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.
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Crypto Key Server — shared address derivation + charge management.
3
+ *
4
+ * Deploys on the chain server (pay.wopr.bot) alongside bitcoind.
5
+ * Products don't run watchers or hold xpubs. They request addresses
6
+ * and receive webhooks.
7
+ *
8
+ * ~200 lines of new code wrapping platform-core's existing crypto modules.
9
+ */
10
+ import { eq, sql } from "drizzle-orm";
11
+ import { Hono } from "hono";
12
+ import type { DrizzleDb } from "../../db/index.js";
13
+ import { derivedAddresses, pathAllocations, paymentMethods } from "../../db/schema/crypto.js";
14
+ import { deriveAddress, deriveP2pkhAddress } from "./btc/address-gen.js";
15
+ import type { ICryptoChargeRepository } from "./charge-store.js";
16
+ import { deriveDepositAddress } from "./evm/address-gen.js";
17
+ import type { IPaymentMethodStore } from "./payment-method-store.js";
18
+
19
+ export interface KeyServerDeps {
20
+ db: DrizzleDb;
21
+ chargeStore: ICryptoChargeRepository;
22
+ methodStore: IPaymentMethodStore;
23
+ /** Bearer token for product API routes. If unset, auth is disabled. */
24
+ serviceKey?: string;
25
+ /** Bearer token for admin routes. If unset, admin routes are disabled. */
26
+ adminToken?: string;
27
+ }
28
+
29
+ /**
30
+ * Derive the next unused address for a chain.
31
+ * Atomically increments next_index and records address in a single transaction.
32
+ */
33
+ async function deriveNextAddress(
34
+ db: DrizzleDb,
35
+ chainId: string,
36
+ tenantId?: string,
37
+ ): Promise<{ address: string; index: number; chain: string; token: string }> {
38
+ // Wrap in transaction: if the address insert fails, next_index is not consumed.
39
+ return (db as unknown as { transaction: (fn: (tx: DrizzleDb) => Promise<unknown>) => Promise<unknown> }).transaction(
40
+ async (tx: DrizzleDb) => {
41
+ // Atomic increment: UPDATE ... SET next_index = next_index + 1 RETURNING *
42
+ const [method] = await tx
43
+ .update(paymentMethods)
44
+ .set({ nextIndex: sql`${paymentMethods.nextIndex} + 1` })
45
+ .where(eq(paymentMethods.id, chainId))
46
+ .returning();
47
+
48
+ if (!method) throw new Error(`Chain not found: ${chainId}`);
49
+ if (!method.xpub) throw new Error(`No xpub configured for chain: ${chainId}`);
50
+
51
+ // The index we use is the value BEFORE increment (returned value - 1)
52
+ const index = method.nextIndex - 1;
53
+
54
+ // Route to the right derivation function
55
+ let address: string;
56
+ if (method.type === "native" && method.chain === "dogecoin") {
57
+ address = deriveP2pkhAddress(method.xpub, index, "dogecoin");
58
+ } else if (method.type === "native" && (method.chain === "bitcoin" || method.chain === "litecoin")) {
59
+ address = deriveAddress(method.xpub, index, "mainnet", method.chain as "bitcoin" | "litecoin");
60
+ } else {
61
+ // EVM (all ERC20 + native ETH) — same derivation
62
+ address = deriveDepositAddress(method.xpub, index);
63
+ }
64
+
65
+ // Record in immutable log (inside same transaction)
66
+ await tx.insert(derivedAddresses).values({
67
+ chainId,
68
+ derivationIndex: index,
69
+ address: address.toLowerCase(),
70
+ tenantId,
71
+ });
72
+
73
+ return { address, index, chain: method.chain, token: method.token };
74
+ },
75
+ ) as Promise<{ address: string; index: number; chain: string; token: string }>;
76
+ }
77
+
78
+ /** Validate Bearer token from Authorization header. */
79
+ function requireAuth(header: string | undefined, expected: string): boolean {
80
+ if (!expected) return true; // auth disabled
81
+ return header === `Bearer ${expected}`;
82
+ }
83
+
84
+ /**
85
+ * Create the Hono app for the crypto key server.
86
+ * Mount this on the chain server at the root.
87
+ */
88
+ export function createKeyServerApp(deps: KeyServerDeps): Hono {
89
+ const app = new Hono();
90
+
91
+ // --- Auth middleware for product routes ---
92
+ app.use("/address", async (c, next) => {
93
+ if (deps.serviceKey && !requireAuth(c.req.header("Authorization"), deps.serviceKey)) {
94
+ return c.json({ error: "Unauthorized" }, 401);
95
+ }
96
+ await next();
97
+ });
98
+ app.use("/charges/*", async (c, next) => {
99
+ if (deps.serviceKey && !requireAuth(c.req.header("Authorization"), deps.serviceKey)) {
100
+ return c.json({ error: "Unauthorized" }, 401);
101
+ }
102
+ await next();
103
+ });
104
+ app.use("/charges", async (c, next) => {
105
+ if (deps.serviceKey && !requireAuth(c.req.header("Authorization"), deps.serviceKey)) {
106
+ return c.json({ error: "Unauthorized" }, 401);
107
+ }
108
+ await next();
109
+ });
110
+
111
+ // --- Auth middleware for admin routes ---
112
+ app.use("/admin/*", async (c, next) => {
113
+ if (!deps.adminToken) return c.json({ error: "Admin API disabled" }, 403);
114
+ if (!requireAuth(c.req.header("Authorization"), deps.adminToken)) {
115
+ return c.json({ error: "Unauthorized" }, 401);
116
+ }
117
+ await next();
118
+ });
119
+
120
+ // --- Product API ---
121
+
122
+ /** POST /address — derive next unused address */
123
+ app.post("/address", async (c) => {
124
+ const body = await c.req.json<{ chain: string }>();
125
+ if (!body.chain) return c.json({ error: "chain is required" }, 400);
126
+
127
+ const tenantId = c.req.header("X-Tenant-Id");
128
+ const result = await deriveNextAddress(deps.db, body.chain, tenantId ?? undefined);
129
+ return c.json(result, 201);
130
+ });
131
+
132
+ /** POST /charges — create charge + derive address + start watching */
133
+ app.post("/charges", async (c) => {
134
+ const body = await c.req.json<{
135
+ chain: string;
136
+ amountUsd: number;
137
+ callbackUrl?: string;
138
+ metadata?: Record<string, unknown>;
139
+ }>();
140
+
141
+ if (!body.chain || typeof body.amountUsd !== "number" || !Number.isFinite(body.amountUsd) || body.amountUsd <= 0) {
142
+ return c.json({ error: "chain is required and amountUsd must be a positive finite number" }, 400);
143
+ }
144
+
145
+ const tenantId = c.req.header("X-Tenant-Id") ?? "unknown";
146
+ const { address, index, chain, token } = await deriveNextAddress(deps.db, body.chain, tenantId);
147
+
148
+ const amountUsdCents = Math.round(body.amountUsd * 100);
149
+ const referenceId = `${token.toLowerCase()}:${address.toLowerCase()}`;
150
+
151
+ await deps.chargeStore.createStablecoinCharge({
152
+ referenceId,
153
+ tenantId,
154
+ amountUsdCents,
155
+ chain,
156
+ token,
157
+ depositAddress: address,
158
+ derivationIndex: index,
159
+ });
160
+
161
+ return c.json(
162
+ {
163
+ chargeId: referenceId,
164
+ address,
165
+ chain: body.chain,
166
+ token,
167
+ amountUsd: body.amountUsd,
168
+ derivationIndex: index,
169
+ expiresAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(), // 30 min
170
+ },
171
+ 201,
172
+ );
173
+ });
174
+
175
+ /** GET /charges/:id — check charge status */
176
+ app.get("/charges/:id", async (c) => {
177
+ const charge = await deps.chargeStore.getByReferenceId(c.req.param("id"));
178
+ if (!charge) return c.json({ error: "Charge not found" }, 404);
179
+
180
+ return c.json({
181
+ chargeId: charge.referenceId,
182
+ status: charge.status,
183
+ address: charge.depositAddress,
184
+ chain: charge.chain,
185
+ token: charge.token,
186
+ amountUsdCents: charge.amountUsdCents,
187
+ creditedAt: charge.creditedAt,
188
+ });
189
+ });
190
+
191
+ /** GET /chains — list enabled payment methods (for checkout UI) */
192
+ app.get("/chains", async (c) => {
193
+ const methods = await deps.methodStore.listEnabled();
194
+ return c.json(
195
+ methods.map((m) => ({
196
+ id: m.id,
197
+ token: m.token,
198
+ chain: m.chain,
199
+ decimals: m.decimals,
200
+ displayName: m.displayName,
201
+ contractAddress: m.contractAddress,
202
+ confirmations: m.confirmations,
203
+ })),
204
+ );
205
+ });
206
+
207
+ // --- Admin API ---
208
+
209
+ /** GET /admin/next-path — which derivation path to use for a coin type */
210
+ app.get("/admin/next-path", async (c) => {
211
+ const coinType = Number(c.req.query("coin_type"));
212
+ if (!Number.isInteger(coinType)) return c.json({ error: "coin_type must be an integer" }, 400);
213
+
214
+ // Find all allocations for this coin type
215
+ const existing = await deps.db.select().from(pathAllocations).where(eq(pathAllocations.coinType, coinType));
216
+
217
+ if (existing.length === 0) {
218
+ return c.json({
219
+ coin_type: coinType,
220
+ account_index: 0,
221
+ path: `m/44'/${coinType}'/0'`,
222
+ status: "available",
223
+ });
224
+ }
225
+
226
+ // If already allocated, return info about existing allocation
227
+ const latest = existing.sort(
228
+ (a: { accountIndex: number }, b: { accountIndex: number }) => b.accountIndex - a.accountIndex,
229
+ )[0];
230
+
231
+ // Find chains using this coin type's allocations
232
+ const chainIds = existing.map((a: { chainId: string | null }) => a.chainId).filter(Boolean);
233
+ return c.json({
234
+ coin_type: coinType,
235
+ account_index: latest.accountIndex,
236
+ path: `m/44'/${coinType}'/${latest.accountIndex}'`,
237
+ status: "allocated",
238
+ allocated_to: chainIds,
239
+ note: "xpub already registered — reuse for new chains with same key type",
240
+ next_available: {
241
+ account_index: latest.accountIndex + 1,
242
+ path: `m/44'/${coinType}'/${latest.accountIndex + 1}'`,
243
+ },
244
+ });
245
+ });
246
+
247
+ /** POST /admin/chains — register a new chain with its xpub */
248
+ app.post("/admin/chains", async (c) => {
249
+ const body = await c.req.json<{
250
+ id: string;
251
+ coin_type: number;
252
+ account_index: number;
253
+ network: string;
254
+ type: string;
255
+ token: string;
256
+ chain: string;
257
+ contract?: string;
258
+ decimals: number;
259
+ xpub: string;
260
+ rpc_url: string;
261
+ confirmations?: number;
262
+ display_name?: string;
263
+ oracle_address?: string;
264
+ }>();
265
+
266
+ if (!body.id || !body.xpub || !body.token) {
267
+ return c.json({ error: "id, xpub, and token are required" }, 400);
268
+ }
269
+
270
+ // Record the path allocation (idempotent — ignore if already exists)
271
+ const inserted = (await deps.db
272
+ .insert(pathAllocations)
273
+ .values({
274
+ coinType: body.coin_type,
275
+ accountIndex: body.account_index,
276
+ chainId: body.id,
277
+ xpub: body.xpub,
278
+ })
279
+ .onConflictDoNothing()) as { rowCount: number };
280
+
281
+ if (inserted.rowCount === 0) {
282
+ return c.json(
283
+ { error: "Path allocation already exists", path: `m/44'/${body.coin_type}'/${body.account_index}'` },
284
+ 409,
285
+ );
286
+ }
287
+
288
+ // Upsert the payment method
289
+ await deps.methodStore.upsert({
290
+ id: body.id,
291
+ type: body.type ?? "native",
292
+ token: body.token,
293
+ chain: body.chain ?? body.network,
294
+ contractAddress: body.contract ?? null,
295
+ decimals: body.decimals,
296
+ displayName: body.display_name ?? `${body.token} on ${body.network}`,
297
+ enabled: true,
298
+ displayOrder: 0,
299
+ rpcUrl: body.rpc_url,
300
+ oracleAddress: body.oracle_address ?? null,
301
+ xpub: body.xpub,
302
+ confirmations: body.confirmations ?? 6,
303
+ });
304
+
305
+ return c.json({ id: body.id, path: `m/44'/${body.coin_type}'/${body.account_index}'` }, 201);
306
+ });
307
+
308
+ /** DELETE /admin/chains/:id — soft disable */
309
+ app.delete("/admin/chains/:id", async (c) => {
310
+ await deps.methodStore.setEnabled(c.req.param("id"), false);
311
+ return c.body(null, 204);
312
+ });
313
+
314
+ return app;
315
+ }
@@ -50,12 +50,16 @@ export const watcherCursors = pgTable("watcher_cursors", {
50
50
  * Payment method registry — runtime-configurable tokens/chains.
51
51
  * Admin inserts a row to enable a new payment method. No deploy needed.
52
52
  * Contract addresses are immutable on-chain but configurable here.
53
+ *
54
+ * nextIndex is an atomic counter for HD derivation — never reuses an index.
55
+ * Increment via UPDATE ... SET next_index = next_index + 1 RETURNING next_index.
53
56
  */
54
57
  export const paymentMethods = pgTable("payment_methods", {
55
- id: text("id").primaryKey(), // "USDC:base", "ETH:base", "BTC:mainnet"
56
- type: text("type").notNull(), // "stablecoin", "eth", "btc"
57
- token: text("token").notNull(), // "USDC", "ETH", "BTC"
58
- chain: text("chain").notNull(), // "base", "ethereum", "bitcoin"
58
+ id: text("id").primaryKey(), // "btc", "base-usdc", "arb-usdc", "doge"
59
+ type: text("type").notNull(), // "erc20", "native", "btc"
60
+ token: text("token").notNull(), // "USDC", "ETH", "BTC", "DOGE"
61
+ chain: text("chain").notNull(), // "base", "ethereum", "bitcoin", "arbitrum"
62
+ network: text("network").notNull().default("mainnet"), // "mainnet", "base", "arbitrum"
59
63
  contractAddress: text("contract_address"), // null for native (ETH, BTC)
60
64
  decimals: integer("decimals").notNull(),
61
65
  displayName: text("display_name").notNull(),
@@ -65,9 +69,46 @@ export const paymentMethods = pgTable("payment_methods", {
65
69
  oracleAddress: text("oracle_address"), // Chainlink feed address for price (null = 1:1 stablecoin)
66
70
  xpub: text("xpub"), // HD wallet extended public key for deposit address derivation
67
71
  confirmations: integer("confirmations").notNull().default(1),
72
+ nextIndex: integer("next_index").notNull().default(0), // atomic derivation counter, never reuses
68
73
  createdAt: text("created_at").notNull().default(sql`(now())`),
69
74
  });
70
75
 
76
+ /**
77
+ * BIP-44 path allocation registry — tracks which derivation paths are in use.
78
+ * The server knows which paths are allocated so you never collide.
79
+ * The seed phrase never touches the server — only xpubs.
80
+ */
81
+ export const pathAllocations = pgTable(
82
+ "path_allocations",
83
+ {
84
+ coinType: integer("coin_type").notNull(), // BIP44 coin type (0=BTC, 60=ETH, 3=DOGE, 501=SOL)
85
+ accountIndex: integer("account_index").notNull(), // m/44'/{coin_type}'/{index}'
86
+ chainId: text("chain_id").references(() => paymentMethods.id),
87
+ xpub: text("xpub").notNull(),
88
+ allocatedAt: text("allocated_at").notNull().default(sql`(now())`),
89
+ },
90
+ (table) => [primaryKey({ columns: [table.coinType, table.accountIndex] })],
91
+ );
92
+
93
+ /**
94
+ * Every address ever derived — immutable append-only log.
95
+ * Used for auditing and ensuring no address is ever reused.
96
+ */
97
+ export const derivedAddresses = pgTable(
98
+ "derived_addresses",
99
+ {
100
+ id: integer("id").primaryKey().generatedAlwaysAsIdentity(),
101
+ chainId: text("chain_id")
102
+ .notNull()
103
+ .references(() => paymentMethods.id),
104
+ derivationIndex: integer("derivation_index").notNull(),
105
+ address: text("address").notNull().unique(),
106
+ tenantId: text("tenant_id"),
107
+ createdAt: text("created_at").notNull().default(sql`(now())`),
108
+ },
109
+ (table) => [index("idx_derived_addresses_chain").on(table.chainId)],
110
+ );
111
+
71
112
  /** Processed transaction IDs for watchers without block cursors (e.g. BTC). */
72
113
  export const watcherProcessed = pgTable(
73
114
  "watcher_processed",