zklicensing 0.1.0-beta.2 → 0.1.0-beta.4

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 (173) hide show
  1. package/README.md +335 -97
  2. package/build/appsLookup.d.ts +14 -0
  3. package/build/appsLookup.d.ts.map +1 -0
  4. package/build/appsLookup.js +12 -0
  5. package/build/appsLookup.js.map +1 -0
  6. package/build/archiveBootstrap.d.ts +15 -1
  7. package/build/archiveBootstrap.d.ts.map +1 -0
  8. package/build/archiveBootstrap.js +62 -9
  9. package/build/archiveBootstrap.js.map +1 -0
  10. package/build/bindClient.d.ts +51 -0
  11. package/build/bindClient.d.ts.map +1 -0
  12. package/build/bindClient.js +115 -0
  13. package/build/bindClient.js.map +1 -0
  14. package/build/buyClient.d.ts +10 -3
  15. package/build/buyClient.d.ts.map +1 -0
  16. package/build/buyClient.js +33 -15
  17. package/build/buyClient.js.map +1 -0
  18. package/build/contractInterface.d.ts +11 -5
  19. package/build/contractInterface.d.ts.map +1 -0
  20. package/build/contractInterface.js +82 -17
  21. package/build/contractInterface.js.map +1 -0
  22. package/build/countryStats.d.ts +6 -1
  23. package/build/countryStats.d.ts.map +1 -0
  24. package/build/countryStats.js +33 -9
  25. package/build/countryStats.js.map +1 -0
  26. package/build/deployClient.d.ts.map +1 -0
  27. package/build/deployClient.js +1 -1
  28. package/build/deployClient.js.map +1 -0
  29. package/build/deviceIdentity.d.ts +68 -0
  30. package/build/deviceIdentity.d.ts.map +1 -0
  31. package/build/deviceIdentity.js +209 -0
  32. package/build/deviceIdentity.js.map +1 -0
  33. package/build/freezeClient.d.ts.map +1 -0
  34. package/build/freezeClient.js +1 -1
  35. package/build/freezeClient.js.map +1 -0
  36. package/build/generationClient.d.ts +1 -0
  37. package/build/generationClient.d.ts.map +1 -0
  38. package/build/generationClient.js +2 -2
  39. package/build/generationClient.js.map +1 -0
  40. package/build/index.d.ts +27 -37
  41. package/build/index.d.ts.map +1 -0
  42. package/build/index.js +85 -116
  43. package/build/index.js.map +1 -0
  44. package/build/licenseLeaf.d.ts +76 -0
  45. package/build/licenseLeaf.d.ts.map +1 -0
  46. package/build/licenseLeaf.js +189 -0
  47. package/build/licenseLeaf.js.map +1 -0
  48. package/build/licenseRecord.d.ts +20 -1
  49. package/build/licenseRecord.d.ts.map +1 -0
  50. package/build/licenseRecord.js +1 -1
  51. package/build/licenseRecord.js.map +1 -0
  52. package/build/licenseStore.d.ts +17 -2
  53. package/build/licenseStore.d.ts.map +1 -0
  54. package/build/licenseStore.js +167 -7
  55. package/build/licenseStore.js.map +1 -0
  56. package/build/manifestVerify.d.ts.map +1 -0
  57. package/build/manifestVerify.js +8 -3
  58. package/build/manifestVerify.js.map +1 -0
  59. package/build/migrateClient.d.ts +6 -21
  60. package/build/migrateClient.d.ts.map +1 -0
  61. package/build/migrateClient.js +30 -17
  62. package/build/migrateClient.js.map +1 -0
  63. package/build/onChainRoot.d.ts +67 -0
  64. package/build/onChainRoot.d.ts.map +1 -0
  65. package/build/onChainRoot.js +87 -0
  66. package/build/onChainRoot.js.map +1 -0
  67. package/build/ownershipLicenseHash.d.ts +25 -0
  68. package/build/ownershipLicenseHash.d.ts.map +1 -0
  69. package/build/ownershipLicenseHash.js +29 -0
  70. package/build/ownershipLicenseHash.js.map +1 -0
  71. package/build/ownershipSignature.d.ts +122 -0
  72. package/build/ownershipSignature.d.ts.map +1 -0
  73. package/build/ownershipSignature.js +244 -0
  74. package/build/ownershipSignature.js.map +1 -0
  75. package/build/proveErrors.d.ts +35 -0
  76. package/build/proveErrors.d.ts.map +1 -0
  77. package/build/proveErrors.js +49 -0
  78. package/build/proveErrors.js.map +1 -0
  79. package/build/refundClient.d.ts +2 -11
  80. package/build/refundClient.d.ts.map +1 -0
  81. package/build/refundClient.js +35 -17
  82. package/build/refundClient.js.map +1 -0
  83. package/build/renewClient.d.ts +4 -1
  84. package/build/renewClient.d.ts.map +1 -0
  85. package/build/renewClient.js +11 -4
  86. package/build/renewClient.js.map +1 -0
  87. package/build/seatName.d.ts +8 -0
  88. package/build/seatName.d.ts.map +1 -0
  89. package/build/seatName.js +136 -0
  90. package/build/seatName.js.map +1 -0
  91. package/build/statsClient.d.ts +47 -4
  92. package/build/statsClient.d.ts.map +1 -0
  93. package/build/statsClient.js +44 -5
  94. package/build/statsClient.js.map +1 -0
  95. package/build/trustAnchorVerify.d.ts +48 -0
  96. package/build/trustAnchorVerify.d.ts.map +1 -0
  97. package/build/trustAnchorVerify.js +431 -0
  98. package/build/trustAnchorVerify.js.map +1 -0
  99. package/build/trustAnchorVerifyCli.d.ts +35 -0
  100. package/build/trustAnchorVerifyCli.d.ts.map +1 -0
  101. package/build/trustAnchorVerifyCli.js +177 -0
  102. package/build/trustAnchorVerifyCli.js.map +1 -0
  103. package/build/txBroadcastClient.d.ts +26 -0
  104. package/build/txBroadcastClient.d.ts.map +1 -0
  105. package/build/txBroadcastClient.js +20 -0
  106. package/build/txBroadcastClient.js.map +1 -0
  107. package/build/unbindClient.d.ts +56 -0
  108. package/build/unbindClient.d.ts.map +1 -0
  109. package/build/unbindClient.js +113 -0
  110. package/build/unbindClient.js.map +1 -0
  111. package/build/vendorAccountClient.d.ts +56 -0
  112. package/build/vendorAccountClient.d.ts.map +1 -0
  113. package/build/vendorAccountClient.js +47 -0
  114. package/build/vendorAccountClient.js.map +1 -0
  115. package/build/verifyCore.d.ts +1 -1
  116. package/build/verifyCore.d.ts.map +1 -0
  117. package/build/verifyCore.js +11 -4
  118. package/build/verifyCore.js.map +1 -0
  119. package/build/verifyOffline.d.ts +85 -0
  120. package/build/verifyOffline.d.ts.map +1 -0
  121. package/build/verifyOffline.js +139 -0
  122. package/build/verifyOffline.js.map +1 -0
  123. package/build/verifyService.d.ts.map +1 -0
  124. package/build/verifyService.js +582 -455
  125. package/build/verifyService.js.map +1 -0
  126. package/build/verifyWithAncestors.d.ts +18 -0
  127. package/build/verifyWithAncestors.d.ts.map +1 -0
  128. package/build/verifyWithAncestors.js +119 -0
  129. package/build/verifyWithAncestors.js.map +1 -0
  130. package/build/zipToState.d.ts +2 -0
  131. package/build/zipToState.d.ts.map +1 -0
  132. package/build/zipToState.js +94 -0
  133. package/build/zipToState.js.map +1 -0
  134. package/package.json +57 -13
  135. package/src/appsLookup.ts +48 -0
  136. package/src/archiveBootstrap.ts +342 -0
  137. package/src/bindClient.ts +175 -0
  138. package/src/buyClient.ts +304 -0
  139. package/src/contractInterface.d.ts +61 -0
  140. package/src/contractInterface.ts +313 -0
  141. package/src/countryStats.ts +171 -0
  142. package/src/deployClient.ts +388 -0
  143. package/src/deviceIdentity.ts +249 -0
  144. package/src/freezeClient.ts +117 -0
  145. package/src/generationClient.ts +165 -0
  146. package/src/index.ts +329 -0
  147. package/src/licenseLeaf.ts +221 -0
  148. package/src/licenseRecord.ts +108 -0
  149. package/src/licenseStore.ts +538 -0
  150. package/src/manifestVerify.ts +111 -0
  151. package/src/migrateClient.ts +84 -0
  152. package/src/onChainRoot.ts +107 -0
  153. package/src/ownershipLicenseHash.ts +31 -0
  154. package/src/ownershipSignature.ts +354 -0
  155. package/src/proveErrors.ts +70 -0
  156. package/src/refundClient.ts +158 -0
  157. package/src/renewClient.ts +214 -0
  158. package/src/seatName.ts +165 -0
  159. package/src/statsClient.ts +235 -0
  160. package/src/trustAnchorVerify.ts +548 -0
  161. package/src/trustAnchorVerifyCli.ts +179 -0
  162. package/src/txBroadcastClient.ts +48 -0
  163. package/src/unbindClient.ts +149 -0
  164. package/src/vendorAccountClient.ts +110 -0
  165. package/src/verifyCore.ts +92 -0
  166. package/src/verifyOffline.ts +212 -0
  167. package/src/verifyService.ts +969 -0
  168. package/src/verifyWithAncestors.ts +153 -0
  169. package/src/zipToState.ts +94 -0
  170. package/build/licenseProof.d.ts +0 -26
  171. package/build/licenseProof.js +0 -41
  172. package/build/ownership.d.ts +0 -34
  173. package/build/ownership.js +0 -147
@@ -0,0 +1,171 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * countryStats.ts
6
+ *
7
+ * Buyer-country breakdown of a vendor's revenue, bucketed by UTC calendar year.
8
+ * Structured for tax reporting: one row per (year, appId, countryCode) with
9
+ * license count + the vendor's cut in MINA. Both the keeper (source of
10
+ * truth for /stats) and the dashboard UI import from here so the numbers can
11
+ * never drift between them.
12
+ *
13
+ * Purchases attribute to the year the buyer confirmed on-chain (LicenseRecord
14
+ * `createdAt` ISO timestamp). Legacy records that predate `createdAt` fall
15
+ * back to slot-derived time. Renewals attribute to the renewal year via
16
+ * `renewals[i].slot → time`. Refunded purchases contribute zero revenue but
17
+ * still count the license (a purchase happened even if the money was
18
+ * returned) — remove `count` from refunded rows client-side if you want a
19
+ * strictly net view.
20
+ *
21
+ * Browser-safe: pure computation, no fs, no fetch.
22
+ */
23
+
24
+ import type { LicenseRecord } from './licenseRecord.js';
25
+ import { zipToState } from './zipToState.js';
26
+
27
+ export { zipToState } from './zipToState.js';
28
+
29
+ // LicensingApp charges a 2 % platform fee (200 basis points); the vendor
30
+ // receives the remaining 9 800 bps. Keep this in sync with the on-chain
31
+ // constant in LicensingApp.
32
+ const PLATFORM_FEE_BASIS_POINTS = 200n;
33
+ const VENDOR_BPS = 10_000n - PLATFORM_FEE_BASIS_POINTS;
34
+
35
+ // 90 s/slot post-Mesa. Used only for slot→time fallback attribution.
36
+ const SLOT_DURATION_MS = 90_000;
37
+
38
+ export type CountryBucket = {
39
+ count: number; // licenses purchased by buyers from this country (renewals don't bump)
40
+ revenueMina: number; // vendor cut in MINA — purchase + renewals combined
41
+ // State sub-buckets — populated only for US buyers, derived from
42
+ // `buyerZip` via zipToState. States are the jurisdictional unit that US
43
+ // sales-tax filings care about; the raw ZIP stays on the LicenseRecord
44
+ // for audit trail but isn't rolled up here. Missing entirely on non-US
45
+ // rows; may be missing on US rows for legacy records that predate ZIP
46
+ // capture or whose ZIP prefix doesn't resolve to a state.
47
+ states?: Record<string, { count: number; revenueMina: number }>;
48
+ };
49
+ export type CountryYearBreakdown = {
50
+ aggregate: Record<string, CountryBucket>; // keyed by ISO-alpha-2 (or '??' when missing)
51
+ byApp: Record<string, Record<string, CountryBucket>>; // appId → country → bucket
52
+ };
53
+ export type CountryBreakdown = {
54
+ years: number[]; // UTC calendar years with activity, most-recent first
55
+ byYear: Record<number, CountryYearBreakdown>;
56
+ };
57
+
58
+ // tzOffsetMinutes: signed minutes east of UTC (e.g. +60 for CET, -480 for PST).
59
+ // Purchase/renewal timestamps are shifted by this offset before extracting the
60
+ // calendar year, so the "tax year" cut-over aligns with the operator's local
61
+ // clock instead of hardcoded UTC. Defaults to 0 (UTC) for callers who don't
62
+ // pass it — preserves the pre-tz behavior.
63
+ export function computeCountryBreakdown(
64
+ apps: { appId: string; zkAppAddress: string }[],
65
+ records: LicenseRecord[],
66
+ currentSlot: number,
67
+ nowMs: number,
68
+ tzOffsetMinutes: number = 0,
69
+ ): CountryBreakdown {
70
+ const appByAddress = new Map(apps.map(a => [a.zkAppAddress, a.appId] as const));
71
+ const byYear: Record<number, CountryYearBreakdown> = {};
72
+ const yearSet = new Set<number>();
73
+ const tzShiftMs = tzOffsetMinutes * 60_000;
74
+
75
+ const ensureYear = (year: number): CountryYearBreakdown => {
76
+ let yb = byYear[year];
77
+ if (!yb) {
78
+ yb = { aggregate: {}, byApp: {} };
79
+ byYear[year] = yb;
80
+ yearSet.add(year);
81
+ }
82
+ return yb;
83
+ };
84
+ const ensureAppBucket = (yb: CountryYearBreakdown, appId: string): Record<string, CountryBucket> => {
85
+ let ab = yb.byApp[appId];
86
+ if (!ab) {
87
+ ab = {};
88
+ yb.byApp[appId] = ab;
89
+ }
90
+ return ab;
91
+ };
92
+ const add = (
93
+ bucket: Record<string, CountryBucket>,
94
+ code: string,
95
+ count: number,
96
+ revenueNano: bigint,
97
+ state?: string,
98
+ ): void => {
99
+ let b = bucket[code];
100
+ if (!b) {
101
+ b = { count: 0, revenueMina: 0 };
102
+ bucket[code] = b;
103
+ }
104
+ b.count += count;
105
+ b.revenueMina += Number(revenueNano) / 1e9;
106
+ // State sub-bucket only for US rows whose ZIP resolved to a state.
107
+ // Non-US or unresolvable rows just add to the country total.
108
+ if (code === 'US' && state) {
109
+ const states = b.states ?? (b.states = {});
110
+ let sb = states[state];
111
+ if (!sb) {
112
+ sb = { count: 0, revenueMina: 0 };
113
+ states[state] = sb;
114
+ }
115
+ sb.count += count;
116
+ sb.revenueMina += Number(revenueNano) / 1e9;
117
+ }
118
+ };
119
+ const slotToYear = (slot: number): number | null => {
120
+ if (currentSlot <= 0) return null;
121
+ const ms = nowMs - (currentSlot - slot) * SLOT_DURATION_MS;
122
+ const y = new Date(ms + tzShiftMs).getUTCFullYear();
123
+ return Number.isFinite(y) ? y : null;
124
+ };
125
+
126
+ for (const r of records) {
127
+ const appId = appByAddress.get(r.zkAppAddress);
128
+ if (!appId) continue;
129
+ const country = r.buyerCountry && /^[A-Z]{2}$/.test(r.buyerCountry) ? r.buyerCountry : '??';
130
+ // Only US rows carry a meaningful ZIP for sales-tax purposes; derive
131
+ // the state jurisdiction here and let `add` roll it up. Non-US ZIPs
132
+ // and unresolvable prefixes fall through to country-total only.
133
+ const state = country === 'US' && r.buyerZip ? zipToState(r.buyerZip) : undefined;
134
+
135
+ // Purchase — attribute to the year of confirm-on-chain (createdAt).
136
+ // Fallback: slot-derived time for legacy records that lack createdAt.
137
+ let purchaseYear: number | null = null;
138
+ if (r.createdAt) {
139
+ const y = new Date(new Date(r.createdAt).getTime() + tzShiftMs).getUTCFullYear();
140
+ if (Number.isFinite(y)) purchaseYear = y;
141
+ }
142
+ if (purchaseYear === null && r.purchaseSlot > 0) {
143
+ purchaseYear = slotToYear(r.purchaseSlot);
144
+ }
145
+ if (purchaseYear !== null) {
146
+ const yb = ensureYear(purchaseYear);
147
+ const ab = ensureAppBucket(yb, appId);
148
+ const purchaseCut = (!r.refunded && r.purchaseAmount && r.purchaseAmount !== '0')
149
+ ? (BigInt(r.purchaseAmount) * VENDOR_BPS) / 10_000n
150
+ : 0n;
151
+ add(ab, country, 1, purchaseCut, state);
152
+ add(yb.aggregate, country, 1, purchaseCut, state);
153
+ }
154
+
155
+ // Renewals — revenue only (no license count), attributed to renewal year.
156
+ for (const rn of r.renewals ?? []) {
157
+ const y = slotToYear(rn.slot);
158
+ if (y === null) continue;
159
+ const yb = ensureYear(y);
160
+ const ab = ensureAppBucket(yb, appId);
161
+ const cut = (BigInt(rn.amount) * VENDOR_BPS) / 10_000n;
162
+ add(ab, country, 0, cut, state);
163
+ add(yb.aggregate, country, 0, cut, state);
164
+ }
165
+ }
166
+
167
+ return {
168
+ years: Array.from(yearSet).sort((a, b) => b - a),
169
+ byYear,
170
+ };
171
+ }
@@ -0,0 +1,388 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * deployClient.ts
6
+ *
7
+ * Browser-safe client for the deploy flow. Mirrors the buy / renew / refund
8
+ * client shape: `proveDeploy` posts to the keeper's `/prove/deploy` endpoint
9
+ * and returns the atomic deploy+initialize tx already signed with the
10
+ * throwaway zkApp key. The vendor's wallet then adds the fee-payer signature
11
+ * and broadcasts.
12
+ *
13
+ * The atomic bundling is what makes single-shot initialization safe:
14
+ * `provenTxJson` holds both `zkApp.deploy()` and `zkApp.initialize()`
15
+ * AccountUpdates in the same transaction, and the keeper generates a
16
+ * throwaway zkApp keypair per request that is discarded before the tx is
17
+ * returned — so the target address is not observable to an attacker until
18
+ * the initialize AU inside is already signed and locked to `(vendor,
19
+ * prices)`. Combined with the in-circuit `vendor.requireEquals(empty())`
20
+ * precondition on `initialize()`, this yields a one-shot init per account.
21
+ *
22
+ * Also exports admin-side `redeployApp` / `redeployAll` for the platform
23
+ * operator to trigger post-hardfork v1→v2 migrations via the keeper's
24
+ * `/admin/redeploy*` endpoints (bearer-token auth).
25
+ */
26
+
27
+ export type ProveDeployRequest = {
28
+ keeperUrl: string;
29
+ senderPublicKey: string; // vendor's fee-payer wallet
30
+ vendorAddress: string; // owner slot; may equal senderPublicKey
31
+ priceMonthlyMina: number;
32
+ priceYearlyMina: number;
33
+ priceFiveYearMina: number;
34
+ fetcher?: typeof fetch;
35
+ signal?: AbortSignal;
36
+ };
37
+
38
+ export type ProveDeployResponse = {
39
+ provenTxJson: string;
40
+ verificationKeyHash: string;
41
+ zkAppAddress: string;
42
+ };
43
+
44
+ export type DeployStatus = {
45
+ status: 'unknown' | 'pending' | 'confirmed' | 'failed';
46
+ landedAtSlot?: number;
47
+ elapsedMs?: number;
48
+ };
49
+
50
+ function baseUrl(url: string): string {
51
+ return url.replace(/\/+$/, '');
52
+ }
53
+
54
+ async function readJsonError(resp: Response): Promise<string> {
55
+ try {
56
+ const body = await resp.json() as Record<string, unknown>;
57
+ if (typeof body.error === 'string') return body.error;
58
+ } catch { /* body wasn't JSON */ }
59
+ return `HTTP ${resp.status}`;
60
+ }
61
+
62
+ // POST /prove/deploy — keeper generates the throwaway zkApp keypair, assembles
63
+ // the deploy+initialize tx, proves it, and signs the zkApp AccountUpdate with
64
+ // the throwaway key. The caller forwards `provenTxJson` to the vendor's wallet
65
+ // for the fee-payer signature.
66
+ //
67
+ // At least one of the three prices must be > 0 (enforced by the keeper *and*
68
+ // by the circuit's `initialize()`).
69
+ export async function proveDeploy(req: ProveDeployRequest): Promise<ProveDeployResponse> {
70
+ const fetcher = req.fetcher ?? fetch;
71
+ const resp = await fetcher(`${baseUrl(req.keeperUrl)}/prove/deploy`, {
72
+ method: 'POST',
73
+ headers: { 'Content-Type': 'application/json' },
74
+ signal: req.signal,
75
+ body: JSON.stringify({
76
+ senderPublicKey: req.senderPublicKey,
77
+ vendorAddress: req.vendorAddress,
78
+ priceMonthlyMina: req.priceMonthlyMina,
79
+ priceYearlyMina: req.priceYearlyMina,
80
+ priceFiveYearMina: req.priceFiveYearMina,
81
+ }),
82
+ });
83
+ if (!resp.ok) throw new Error(await readJsonError(resp));
84
+ return await resp.json() as ProveDeployResponse;
85
+ }
86
+
87
+ export type PollDeployStatusOptions = {
88
+ keeperUrl: string;
89
+ zkAppAddress: string;
90
+ fetcher?: typeof fetch;
91
+ intervalMs?: number; // default 3 000
92
+ timeoutMs?: number; // default 10 min
93
+ signal?: AbortSignal;
94
+ onTick?: (status: DeployStatus) => void;
95
+ };
96
+
97
+ // Polls GET /deploy/status until it returns a terminal state ('confirmed' or
98
+ // 'failed') or the timeout fires. 'unknown' means the keeper hasn't seen the
99
+ // tx yet (register step not called or watch not armed).
100
+ export async function pollDeployStatus(opts: PollDeployStatusOptions): Promise<DeployStatus> {
101
+ const fetcher = opts.fetcher ?? fetch;
102
+ const interval = opts.intervalMs ?? 3_000;
103
+ const timeout = opts.timeoutMs ?? 10 * 60 * 1000;
104
+ const deadline = Date.now() + timeout;
105
+ const url = `${baseUrl(opts.keeperUrl)}/deploy/status?zkAppAddress=${encodeURIComponent(opts.zkAppAddress)}`;
106
+
107
+ while (true) {
108
+ if (opts.signal?.aborted) throw new Error('pollDeployStatus aborted');
109
+ let status: DeployStatus = { status: 'unknown' };
110
+ try {
111
+ const resp = await fetcher(url, { signal: opts.signal });
112
+ if (resp.ok) status = await resp.json() as DeployStatus;
113
+ } catch { /* transient network — try again on next tick */ }
114
+ opts.onTick?.(status);
115
+ if (status.status === 'confirmed' || status.status === 'failed') return status;
116
+ if (Date.now() >= deadline) return status;
117
+ await new Promise<void>((r) => setTimeout(r, interval));
118
+ }
119
+ }
120
+
121
+ // ─── Admin redeploy (post-hardfork v1 → v2 migration) ────────────────────────
122
+ //
123
+ // Wraps the keeper's `/admin/redeploy*` endpoints. These are platform-operator
124
+ // tools — the keeper pays gas with its own FEEPAYER_KEY and reads authoritative
125
+ // vendor/prices from the on-chain v1 contract, so the caller supplies no
126
+ // per-app parameters. Guards enforced keeper-side: refund window closed,
127
+ // escrow empty, on-chain version still in supported range. Auth is
128
+ // KEEPER_ADMIN_TOKEN as a Bearer header.
129
+
130
+ export type RedeployAppRequest = {
131
+ keeperUrl: string;
132
+ appId: string;
133
+ adminToken: string;
134
+ // Bypass the `escrowRoot === EMPTY_ROOT` guard. Other guards (refund
135
+ // window, app status, on-chain version, keeper key configuration) are not
136
+ // bypassable. Buyers with unrefunded escrow can still call requestRefund
137
+ // against the retired v1 address directly (its on-chain state persists).
138
+ force?: boolean;
139
+ fetcher?: typeof fetch;
140
+ signal?: AbortSignal;
141
+ };
142
+
143
+ export type RedeployAppResponse = {
144
+ ok: true;
145
+ zkAppAddress: string;
146
+ txHash: string;
147
+ verificationKeyHash: string;
148
+ onChainVersion: number;
149
+ // Present (=== true) when `force: true` was used and the v1 escrowRoot was
150
+ // non-empty at the time of redeploy. Absent otherwise.
151
+ forcedEscrowNonEmpty?: true;
152
+ };
153
+
154
+ export type RedeployAllRequest = {
155
+ keeperUrl: string;
156
+ adminToken: string;
157
+ // Applied uniformly to every app in the batch. See RedeployAppRequest.force.
158
+ force?: boolean;
159
+ fetcher?: typeof fetch;
160
+ signal?: AbortSignal;
161
+ };
162
+
163
+ export type RedeployAllResponse = {
164
+ ok: true;
165
+ count: number;
166
+ succeeded: number;
167
+ results: Array<
168
+ | { appId: string; ok: true; zkAppAddress: string; txHash: string; verificationKeyHash: string; onChainVersion: number; forcedEscrowNonEmpty?: true }
169
+ | { appId: string; ok: false; error: string }
170
+ >;
171
+ };
172
+
173
+ function adminHeaders(token: string): Record<string, string> {
174
+ return {
175
+ 'Content-Type': 'application/json',
176
+ 'Authorization': `Bearer ${token}`,
177
+ };
178
+ }
179
+
180
+ // POST /admin/redeploy/:appId — one-shot migration for a single app. Rejects
181
+ // with a descriptive error if any keeper-side guard fails (409) or the deploy
182
+ // itself throws (500). The returned `zkAppAddress` is the *new* v2 address; the
183
+ // old one stays on chain but is no longer referenced by keeper records.
184
+ export async function redeployApp(req: RedeployAppRequest): Promise<RedeployAppResponse> {
185
+ const fetcher = req.fetcher ?? fetch;
186
+ const resp = await fetcher(`${baseUrl(req.keeperUrl)}/admin/redeploy/${encodeURIComponent(req.appId)}`, {
187
+ method: 'POST',
188
+ headers: adminHeaders(req.adminToken),
189
+ signal: req.signal,
190
+ body: JSON.stringify(req.force ? { force: true } : {}),
191
+ });
192
+ if (!resp.ok) throw new Error(await readJsonError(resp));
193
+ return await resp.json() as RedeployAppResponse;
194
+ }
195
+
196
+ // POST /admin/redeploy-all — iterate every registered app and attempt migration.
197
+ // Idempotent: apps already migrated surface as ok:false with a clear error, so
198
+ // a rerun after a partial failure retries only the remaining ones. Callers
199
+ // should inspect `results` for per-app outcomes rather than relying on the
200
+ // top-level `ok`, which is always true unless the whole request failed.
201
+ export async function redeployAll(req: RedeployAllRequest): Promise<RedeployAllResponse> {
202
+ const fetcher = req.fetcher ?? fetch;
203
+ const resp = await fetcher(`${baseUrl(req.keeperUrl)}/admin/redeploy-all`, {
204
+ method: 'POST',
205
+ headers: adminHeaders(req.adminToken),
206
+ signal: req.signal,
207
+ body: JSON.stringify(req.force ? { force: true } : {}),
208
+ });
209
+ if (!resp.ok) throw new Error(await readJsonError(resp));
210
+ return await resp.json() as RedeployAllResponse;
211
+ }
212
+
213
+ // ─── Vendor-triggered redeploy (post-hardfork v1 → v2 migration) ─────────────
214
+ //
215
+ // Same migration flow as the admin path, but authenticated by a Mina signature
216
+ // against the on-chain vendor of the target app (no admin token required).
217
+ // Vendor pays gas via their own fee-payer AU. Three-step flow, mirroring
218
+ // first-time /prove/deploy → wallet-broadcast → /apps register:
219
+ //
220
+ // 1. getVendorRedeployChallenge → { nonce, expiresAt }
221
+ // 2. vendor's wallet signs `nonce` → { field, scalar }
222
+ // 3. proveVendorRedeploy → { provenTxJson, zkAppAddress, redeployId }
223
+ // 4. wallet adds fee-payer sig + broadcasts (mirrors proveDeploy flow)
224
+ // 5. registerVendorRedeploy → arms the keeper's deploy-watcher on
225
+ // the new address. On landing, keeper
226
+ // promotes the new deployment onto the
227
+ // AppRecord (deploymentHistory[] etc).
228
+ //
229
+ // `force: true` is allowed on the vendor path (same semantics as admin —
230
+ // bypasses the escrow-empty guard; unrefunded buyers retain the v1 refund
231
+ // path against the retired address). All other guards (freeze slot
232
+ // configured, refund window closed, active status, supported version) apply.
233
+ //
234
+ // ⚠ Vendor-embedded buy links — after redeploy, `proveVendorRedeploy` returns
235
+ // the NEW v2 `zkAppAddress`. Platform-hosted marketplace pages handle this
236
+ // automatically: the marketplace stores your registered `buyUrl`/`renewUrl`/
237
+ // `refundUrl` as base URLs and appends `?app=<zkAppAddress>&network=<net>`
238
+ // at render time, so the "Get" button routes to the new v2 address the
239
+ // moment `finalizeRedeploy` promotes it onto the AppRecord — no vendor
240
+ // action required. Only vendor-hosted surfaces where the raw `zkAppAddress`
241
+ // is hand-embedded (docs, storefront, emails) need manual updating.
242
+ // Existing licenses on the retired v1 address remain independently
243
+ // verifiable (v1 on-chain state persists), but new buys against the old URL
244
+ // would land on the retired contract and be refused (its v1 version is
245
+ // outside the supported range
246
+ // after migration).
247
+
248
+ export type VendorRedeployPreflight = {
249
+ // True iff the vendor path can proceed without `force`. Escrow non-empty is
250
+ // NOT part of `ok`: the button should still be actionable with a
251
+ // force-required warning when the only failing guard is escrow.
252
+ ok: boolean;
253
+ freezeSlotConfigured: boolean;
254
+ appExists: boolean;
255
+ status?: 'active' | 'inactive' | 'pending';
256
+ refundWindow: { closed: boolean; opensAtSlot: number; currentSlot: number };
257
+ onChainAccount: { exists: boolean };
258
+ // `empty: false` alone does not disqualify the redeploy — `force: true` on
259
+ // /prove bypasses this guard. UIs should surface the state as a warning.
260
+ escrow: { empty: boolean };
261
+ version: { current: number; supported: boolean; supportedList: readonly number[] };
262
+ // Human-readable reasons for every failing guard, in evaluation order. Empty
263
+ // array iff every guard passes and no force is needed.
264
+ reasons: string[];
265
+ };
266
+
267
+ // GET /vendor/redeploy/:appId/preflight — read-only guard status. No nonce
268
+ // consumed, no signature required. UI decides button state from the returned
269
+ // fields; 404 means the app itself is unknown (a distinct failure mode from a
270
+ // known app failing individual guards).
271
+ export async function fetchVendorRedeployPreflight(opts: {
272
+ keeperUrl: string;
273
+ appId: string;
274
+ fetcher?: typeof fetch;
275
+ signal?: AbortSignal;
276
+ }): Promise<VendorRedeployPreflight> {
277
+ const fetcher = opts.fetcher ?? fetch;
278
+ const resp = await fetcher(`${baseUrl(opts.keeperUrl)}/vendor/redeploy/${encodeURIComponent(opts.appId)}/preflight`, {
279
+ signal: opts.signal,
280
+ });
281
+ if (!resp.ok) throw new Error(await readJsonError(resp));
282
+ return await resp.json() as VendorRedeployPreflight;
283
+ }
284
+
285
+ export type VendorRedeployChallenge = {
286
+ nonce: string;
287
+ expiresAt: number; // ms epoch
288
+ };
289
+
290
+ // GET /vendor/redeploy/:appId/challenge — mint a one-shot nonce that the
291
+ // vendor's wallet signs. The nonce is bound to the appId and expires in 60s;
292
+ // consumed on /prove.
293
+ export async function getVendorRedeployChallenge(opts: {
294
+ keeperUrl: string;
295
+ appId: string;
296
+ fetcher?: typeof fetch;
297
+ signal?: AbortSignal;
298
+ }): Promise<VendorRedeployChallenge> {
299
+ const fetcher = opts.fetcher ?? fetch;
300
+ const resp = await fetcher(`${baseUrl(opts.keeperUrl)}/vendor/redeploy/${encodeURIComponent(opts.appId)}/challenge`, {
301
+ signal: opts.signal,
302
+ });
303
+ if (!resp.ok) throw new Error(await readJsonError(resp));
304
+ return await resp.json() as VendorRedeployChallenge;
305
+ }
306
+
307
+ export type ProveVendorRedeployRequest = {
308
+ keeperUrl: string;
309
+ appId: string;
310
+ nonce: string;
311
+ signature: { field: string; scalar: string };
312
+ senderPublicKey: string; // vendor's fee-payer wallet
313
+ // Bypass the `escrowRoot === EMPTY_ROOT` guard. Unlike the admin path this
314
+ // is available to the vendor as well — in case the freeze is scheduled
315
+ // late enough that a straggling refund is still pending when they want to
316
+ // migrate. Buyers with unrefunded escrow can still call requestRefund
317
+ // against the retired v1 address directly (its on-chain state persists).
318
+ force?: boolean;
319
+ fetcher?: typeof fetch;
320
+ signal?: AbortSignal;
321
+ };
322
+
323
+ export type ProveVendorRedeployResponse = {
324
+ provenTxJson: string;
325
+ // New v2 zkApp address (fresh throwaway keypair, discarded by the keeper).
326
+ // Marketplace links auto-update: the platform appends `?app=<zkAppAddress>
327
+ // &network=<net>` to your registered `buyUrl`/`renewUrl`/`refundUrl` at
328
+ // render time, so the "Get" button routes to this new address once
329
+ // `finalizeRedeploy` promotes it onto the AppRecord — no vendor action
330
+ // required. Only vendor-hosted surfaces where the raw address is embedded
331
+ // by hand need manual updating.
332
+ zkAppAddress: string;
333
+ verificationKeyHash: string;
334
+ redeployId: string; // capability token — pass to registerVendorRedeploy
335
+ // Present (=== true) when `force: true` was used and the v1 escrowRoot was
336
+ // non-empty at the time of the prove call. Absent otherwise.
337
+ forcedEscrowNonEmpty?: true;
338
+ };
339
+
340
+ // POST /vendor/redeploy/:appId/prove — keeper verifies the nonce + signature
341
+ // against the on-chain vendor of the app, runs all redeploy guards, generates
342
+ // a throwaway zkApp keypair, builds and proves the deploy+initialize tx, and
343
+ // signs the zkApp AU with the throwaway key. Returns the tx JSON for the
344
+ // vendor's wallet to add the fee-payer signature and broadcast.
345
+ export async function proveVendorRedeploy(req: ProveVendorRedeployRequest): Promise<ProveVendorRedeployResponse> {
346
+ const fetcher = req.fetcher ?? fetch;
347
+ const resp = await fetcher(`${baseUrl(req.keeperUrl)}/vendor/redeploy/${encodeURIComponent(req.appId)}/prove`, {
348
+ method: 'POST',
349
+ headers: { 'Content-Type': 'application/json' },
350
+ signal: req.signal,
351
+ body: JSON.stringify({
352
+ nonce: req.nonce,
353
+ signature: req.signature,
354
+ senderPublicKey: req.senderPublicKey,
355
+ ...(req.force ? { force: true } : {}),
356
+ }),
357
+ });
358
+ if (!resp.ok) throw new Error(await readJsonError(resp));
359
+ return await resp.json() as ProveVendorRedeployResponse;
360
+ }
361
+
362
+ export type RegisterVendorRedeployRequest = {
363
+ keeperUrl: string;
364
+ appId: string;
365
+ redeployId: string; // capability token from proveVendorRedeploy
366
+ txHash: string; // returned by the vendor's wallet after broadcast
367
+ fetcher?: typeof fetch;
368
+ signal?: AbortSignal;
369
+ };
370
+
371
+ // POST /vendor/redeploy/:appId/register — arm the keeper's deploy-watcher on
372
+ // the new address. On confirmation the keeper mutates AppRecord to promote
373
+ // the new deployment (push old to deploymentHistory[], overwrite live fields,
374
+ // clear event-sync cursors). Idempotent to duplicate calls (the watcher
375
+ // checks whether one is already armed for the address). Poll GET
376
+ // /deploy/status?zkAppAddress=<new> — or use pollDeployStatus — for landing
377
+ // progress, same as first-time deploys.
378
+ export async function registerVendorRedeploy(req: RegisterVendorRedeployRequest): Promise<{ ok: true }> {
379
+ const fetcher = req.fetcher ?? fetch;
380
+ const resp = await fetcher(`${baseUrl(req.keeperUrl)}/vendor/redeploy/${encodeURIComponent(req.appId)}/register`, {
381
+ method: 'POST',
382
+ headers: { 'Content-Type': 'application/json' },
383
+ signal: req.signal,
384
+ body: JSON.stringify({ redeployId: req.redeployId, txHash: req.txHash }),
385
+ });
386
+ if (!resp.ok) throw new Error(await readJsonError(resp));
387
+ return await resp.json() as { ok: true };
388
+ }