@cicero-zcash/react 0.0.0-stage → 0.2.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,1960 @@
1
+ // src/context/CiceroContext.tsx
2
+ import {
3
+ createContext,
4
+ useContext,
5
+ useState as useState4,
6
+ useEffect as useEffect4,
7
+ useCallback as useCallback2,
8
+ useMemo,
9
+ useRef
10
+ } from "react";
11
+
12
+ // src/utils/zip321.ts
13
+ function encodeBase64Url(str) {
14
+ try {
15
+ const bytes = new TextEncoder().encode(str);
16
+ let binary = "";
17
+ const len = bytes.byteLength;
18
+ for (let i = 0; i < len; i++) {
19
+ binary += String.fromCharCode(bytes[i]);
20
+ }
21
+ const base64 = btoa(binary);
22
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
23
+ } catch {
24
+ return "";
25
+ }
26
+ }
27
+ function decodeBase64Url(base64url) {
28
+ try {
29
+ let base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");
30
+ while (base64.length % 4) {
31
+ base64 += "=";
32
+ }
33
+ const binary = atob(base64);
34
+ const bytes = new Uint8Array(binary.length);
35
+ for (let i = 0; i < binary.length; i++) {
36
+ bytes[i] = binary.charCodeAt(i);
37
+ }
38
+ return new TextDecoder().decode(bytes);
39
+ } catch {
40
+ return "";
41
+ }
42
+ }
43
+ function generateZip321Uri({
44
+ address,
45
+ amount,
46
+ memo,
47
+ message
48
+ }) {
49
+ const cleanAddress = address.trim();
50
+ const params = new URLSearchParams();
51
+ if (amount !== void 0 && amount !== null && amount !== "") {
52
+ const numAmount = typeof amount === "number" ? amount : parseFloat(amount);
53
+ if (!isNaN(numAmount) && numAmount > 0) {
54
+ params.append("amount", numAmount.toString());
55
+ }
56
+ }
57
+ if (memo && memo.trim().length > 0) {
58
+ const encodedMemo = encodeBase64Url(memo.trim());
59
+ if (encodedMemo) {
60
+ params.append("memo", encodedMemo);
61
+ }
62
+ }
63
+ if (message && message.trim().length > 0) {
64
+ params.append("message", message.trim());
65
+ }
66
+ const queryString = params.toString();
67
+ return queryString ? `zcash:${cleanAddress}?${queryString}` : `zcash:${cleanAddress}`;
68
+ }
69
+ function parseZip321Uri(rawUri) {
70
+ const trimmed = rawUri.trim();
71
+ const withoutScheme = trimmed.startsWith("zcash:") ? trimmed.slice(6) : trimmed;
72
+ const [addressPart, queryPart] = withoutScheme.split("?");
73
+ const result = {
74
+ address: addressPart || "",
75
+ rawUri: trimmed
76
+ };
77
+ if (!queryPart) {
78
+ return result;
79
+ }
80
+ const searchParams = new URLSearchParams(queryPart);
81
+ const amount = searchParams.get("amount");
82
+ const memo = searchParams.get("memo");
83
+ const message = searchParams.get("message");
84
+ if (amount) result.amount = amount;
85
+ if (memo) result.memo = decodeBase64Url(memo);
86
+ if (message) result.message = message;
87
+ return result;
88
+ }
89
+ function getWalletDeepLinks(zip321Uri) {
90
+ return {
91
+ generic: zip321Uri,
92
+ zashi: zip321Uri,
93
+ // Zashi registers the native zcash: URI handler on iOS/Android
94
+ ywallet: zip321Uri
95
+ // Ywallet also natively handles zcash: protocol
96
+ };
97
+ }
98
+
99
+ // src/wallet/zucchini.ts
100
+ var ZucchiniWalletAdapter = class _ZucchiniWalletAdapter {
101
+ client = null;
102
+ provider = null;
103
+ _connected = false;
104
+ _address = null;
105
+ _lastAccounts = [];
106
+ /**
107
+ * Checks whether the Zucchini Wallet extension is installed and its
108
+ * provider is available in the current browser environment.
109
+ */
110
+ static isAvailable() {
111
+ if (typeof window === "undefined") return false;
112
+ const win = window;
113
+ if (win.zucchini && typeof win.zucchini.request === "function") {
114
+ return true;
115
+ }
116
+ if (win.zcash) {
117
+ return true;
118
+ }
119
+ return !!win.zucchini;
120
+ }
121
+ /**
122
+ * Subscribes to wallet readiness. Fires callback immediately if already available,
123
+ * or listens for injection events / polls briefly for late extension initialization.
124
+ */
125
+ static onReady(callback) {
126
+ if (typeof window === "undefined") return () => {
127
+ };
128
+ if (_ZucchiniWalletAdapter.isAvailable()) {
129
+ callback();
130
+ return () => {
131
+ };
132
+ }
133
+ const handler = () => callback();
134
+ window.addEventListener("zucchini#initialized", handler);
135
+ window.addEventListener("zcash#initialized", handler);
136
+ const interval = setInterval(() => {
137
+ if (_ZucchiniWalletAdapter.isAvailable()) {
138
+ clearInterval(interval);
139
+ callback();
140
+ }
141
+ }, 150);
142
+ const timeout = setTimeout(() => {
143
+ clearInterval(interval);
144
+ }, 3500);
145
+ return () => {
146
+ window.removeEventListener("zucchini#initialized", handler);
147
+ window.removeEventListener("zcash#initialized", handler);
148
+ clearInterval(interval);
149
+ clearTimeout(timeout);
150
+ };
151
+ }
152
+ /**
153
+ * Discovers and initializes the Zucchini Client using @zucchinifi/dapp-sdk/zcash
154
+ * with graceful fallback to raw window.zucchini / window.zcash globals.
155
+ */
156
+ async getClient() {
157
+ if (this.client) return this.client;
158
+ if (typeof window === "undefined") {
159
+ throw new Error("Zucchini Wallet is only available in browser environments.");
160
+ }
161
+ const win = window;
162
+ let rawProvider = win.zucchini || win.zcash;
163
+ try {
164
+ const { discoverZucchiniProvider, createZucchiniClient } = await import("@zucchinifi/dapp-sdk/zcash");
165
+ const discovered = discoverZucchiniProvider() || rawProvider;
166
+ if (discovered) {
167
+ this.provider = discovered;
168
+ this.client = createZucchiniClient(discovered);
169
+ return this.client;
170
+ }
171
+ } catch {
172
+ }
173
+ if (rawProvider) {
174
+ this.provider = rawProvider;
175
+ this.client = {
176
+ async connect(req) {
177
+ if (typeof rawProvider.connect === "function") {
178
+ return rawProvider.connect(req?.permissions || ["view_addresses", "view_balance", "send_transaction"]);
179
+ }
180
+ if (typeof rawProvider.request === "function") {
181
+ return rawProvider.request({ method: "connect", params: req });
182
+ }
183
+ return { connected: true };
184
+ },
185
+ async disconnect() {
186
+ if (typeof rawProvider.disconnect === "function") {
187
+ return rawProvider.disconnect();
188
+ }
189
+ },
190
+ async requestPayment(uri) {
191
+ if (typeof rawProvider.request === "function") {
192
+ const res = await rawProvider.request({
193
+ method: "zcash_requestPayment",
194
+ params: { uri }
195
+ });
196
+ return { txid: res?.txid || res?.txId || res };
197
+ }
198
+ throw new Error("Direct ZIP-321 send not supported by provider");
199
+ },
200
+ async getAddresses() {
201
+ if (typeof rawProvider.request === "function") {
202
+ return rawProvider.request({ method: "getAddresses" });
203
+ }
204
+ return {};
205
+ },
206
+ on(event, listener) {
207
+ rawProvider.on?.(event, listener);
208
+ return () => rawProvider.off?.(event, listener);
209
+ }
210
+ };
211
+ return this.client;
212
+ }
213
+ throw new Error(
214
+ "Zucchini Wallet extension not detected. Please install it from the Chrome Web Store or ensure the side-panel is open."
215
+ );
216
+ }
217
+ /**
218
+ * Requests connection with view_addresses and send_transaction permissions.
219
+ * Resolves the user's active Shielded Unified Address.
220
+ */
221
+ async connect() {
222
+ const client = await this.getClient();
223
+ const connection = await client.connect({
224
+ permissions: ["view_addresses", "view_balance", "send_transaction"]
225
+ });
226
+ let address = void 0;
227
+ if (connection?.accounts && connection.accounts.length > 0) {
228
+ address = connection.accounts[0].address;
229
+ }
230
+ if (!address && typeof client.getAddresses === "function") {
231
+ try {
232
+ const addresses = await client.getAddresses();
233
+ address = addresses?.unified || addresses?.orchard || addresses?.sapling || addresses?.transparent;
234
+ } catch {
235
+ }
236
+ }
237
+ this._lastAccounts = connection?.accounts || [];
238
+ const network = await this.getNetwork();
239
+ const balance = await this.getBalance({ address, network });
240
+ this._connected = true;
241
+ this._address = address || null;
242
+ return {
243
+ address,
244
+ connected: true,
245
+ network,
246
+ balance: balance ?? void 0
247
+ };
248
+ }
249
+ /**
250
+ * Queries the active network of the Zucchini Wallet ('mainnet' | 'testnet').
251
+ */
252
+ async getNetwork() {
253
+ try {
254
+ const client = await this.getClient();
255
+ if (typeof client.network === "function") {
256
+ const net = await client.network();
257
+ if (net === "mainnet" || net === "testnet") {
258
+ return net;
259
+ }
260
+ }
261
+ } catch {
262
+ }
263
+ const raw = this.provider || (typeof window !== "undefined" ? window.zucchini || window.zcash : null);
264
+ if (raw && typeof raw.request === "function") {
265
+ try {
266
+ const res = await raw.request({ method: "getNetwork" });
267
+ if (res?.network === "main" || res === "main" || res === "mainnet") return "mainnet";
268
+ if (res?.network === "test" || res === "test" || res === "testnet") return "testnet";
269
+ } catch {
270
+ }
271
+ }
272
+ if (this._address) {
273
+ if (this._address.startsWith("utest1") || this._address.startsWith("ztestsapling") || this._address.startsWith("tm")) {
274
+ return "testnet";
275
+ }
276
+ if (this._address.startsWith("u1") || this._address.startsWith("zs1") || this._address.startsWith("t1")) {
277
+ return "mainnet";
278
+ }
279
+ }
280
+ return "mainnet";
281
+ }
282
+ /**
283
+ * Requests a network change. If the extension does not support programmatic
284
+ * switching, informs the application that manual user toggle is needed.
285
+ */
286
+ async switchNetwork(targetNetwork) {
287
+ const current = await this.getNetwork();
288
+ if (current === targetNetwork) {
289
+ return { success: true, currentNetwork: current };
290
+ }
291
+ const raw = this.provider || (typeof window !== "undefined" ? window.zucchini || window.zcash : null);
292
+ if (raw && typeof raw.request === "function") {
293
+ try {
294
+ await raw.request({
295
+ method: "switchNetwork",
296
+ params: { network: targetNetwork === "mainnet" ? "main" : "test" }
297
+ });
298
+ const updated = await this.getNetwork();
299
+ return { success: updated === targetNetwork, currentNetwork: updated };
300
+ } catch {
301
+ }
302
+ }
303
+ return {
304
+ success: false,
305
+ requiresManualSwitch: true,
306
+ currentNetwork: current
307
+ };
308
+ }
309
+ /**
310
+ * Subscribes to network change events from the wallet extension.
311
+ */
312
+ onNetworkChanged(listener) {
313
+ const raw = this.provider || (typeof window !== "undefined" ? window.zucchini || window.zcash : null);
314
+ const handler = async () => {
315
+ const net = await this.getNetwork();
316
+ listener(net);
317
+ };
318
+ if (raw?.on) {
319
+ raw.on("networkChanged", handler);
320
+ raw.on("chainChanged", handler);
321
+ raw.on("accountsChanged", handler);
322
+ return () => {
323
+ raw.off?.("networkChanged", handler);
324
+ raw.off?.("chainChanged", handler);
325
+ raw.off?.("accountsChanged", handler);
326
+ };
327
+ }
328
+ return () => {
329
+ };
330
+ }
331
+ /**
332
+ * Helper to normalize raw balance formats (e.g. number, string, zatoshis, or pool totals).
333
+ */
334
+ parseBalancePayload(payload) {
335
+ if (payload === void 0 || payload === null) return null;
336
+ if (typeof payload === "number") {
337
+ return payload > 1e6 ? payload / 1e8 : payload;
338
+ }
339
+ if (typeof payload === "string") {
340
+ const parsed = parseFloat(payload);
341
+ if (!isNaN(parsed)) {
342
+ return parsed > 1e6 ? parsed / 1e8 : parsed;
343
+ }
344
+ }
345
+ if (typeof payload === "object") {
346
+ const cand = payload.total ?? payload.balance ?? payload.amount ?? payload.zec ?? payload.value ?? payload.zatoshis;
347
+ if (cand !== void 0 && cand !== null) {
348
+ return this.parseBalancePayload(cand);
349
+ }
350
+ let sum = 0;
351
+ let hasPool = false;
352
+ for (const pool of ["orchard", "sapling", "transparent", "shielded", "unshielded"]) {
353
+ if (payload[pool] !== void 0) {
354
+ const v = this.parseBalancePayload(payload[pool]);
355
+ if (v !== null) {
356
+ sum += v;
357
+ hasPool = true;
358
+ }
359
+ }
360
+ }
361
+ if (hasPool) return sum;
362
+ }
363
+ return null;
364
+ }
365
+ /**
366
+ * Reads real-time balance from Zucchini provider.
367
+ */
368
+ async getBalance(options) {
369
+ const raw = this.provider || (typeof window !== "undefined" ? window.zucchini || window.zcash : null);
370
+ const methods = [
371
+ "getBalance",
372
+ "getBalances",
373
+ "zcash_getBalance",
374
+ "zcash_getBalances",
375
+ "view_balance",
376
+ "getBalanceSummary"
377
+ ];
378
+ if (raw && typeof raw.request === "function") {
379
+ for (const method of methods) {
380
+ try {
381
+ const res = await raw.request({ method, params: options });
382
+ const parsed = this.parseBalancePayload(res);
383
+ if (parsed !== null) return parsed;
384
+ } catch {
385
+ }
386
+ }
387
+ }
388
+ if (this._lastAccounts && this._lastAccounts.length > 0) {
389
+ for (const acc of this._lastAccounts) {
390
+ const parsed = this.parseBalancePayload(acc);
391
+ if (parsed !== null) return parsed;
392
+ }
393
+ }
394
+ return null;
395
+ }
396
+ /**
397
+ * Sends payment via standard ZIP-321 URI requestPayment or transaction fallback.
398
+ */
399
+ async requestPayment(params) {
400
+ if (!this._connected) {
401
+ await this.connect();
402
+ }
403
+ const client = await this.getClient();
404
+ const numAmount = typeof params.amount === "number" ? params.amount : parseFloat(params.amount);
405
+ if (isNaN(numAmount) || numAmount <= 0) {
406
+ throw new Error("Payment amount must be a positive number.");
407
+ }
408
+ const uri = generateZip321Uri({
409
+ address: params.recipient.trim(),
410
+ amount: numAmount,
411
+ memo: params.memo?.trim()
412
+ });
413
+ try {
414
+ if (typeof client.requestPayment === "function") {
415
+ const res = await client.requestPayment(uri);
416
+ const txId = res?.txid || res?.txId || "";
417
+ return { txId, submitted: true };
418
+ }
419
+ } catch (e) {
420
+ }
421
+ if (typeof client.requestTransaction === "function") {
422
+ const zatoshis = BigInt(Math.round(numAmount * 1e8));
423
+ const res = await client.requestTransaction({
424
+ amountZatoshis: zatoshis,
425
+ recipient: params.recipient.trim(),
426
+ memo: params.memo?.trim()
427
+ });
428
+ return { txId: res?.txid || "", submitted: true };
429
+ }
430
+ throw new Error("Zucchini Wallet does not support payment dispatch.");
431
+ }
432
+ /**
433
+ * Subscribes to accountsChanged events.
434
+ */
435
+ onAccountsChanged(listener) {
436
+ if (this.client?.on) {
437
+ return this.client.on("accountsChanged", listener);
438
+ }
439
+ if (this.provider?.on) {
440
+ this.provider.on("accountsChanged", listener);
441
+ return () => this.provider?.off?.("accountsChanged", listener);
442
+ }
443
+ return () => {
444
+ };
445
+ }
446
+ /**
447
+ * Subscribes to disconnect events.
448
+ */
449
+ onDisconnect(listener) {
450
+ if (this.client?.on) {
451
+ return this.client.on("disconnect", listener);
452
+ }
453
+ if (this.provider?.on) {
454
+ this.provider.on("disconnect", listener);
455
+ return () => this.provider?.off?.("disconnect", listener);
456
+ }
457
+ return () => {
458
+ };
459
+ }
460
+ /**
461
+ * Disconnects the current session.
462
+ */
463
+ async disconnect() {
464
+ try {
465
+ if (this.client?.disconnect) {
466
+ await this.client.disconnect();
467
+ } else if (this.provider?.disconnect) {
468
+ await this.provider.disconnect();
469
+ }
470
+ } catch {
471
+ }
472
+ this._connected = false;
473
+ this._address = null;
474
+ }
475
+ get isConnected() {
476
+ return this._connected;
477
+ }
478
+ get address() {
479
+ return this._address;
480
+ }
481
+ };
482
+
483
+ // src/wallets/zucchini.ts
484
+ var adapter = new ZucchiniWalletAdapter();
485
+ var zucchiniWallet = {
486
+ id: "zucchini",
487
+ name: "Zucchini Wallet",
488
+ icon: "\u{1F952}",
489
+ description: "In-browser Chrome extension with 1-click side-panel approvals",
490
+ category: "extension",
491
+ downloadUrl: "https://chromewebstore.google.com/detail/zucchini-wallet",
492
+ isAvailable: () => ZucchiniWalletAdapter.isAvailable(),
493
+ connect: async (options) => {
494
+ const session = await adapter.connect();
495
+ return {
496
+ address: session.address,
497
+ connected: true,
498
+ network: session.network || options?.network || "mainnet",
499
+ walletId: "zucchini",
500
+ balance: session.balance
501
+ };
502
+ },
503
+ disconnect: async () => {
504
+ await adapter.disconnect();
505
+ },
506
+ getBalance: async (options) => {
507
+ return adapter.getBalance(options);
508
+ },
509
+ getNetwork: async () => {
510
+ return adapter.getNetwork();
511
+ },
512
+ switchNetwork: async (network) => {
513
+ return adapter.switchNetwork(network);
514
+ },
515
+ sendPayment: async (params) => {
516
+ const res = await adapter.requestPayment({
517
+ recipient: params.recipient,
518
+ amount: params.amount,
519
+ memo: params.memo
520
+ });
521
+ return {
522
+ txId: res.txId,
523
+ submitted: res.submitted
524
+ };
525
+ }
526
+ };
527
+
528
+ // src/wallets/zashi.ts
529
+ var zashiWallet = {
530
+ id: "zashi",
531
+ name: "Zashi by ECC",
532
+ icon: "\u{1F6E1}\uFE0F",
533
+ description: "Official zero-knowledge mobile wallet by Electric Coin Co.",
534
+ category: "mobile",
535
+ downloadUrl: "https://electriccoin.co/zashi/",
536
+ isAvailable: () => true,
537
+ // Available via mobile QR or deep link
538
+ connect: async (options) => {
539
+ return {
540
+ connected: true,
541
+ network: options?.network || "mainnet",
542
+ walletId: "zashi"
543
+ };
544
+ },
545
+ sendPayment: async (params) => {
546
+ const rawUri = generateZip321Uri({
547
+ address: params.recipient,
548
+ amount: params.amount,
549
+ memo: params.memo,
550
+ message: params.message
551
+ });
552
+ if (typeof window !== "undefined") {
553
+ window.location.href = rawUri;
554
+ }
555
+ return {
556
+ txId: "",
557
+ submitted: false,
558
+ rawUri
559
+ };
560
+ }
561
+ };
562
+
563
+ // src/wallets/ywallet.ts
564
+ var ywallet = {
565
+ id: "ywallet",
566
+ name: "Ywallet",
567
+ icon: "\u26A1",
568
+ description: "Fast-syncing multi-platform shielded wallet for mobile & desktop",
569
+ category: "mobile",
570
+ downloadUrl: "https://ywallet.app/",
571
+ isAvailable: () => true,
572
+ connect: async (options) => {
573
+ return {
574
+ connected: true,
575
+ network: options?.network || "mainnet",
576
+ walletId: "ywallet"
577
+ };
578
+ },
579
+ sendPayment: async (params) => {
580
+ const rawUri = generateZip321Uri({
581
+ address: params.recipient,
582
+ amount: params.amount,
583
+ memo: params.memo,
584
+ message: params.message
585
+ });
586
+ if (typeof window !== "undefined") {
587
+ window.location.href = rawUri;
588
+ }
589
+ return {
590
+ txId: "",
591
+ submitted: false,
592
+ rawUri
593
+ };
594
+ }
595
+ };
596
+
597
+ // src/wallets/viewingKey.ts
598
+ var viewingKeyWallet = {
599
+ id: "viewing-key",
600
+ name: "Viewing Key / Auditor",
601
+ icon: "\u{1F441}\uFE0F",
602
+ description: "Connect with a Unified Address or Viewing Key for read-only audit mode",
603
+ category: "read-only",
604
+ isAvailable: () => true,
605
+ connect: async (options) => {
606
+ return {
607
+ connected: true,
608
+ network: options?.network || "mainnet",
609
+ walletId: "viewing-key"
610
+ };
611
+ }
612
+ };
613
+
614
+ // src/wallets/burner.ts
615
+ var MOCK_BURNER_ADDR = "u1qwe829xkps9482mzsll049281kz8471hzkas093847zkd09472619as8361048293710293847102938471029384710";
616
+ var burnerWallet = {
617
+ id: "burner",
618
+ name: "Dev Session Wallet",
619
+ icon: "\u{1F9EA}",
620
+ description: "Instant ephemeral shielded test wallet for rapid local testing",
621
+ category: "developer",
622
+ isAvailable: () => true,
623
+ connect: async (options) => {
624
+ return {
625
+ address: MOCK_BURNER_ADDR,
626
+ connected: true,
627
+ network: options?.network || "testnet",
628
+ walletId: "burner"
629
+ };
630
+ },
631
+ sendPayment: async (_params) => {
632
+ const mockTxId = `0x${Array.from(
633
+ { length: 64 },
634
+ () => Math.floor(Math.random() * 16).toString(16)
635
+ ).join("")}`;
636
+ return {
637
+ txId: mockTxId,
638
+ submitted: true
639
+ };
640
+ }
641
+ };
642
+
643
+ // src/wallets/index.ts
644
+ function getDefaultWallets() {
645
+ return [
646
+ zucchiniWallet,
647
+ zashiWallet,
648
+ ywallet,
649
+ viewingKeyWallet,
650
+ burnerWallet
651
+ ];
652
+ }
653
+
654
+ // src/hooks/useZcashPrice.ts
655
+ import { useState, useEffect, useCallback } from "react";
656
+ var cachedPrice = null;
657
+ var lastFetchTime = 0;
658
+ var CACHE_DURATION_MS = 6e4;
659
+ function useZcashPrice(enabled = true) {
660
+ const [state, setState] = useState(() => ({
661
+ usdPrice: cachedPrice,
662
+ loading: !cachedPrice && enabled,
663
+ error: null,
664
+ lastUpdated: lastFetchTime || null
665
+ }));
666
+ useEffect(() => {
667
+ if (!enabled) return;
668
+ let isMounted = true;
669
+ const now = Date.now();
670
+ if (cachedPrice && now - lastFetchTime < CACHE_DURATION_MS) {
671
+ setState((prev) => {
672
+ if (prev.usdPrice === cachedPrice && !prev.loading) return prev;
673
+ return {
674
+ usdPrice: cachedPrice,
675
+ loading: false,
676
+ error: null,
677
+ lastUpdated: lastFetchTime
678
+ };
679
+ });
680
+ return;
681
+ }
682
+ async function fetchPrice() {
683
+ try {
684
+ const res = await fetch(
685
+ "https://api.coingecko.com/api/v3/simple/price?ids=zcash&vs_currencies=usd",
686
+ { signal: AbortSignal.timeout(4e3) }
687
+ );
688
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
689
+ const data = await res.json();
690
+ const price = data?.zcash?.usd;
691
+ if (typeof price === "number") {
692
+ cachedPrice = price;
693
+ lastFetchTime = Date.now();
694
+ if (isMounted) {
695
+ setState({
696
+ usdPrice: price,
697
+ loading: false,
698
+ error: null,
699
+ lastUpdated: lastFetchTime
700
+ });
701
+ }
702
+ return;
703
+ }
704
+ throw new Error("Invalid price payload");
705
+ } catch (err) {
706
+ try {
707
+ const binanceRes = await fetch(
708
+ "https://api.binance.com/api/v3/ticker/price?symbol=ZECUSDT",
709
+ { signal: AbortSignal.timeout(3e3) }
710
+ );
711
+ if (binanceRes.ok) {
712
+ const bData = await binanceRes.json();
713
+ const bPrice = parseFloat(bData.price);
714
+ if (!isNaN(bPrice) && bPrice > 0) {
715
+ cachedPrice = bPrice;
716
+ lastFetchTime = Date.now();
717
+ if (isMounted) {
718
+ setState({
719
+ usdPrice: bPrice,
720
+ loading: false,
721
+ error: null,
722
+ lastUpdated: lastFetchTime
723
+ });
724
+ }
725
+ return;
726
+ }
727
+ }
728
+ } catch {
729
+ }
730
+ if (isMounted) {
731
+ const fallback = cachedPrice ?? 38.5;
732
+ setState({
733
+ usdPrice: fallback,
734
+ loading: false,
735
+ error: err instanceof Error ? err.message : "Price fetch error",
736
+ lastUpdated: Date.now()
737
+ });
738
+ }
739
+ }
740
+ }
741
+ fetchPrice();
742
+ return () => {
743
+ isMounted = false;
744
+ };
745
+ }, [enabled]);
746
+ const convertZecToUsd = useCallback(
747
+ (zecAmount) => {
748
+ const num = typeof zecAmount === "number" ? zecAmount : parseFloat(zecAmount);
749
+ if (isNaN(num) || state.usdPrice === null) return null;
750
+ return (num * state.usdPrice).toFixed(2);
751
+ },
752
+ [state.usdPrice]
753
+ );
754
+ return {
755
+ ...state,
756
+ convertZecToUsd
757
+ };
758
+ }
759
+
760
+ // src/components/CiceroConnectModal.tsx
761
+ import { useState as useState2, useEffect as useEffect2 } from "react";
762
+ import { createPortal } from "react-dom";
763
+ import {
764
+ X,
765
+ ExternalLink,
766
+ Shield,
767
+ Sparkles,
768
+ AlertCircle,
769
+ ArrowRight
770
+ } from "lucide-react";
771
+
772
+ // src/components/CiceroQRCode.tsx
773
+ import { QRCodeSVG } from "qrcode.react";
774
+ import { jsx } from "react/jsx-runtime";
775
+ var CiceroQRCode = ({
776
+ value,
777
+ size = 200,
778
+ className = "",
779
+ level = "M",
780
+ includeMargin = true
781
+ }) => {
782
+ return /* @__PURE__ */ jsx(
783
+ "div",
784
+ {
785
+ className: `inline-flex items-center justify-center p-3 bg-white rounded-lg border border-[#ededed] shadow-sm ${className}`,
786
+ children: /* @__PURE__ */ jsx(
787
+ QRCodeSVG,
788
+ {
789
+ value,
790
+ size,
791
+ level,
792
+ includeMargin,
793
+ imageSettings: {
794
+ src: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23171717'%3E%3Cpath d='M12 2L3 7v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V7l-9-5zm0 4.5l5 2.5v4.5c0 3.3-2.1 6.3-5 7.2-2.9-.9-5-3.9-5-7.2V9l5-2.5z'/%3E%3Cpath d='M10 11h4l-3 4h3' stroke='%233ecf8e' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E",
795
+ height: 28,
796
+ width: 28,
797
+ excavate: true
798
+ }
799
+ }
800
+ )
801
+ }
802
+ );
803
+ };
804
+
805
+ // src/components/CiceroConnectModal.tsx
806
+ import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
807
+ var CiceroConnectModal = ({
808
+ isOpen: propIsOpen,
809
+ onClose: propOnClose
810
+ }) => {
811
+ const {
812
+ isConnectModalOpen,
813
+ closeConnectModal,
814
+ wallets,
815
+ connect,
816
+ network,
817
+ appName
818
+ } = useCicero();
819
+ const isOpen = propIsOpen !== void 0 ? propIsOpen : isConnectModalOpen;
820
+ const handleClose = propOnClose || closeConnectModal;
821
+ const [selectedWalletId, setSelectedWalletId] = useState2("zucchini");
822
+ const [customKeyInput, setCustomKeyInput] = useState2("");
823
+ const [error, setError] = useState2(null);
824
+ const [isSubmitting, setIsSubmitting] = useState2(false);
825
+ const [mounted, setMounted] = useState2(false);
826
+ const [, setAvailabilityTick] = useState2(0);
827
+ useEffect2(() => {
828
+ setMounted(true);
829
+ }, []);
830
+ useEffect2(() => {
831
+ if (!isOpen) return;
832
+ const cleanupReady = ZucchiniWalletAdapter.onReady(() => {
833
+ setAvailabilityTick((t) => t + 1);
834
+ });
835
+ const interval = setInterval(() => {
836
+ setAvailabilityTick((t) => t + 1);
837
+ }, 600);
838
+ return () => {
839
+ cleanupReady();
840
+ clearInterval(interval);
841
+ };
842
+ }, [isOpen]);
843
+ useEffect2(() => {
844
+ const handleKeyDown = (e) => {
845
+ if (e.key === "Escape" && isOpen) {
846
+ handleClose();
847
+ }
848
+ };
849
+ window.addEventListener("keydown", handleKeyDown);
850
+ return () => window.removeEventListener("keydown", handleKeyDown);
851
+ }, [isOpen, handleClose]);
852
+ if (!isOpen || !mounted) return null;
853
+ const selectedWallet = wallets.find((w) => w.id === selectedWalletId) || wallets[0];
854
+ const isAvailable = selectedWallet?.isAvailable();
855
+ const handleWalletSelect = (walletId) => {
856
+ setSelectedWalletId(walletId);
857
+ setError(null);
858
+ };
859
+ const handleConnectAction = async () => {
860
+ if (!selectedWallet) return;
861
+ setError(null);
862
+ setIsSubmitting(true);
863
+ try {
864
+ if (selectedWallet.id === "viewing-key") {
865
+ if (!customKeyInput.trim()) {
866
+ throw new Error("Please enter a valid Unified Address or Viewing Key.");
867
+ }
868
+ await connect(selectedWallet.id, customKeyInput.trim());
869
+ } else {
870
+ await connect(selectedWallet.id);
871
+ }
872
+ } catch (err) {
873
+ setError(err instanceof Error ? err.message : "Connection failed");
874
+ } finally {
875
+ setIsSubmitting(false);
876
+ }
877
+ };
878
+ return createPortal(
879
+ /* @__PURE__ */ jsxs("div", { className: "fixed inset-0 z-[99999] flex items-center justify-center p-4 sm:p-6 overflow-y-auto font-sans", children: [
880
+ /* @__PURE__ */ jsx2(
881
+ "div",
882
+ {
883
+ className: "fixed inset-0 bg-[#171717]/60 backdrop-blur-sm transition-opacity z-[99999]",
884
+ onClick: handleClose
885
+ }
886
+ ),
887
+ /* @__PURE__ */ jsxs("div", { className: "relative w-full max-w-2xl bg-white rounded-xl border border-[#ededed] shadow-2xl overflow-hidden z-[100000] text-[#171717] animate-in fade-in zoom-in-95 duration-150", children: [
888
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-6 py-4 border-b border-[#ededed] bg-[#fafafa]", children: [
889
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2.5", children: [
890
+ /* @__PURE__ */ jsx2("div", { className: "w-8 h-8 rounded-md bg-[#171717] flex items-center justify-center text-[#3ecf8e]", children: /* @__PURE__ */ jsx2(Shield, { className: "w-4 h-4 fill-[#3ecf8e]" }) }),
891
+ /* @__PURE__ */ jsxs("div", { children: [
892
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
893
+ /* @__PURE__ */ jsx2("span", { className: "font-semibold text-sm text-[#171717]", children: "Connect Zcash Wallet" }),
894
+ /* @__PURE__ */ jsx2("span", { className: "text-[10px] uppercase tracking-wider font-semibold px-2 py-0.5 rounded-full bg-[#3ecf8e]/15 text-[#24b47e] border border-[#3ecf8e]/30", children: network })
895
+ ] }),
896
+ /* @__PURE__ */ jsxs("p", { className: "text-xs text-[#707070] mt-0.5", children: [
897
+ "Connect to ",
898
+ /* @__PURE__ */ jsx2("strong", { className: "text-[#171717]", children: appName }),
899
+ " with your preferred zero-knowledge wallet."
900
+ ] })
901
+ ] })
902
+ ] }),
903
+ /* @__PURE__ */ jsx2(
904
+ "button",
905
+ {
906
+ onClick: handleClose,
907
+ className: "p-1 rounded-md text-[#707070] hover:text-[#171717] hover:bg-[#ededed] transition-colors",
908
+ "aria-label": "Close modal",
909
+ children: /* @__PURE__ */ jsx2(X, { className: "w-4 h-4" })
910
+ }
911
+ )
912
+ ] }),
913
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 md:grid-cols-12 min-h-[380px]", children: [
914
+ /* @__PURE__ */ jsxs("div", { className: "md:col-span-5 p-3 bg-[#fafafa] border-r border-[#ededed] space-y-1", children: [
915
+ /* @__PURE__ */ jsx2("div", { className: "px-3 py-2 text-[11px] font-mono uppercase tracking-wider text-[#707070]", children: "Available Wallets" }),
916
+ wallets.map((w) => {
917
+ const active = w.id === selectedWalletId;
918
+ const available = w.isAvailable();
919
+ return /* @__PURE__ */ jsx2(
920
+ "button",
921
+ {
922
+ onClick: () => handleWalletSelect(w.id),
923
+ className: `w-full flex items-center justify-between p-3 rounded-lg text-left text-xs transition-all ${active ? "bg-white shadow-sm border border-[#dfdfdf] text-[#171717] font-medium" : "hover:bg-white/60 text-[#707070] hover:text-[#171717] border border-transparent"}`,
924
+ children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2.5", children: [
925
+ /* @__PURE__ */ jsx2("span", { className: "text-base", children: w.icon }),
926
+ /* @__PURE__ */ jsxs("div", { children: [
927
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
928
+ /* @__PURE__ */ jsx2("span", { className: "text-sm text-[#171717] font-medium", children: w.name }),
929
+ w.id === "zucchini" && available && /* @__PURE__ */ jsx2("span", { className: "text-[9px] uppercase font-mono px-1.5 py-0.2 rounded bg-emerald-100 text-emerald-800 font-bold", children: "Detected" })
930
+ ] }),
931
+ /* @__PURE__ */ jsx2("span", { className: "text-[11px] text-[#9a9a9a] line-clamp-1", children: w.category === "extension" ? "Browser Extension" : w.category === "mobile" ? "Mobile / QR" : w.category === "read-only" ? "Auditor View" : "Dev Session" })
932
+ ] })
933
+ ] })
934
+ },
935
+ w.id
936
+ );
937
+ })
938
+ ] }),
939
+ /* @__PURE__ */ jsxs("div", { className: "md:col-span-7 p-6 flex flex-col justify-between bg-white", children: [
940
+ /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
941
+ /* @__PURE__ */ jsx2("div", { className: "flex items-start justify-between pb-4 border-b border-[#ededed]", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2.5", children: [
942
+ /* @__PURE__ */ jsx2("span", { className: "text-2xl", children: selectedWallet.icon }),
943
+ /* @__PURE__ */ jsxs("div", { children: [
944
+ /* @__PURE__ */ jsx2("h4", { className: "text-base font-semibold text-[#171717]", children: selectedWallet.name }),
945
+ /* @__PURE__ */ jsx2("p", { className: "text-xs text-[#707070] mt-0.5", children: selectedWallet.description })
946
+ ] })
947
+ ] }) }),
948
+ error && /* @__PURE__ */ jsxs("div", { className: "p-3 rounded-md bg-rose-50 border border-rose-200 text-rose-800 text-xs flex items-start gap-2", children: [
949
+ /* @__PURE__ */ jsx2(AlertCircle, { className: "w-4 h-4 text-rose-600 flex-shrink-0 mt-0.5" }),
950
+ /* @__PURE__ */ jsx2("span", { children: error })
951
+ ] }),
952
+ selectedWallet.id === "zucchini" && /* @__PURE__ */ jsx2("div", { className: "space-y-4 py-2", children: isAvailable ? /* @__PURE__ */ jsxs("div", { className: "p-4 rounded-lg bg-emerald-50 border border-emerald-200 text-xs text-emerald-950 space-y-2", children: [
953
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 font-semibold", children: [
954
+ /* @__PURE__ */ jsx2(Sparkles, { className: "w-4 h-4 text-[#24b47e]" }),
955
+ /* @__PURE__ */ jsx2("span", { children: "Extension Detected & Ready" })
956
+ ] }),
957
+ /* @__PURE__ */ jsx2("p", { className: "text-emerald-800 leading-relaxed", children: "Clicking connect will prompt your Zucchini Wallet side-panel to authorize access." })
958
+ ] }) : /* @__PURE__ */ jsxs("div", { className: "p-4 rounded-lg bg-[#fafafa] border border-[#ededed] text-xs text-[#707070] space-y-3", children: [
959
+ /* @__PURE__ */ jsx2("p", { children: "Zucchini Wallet extension was not detected in this browser. Install it to enable 1-click in-browser approvals." }),
960
+ selectedWallet.downloadUrl && /* @__PURE__ */ jsxs(
961
+ "a",
962
+ {
963
+ href: selectedWallet.downloadUrl,
964
+ target: "_blank",
965
+ rel: "noopener noreferrer",
966
+ className: "inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-[#171717] text-white text-xs font-medium hover:bg-[#212121]",
967
+ children: [
968
+ /* @__PURE__ */ jsx2("span", { children: "Install from Chrome Web Store" }),
969
+ /* @__PURE__ */ jsx2(ExternalLink, { className: "w-3.5 h-3.5" })
970
+ ]
971
+ }
972
+ )
973
+ ] }) }),
974
+ (selectedWallet.id === "zashi" || selectedWallet.id === "ywallet") && /* @__PURE__ */ jsxs("div", { className: "text-center space-y-3 py-1", children: [
975
+ /* @__PURE__ */ jsx2("div", { className: "flex justify-center", children: /* @__PURE__ */ jsx2(
976
+ CiceroQRCode,
977
+ {
978
+ value: `zcash:u1demo?message=Connect%20to%20${encodeURIComponent(appName || "Cicero App")}`,
979
+ size: 150
980
+ }
981
+ ) }),
982
+ /* @__PURE__ */ jsxs("div", { children: [
983
+ /* @__PURE__ */ jsxs("p", { className: "text-xs font-medium text-[#171717]", children: [
984
+ "Scan with ",
985
+ selectedWallet.name,
986
+ " app"
987
+ ] }),
988
+ /* @__PURE__ */ jsxs("p", { className: "text-[11px] text-[#707070] mt-0.5", children: [
989
+ "Open ",
990
+ selectedWallet.name,
991
+ " on iOS/Android and scan this QR code to authenticate."
992
+ ] })
993
+ ] })
994
+ ] }),
995
+ selectedWallet.id === "viewing-key" && /* @__PURE__ */ jsxs("div", { className: "space-y-3 py-2 text-xs", children: [
996
+ /* @__PURE__ */ jsxs("div", { children: [
997
+ /* @__PURE__ */ jsx2("label", { className: "font-medium text-[#171717] block mb-1", children: "Unified Address or Viewing Key" }),
998
+ /* @__PURE__ */ jsx2(
999
+ "textarea",
1000
+ {
1001
+ rows: 3,
1002
+ value: customKeyInput,
1003
+ onChange: (e) => setCustomKeyInput(e.target.value),
1004
+ placeholder: "Paste u1... address, zxviews... or uview... key",
1005
+ className: "w-full p-2.5 rounded-md bg-white border border-[#dfdfdf] font-mono text-xs text-[#171717] focus:outline-none focus:border-[#3ecf8e]"
1006
+ }
1007
+ )
1008
+ ] }),
1009
+ /* @__PURE__ */ jsx2("p", { className: "text-[11px] text-[#707070]", children: "Read-only connection for tax calculation, accounting reconciliation, or proof-of-reserves." })
1010
+ ] }),
1011
+ selectedWallet.id === "burner" && /* @__PURE__ */ jsx2("div", { className: "space-y-3 py-2 text-xs", children: /* @__PURE__ */ jsxs("div", { className: "p-3.5 rounded-lg bg-[#fafafa] border border-[#ededed] space-y-1.5", children: [
1012
+ /* @__PURE__ */ jsx2("span", { className: "font-semibold text-[#171717]", children: "Ephemeral Shielded Test Wallet" }),
1013
+ /* @__PURE__ */ jsx2("p", { className: "text-[#707070] leading-relaxed", children: "Instantly creates an in-memory session wallet pre-funded with simulated testnet ZEC. Perfect for testing dApps without needing external extensions." })
1014
+ ] }) })
1015
+ ] }),
1016
+ /* @__PURE__ */ jsxs("div", { className: "pt-4 border-t border-[#ededed] mt-4 flex items-center justify-between", children: [
1017
+ /* @__PURE__ */ jsx2("span", { className: "text-[11px] text-[#9a9a9a]", children: "End-to-End Encrypted" }),
1018
+ /* @__PURE__ */ jsx2(
1019
+ "button",
1020
+ {
1021
+ onClick: handleConnectAction,
1022
+ disabled: isSubmitting,
1023
+ className: "inline-flex items-center gap-2 px-5 py-2.5 rounded-md bg-[#3ecf8e] text-[#171717] font-semibold text-xs hover:bg-[#24b47e] transition-colors disabled:opacity-50 shadow-sm",
1024
+ children: isSubmitting ? /* @__PURE__ */ jsxs(Fragment, { children: [
1025
+ /* @__PURE__ */ jsx2("span", { className: "w-3.5 h-3.5 border-2 border-[#171717]/30 border-t-[#171717] rounded-full animate-spin" }),
1026
+ /* @__PURE__ */ jsx2("span", { children: "Connecting..." })
1027
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1028
+ /* @__PURE__ */ jsx2("span", { children: selectedWallet.id === "viewing-key" ? "Connect Read-Only" : selectedWallet.id === "burner" ? "Launch Dev Session" : `Connect ${selectedWallet.name}` }),
1029
+ /* @__PURE__ */ jsx2(ArrowRight, { className: "w-3.5 h-3.5" })
1030
+ ] })
1031
+ }
1032
+ )
1033
+ ] })
1034
+ ] })
1035
+ ] })
1036
+ ] })
1037
+ ] }),
1038
+ document.body
1039
+ );
1040
+ };
1041
+
1042
+ // src/components/CiceroAccountModal.tsx
1043
+ import { useState as useState3, useEffect as useEffect3 } from "react";
1044
+ import { createPortal as createPortal2 } from "react-dom";
1045
+ import {
1046
+ X as X2,
1047
+ Copy,
1048
+ Check,
1049
+ LogOut,
1050
+ ExternalLink as ExternalLink2,
1051
+ Shield as Shield2,
1052
+ RefreshCw,
1053
+ QrCode,
1054
+ ArrowRightLeft
1055
+ } from "lucide-react";
1056
+
1057
+ // src/utils/address.ts
1058
+ function getAddressType(address) {
1059
+ if (!address || typeof address !== "string") {
1060
+ return "unknown";
1061
+ }
1062
+ const clean = address.trim();
1063
+ if (clean.startsWith("u1") || clean.startsWith("utest1")) {
1064
+ return "unified";
1065
+ }
1066
+ if (clean.startsWith("zs1") || clean.startsWith("ztestsapling1")) {
1067
+ return "sapling";
1068
+ }
1069
+ if (clean.startsWith("t1") || clean.startsWith("t3") || clean.startsWith("tm")) {
1070
+ return "transparent";
1071
+ }
1072
+ return "unknown";
1073
+ }
1074
+ function isShieldedAddress(address) {
1075
+ const type = getAddressType(address);
1076
+ return type === "unified" || type === "sapling";
1077
+ }
1078
+ function truncateAddress(address, start = 8, end = 8) {
1079
+ if (!address) return "";
1080
+ const clean = address.trim();
1081
+ if (clean.length <= start + end + 3) {
1082
+ return clean;
1083
+ }
1084
+ return `${clean.slice(0, start)}...${clean.slice(-end)}`;
1085
+ }
1086
+ function validateMemoSupport(address, memo) {
1087
+ const byteLength = memo ? new TextEncoder().encode(memo).length : 0;
1088
+ const isAddressShielded = isShieldedAddress(address);
1089
+ if (byteLength > 512) {
1090
+ return {
1091
+ valid: false,
1092
+ warning: `Memo exceeds Zcash protocol limit of 512 bytes (current: ${byteLength} bytes).`,
1093
+ byteLength
1094
+ };
1095
+ }
1096
+ if (memo && !isAddressShielded) {
1097
+ return {
1098
+ valid: true,
1099
+ warning: "Warning: Transparent addresses (t-addr) do not support shielded encrypted memos. Use a Unified (u1) or Sapling (zs1) address to protect your memo.",
1100
+ byteLength
1101
+ };
1102
+ }
1103
+ return {
1104
+ valid: true,
1105
+ byteLength
1106
+ };
1107
+ }
1108
+
1109
+ // src/components/CiceroAccountModal.tsx
1110
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
1111
+ var CiceroAccountModal = ({
1112
+ isOpen: propIsOpen,
1113
+ onClose: propOnClose
1114
+ }) => {
1115
+ const {
1116
+ isAccountModalOpen,
1117
+ closeAccountModal,
1118
+ address,
1119
+ wallet,
1120
+ network,
1121
+ switchNetwork,
1122
+ balance,
1123
+ refetchBalance,
1124
+ disconnect
1125
+ } = useCicero();
1126
+ const isOpen = propIsOpen !== void 0 ? propIsOpen : isAccountModalOpen;
1127
+ const handleClose = propOnClose || closeAccountModal;
1128
+ const [copied, setCopied] = useState3(false);
1129
+ const [showQr, setShowQr] = useState3(false);
1130
+ const [mounted, setMounted] = useState3(false);
1131
+ const [manualNotice, setManualNotice] = useState3(null);
1132
+ useEffect3(() => {
1133
+ setMounted(true);
1134
+ }, []);
1135
+ useEffect3(() => {
1136
+ setManualNotice(null);
1137
+ }, [network, isOpen]);
1138
+ const handleNetworkChange = async (targetNet) => {
1139
+ if (targetNet === network) {
1140
+ setManualNotice(null);
1141
+ return;
1142
+ }
1143
+ const res = await switchNetwork(targetNet);
1144
+ if (res?.requiresManualSwitch) {
1145
+ setManualNotice(
1146
+ `Wallet is currently active on ${network === "mainnet" ? "Mainnet" : "Testnet"}. Switch network inside your extension settings (Settings \u2192 Network) and Cicero will automatically update your balance.`
1147
+ );
1148
+ } else {
1149
+ setManualNotice(null);
1150
+ }
1151
+ };
1152
+ useEffect3(() => {
1153
+ const handleKeyDown = (e) => {
1154
+ if (e.key === "Escape" && isOpen) {
1155
+ handleClose();
1156
+ }
1157
+ };
1158
+ window.addEventListener("keydown", handleKeyDown);
1159
+ return () => window.removeEventListener("keydown", handleKeyDown);
1160
+ }, [isOpen, handleClose]);
1161
+ if (!isOpen || !mounted) return null;
1162
+ const copyAddress = async () => {
1163
+ if (!address) return;
1164
+ try {
1165
+ await navigator.clipboard.writeText(address);
1166
+ setCopied(true);
1167
+ setTimeout(() => setCopied(false), 2e3);
1168
+ } catch {
1169
+ }
1170
+ };
1171
+ return createPortal2(
1172
+ /* @__PURE__ */ jsxs2("div", { className: "fixed inset-0 z-[99999] flex items-center justify-center p-4 sm:p-6 overflow-y-auto font-sans", children: [
1173
+ /* @__PURE__ */ jsx3(
1174
+ "div",
1175
+ {
1176
+ className: "fixed inset-0 bg-[#171717]/60 backdrop-blur-sm transition-opacity z-[99999]",
1177
+ onClick: handleClose
1178
+ }
1179
+ ),
1180
+ /* @__PURE__ */ jsxs2("div", { className: "relative w-full max-w-md bg-white rounded-xl border border-[#ededed] shadow-2xl overflow-hidden z-[100000] text-[#171717] animate-in fade-in zoom-in-95 duration-150", children: [
1181
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between px-6 py-4 border-b border-[#ededed] bg-[#fafafa]", children: [
1182
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-2", children: [
1183
+ /* @__PURE__ */ jsx3("span", { className: "text-xl", children: wallet?.icon || "\u{1F6E1}\uFE0F" }),
1184
+ /* @__PURE__ */ jsxs2("div", { children: [
1185
+ /* @__PURE__ */ jsx3("span", { className: "font-semibold text-sm text-[#171717]", children: wallet?.name || "Zcash Wallet" }),
1186
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-1.5 text-[11px] text-[#707070]", children: [
1187
+ /* @__PURE__ */ jsx3("span", { className: "w-1.5 h-1.5 rounded-full bg-[#24b47e]" }),
1188
+ /* @__PURE__ */ jsx3("span", { children: "Connected" })
1189
+ ] })
1190
+ ] })
1191
+ ] }),
1192
+ /* @__PURE__ */ jsx3(
1193
+ "button",
1194
+ {
1195
+ onClick: handleClose,
1196
+ className: "p-1 rounded-md text-[#707070] hover:text-[#171717] hover:bg-[#ededed] transition-colors",
1197
+ children: /* @__PURE__ */ jsx3(X2, { className: "w-4 h-4" })
1198
+ }
1199
+ )
1200
+ ] }),
1201
+ /* @__PURE__ */ jsxs2("div", { className: "p-6 space-y-5", children: [
1202
+ /* @__PURE__ */ jsxs2("div", { className: "p-4 rounded-lg bg-[#fafafa] border border-[#ededed] text-center space-y-1", children: [
1203
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-center gap-1.5 text-xs text-[#707070]", children: [
1204
+ /* @__PURE__ */ jsx3("span", { children: "Shielded Balance" }),
1205
+ /* @__PURE__ */ jsx3(
1206
+ "button",
1207
+ {
1208
+ onClick: () => refetchBalance(),
1209
+ className: "hover:text-[#171717] p-0.5",
1210
+ title: "Refresh balance",
1211
+ children: /* @__PURE__ */ jsx3(
1212
+ RefreshCw,
1213
+ {
1214
+ className: `w-3 h-3 ${balance.isLoading ? "animate-spin text-[#3ecf8e]" : ""}`
1215
+ }
1216
+ )
1217
+ }
1218
+ )
1219
+ ] }),
1220
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-baseline justify-center gap-1.5", children: [
1221
+ /* @__PURE__ */ jsx3("span", { className: "text-3xl font-bold font-mono text-[#171717] tracking-tight", children: balance.zec }),
1222
+ /* @__PURE__ */ jsx3("span", { className: "text-sm font-medium text-[#707070]", children: "ZEC" })
1223
+ ] }),
1224
+ balance.usd && /* @__PURE__ */ jsxs2("p", { className: "text-xs text-[#707070] font-mono", children: [
1225
+ "\u2248 $",
1226
+ balance.usd,
1227
+ " USD"
1228
+ ] })
1229
+ ] }),
1230
+ /* @__PURE__ */ jsxs2("div", { className: "space-y-2 text-xs", children: [
1231
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between text-[#707070]", children: [
1232
+ /* @__PURE__ */ jsx3("span", { children: "Your Shielded Address" }),
1233
+ /* @__PURE__ */ jsxs2(
1234
+ "button",
1235
+ {
1236
+ onClick: () => setShowQr(!showQr),
1237
+ className: "flex items-center gap-1 text-[#24b47e] hover:underline",
1238
+ children: [
1239
+ /* @__PURE__ */ jsx3(QrCode, { className: "w-3.5 h-3.5" }),
1240
+ /* @__PURE__ */ jsx3("span", { children: showQr ? "Hide QR" : "Show QR" })
1241
+ ]
1242
+ }
1243
+ )
1244
+ ] }),
1245
+ address ? /* @__PURE__ */ jsxs2("div", { className: "p-3 bg-[#fafafa] rounded-md border border-[#ededed] font-mono text-xs text-[#171717] break-all select-all flex items-center justify-between gap-2", children: [
1246
+ /* @__PURE__ */ jsx3("span", { className: "truncate", children: truncateAddress(address, 16, 12) }),
1247
+ /* @__PURE__ */ jsx3(
1248
+ "button",
1249
+ {
1250
+ onClick: copyAddress,
1251
+ className: "p-1 rounded hover:bg-white text-[#707070] hover:text-[#171717] transition-colors flex-shrink-0",
1252
+ title: "Copy full address",
1253
+ children: copied ? /* @__PURE__ */ jsx3(Check, { className: "w-3.5 h-3.5 text-[#24b47e]" }) : /* @__PURE__ */ jsx3(Copy, { className: "w-3.5 h-3.5" })
1254
+ }
1255
+ )
1256
+ ] }) : /* @__PURE__ */ jsx3("div", { className: "p-3 bg-[#fafafa] rounded-md border border-[#ededed] text-xs text-[#707070]", children: "Connected in Read-Only Mode" }),
1257
+ showQr && address && /* @__PURE__ */ jsx3("div", { className: "pt-2 flex justify-center", children: /* @__PURE__ */ jsx3(CiceroQRCode, { value: `zcash:${address}`, size: 160 }) }),
1258
+ address && /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between text-[11px] pt-1", children: [
1259
+ /* @__PURE__ */ jsxs2("span", { className: "flex items-center gap-1 text-[#707070]", children: [
1260
+ /* @__PURE__ */ jsx3(Shield2, { className: "w-3 h-3 text-[#3ecf8e]" }),
1261
+ /* @__PURE__ */ jsx3("span", { children: "zk-Shielded Address" })
1262
+ ] }),
1263
+ /* @__PURE__ */ jsxs2(
1264
+ "a",
1265
+ {
1266
+ href: network === "testnet" ? `https://blockexplorer.one/zcash/testnet/address/${address}` : `https://blockchair.com/zcash/address/${address}`,
1267
+ target: "_blank",
1268
+ rel: "noopener noreferrer",
1269
+ className: "flex items-center gap-1 text-[#24b47e] hover:underline",
1270
+ children: [
1271
+ /* @__PURE__ */ jsx3("span", { children: "View on Explorer" }),
1272
+ /* @__PURE__ */ jsx3(ExternalLink2, { className: "w-3 h-3" })
1273
+ ]
1274
+ }
1275
+ )
1276
+ ] })
1277
+ ] }),
1278
+ /* @__PURE__ */ jsxs2("div", { className: "space-y-2", children: [
1279
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between p-3 rounded-lg border border-[#ededed] bg-white text-xs", children: [
1280
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-2", children: [
1281
+ /* @__PURE__ */ jsx3(ArrowRightLeft, { className: "w-4 h-4 text-[#707070]" }),
1282
+ /* @__PURE__ */ jsx3("span", { className: "text-[#171717] font-medium", children: "Active Network" })
1283
+ ] }),
1284
+ /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-1 p-0.5 rounded bg-[#fafafa] border border-[#dfdfdf]", children: [
1285
+ /* @__PURE__ */ jsx3(
1286
+ "button",
1287
+ {
1288
+ type: "button",
1289
+ onClick: () => handleNetworkChange("mainnet"),
1290
+ className: `px-2 py-1 rounded text-[11px] font-medium transition-colors ${network === "mainnet" ? "bg-white shadow-sm text-[#24b47e] font-semibold" : "text-[#707070] hover:text-[#171717]"}`,
1291
+ children: "Mainnet"
1292
+ }
1293
+ ),
1294
+ /* @__PURE__ */ jsx3(
1295
+ "button",
1296
+ {
1297
+ type: "button",
1298
+ onClick: () => handleNetworkChange("testnet"),
1299
+ className: `px-2 py-1 rounded text-[11px] font-medium transition-colors ${network === "testnet" ? "bg-white shadow-sm text-amber-700 font-semibold" : "text-[#707070] hover:text-[#171717]"}`,
1300
+ children: "Testnet"
1301
+ }
1302
+ )
1303
+ ] })
1304
+ ] }),
1305
+ manualNotice && /* @__PURE__ */ jsx3("div", { className: "p-2.5 rounded-md bg-amber-50 border border-amber-200 text-amber-800 text-[11px] leading-relaxed animate-in fade-in", children: /* @__PURE__ */ jsx3("span", { children: manualNotice }) })
1306
+ ] })
1307
+ ] }),
1308
+ /* @__PURE__ */ jsxs2("div", { className: "px-6 py-3.5 bg-[#fafafa] border-t border-[#ededed] flex items-center justify-between", children: [
1309
+ /* @__PURE__ */ jsxs2(
1310
+ "button",
1311
+ {
1312
+ onClick: disconnect,
1313
+ className: "flex items-center gap-1.5 text-xs text-rose-600 hover:text-rose-700 font-medium transition-colors",
1314
+ children: [
1315
+ /* @__PURE__ */ jsx3(LogOut, { className: "w-3.5 h-3.5" }),
1316
+ /* @__PURE__ */ jsx3("span", { children: "Disconnect Wallet" })
1317
+ ]
1318
+ }
1319
+ ),
1320
+ /* @__PURE__ */ jsx3(
1321
+ "button",
1322
+ {
1323
+ onClick: handleClose,
1324
+ className: "px-3.5 py-1.5 rounded-md border border-[#dfdfdf] bg-white hover:bg-[#fafafa] text-xs font-medium text-[#171717] transition-colors",
1325
+ children: "Done"
1326
+ }
1327
+ )
1328
+ ] })
1329
+ ] })
1330
+ ] }),
1331
+ document.body
1332
+ );
1333
+ };
1334
+
1335
+ // src/context/CiceroContext.tsx
1336
+ import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
1337
+ var CiceroContext = createContext(null);
1338
+ var CiceroProvider = ({
1339
+ children,
1340
+ initialNetwork = "mainnet",
1341
+ wallets = getDefaultWallets(),
1342
+ appName = "Zcash App",
1343
+ appLogo,
1344
+ autoConnect = true
1345
+ }) => {
1346
+ const [network, setNetwork] = useState4(initialNetwork);
1347
+ const [account, setAccount] = useState4({
1348
+ address: null,
1349
+ viewingKey: null,
1350
+ isConnected: false,
1351
+ isConnecting: false,
1352
+ status: "disconnected",
1353
+ wallet: null,
1354
+ error: null
1355
+ });
1356
+ const [balance, setBalance] = useState4({
1357
+ zec: 0,
1358
+ usd: null,
1359
+ isLoading: false
1360
+ });
1361
+ const [isConnectModalOpen, setIsConnectModalOpen] = useState4(false);
1362
+ const [isAccountModalOpen, setIsAccountModalOpen] = useState4(false);
1363
+ const { convertZecToUsd } = useZcashPrice(true);
1364
+ const convertZecToUsdRef = useRef(convertZecToUsd);
1365
+ convertZecToUsdRef.current = convertZecToUsd;
1366
+ const walletsRef = useRef(wallets);
1367
+ walletsRef.current = wallets;
1368
+ useEffect4(() => {
1369
+ if (typeof window === "undefined") return;
1370
+ const savedWalletId = localStorage.getItem("cicero_wallet_id");
1371
+ const savedAddress = localStorage.getItem("cicero_address");
1372
+ const savedNetwork = localStorage.getItem("cicero_network");
1373
+ if (savedNetwork) {
1374
+ setNetwork(savedNetwork);
1375
+ }
1376
+ if (autoConnect && savedWalletId) {
1377
+ const targetWallet = walletsRef.current.find((w) => w.id === savedWalletId);
1378
+ if (targetWallet && (savedAddress || targetWallet.isAvailable())) {
1379
+ const savedBal = localStorage.getItem("cicero_balance");
1380
+ const parsedBal = savedBal ? parseFloat(savedBal) : null;
1381
+ const activeZec = parsedBal !== null && !isNaN(parsedBal) ? parsedBal : 0;
1382
+ const initialUsd = convertZecToUsdRef.current(activeZec);
1383
+ setAccount({
1384
+ address: savedAddress || null,
1385
+ viewingKey: null,
1386
+ isConnected: true,
1387
+ isConnecting: false,
1388
+ status: "connected",
1389
+ wallet: targetWallet,
1390
+ error: null
1391
+ });
1392
+ setBalance({
1393
+ zec: activeZec,
1394
+ usd: initialUsd,
1395
+ isLoading: false
1396
+ });
1397
+ if (targetWallet.getBalance) {
1398
+ targetWallet.getBalance({ address: savedAddress || void 0, network }).then((freshBal) => {
1399
+ if (freshBal !== null && !isNaN(freshBal)) {
1400
+ setBalance({
1401
+ zec: freshBal,
1402
+ usd: convertZecToUsdRef.current(freshBal),
1403
+ isLoading: false
1404
+ });
1405
+ localStorage.setItem("cicero_balance", freshBal.toString());
1406
+ }
1407
+ }).catch(() => {
1408
+ });
1409
+ }
1410
+ }
1411
+ }
1412
+ }, [autoConnect]);
1413
+ useEffect4(() => {
1414
+ if (typeof window === "undefined") return;
1415
+ const cleanupReady = ZucchiniWalletAdapter.onReady(() => {
1416
+ const savedWalletId = localStorage.getItem("cicero_wallet_id");
1417
+ const savedAddress = localStorage.getItem("cicero_address");
1418
+ if (savedWalletId === "zucchini" && autoConnect) {
1419
+ const zucchini = walletsRef.current.find((w) => w.id === "zucchini");
1420
+ if (zucchini) {
1421
+ setAccount((prev) => {
1422
+ if (prev.isConnected && prev.wallet?.id === "zucchini") return prev;
1423
+ return {
1424
+ address: savedAddress || null,
1425
+ viewingKey: null,
1426
+ isConnected: true,
1427
+ isConnecting: false,
1428
+ status: "connected",
1429
+ wallet: zucchini,
1430
+ error: null
1431
+ };
1432
+ });
1433
+ }
1434
+ }
1435
+ });
1436
+ return () => {
1437
+ cleanupReady();
1438
+ };
1439
+ }, [autoConnect]);
1440
+ useEffect4(() => {
1441
+ if (typeof window === "undefined") return;
1442
+ const adapter2 = new ZucchiniWalletAdapter();
1443
+ const cleanup = adapter2.onNetworkChanged(async (detectedNet) => {
1444
+ setNetwork(detectedNet);
1445
+ localStorage.setItem("cicero_network", detectedNet);
1446
+ if (account.wallet?.id === "zucchini") {
1447
+ setBalance((prev) => ({ ...prev, isLoading: true }));
1448
+ try {
1449
+ const freshBal = await adapter2.getBalance({
1450
+ address: account.address || void 0,
1451
+ network: detectedNet
1452
+ });
1453
+ const activeZec = freshBal !== null && !isNaN(freshBal) ? freshBal : 0;
1454
+ setBalance({
1455
+ zec: activeZec,
1456
+ usd: convertZecToUsdRef.current(activeZec),
1457
+ isLoading: false
1458
+ });
1459
+ localStorage.setItem("cicero_balance", activeZec.toString());
1460
+ localStorage.setItem(`cicero_balance_${detectedNet}`, activeZec.toString());
1461
+ } catch {
1462
+ setBalance((prev) => ({ ...prev, isLoading: false }));
1463
+ }
1464
+ }
1465
+ });
1466
+ return () => {
1467
+ cleanup();
1468
+ };
1469
+ }, [account.wallet?.id, account.address]);
1470
+ useEffect4(() => {
1471
+ if (account.isConnected) {
1472
+ setBalance((prev) => {
1473
+ const newUsd = convertZecToUsd(prev.zec);
1474
+ if (prev.usd === newUsd) return prev;
1475
+ return {
1476
+ ...prev,
1477
+ usd: newUsd
1478
+ };
1479
+ });
1480
+ }
1481
+ }, [account.isConnected, balance.zec, convertZecToUsd]);
1482
+ const switchNetwork = useCallback2(
1483
+ async (newNet) => {
1484
+ if (account.wallet?.switchNetwork) {
1485
+ try {
1486
+ const switchRes = await account.wallet.switchNetwork(newNet);
1487
+ if (switchRes && switchRes.requiresManualSwitch) {
1488
+ const currentNet = switchRes.currentNetwork || (account.wallet.getNetwork ? await account.wallet.getNetwork() : network);
1489
+ setNetwork(currentNet);
1490
+ if (typeof window !== "undefined") {
1491
+ localStorage.setItem("cicero_network", currentNet);
1492
+ }
1493
+ return {
1494
+ success: false,
1495
+ requiresManualSwitch: true,
1496
+ currentNetwork: currentNet
1497
+ };
1498
+ }
1499
+ } catch {
1500
+ }
1501
+ }
1502
+ setNetwork(newNet);
1503
+ if (typeof window !== "undefined") {
1504
+ localStorage.setItem("cicero_network", newNet);
1505
+ }
1506
+ if (account.wallet?.getBalance) {
1507
+ setBalance((prev) => ({ ...prev, isLoading: true }));
1508
+ try {
1509
+ const freshBal = await account.wallet.getBalance({
1510
+ address: account.address || void 0,
1511
+ network: newNet
1512
+ });
1513
+ const activeZec = freshBal !== null && !isNaN(freshBal) ? freshBal : 0;
1514
+ setBalance({
1515
+ zec: activeZec,
1516
+ usd: convertZecToUsdRef.current(activeZec),
1517
+ isLoading: false
1518
+ });
1519
+ if (typeof window !== "undefined" && freshBal !== null) {
1520
+ localStorage.setItem(`cicero_balance_${newNet}`, freshBal.toString());
1521
+ localStorage.setItem("cicero_balance", freshBal.toString());
1522
+ }
1523
+ } catch {
1524
+ setBalance((prev) => ({ ...prev, isLoading: false }));
1525
+ }
1526
+ }
1527
+ return { success: true, currentNetwork: newNet };
1528
+ },
1529
+ [account.wallet, account.address, network]
1530
+ );
1531
+ const connect = useCallback2(
1532
+ async (walletId, customAddressOrKey) => {
1533
+ const targetWallet = wallets.find((w) => w.id === walletId);
1534
+ if (!targetWallet) {
1535
+ throw new Error(`Wallet ${walletId} not found in registered wallets`);
1536
+ }
1537
+ setAccount((prev) => ({
1538
+ ...prev,
1539
+ isConnecting: true,
1540
+ status: "connecting",
1541
+ error: null
1542
+ }));
1543
+ try {
1544
+ let session;
1545
+ if (walletId === "viewing-key" && customAddressOrKey) {
1546
+ session = {
1547
+ address: customAddressOrKey,
1548
+ viewingKey: customAddressOrKey.startsWith("zx") || customAddressOrKey.startsWith("uview") ? customAddressOrKey : void 0,
1549
+ connected: true,
1550
+ network,
1551
+ walletId: "viewing-key"
1552
+ };
1553
+ } else {
1554
+ session = await targetWallet.connect({ network });
1555
+ }
1556
+ const resolvedAddress = session.address || customAddressOrKey || null;
1557
+ const walletNetwork = session.network || (targetWallet.getNetwork ? await targetWallet.getNetwork() : network);
1558
+ if (walletNetwork && walletNetwork !== network) {
1559
+ setNetwork(walletNetwork);
1560
+ if (typeof window !== "undefined") {
1561
+ localStorage.setItem("cicero_network", walletNetwork);
1562
+ }
1563
+ }
1564
+ setAccount({
1565
+ address: resolvedAddress,
1566
+ viewingKey: session.viewingKey || null,
1567
+ isConnected: true,
1568
+ isConnecting: false,
1569
+ status: "connected",
1570
+ wallet: targetWallet,
1571
+ error: null
1572
+ });
1573
+ let resolvedZec = session.balance ?? null;
1574
+ if (resolvedZec === null && targetWallet.getBalance) {
1575
+ try {
1576
+ resolvedZec = await targetWallet.getBalance({
1577
+ address: resolvedAddress || void 0,
1578
+ network
1579
+ });
1580
+ } catch {
1581
+ }
1582
+ }
1583
+ if (resolvedZec === null && typeof window !== "undefined") {
1584
+ const cached = localStorage.getItem("cicero_balance");
1585
+ if (cached && !isNaN(parseFloat(cached))) {
1586
+ resolvedZec = parseFloat(cached);
1587
+ }
1588
+ }
1589
+ const activeZec = resolvedZec !== null && !isNaN(resolvedZec) ? resolvedZec : 0;
1590
+ setBalance({
1591
+ zec: activeZec,
1592
+ usd: convertZecToUsd(activeZec),
1593
+ isLoading: false
1594
+ });
1595
+ if (typeof window !== "undefined" && resolvedZec !== null) {
1596
+ localStorage.setItem("cicero_balance", resolvedZec.toString());
1597
+ }
1598
+ if (typeof window !== "undefined") {
1599
+ localStorage.setItem("cicero_wallet_id", walletId);
1600
+ if (resolvedAddress) {
1601
+ localStorage.setItem("cicero_address", resolvedAddress);
1602
+ }
1603
+ }
1604
+ setIsConnectModalOpen(false);
1605
+ } catch (err) {
1606
+ const msg = err instanceof Error ? err.message : "Connection failed";
1607
+ setAccount((prev) => ({
1608
+ ...prev,
1609
+ isConnecting: false,
1610
+ status: "error",
1611
+ error: msg
1612
+ }));
1613
+ throw err;
1614
+ }
1615
+ },
1616
+ [wallets, network, convertZecToUsd]
1617
+ );
1618
+ const disconnect = useCallback2(async () => {
1619
+ if (account.wallet?.disconnect) {
1620
+ try {
1621
+ await account.wallet.disconnect();
1622
+ } catch {
1623
+ }
1624
+ }
1625
+ setAccount({
1626
+ address: null,
1627
+ viewingKey: null,
1628
+ isConnected: false,
1629
+ isConnecting: false,
1630
+ status: "disconnected",
1631
+ wallet: null,
1632
+ error: null
1633
+ });
1634
+ setBalance({
1635
+ zec: 0,
1636
+ usd: null,
1637
+ isLoading: false
1638
+ });
1639
+ if (typeof window !== "undefined") {
1640
+ localStorage.removeItem("cicero_wallet_id");
1641
+ localStorage.removeItem("cicero_address");
1642
+ localStorage.removeItem("cicero_balance");
1643
+ }
1644
+ setIsAccountModalOpen(false);
1645
+ }, [account.wallet]);
1646
+ const sendPayment = useCallback2(
1647
+ async (params) => {
1648
+ if (!account.wallet) {
1649
+ throw new Error("No wallet connected. Please connect a Zcash wallet first.");
1650
+ }
1651
+ if (account.wallet.sendPayment) {
1652
+ return account.wallet.sendPayment(params);
1653
+ }
1654
+ throw new Error(`Wallet ${account.wallet.name} does not support programmatic send.`);
1655
+ },
1656
+ [account.wallet]
1657
+ );
1658
+ const refetchBalance = useCallback2(async () => {
1659
+ if (!account.wallet) return;
1660
+ setBalance((prev) => ({ ...prev, isLoading: true }));
1661
+ try {
1662
+ let freshZec = null;
1663
+ if (account.wallet.getBalance) {
1664
+ freshZec = await account.wallet.getBalance({
1665
+ address: account.address || void 0,
1666
+ network
1667
+ });
1668
+ }
1669
+ if (freshZec !== null && !isNaN(freshZec)) {
1670
+ setBalance({
1671
+ zec: freshZec,
1672
+ usd: convertZecToUsd(freshZec),
1673
+ isLoading: false
1674
+ });
1675
+ if (typeof window !== "undefined") {
1676
+ localStorage.setItem("cicero_balance", freshZec.toString());
1677
+ }
1678
+ return;
1679
+ }
1680
+ } catch {
1681
+ }
1682
+ setBalance((prev) => ({
1683
+ ...prev,
1684
+ isLoading: false,
1685
+ usd: convertZecToUsd(prev.zec)
1686
+ }));
1687
+ }, [account.wallet, account.address, network, convertZecToUsd]);
1688
+ const openConnectModal = useCallback2(() => setIsConnectModalOpen(true), []);
1689
+ const closeConnectModal = useCallback2(() => setIsConnectModalOpen(false), []);
1690
+ const openAccountModal = useCallback2(() => setIsAccountModalOpen(true), []);
1691
+ const closeAccountModal = useCallback2(() => setIsAccountModalOpen(false), []);
1692
+ const value = useMemo(
1693
+ () => ({
1694
+ account,
1695
+ address: account.address,
1696
+ isConnected: account.isConnected,
1697
+ isConnecting: account.isConnecting,
1698
+ wallet: account.wallet,
1699
+ network,
1700
+ switchNetwork,
1701
+ balance,
1702
+ refetchBalance,
1703
+ connect,
1704
+ disconnect,
1705
+ sendPayment,
1706
+ isConnectModalOpen,
1707
+ openConnectModal,
1708
+ closeConnectModal,
1709
+ isAccountModalOpen,
1710
+ openAccountModal,
1711
+ closeAccountModal,
1712
+ wallets,
1713
+ appName,
1714
+ appLogo
1715
+ }),
1716
+ [
1717
+ account,
1718
+ network,
1719
+ switchNetwork,
1720
+ balance,
1721
+ refetchBalance,
1722
+ connect,
1723
+ disconnect,
1724
+ sendPayment,
1725
+ isConnectModalOpen,
1726
+ openConnectModal,
1727
+ closeConnectModal,
1728
+ isAccountModalOpen,
1729
+ openAccountModal,
1730
+ closeAccountModal,
1731
+ wallets,
1732
+ appName,
1733
+ appLogo
1734
+ ]
1735
+ );
1736
+ return /* @__PURE__ */ jsxs3(CiceroContext.Provider, { value, children: [
1737
+ children,
1738
+ /* @__PURE__ */ jsx4(CiceroConnectModal, {}),
1739
+ /* @__PURE__ */ jsx4(CiceroAccountModal, {})
1740
+ ] });
1741
+ };
1742
+ function useCicero() {
1743
+ const ctx = useContext(CiceroContext);
1744
+ if (!ctx) {
1745
+ throw new Error("useCicero must be used within a <CiceroProvider>");
1746
+ }
1747
+ return ctx;
1748
+ }
1749
+ var useAccount = () => {
1750
+ const { account, address, isConnected, isConnecting, wallet, disconnect } = useCicero();
1751
+ return { ...account, address, isConnected, isConnecting, wallet, disconnect };
1752
+ };
1753
+ var useBalance = () => {
1754
+ const { balance, refetchBalance } = useCicero();
1755
+ return { ...balance, refetch: refetchBalance };
1756
+ };
1757
+ var useConnectModal = () => {
1758
+ const { isConnectModalOpen, openConnectModal, closeConnectModal } = useCicero();
1759
+ return {
1760
+ isOpen: isConnectModalOpen,
1761
+ openConnectModal,
1762
+ closeConnectModal
1763
+ };
1764
+ };
1765
+ var useAccountModal = () => {
1766
+ const { isAccountModalOpen, openAccountModal, closeAccountModal } = useCicero();
1767
+ return {
1768
+ isOpen: isAccountModalOpen,
1769
+ openAccountModal,
1770
+ closeAccountModal
1771
+ };
1772
+ };
1773
+
1774
+ // src/components/CiceroConnectButton.tsx
1775
+ import { Shield as Shield3, ChevronDown } from "lucide-react";
1776
+ import { Fragment as Fragment2, jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
1777
+ var CiceroConnectButton = ({
1778
+ label = "Connect Zcash Wallet",
1779
+ variant = "primary",
1780
+ size = "md",
1781
+ showBalance = true,
1782
+ showNetwork = true,
1783
+ className = ""
1784
+ }) => {
1785
+ const {
1786
+ account,
1787
+ address,
1788
+ isConnected,
1789
+ isConnecting,
1790
+ network,
1791
+ balance,
1792
+ openConnectModal,
1793
+ openAccountModal
1794
+ } = useCicero();
1795
+ const sizeClasses = {
1796
+ sm: "text-xs px-2.5 py-1.5 gap-1.5",
1797
+ md: "text-sm px-3.5 py-2 gap-2",
1798
+ lg: "text-base px-4.5 py-2.5 gap-2.5"
1799
+ }[size];
1800
+ const variantClasses = {
1801
+ primary: "bg-[#3ecf8e] text-[#171717] hover:bg-[#24b47e] font-semibold shadow-sm",
1802
+ outline: "bg-white text-[#171717] border border-[#dfdfdf] hover:border-[#c7c7c7] hover:bg-[#fafafa] font-medium shadow-sm",
1803
+ dark: "bg-[#1c1c1c] text-white hover:bg-[#242424] font-medium shadow-sm"
1804
+ }[variant];
1805
+ return /* @__PURE__ */ jsx5(Fragment2, { children: !isConnected ? /* @__PURE__ */ jsxs4(
1806
+ "button",
1807
+ {
1808
+ type: "button",
1809
+ onClick: openConnectModal,
1810
+ disabled: isConnecting,
1811
+ className: `inline-flex items-center justify-center rounded-[6px] transition-all select-none ${sizeClasses} ${variantClasses} ${className}`,
1812
+ children: [
1813
+ /* @__PURE__ */ jsx5(
1814
+ Shield3,
1815
+ {
1816
+ className: `flex-shrink-0 ${size === "sm" ? "w-3.5 h-3.5" : size === "lg" ? "w-5 h-5" : "w-4 h-4"} ${variant === "primary" ? "fill-[#171717]/20" : "text-[#3ecf8e]"}`
1817
+ }
1818
+ ),
1819
+ /* @__PURE__ */ jsx5("span", { children: isConnecting ? "Connecting..." : label })
1820
+ ]
1821
+ }
1822
+ ) : (
1823
+ /* Connected State Pill (RainbowKit style) */
1824
+ /* @__PURE__ */ jsxs4("div", { className: `inline-flex items-center rounded-[6px] border border-[#dfdfdf] bg-white p-0.5 shadow-sm text-xs ${className}`, children: [
1825
+ showNetwork && /* @__PURE__ */ jsxs4("div", { className: "flex items-center gap-1.5 px-2.5 py-1 text-[11px] font-medium text-[#707070] border-r border-[#ededed]", children: [
1826
+ /* @__PURE__ */ jsx5(
1827
+ "span",
1828
+ {
1829
+ className: `w-2 h-2 rounded-full ${network === "mainnet" ? "bg-[#3ecf8e]" : "bg-amber-400"}`
1830
+ }
1831
+ ),
1832
+ /* @__PURE__ */ jsx5("span", { className: "capitalize", children: network })
1833
+ ] }),
1834
+ showBalance && /* @__PURE__ */ jsxs4("div", { className: "px-2.5 py-1 font-mono font-medium text-[#171717] border-r border-[#ededed]", children: [
1835
+ /* @__PURE__ */ jsx5("span", { children: balance.zec }),
1836
+ " ",
1837
+ /* @__PURE__ */ jsx5("span", { className: "text-[#707070] font-normal", children: "ZEC" })
1838
+ ] }),
1839
+ /* @__PURE__ */ jsxs4(
1840
+ "button",
1841
+ {
1842
+ type: "button",
1843
+ onClick: openAccountModal,
1844
+ className: "flex items-center gap-1.5 px-2.5 py-1 rounded-[4px] hover:bg-[#fafafa] text-[#171717] font-medium transition-colors",
1845
+ children: [
1846
+ /* @__PURE__ */ jsx5("span", { className: "text-sm", children: account.wallet?.icon || "\u{1F6E1}\uFE0F" }),
1847
+ /* @__PURE__ */ jsx5("span", { className: "font-mono text-[11px]", children: address ? truncateAddress(address, 6, 4) : "Connected" }),
1848
+ /* @__PURE__ */ jsx5(ChevronDown, { className: "w-3 h-3 text-[#707070]" })
1849
+ ]
1850
+ }
1851
+ )
1852
+ ] })
1853
+ ) });
1854
+ };
1855
+
1856
+ // src/hooks/useZucchiniWallet.ts
1857
+ import { useState as useState5, useEffect as useEffect5, useCallback as useCallback3 } from "react";
1858
+ function useZucchiniWallet(options = {}) {
1859
+ const { autoConnect = false } = options;
1860
+ const [adapter2] = useState5(() => new ZucchiniWalletAdapter());
1861
+ const [isAvailable, setIsAvailable] = useState5(false);
1862
+ const [connectionStatus, setConnectionStatus] = useState5("disconnected");
1863
+ const [paymentStatus, setPaymentStatus] = useState5("idle");
1864
+ const [session, setSession] = useState5(null);
1865
+ const [error, setError] = useState5(null);
1866
+ useEffect5(() => {
1867
+ const detected = ZucchiniWalletAdapter.isAvailable();
1868
+ setIsAvailable(detected);
1869
+ if (detected && autoConnect) {
1870
+ connect();
1871
+ }
1872
+ }, []);
1873
+ const connect = useCallback3(async () => {
1874
+ setConnectionStatus("connecting");
1875
+ setError(null);
1876
+ try {
1877
+ const sess = await adapter2.connect();
1878
+ setSession(sess);
1879
+ setConnectionStatus("connected");
1880
+ return sess;
1881
+ } catch (err) {
1882
+ const msg = err instanceof Error ? err.message : "Failed to connect to Zucchini Wallet";
1883
+ setError(msg);
1884
+ setConnectionStatus("error");
1885
+ throw err;
1886
+ }
1887
+ }, [adapter2]);
1888
+ const requestPayment = useCallback3(
1889
+ async (params) => {
1890
+ setPaymentStatus("requesting");
1891
+ setError(null);
1892
+ try {
1893
+ const result = await adapter2.requestPayment(params);
1894
+ setPaymentStatus("submitted");
1895
+ return result;
1896
+ } catch (err) {
1897
+ const msg = err instanceof Error ? err.message : "Payment request failed";
1898
+ setError(msg);
1899
+ setPaymentStatus("error");
1900
+ throw err;
1901
+ }
1902
+ },
1903
+ [adapter2]
1904
+ );
1905
+ const disconnect = useCallback3(async () => {
1906
+ await adapter2.disconnect();
1907
+ setSession(null);
1908
+ setConnectionStatus("disconnected");
1909
+ setPaymentStatus("idle");
1910
+ }, [adapter2]);
1911
+ return {
1912
+ /** Whether the Zucchini extension is installed in this browser */
1913
+ isAvailable,
1914
+ /** Current wallet connection lifecycle state */
1915
+ connectionStatus,
1916
+ /** Current payment request lifecycle state */
1917
+ paymentStatus,
1918
+ /** Active session info (address, etc.) */
1919
+ session,
1920
+ /** Last error message (if any) */
1921
+ error,
1922
+ /** Prompt the user to connect their Zucchini Wallet */
1923
+ connect,
1924
+ /** Send a ZIP-321 payment request for user review & approval */
1925
+ requestPayment,
1926
+ /** Disconnect the current session */
1927
+ disconnect
1928
+ };
1929
+ }
1930
+ export {
1931
+ CiceroAccountModal,
1932
+ CiceroConnectButton,
1933
+ CiceroConnectModal,
1934
+ CiceroProvider,
1935
+ CiceroQRCode,
1936
+ ZucchiniWalletAdapter,
1937
+ burnerWallet,
1938
+ decodeBase64Url,
1939
+ encodeBase64Url,
1940
+ generateZip321Uri,
1941
+ getAddressType,
1942
+ getDefaultWallets,
1943
+ getWalletDeepLinks,
1944
+ isShieldedAddress,
1945
+ parseZip321Uri,
1946
+ truncateAddress,
1947
+ useAccount,
1948
+ useAccountModal,
1949
+ useBalance,
1950
+ useCicero,
1951
+ useConnectModal,
1952
+ useZcashPrice,
1953
+ useZucchiniWallet,
1954
+ validateMemoSupport,
1955
+ viewingKeyWallet,
1956
+ ywallet,
1957
+ zashiWallet,
1958
+ zucchiniWallet
1959
+ };
1960
+ //# sourceMappingURL=index.mjs.map