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,158 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * refundClient.ts
6
+ *
7
+ * Browser-safe client for the refund flow. Mirrors `buyClient.ts` in shape:
8
+ * the caller drives the wallet step between `proveRefund` and
9
+ * `confirmRefund` so the SDK stays wallet-agnostic.
10
+ *
11
+ * The 14-day refund window is enforced on the keeper side (returns HTTP 409
12
+ * when closed) and cross-checked in the circuit; the SDK doesn't second-guess
13
+ * it locally so a single source of truth stays authoritative.
14
+ *
15
+ * `/prove/refund` shares the per-app in-flight slot with buy/renew/migrate:
16
+ * a concurrent request for the same app receives 409 { error: "proving queue
17
+ * busy", retryAfterMs, queueDepth }, which this client classifies into a
18
+ * `ProveQueueBusyError` so callers can wait+retry without opening a wallet.
19
+ */
20
+
21
+ import { readErrorBody, tryQueueBusyFromBody } from './proveErrors.js';
22
+
23
+ export type ProveRefundRequest = {
24
+ keeperUrl: string;
25
+ licenseHash: string;
26
+ buyerAddress: string;
27
+ zkAppAddress: string;
28
+ // Mina network this refund targets. Pull from your persisted ProofFile
29
+ // so it always matches the network the original buy was proved against.
30
+ network: 'devnet' | 'mainnet';
31
+ fetcher?: typeof fetch;
32
+ signal?: AbortSignal;
33
+ };
34
+
35
+ export type ProveRefundResponse = {
36
+ provenTxJson: string;
37
+ licenseHash: string;
38
+ };
39
+
40
+ export type ConfirmRefundRequest = {
41
+ keeperUrl: string;
42
+ zkAppAddress: string;
43
+ licenseHash: string;
44
+ txHash: string;
45
+ fetcher?: typeof fetch;
46
+ signal?: AbortSignal;
47
+ };
48
+
49
+ function baseUrl(url: string): string {
50
+ return url.replace(/\/+$/, '');
51
+ }
52
+
53
+ // POST /prove/refund — keeper compiles + proves the refund tx.
54
+ // The keeper 409s when the 14-day window has closed (surfaces through the
55
+ // thrown `Error` message) and also when the shared per-app in-flight slot
56
+ // is held by a concurrent buy/renew/migrate/refund (surfaces as a typed
57
+ // `ProveQueueBusyError` — caller waits `retryAfterMs` and retries).
58
+ export async function proveRefund(req: ProveRefundRequest): Promise<ProveRefundResponse> {
59
+ const fetcher = req.fetcher ?? fetch;
60
+ const resp = await fetcher(`${baseUrl(req.keeperUrl)}/prove/refund`, {
61
+ method: 'POST',
62
+ headers: { 'Content-Type': 'application/json' },
63
+ signal: req.signal,
64
+ body: JSON.stringify({
65
+ licenseHash: req.licenseHash,
66
+ buyerAddress: req.buyerAddress,
67
+ zkAppAddress: req.zkAppAddress,
68
+ network: req.network,
69
+ }),
70
+ });
71
+ if (!resp.ok) {
72
+ const parsed = await readErrorBody(resp);
73
+ const queueBusy = tryQueueBusyFromBody(parsed);
74
+ if (queueBusy) throw queueBusy;
75
+ throw new Error(parsed.message);
76
+ }
77
+ return await resp.json() as ProveRefundResponse;
78
+ }
79
+
80
+ // POST /confirm/refund — promotes the in-memory refund intent to a
81
+ // pending (refunded: true) LicenseRecord. Best-effort: if the caller
82
+ // swallows the failure, eventSyncLoop will still pick up the on-chain
83
+ // refund event.
84
+ export async function confirmRefund(req: ConfirmRefundRequest): Promise<{ ok: true }> {
85
+ const fetcher = req.fetcher ?? fetch;
86
+ const resp = await fetcher(`${baseUrl(req.keeperUrl)}/confirm/refund`, {
87
+ method: 'POST',
88
+ headers: { 'Content-Type': 'application/json' },
89
+ signal: req.signal,
90
+ body: JSON.stringify({
91
+ zkAppAddress: req.zkAppAddress,
92
+ licenseHash: req.licenseHash,
93
+ txHash: req.txHash,
94
+ }),
95
+ });
96
+ if (!resp.ok) {
97
+ const parsed = await readErrorBody(resp);
98
+ throw new Error(parsed.message);
99
+ }
100
+ return { ok: true };
101
+ }
102
+
103
+ export type RefundStatus = {
104
+ // 'confirmed' once the eventSync sweep has observed the refundIssued event
105
+ // on-chain (record.status flips to 'refunded'). 'pending' while the tx is
106
+ // in flight. 'unknown' if no record has been persisted yet.
107
+ status: 'confirmed' | 'pending' | 'unknown';
108
+ txHash?: string | null;
109
+ elapsedMs?: number;
110
+ };
111
+
112
+ export type PollRefundStatusOptions = {
113
+ keeperUrl: string;
114
+ network: 'devnet' | 'mainnet';
115
+ zkAppAddress: string;
116
+ licenseHash: string;
117
+ fetcher?: typeof fetch;
118
+ intervalMs?: number; // default 10 000
119
+ timeoutMs?: number; // default 20 min
120
+ signal?: AbortSignal;
121
+ onTick?: (status: RefundStatus) => void;
122
+ };
123
+
124
+ // Polls GET /license/:zkAppAddress/:licenseHash until the refund has landed
125
+ // on-chain (record.status === 'refunded') or the timeout fires. Mirrors
126
+ // pollBuyStatus / pollRenewStatus.
127
+ export async function pollRefundStatus(opts: PollRefundStatusOptions): Promise<RefundStatus> {
128
+ const fetcher = opts.fetcher ?? fetch;
129
+ const interval = opts.intervalMs ?? 10_000;
130
+ const timeout = opts.timeoutMs ?? 20 * 60 * 1000;
131
+ const startedAt = Date.now();
132
+ const deadline = startedAt + timeout;
133
+ const url = `${baseUrl(opts.keeperUrl)}/license/${encodeURIComponent(opts.zkAppAddress)}/${encodeURIComponent(opts.licenseHash)}?network=${opts.network}`;
134
+
135
+ while (true) {
136
+ if (opts.signal?.aborted) throw new Error('pollRefundStatus aborted');
137
+ let status: RefundStatus = { status: 'unknown', elapsedMs: Date.now() - startedAt };
138
+ try {
139
+ const resp = await fetcher(url, { signal: opts.signal });
140
+ if (resp.ok) {
141
+ const body = await resp.json() as {
142
+ found?: boolean; status?: 'active' | 'refunded' | 'expired' | 'unknown'; txHash?: string | null;
143
+ };
144
+ if (!body.found) {
145
+ status = { status: 'unknown', elapsedMs: Date.now() - startedAt };
146
+ } else if (body.status === 'refunded') {
147
+ status = { status: 'confirmed', txHash: body.txHash ?? null, elapsedMs: Date.now() - startedAt };
148
+ } else {
149
+ status = { status: 'pending', txHash: body.txHash ?? null, elapsedMs: Date.now() - startedAt };
150
+ }
151
+ }
152
+ } catch { /* transient network — try again on next tick */ }
153
+ opts.onTick?.(status);
154
+ if (status.status === 'confirmed') return status;
155
+ if (Date.now() >= deadline) return status;
156
+ await new Promise<void>((r) => setTimeout(r, interval));
157
+ }
158
+ }
@@ -0,0 +1,214 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * renewClient.ts
6
+ *
7
+ * Browser-safe client for the renew flow. Mirrors `buyClient.ts` in shape:
8
+ * the caller drives the wallet step between `proveRenew` and `confirmRenew`
9
+ * so the SDK stays wallet-agnostic.
10
+ *
11
+ * Unlike buy, renew carries a legally load-bearing `waiverAccepted` flag —
12
+ * EU/UK CRD Article 16(m) extinguishes the 14-day right of withdrawal only
13
+ * on the buyer's express affirmative act (consent to immediate delivery +
14
+ * acknowledgment of loss of withdrawal). We refuse the /prove/renew call
15
+ * when the flag is false to keep third-party integrators from silently
16
+ * shipping a UI that omits the waiver gate.
17
+ *
18
+ * Also refused pre-network when the keeper's sales-freeze schedule has
19
+ * fired (salesFrozen === true) — the keeper would 423 the request anyway,
20
+ * so surfacing the specific message client-side avoids a wasted round-trip.
21
+ */
22
+
23
+ import { resolveFreezeState } from './freezeClient.js';
24
+ import { readErrorBody, tryQueueBusyFromBody } from './proveErrors.js';
25
+
26
+ export type ProveRenewRequest = {
27
+ keeperUrl: string;
28
+ licenseHash: string;
29
+ buyerAddress: string;
30
+ zkAppAddress: string;
31
+ // Mina network this renewal targets. Pull from your persisted ProofFile
32
+ // so it always matches the network the original buy was proved against.
33
+ network: 'devnet' | 'mainnet';
34
+ duration: 0 | 1 | 2 | 3; // 0 = Monthly, 1 = Yearly, 2 = 5 Years, 3 = Perpetual
35
+ // Set from the UI's Article 16(m) consent gate. Missing/false raises
36
+ // before the network call — the SDK never proves a renew without it.
37
+ waiverAccepted: boolean;
38
+ // Optional freeze-slot override. When omitted the SDK reads
39
+ // `process.env.FREEZE_AFTER_SLOT` (Node only), else GET /health.
40
+ freezeAfterSlot?: number | null;
41
+ fetcher?: typeof fetch;
42
+ signal?: AbortSignal;
43
+ };
44
+
45
+ export type ProveRenewResponse = {
46
+ provenTxJson: string;
47
+ newExpirySlot: number;
48
+ licenseHash: string;
49
+ renewAmount: string; // nanomina
50
+ // Deployment generation the keeper proved against. If the buyer's stored
51
+ // ProofFile.generation is smaller, renew.ts walks ancestors and calls
52
+ // migrateLicense on each hop before submitting the renew.
53
+ generation: number;
54
+ // Key the keeper stored the per-app in-flight slot under. Passed back to
55
+ // POST /tx-broadcast after the wallet returns a hash. See ProveBuyResponse.
56
+ appKey: string;
57
+ };
58
+
59
+ export type ConfirmRenewRequest = {
60
+ keeperUrl: string;
61
+ zkAppAddress: string;
62
+ licenseHash: string;
63
+ txHash: string;
64
+ fetcher?: typeof fetch;
65
+ signal?: AbortSignal;
66
+ };
67
+
68
+ function baseUrl(url: string): string {
69
+ return url.replace(/\/+$/, '');
70
+ }
71
+
72
+ async function readJsonError(resp: Response): Promise<string> {
73
+ try {
74
+ const body = await resp.json() as Record<string, unknown>;
75
+ if (typeof body.error === 'string') return body.error;
76
+ } catch { /* body wasn't JSON */ }
77
+ return `HTTP ${resp.status}`;
78
+ }
79
+
80
+ // POST /prove/renew — keeper compiles + proves the renew tx.
81
+ // Rejects locally when `waiverAccepted` is false; a network call in that
82
+ // state would be wasted work and would give the caller no signal that the
83
+ // legal precondition was missing. Also rejects when the keeper's freeze
84
+ // has fired — same reasoning.
85
+ export async function proveRenew(req: ProveRenewRequest): Promise<ProveRenewResponse> {
86
+ if (req.waiverAccepted !== true) {
87
+ throw new Error('waiverAccepted must be true — Article 16(m) waiver required to renew');
88
+ }
89
+ const fetcher = req.fetcher ?? fetch;
90
+ const freeze = await resolveFreezeState({
91
+ keeperUrl: req.keeperUrl,
92
+ freezeAfterSlot: req.freezeAfterSlot,
93
+ fetcher,
94
+ signal: req.signal,
95
+ });
96
+ if (freeze.salesFrozen) {
97
+ throw new Error('Sales frozen — new renewals refused ahead of scheduled hardfork migration');
98
+ }
99
+ const resp = await fetcher(`${baseUrl(req.keeperUrl)}/prove/renew`, {
100
+ method: 'POST',
101
+ headers: { 'Content-Type': 'application/json' },
102
+ signal: req.signal,
103
+ body: JSON.stringify({
104
+ licenseHash: req.licenseHash,
105
+ buyerAddress: req.buyerAddress,
106
+ zkAppAddress: req.zkAppAddress,
107
+ network: req.network,
108
+ duration: req.duration,
109
+ }),
110
+ });
111
+ if (!resp.ok) {
112
+ const parsed = await readErrorBody(resp);
113
+ const queueBusy = tryQueueBusyFromBody(parsed);
114
+ if (queueBusy) throw queueBusy;
115
+ throw new Error(parsed.message);
116
+ }
117
+ return await resp.json() as ProveRenewResponse;
118
+ }
119
+
120
+ // POST /confirm/renew — promotes the in-memory renew intent to a pending
121
+ // LicenseRecord. Call this only after the wallet returns a txHash.
122
+ export async function confirmRenew(req: ConfirmRenewRequest): Promise<{ ok: true }> {
123
+ const fetcher = req.fetcher ?? fetch;
124
+ const resp = await fetcher(`${baseUrl(req.keeperUrl)}/confirm/renew`, {
125
+ method: 'POST',
126
+ headers: { 'Content-Type': 'application/json' },
127
+ signal: req.signal,
128
+ body: JSON.stringify({
129
+ zkAppAddress: req.zkAppAddress,
130
+ licenseHash: req.licenseHash,
131
+ txHash: req.txHash,
132
+ }),
133
+ });
134
+ if (!resp.ok) throw new Error(await readJsonError(resp));
135
+ return { ok: true };
136
+ }
137
+
138
+ export type RenewStatus = {
139
+ // 'confirmed' once the eventSync sweep has observed the licenseRenewed event
140
+ // on-chain and cleared the pending flag with the new expiry in place.
141
+ // 'pending' while the tx is in flight. 'unknown' if the license record
142
+ // hasn't been persisted yet (confirmRenew hasn't run or the intent expired).
143
+ status: 'confirmed' | 'pending' | 'unknown';
144
+ expirySlot?: number;
145
+ txHash?: string | null;
146
+ elapsedMs?: number;
147
+ };
148
+
149
+ export type PollRenewStatusOptions = {
150
+ keeperUrl: string;
151
+ network: 'devnet' | 'mainnet';
152
+ zkAppAddress: string;
153
+ licenseHash: string;
154
+ // The expected new expiry (from ProveRenewResponse). Confirmation requires
155
+ // BOTH pending=false AND the on-chain record's expirySlot matching or
156
+ // exceeding this — the pending flag alone flips before the sweep, so
157
+ // matching against the expected slot avoids reporting confirmed on the
158
+ // stale pre-renew record.
159
+ newExpirySlot: number;
160
+ fetcher?: typeof fetch;
161
+ // Mina slots are ~90 s and a tx usually lands within a few slots, so a
162
+ // 10 s tick keeps the UI live without hammering the keeper.
163
+ intervalMs?: number; // default 10 000
164
+ timeoutMs?: number; // default 20 min
165
+ signal?: AbortSignal;
166
+ onTick?: (status: RenewStatus) => void;
167
+ };
168
+
169
+ // Polls GET /license/:zkAppAddress/:licenseHash until the renew has landed
170
+ // on-chain (pending flipped and new expiry recorded) or the timeout fires.
171
+ // Mirrors pollBuyStatus, except the terminal condition is Mina-side rather
172
+ // than keeper-side buy-watch — renew has no dedicated watch map.
173
+ export async function pollRenewStatus(opts: PollRenewStatusOptions): Promise<RenewStatus> {
174
+ const fetcher = opts.fetcher ?? fetch;
175
+ const interval = opts.intervalMs ?? 10_000;
176
+ const timeout = opts.timeoutMs ?? 20 * 60 * 1000;
177
+ const startedAt = Date.now();
178
+ const deadline = startedAt + timeout;
179
+ const url = `${baseUrl(opts.keeperUrl)}/license/${encodeURIComponent(opts.zkAppAddress)}/${encodeURIComponent(opts.licenseHash)}?network=${opts.network}`;
180
+
181
+ while (true) {
182
+ if (opts.signal?.aborted) throw new Error('pollRenewStatus aborted');
183
+ let status: RenewStatus = { status: 'unknown', elapsedMs: Date.now() - startedAt };
184
+ try {
185
+ const resp = await fetcher(url, { signal: opts.signal });
186
+ if (resp.ok) {
187
+ const body = await resp.json() as {
188
+ found?: boolean; expirySlot?: number; pending?: boolean; txHash?: string | null;
189
+ };
190
+ if (!body.found) {
191
+ status = { status: 'unknown', elapsedMs: Date.now() - startedAt };
192
+ } else if (body.pending === false && (body.expirySlot ?? 0) >= opts.newExpirySlot) {
193
+ status = {
194
+ status: 'confirmed',
195
+ expirySlot: body.expirySlot,
196
+ txHash: body.txHash ?? null,
197
+ elapsedMs: Date.now() - startedAt,
198
+ };
199
+ } else {
200
+ status = {
201
+ status: 'pending',
202
+ expirySlot: body.expirySlot,
203
+ txHash: body.txHash ?? null,
204
+ elapsedMs: Date.now() - startedAt,
205
+ };
206
+ }
207
+ }
208
+ } catch { /* transient network — try again on next tick */ }
209
+ opts.onTick?.(status);
210
+ if (status.status === 'confirmed') return status;
211
+ if (Date.now() >= deadline) return status;
212
+ await new Promise<void>((r) => setTimeout(r, interval));
213
+ }
214
+ }
@@ -0,0 +1,165 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * seatName.ts
6
+ *
7
+ * Human-readable device names for the device-binding slot list
8
+ * ("Silent Otter", "Curious Panda"). Meant for the SDK UI so a buyer
9
+ * looking at their bound-devices panel sees "the laptop I left in the
10
+ * office" instead of an opaque device commitment.
11
+ *
12
+ * The name is purely cosmetic — the on-chain circuit never gates on it,
13
+ * verifyOffline never inspects it, and unbind targets `slotIndex`, not
14
+ * name. It exists solely so the SDK's device-manager UI has something
15
+ * readable to render next to each slot.
16
+ *
17
+ * Names are NOT persisted on-chain and NOT persisted off-chain either —
18
+ * `seatNameFor` derives the label deterministically from three on-chain
19
+ * fields (`licenseHash`, `slotIndex`, `boundAtSlot`), so every viewer of
20
+ * the same license computes the same name for a given occupied slot with
21
+ * no naming sidecar and no stored state.
22
+ *
23
+ * The wordlists are intentionally boring: no scary animals, no negative
24
+ * adjectives, no cultural landmines, no words with awkward secondary
25
+ * meanings. Order and word choice are stable — changing them shifts every
26
+ * slot's name on the next mint, which would be jarring for users looking
27
+ * at their device list.
28
+ */
29
+
30
+ // 250 friendly adjectives. Short, common, unambiguously positive or
31
+ // neutral. Ordering is alphabetical for maintainability — the derivation
32
+ // is index-based so order does not affect behavior.
33
+ const ADJECTIVES: readonly string[] = [
34
+ 'Agile', 'Alert', 'Amber', 'Ample', 'Ancient', 'Apricot', 'Arctic', 'Ashen',
35
+ 'Aspen', 'Autumn', 'Azure', 'Balmy', 'Bashful', 'Beaming', 'Beige', 'Bold',
36
+ 'Bouncy', 'Brave', 'Breezy', 'Bright', 'Brisk', 'Bronze', 'Bubbly', 'Busy',
37
+ 'Calm', 'Candid', 'Cedar', 'Cheery', 'Chic', 'Chipper', 'Chunky', 'Classic',
38
+ 'Clean', 'Clever', 'Cloudy', 'Clumsy', 'Coastal', 'Comet', 'Cool', 'Copper',
39
+ 'Coral', 'Cosmic', 'Cosy', 'Crafty', 'Creamy', 'Crimson', 'Crisp', 'Cuddly',
40
+ 'Curious', 'Daisy', 'Dandy', 'Dapper', 'Daring', 'Dawn', 'Deft', 'Delta',
41
+ 'Devout', 'Dewy', 'Diamond', 'Doughty', 'Dreamy', 'Dusky', 'Dusty', 'Eager',
42
+ 'Earnest', 'Earthy', 'Easy', 'Ebony', 'Elder', 'Elm', 'Ember', 'Emerald',
43
+ 'Epic', 'Fabled', 'Faint', 'Fair', 'Fancy', 'Fearless', 'Feisty', 'Fern',
44
+ 'Fiery', 'Fine', 'Firm', 'Flaxen', 'Fleet', 'Floral', 'Fluffy', 'Foggy',
45
+ 'Fond', 'Forest', 'Frank', 'Freckled', 'Friendly', 'Frosty', 'Frugal', 'Furry',
46
+ 'Fuzzy', 'Gallant', 'Genial', 'Gentle', 'Gilded', 'Ginger', 'Glad', 'Glassy',
47
+ 'Gleaming', 'Glossy', 'Glowing', 'Golden', 'Graceful', 'Grand', 'Grassy',
48
+ 'Green', 'Handy', 'Happy', 'Hardy', 'Hazel', 'Hearty', 'Helpful', 'Honest',
49
+ 'Humble', 'Icy', 'Indigo', 'Inky', 'Iron', 'Ivory', 'Jade', 'Jaunty', 'Jazzy',
50
+ 'Jolly', 'Jovial', 'Joyful', 'Juniper', 'Keen', 'Kind', 'Lanky', 'Lark',
51
+ 'Lavender', 'Lazy', 'Leaf', 'Lilac', 'Limber', 'Lively', 'Lofty', 'Loyal',
52
+ 'Lucky', 'Lush', 'Marble', 'Matte', 'Meadow', 'Mellow', 'Merry', 'Mighty',
53
+ 'Milky', 'Mindful', 'Minty', 'Misty', 'Modest', 'Mossy', 'Nautical', 'Nectar',
54
+ 'Nifty', 'Nimble', 'Noble', 'Nutmeg', 'Oaken', 'Ochre', 'Olive', 'Onyx',
55
+ 'Opal', 'Orange', 'Orchid', 'Pale', 'Patient', 'Peachy', 'Pearl', 'Pebble',
56
+ 'Perky', 'Piney', 'Placid', 'Playful', 'Plucky', 'Plum', 'Plush', 'Polar',
57
+ 'Polite', 'Prairie', 'Proud', 'Prudent', 'Punchy', 'Purple', 'Quaint', 'Quick',
58
+ 'Quiet', 'Radiant', 'Rainy', 'Rapid', 'Rare', 'Ready', 'Ripe', 'River',
59
+ 'Rocky', 'Rosy', 'Royal', 'Ruby', 'Rugged', 'Rustic', 'Saffron', 'Sage',
60
+ 'Sandy', 'Sapphire', 'Scarlet', 'Serene', 'Shady', 'Sharp', 'Shy', 'Silent',
61
+ 'Silken', 'Silky', 'Silver', 'Sincere', 'Sleek', 'Sleepy', 'Slender', 'Small',
62
+ 'Smart', 'Smiling', 'Snowy', 'Solar', 'Solid', 'Sonic', 'Soulful', 'Speedy',
63
+ 'Spirited', 'Splendid', 'Sprightly', 'Spry', 'Starry', 'Steady', 'Stellar',
64
+ 'Sterling', 'Stormy', 'Stout', 'Sunny', 'Sunset', 'Swift', 'Tangy', 'Teal',
65
+ 'Tender', 'Thankful', 'Thoughtful', 'Thrifty', 'Tidy', 'Timber', 'Tiny',
66
+ 'Topaz', 'Tranquil', 'Trusty', 'Turquoise', 'Twilight', 'Upright', 'Valiant',
67
+ 'Velvet', 'Verdant', 'Violet', 'Vivid', 'Warm', 'Whimsical', 'Willow',
68
+ 'Windy', 'Winsome', 'Wise', 'Witty', 'Woodland', 'Woolly', 'Zealous', 'Zesty',
69
+ ];
70
+
71
+ // 250 friendly animals. Common, recognisable, unambiguously non-threatening
72
+ // (no predators-of-humans, no venomous ones, no polarising taxidermy). Two-
73
+ // word species (mountain goat, sea otter) are collapsed to the base name so
74
+ // the final "Adjective Animal" reads cleanly. Ordering is alphabetical.
75
+ const ANIMALS: readonly string[] = [
76
+ 'Alpaca', 'Anteater', 'Antelope', 'Ape', 'Armadillo', 'Auk', 'Aurochs',
77
+ 'Axolotl', 'Baboon', 'Badger', 'Barnacle', 'Bat', 'Beagle', 'Bear', 'Beaver',
78
+ 'Bee', 'Beetle', 'Bison', 'Blackbird', 'Bluebird', 'Boar', 'Bobcat', 'Bonobo',
79
+ 'Booby', 'Buffalo', 'Bulldog', 'Bullfinch', 'Bumblebee', 'Butterfly', 'Camel',
80
+ 'Capybara', 'Cardinal', 'Caribou', 'Cassowary', 'Cat', 'Caterpillar',
81
+ 'Catfish', 'Chameleon', 'Chamois', 'Cheetah', 'Chickadee', 'Chinchilla',
82
+ 'Chipmunk', 'Clam', 'Clownfish', 'Coati', 'Cobra', 'Cockatoo', 'Codfish',
83
+ 'Colt', 'Condor', 'Coot', 'Cormorant', 'Corgi', 'Cougar', 'Cow', 'Coyote',
84
+ 'Crab', 'Crane', 'Cricket', 'Crow', 'Cub', 'Cuckoo', 'Curlew', 'Deer',
85
+ 'Dingo', 'Dolphin', 'Donkey', 'Dormouse', 'Dove', 'Dragonfly', 'Drake',
86
+ 'Duck', 'Duckling', 'Eagle', 'Echidna', 'Eel', 'Egret', 'Elephant', 'Elk',
87
+ 'Emu', 'Falcon', 'Fawn', 'Ferret', 'Finch', 'Firefly', 'Fish', 'Flamingo',
88
+ 'Fox', 'Frog', 'Gecko', 'Gerbil', 'Gibbon', 'Giraffe', 'Gnu', 'Goat',
89
+ 'Godwit', 'Goldfinch', 'Goldfish', 'Goose', 'Gorilla', 'Grebe', 'Griffon',
90
+ 'Grouse', 'Guanaco', 'Guineafowl', 'Gull', 'Guppy', 'Hamster', 'Hare',
91
+ 'Harrier', 'Hawk', 'Hedgehog', 'Heron', 'Herring', 'Hippo', 'Hoatzin',
92
+ 'Hoopoe', 'Hornbill', 'Horse', 'Hound', 'Hummingbird', 'Ibex', 'Ibis',
93
+ 'Iguana', 'Impala', 'Jackal', 'Jackrabbit', 'Jaguar', 'Jay', 'Jellyfish',
94
+ 'Kakapo', 'Kangaroo', 'Kestrel', 'Kingfisher', 'Kinkajou', 'Kite', 'Kitten',
95
+ 'Kiwi', 'Koala', 'Kookaburra', 'Ladybug', 'Lamb', 'Lapwing', 'Lark',
96
+ 'Lemming', 'Lemur', 'Leopard', 'Lion', 'Lizard', 'Llama', 'Lobster',
97
+ 'Lorikeet', 'Loris', 'Lynx', 'Macaque', 'Macaw', 'Magpie', 'Mallard',
98
+ 'Manatee', 'Mandrill', 'Mantis', 'Marmoset', 'Marmot', 'Marten', 'Meerkat',
99
+ 'Mink', 'Minnow', 'Mole', 'Mongoose', 'Monkey', 'Moose', 'Moth', 'Mouse',
100
+ 'Mule', 'Muntjac', 'Muskrat', 'Narwhal', 'Newt', 'Nightingale', 'Numbat',
101
+ 'Nuthatch', 'Ocelot', 'Octopus', 'Okapi', 'Opossum', 'Orangutan', 'Oriole',
102
+ 'Ostrich', 'Otter', 'Owl', 'Ox', 'Oyster', 'Panda', 'Pangolin', 'Panther',
103
+ 'Parakeet', 'Parrot', 'Partridge', 'Peacock', 'Pelican', 'Penguin', 'Perch',
104
+ 'Pheasant', 'Pig', 'Pigeon', 'Piglet', 'Pika', 'Pipit', 'Platypus', 'Plover',
105
+ 'Pointer', 'Polecat', 'Pony', 'Porcupine', 'Porpoise', 'Possum', 'Prawn',
106
+ 'Ptarmigan', 'Puffin', 'Puma', 'Pup', 'Puppy', 'Quail', 'Quokka', 'Rabbit',
107
+ 'Raccoon', 'Ram', 'Rat', 'Raven', 'Reindeer', 'Rhino', 'Roadrunner', 'Robin',
108
+ 'Rook', 'Salamander', 'Salmon', 'Sandpiper', 'Sardine', 'Scallop', 'Seahorse',
109
+ 'Seal', 'Serval', 'Shrew', 'Shrimp', 'Skunk', 'Sloth', 'Snail', 'Snake',
110
+ 'Snipe', 'Sparrow', 'Spider', 'Squid', 'Squirrel', 'Starling', 'Stoat',
111
+ 'Stork', 'Sturgeon', 'Swallow', 'Swan', 'Tamarin', 'Tanager', 'Tapir',
112
+ 'Tarsier', 'Teal', 'Tern', 'Terrier', 'Thrush', 'Tiger', 'Toad', 'Toucan',
113
+ 'Trout', 'Tuna', 'Turkey', 'Turtle', 'Vole', 'Wagtail', 'Walrus', 'Wapiti',
114
+ 'Warbler', 'Wasp', 'Weasel', 'Whale', 'Whippet', 'Wolf', 'Wolverine',
115
+ 'Wombat', 'Woodchuck', 'Woodpecker', 'Wren', 'Yak', 'Zebra',
116
+ ];
117
+
118
+ // Total combinations = ADJECTIVES.length * ANIMALS.length. Exposed for
119
+ // diagnostics and for tests that want to assert the name space is large
120
+ // enough to cover the expected ceiling of licenses × cap.
121
+ export const SEAT_NAME_COMBINATIONS: number = ADJECTIVES.length * ANIMALS.length;
122
+
123
+ // FNV-1a — a fast, non-cryptographic 32-bit hash. Uniform enough over 250
124
+ // buckets that the modulo bias (~1 in 17M) is invisible in practice. Not
125
+ // used for security; just to derive a stable pair of small indices from
126
+ // the seat's on-chain identity fields.
127
+ function fnv1a(s: string, seed: number): number {
128
+ let h = seed >>> 0;
129
+ for (let i = 0; i < s.length; i++) {
130
+ h ^= s.charCodeAt(i);
131
+ h = Math.imul(h, 0x01000193);
132
+ }
133
+ return h >>> 0;
134
+ }
135
+
136
+ // Deterministic seat-name derivation. Two viewers holding the same
137
+ // `LicenseLeaf` compute the same name for a given occupied slot, without
138
+ // a naming sidecar or any persisted state — the function is a pure fold
139
+ // over three on-chain fields.
140
+ //
141
+ // Key composition — `licenseHash + slotIndex + boundAtSlot`:
142
+ // - `licenseHash` scopes names to a single license, so slot 0 on
143
+ // license A doesn't collide with slot 0 on license B.
144
+ // - `slotIndex` separates concurrent occupants of the same license.
145
+ // - `boundAtSlot` binds the name to the device-instance in that slot at
146
+ // that bind moment. Unbind + rebind at the same slotIndex produces
147
+ // a fresh name, matching the mental model of "the laptop I bound in
148
+ // March" rather than "seat 0 forever".
149
+ //
150
+ // Empty slots (`boundAtSlot === 0`) are the caller's responsibility to
151
+ // filter — the function returns a valid string for any input rather than
152
+ // throwing, to keep the surface pure. Match on `deviceCommitment !== '0'`
153
+ // or `boundAtSlot > 0` before calling.
154
+ export type SeatNameInput = {
155
+ licenseHash: string; // Poseidon-hash decimal string from ProofFile / LicenseRecord
156
+ slotIndex: number; // 0..deviceCap-1
157
+ boundAtSlot: number; // Mina slot the bind() tx landed at
158
+ };
159
+
160
+ export function seatNameFor(input: SeatNameInput): string {
161
+ const key = `${input.licenseHash}|${input.slotIndex}|${input.boundAtSlot}`;
162
+ const adj = ADJECTIVES[fnv1a(key, 0x811c9dc5) % ADJECTIVES.length];
163
+ const animal = ANIMALS[ fnv1a(key, 0xdeadbeef) % ANIMALS.length];
164
+ return `${adj} ${animal}`;
165
+ }