@goodwidget/ai-credits-widget 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4786 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/mocked/index.ts
31
+ var mocked_exports = {};
32
+ __export(mocked_exports, {
33
+ MockAiCreditsBackendClient: () => MockAiCreditsBackendClient,
34
+ MockAiCreditsChainClient: () => MockAiCreditsChainClient,
35
+ MockAiCreditsWidget: () => MockAiCreditsWidget
36
+ });
37
+ module.exports = __toCommonJS(mocked_exports);
38
+
39
+ // src/mocked/AiCreditsMockWidget.tsx
40
+ var import_react15 = require("react");
41
+
42
+ // src/quoteMath.ts
43
+ var import_viem = require("viem");
44
+ var DEPOSIT_BONUS_PERCENT = 10;
45
+ var STREAM_BONUS_PERCENT = 20;
46
+ var SECONDS_PER_MONTH = 30n * 24n * 60n * 60n;
47
+ function parseGAmount(amount) {
48
+ const normalized = amount.trim().replace(/,/g, "");
49
+ if (!normalized) return 0;
50
+ const value = Number.parseFloat(normalized);
51
+ return Number.isFinite(value) ? value : 0;
52
+ }
53
+ function gToWei(amountG) {
54
+ const trimmed = amountG.trim();
55
+ if (!trimmed || Number.parseFloat(trimmed) <= 0) return 0n;
56
+ return (0, import_viem.parseUnits)(trimmed, 18);
57
+ }
58
+ function weiToG(amountWei) {
59
+ const value = Number(amountWei) / 1e18;
60
+ return value.toFixed(2);
61
+ }
62
+ function gdWeiToUsd(gdAmountWei, gdUsdPerToken) {
63
+ const usdPerToken = BigInt(Math.round(gdUsdPerToken * 1e6));
64
+ return gdAmountWei * usdPerToken / 1000000000000000000n;
65
+ }
66
+ function getDepositBonusPercent(isGoodIdVerified, depositBonusPercent = DEPOSIT_BONUS_PERCENT) {
67
+ return isGoodIdVerified ? depositBonusPercent : 0;
68
+ }
69
+ function getStreamBonusPercent(isGoodIdVerified, streamBonusPercent = STREAM_BONUS_PERCENT) {
70
+ return isGoodIdVerified ? streamBonusPercent : 0;
71
+ }
72
+ function formatProfileUsd(usd) {
73
+ return (Number(usd) / 1e6).toFixed(4);
74
+ }
75
+ function formatUsdDisplay(usd, decimals = 2) {
76
+ const value = Number.parseFloat(usd);
77
+ if (!Number.isFinite(value) || value <= 0) return `US$ ${0 .toFixed(decimals)}`;
78
+ return `US$ ${value.toFixed(decimals)}`;
79
+ }
80
+ function formatUsd1ToG(gdUsdPerToken) {
81
+ if (!Number.isFinite(gdUsdPerToken) || gdUsdPerToken <= 0) return null;
82
+ const gPerUsd = 1 / gdUsdPerToken;
83
+ if (!Number.isFinite(gPerUsd) || gPerUsd <= 0) return null;
84
+ if (gPerUsd >= 100) return Math.round(gPerUsd).toLocaleString("en-US");
85
+ if (gPerUsd >= 10) return gPerUsd.toFixed(1);
86
+ return gPerUsd.toFixed(2);
87
+ }
88
+ function formatUsdWithBonus(principalUsd, bonusPercent) {
89
+ const principal = Number.parseFloat(principalUsd);
90
+ if (!Number.isFinite(principal) || principal <= 0) return formatUsdDisplay("0", 4);
91
+ if (bonusPercent <= 0) return formatUsdDisplay(principalUsd, 4);
92
+ return formatUsdDisplay((principal * (1 + bonusPercent / 100)).toFixed(4), 4);
93
+ }
94
+ function formatUsdMicro(usdMicro) {
95
+ return (Number(usdMicro || "0") / 1e6).toFixed(4);
96
+ }
97
+ function usdDisplayToMicro(usdDisplay) {
98
+ const value = Number.parseFloat(usdDisplay);
99
+ if (!Number.isFinite(value) || value <= 0) {
100
+ throw new Error("Enter a valid USD amount");
101
+ }
102
+ return Math.round(value * 1e6).toString();
103
+ }
104
+ function flowRateWeiToMonthlyG(flowRateWeiPerSecond) {
105
+ const rate = BigInt(flowRateWeiPerSecond || "0");
106
+ if (rate <= 0n) return "0.00";
107
+ return weiToG(rate * SECONDS_PER_MONTH);
108
+ }
109
+ function bonusUsdFromPrincipal(principalUsd, bonusPercent) {
110
+ if (principalUsd <= 0n || bonusPercent <= 0) return 0n;
111
+ return principalUsd * BigInt(bonusPercent) / 100n;
112
+ }
113
+ function buildQuoteAmounts(depositG, streamG) {
114
+ return {
115
+ depositAmountG: depositG,
116
+ streamAmountG: streamG
117
+ };
118
+ }
119
+ function quoteDepositPrincipalUsd(quote, gdUsdPerToken) {
120
+ const principal = gdWeiToUsd(gToWei(quote.depositAmountG), gdUsdPerToken);
121
+ return formatProfileUsd(principal);
122
+ }
123
+ function quoteStreamPrincipalUsd(quote, gdUsdPerToken) {
124
+ const principal = gdWeiToUsd(gToWei(quote.streamAmountG), gdUsdPerToken);
125
+ return formatProfileUsd(principal);
126
+ }
127
+ function quoteDepositBonusUsd(quote, gdUsdPerToken, isGoodIdVerified, depositBonusPercent = DEPOSIT_BONUS_PERCENT) {
128
+ const principal = gdWeiToUsd(gToWei(quote.depositAmountG), gdUsdPerToken);
129
+ return formatProfileUsd(
130
+ bonusUsdFromPrincipal(
131
+ principal,
132
+ getDepositBonusPercent(isGoodIdVerified, depositBonusPercent)
133
+ )
134
+ );
135
+ }
136
+ function quoteStreamBonusUsd(quote, gdUsdPerToken, isGoodIdVerified, streamBonusPercent = STREAM_BONUS_PERCENT) {
137
+ const principal = gdWeiToUsd(gToWei(quote.streamAmountG), gdUsdPerToken);
138
+ return formatProfileUsd(
139
+ bonusUsdFromPrincipal(
140
+ principal,
141
+ getStreamBonusPercent(isGoodIdVerified, streamBonusPercent)
142
+ )
143
+ );
144
+ }
145
+ function quoteTotalUsdMicro(quote, gdUsdPerToken, isGoodIdVerified, bonusPercents) {
146
+ const depositPrincipal = gdWeiToUsd(gToWei(quote.depositAmountG), gdUsdPerToken);
147
+ const streamPrincipal = gdWeiToUsd(gToWei(quote.streamAmountG), gdUsdPerToken);
148
+ const depositBonus = bonusUsdFromPrincipal(
149
+ depositPrincipal,
150
+ getDepositBonusPercent(
151
+ isGoodIdVerified,
152
+ bonusPercents?.depositBonusPercent ?? DEPOSIT_BONUS_PERCENT
153
+ )
154
+ );
155
+ const streamBonus = bonusUsdFromPrincipal(
156
+ streamPrincipal,
157
+ getStreamBonusPercent(
158
+ isGoodIdVerified,
159
+ bonusPercents?.streamBonusPercent ?? STREAM_BONUS_PERCENT
160
+ )
161
+ );
162
+ return depositPrincipal + depositBonus + streamPrincipal + streamBonus;
163
+ }
164
+
165
+ // src/backendClient.ts
166
+ var import_viem2 = require("viem");
167
+ function sleep(ms) {
168
+ return new Promise((resolve) => setTimeout(resolve, ms));
169
+ }
170
+ var BRIDGE_POLL_INTERVAL_MS = 3e3;
171
+ var BRIDGE_POLL_MAX_ATTEMPTS = 20;
172
+ function normalizeAddress(address) {
173
+ return address.toLowerCase();
174
+ }
175
+ async function readBridgeResponseBody(response, actionLabel) {
176
+ if (!response.ok) {
177
+ let detail = "";
178
+ try {
179
+ const body2 = await response.json();
180
+ if (body2.error) detail = ` \u2014 ${JSON.stringify(body2.error)}`;
181
+ } catch {
182
+ detail = "";
183
+ }
184
+ throw new Error(`${actionLabel} failed: ${response.status}${detail}`);
185
+ }
186
+ const body = await response.json();
187
+ const bridge = body.bridge ?? { enabled: false };
188
+ if (!bridge.enabled) {
189
+ throw new Error(`${actionLabel} bridge is not configured on the backend`);
190
+ }
191
+ return { ...body, bridge };
192
+ }
193
+ async function parseBridgeResponse(response, actionLabel) {
194
+ const body = await readBridgeResponseBody(response, actionLabel);
195
+ return body.bridge;
196
+ }
197
+ var DEFAULT_HISTORY_LIMIT = 20;
198
+ var MAX_HISTORY_LIMIT = 100;
199
+ function clampHistoryLimit(limit) {
200
+ if (limit === void 0) return DEFAULT_HISTORY_LIMIT;
201
+ return Math.min(Math.max(1, Math.floor(limit)), MAX_HISTORY_LIMIT);
202
+ }
203
+ function resolveBuyerAddress(entries) {
204
+ for (const entry of entries) {
205
+ if (entry.buyerAddress && (0, import_viem2.isAddress)(entry.buyerAddress)) {
206
+ return normalizeAddress(entry.buyerAddress);
207
+ }
208
+ }
209
+ return null;
210
+ }
211
+ function defaultOperatorStatus(payer) {
212
+ const account = normalizeAddress(payer);
213
+ return {
214
+ enabled: false,
215
+ account,
216
+ buyerAddress: account,
217
+ currentOperator: "0x0000000000000000000000000000000000000000",
218
+ operatorAccepted: false,
219
+ consentNonce: "0"
220
+ };
221
+ }
222
+ function totalCreditUsdFromProfile(profile) {
223
+ const principal = BigInt(profile.totalPrincipalUsd || "0");
224
+ const bonus = BigInt(profile.totalBonusUsd || "0");
225
+ return (principal + bonus).toString();
226
+ }
227
+ async function enrichAccountView(view, chain) {
228
+ const { profile } = view;
229
+ const goodIdVerified = await chain.isGoodIdVerified(view.account);
230
+ const monthlyStreamG = flowRateWeiToMonthlyG(profile.streamFlowRateWeiPerSecond);
231
+ const depositedWei = BigInt(profile.totalGdDepositedWei);
232
+ return {
233
+ totalCreditUsd: totalCreditUsdFromProfile(profile),
234
+ goodIdVerified,
235
+ totalGdDepositedG: depositedWei > 0n ? weiToG(depositedWei) : "0.00",
236
+ monthlyStreamG
237
+ };
238
+ }
239
+ var BPS_PER_PERCENT = 100;
240
+ var DEFAULT_DISCOUNT_CONFIG = {
241
+ depositBonusPercent: 10,
242
+ streamBonusPercent: 20
243
+ };
244
+ function bpsToPercent(bps, fallbackPercent) {
245
+ const raw = typeof bps === "number" ? bps : typeof bps === "string" ? Number(bps) : NaN;
246
+ if (!Number.isFinite(raw) || raw < 0) return fallbackPercent;
247
+ return Math.trunc(raw / BPS_PER_PERCENT);
248
+ }
249
+ function discountConfigFromConfigValues(response) {
250
+ const config = response?.config;
251
+ return {
252
+ depositBonusPercent: bpsToPercent(
253
+ config?.REGULAR_BONUS_BPS,
254
+ DEFAULT_DISCOUNT_CONFIG.depositBonusPercent
255
+ ),
256
+ streamBonusPercent: bpsToPercent(
257
+ config?.STREAMING_BONUS_BPS,
258
+ DEFAULT_DISCOUNT_CONFIG.streamBonusPercent
259
+ )
260
+ };
261
+ }
262
+ var ProductionAiCreditsBackendClient = class {
263
+ backendUrl;
264
+ constructor(backendUrl) {
265
+ this.backendUrl = backendUrl.replace(/\/$/, "");
266
+ }
267
+ async getDiscountConfig() {
268
+ const response = await fetch(`${this.backendUrl}/config/values`);
269
+ if (!response.ok) throw new Error(`Config values request failed: ${response.status}`);
270
+ const payload = await response.json();
271
+ return discountConfigFromConfigValues(payload);
272
+ }
273
+ accountBase(payer) {
274
+ return `${this.backendUrl}/v1/accounts/${encodeURIComponent(normalizeAddress(payer))}`;
275
+ }
276
+ async getAccountCredit(payer) {
277
+ const response = await fetch(`${this.accountBase(payer)}/profile`);
278
+ if (!response.ok) throw new Error(`Account profile request failed: ${response.status}`);
279
+ return response.json();
280
+ }
281
+ async getCreditHistory(payer, options = {}) {
282
+ const params = new URLSearchParams();
283
+ const limit = clampHistoryLimit(options.limit);
284
+ const offset = Math.max(0, Math.floor(options.offset ?? 0));
285
+ params.set("limit", String(limit));
286
+ params.set("offset", String(offset));
287
+ if (options.source) params.set("source", options.source);
288
+ if (options.fundingStatus) params.set("fundingStatus", options.fundingStatus);
289
+ if (options.from) params.set("from", options.from);
290
+ if (options.to) params.set("to", options.to);
291
+ const response = await fetch(`${this.accountBase(payer)}/credit-history?${params.toString()}`);
292
+ if (!response.ok) throw new Error(`Credit history request failed: ${response.status}`);
293
+ return response.json();
294
+ }
295
+ async getOutstanding(payer) {
296
+ const response = await fetch(`${this.accountBase(payer)}/outstanding`);
297
+ if (!response.ok) throw new Error(`Outstanding funding request failed: ${response.status}`);
298
+ const data = await response.json();
299
+ return {
300
+ outstandingFundingUsd: data.outstandingFundingUsd ?? "0",
301
+ count: data.failedFundingCredits?.length ?? 0
302
+ };
303
+ }
304
+ async getTransactions(payer, options = {}) {
305
+ const history = await this.getCreditHistory(payer, {
306
+ fundingStatus: options.status,
307
+ limit: options.limit,
308
+ offset: options.cursor ? Number(options.cursor) || 0 : 0
309
+ });
310
+ return { account: history.account, transactions: history.items };
311
+ }
312
+ async getUsageLog(payer) {
313
+ const history = await this.getCreditHistory(payer, { limit: DEFAULT_HISTORY_LIMIT, offset: 0 });
314
+ return history.items;
315
+ }
316
+ async notifyPayment(txHash) {
317
+ const response = await fetch(`${this.backendUrl}/v1/celo/events/record`, {
318
+ method: "POST",
319
+ headers: { "Content-Type": "application/json" },
320
+ body: JSON.stringify({ txHash })
321
+ });
322
+ if (!response.ok) throw new Error(`Payment notification failed: ${response.status}`);
323
+ return response.json();
324
+ }
325
+ async waitForSettlement(ref, options = {}) {
326
+ const txHashes = new Set((options.txHashes ?? []).map((hash) => hash.toLowerCase()));
327
+ for (let attempt = 0; attempt < BRIDGE_POLL_MAX_ATTEMPTS; attempt++) {
328
+ if (attempt > 0) await sleep(BRIDGE_POLL_INTERVAL_MS);
329
+ if (txHashes.size > 0) {
330
+ const history = await this.getCreditHistory(ref.payer, {
331
+ limit: MAX_HISTORY_LIMIT,
332
+ offset: 0
333
+ });
334
+ const matching = history.items.filter(
335
+ (entry) => entry.txHash && txHashes.has(entry.txHash.toLowerCase())
336
+ );
337
+ const failed = matching.find((entry) => entry.fundingStatus === "failed");
338
+ if (failed) {
339
+ throw new Error(failed.fundingError ?? "Base funding failed for this deposit");
340
+ }
341
+ if (matching.length > 0 && matching.every((entry) => entry.fundingStatus === "funded")) {
342
+ const credit2 = await this.getAccountCredit(ref.payer);
343
+ return { totalCreditUsd: totalCreditUsdFromProfile(credit2.profile) };
344
+ }
345
+ if (matching.some((entry) => entry.fundingStatus === "pending")) continue;
346
+ }
347
+ const credit = await this.getAccountCredit(ref.payer);
348
+ const balanceMicro = BigInt(totalCreditUsdFromProfile(credit.profile));
349
+ const baselineMicro = BigInt(options.previousBalance || "0");
350
+ if (balanceMicro > baselineMicro) {
351
+ return { totalCreditUsd: balanceMicro.toString() };
352
+ }
353
+ }
354
+ throw new Error("Settlement polling timeout \u2014 credits may still be arriving");
355
+ }
356
+ async closeChannel(channelId, body = {}) {
357
+ const response = await fetch(
358
+ `${this.backendUrl}/v1/channels/${encodeURIComponent(channelId)}/close`,
359
+ {
360
+ method: "POST",
361
+ headers: { "Content-Type": "application/json" },
362
+ body: JSON.stringify(body)
363
+ }
364
+ );
365
+ const bridge = await parseBridgeResponse(response, "Close channel");
366
+ return { channelId, action: "close", bridge };
367
+ }
368
+ async withdrawCredits(buyer, body) {
369
+ const response = await fetch(`${this.accountBase(buyer)}/withdraw`, {
370
+ method: "POST",
371
+ headers: { "Content-Type": "application/json" },
372
+ body: JSON.stringify(body)
373
+ });
374
+ const bridge = await parseBridgeResponse(response, "Withdraw");
375
+ return { account: normalizeAddress(buyer), amountUsd: body.amount, bridge };
376
+ }
377
+ async submitOperatorConsent(buyer, body) {
378
+ const response = await fetch(`${this.accountBase(buyer)}/operator-consent`, {
379
+ method: "POST",
380
+ headers: { "Content-Type": "application/json" },
381
+ body: JSON.stringify({
382
+ nonce: body.nonce,
383
+ signature: body.signature
384
+ })
385
+ });
386
+ const payload = await readBridgeResponseBody(response, "Operator consent");
387
+ return {
388
+ buyer: normalizeAddress(payload.buyer ?? buyer),
389
+ bridge: payload.bridge
390
+ };
391
+ }
392
+ };
393
+ var UnavailableAiCreditsBackendClient = class {
394
+ unavailable() {
395
+ throw new Error("AI Credits backend is not configured");
396
+ }
397
+ async getDiscountConfig() {
398
+ return this.unavailable();
399
+ }
400
+ async getAccountCredit() {
401
+ return this.unavailable();
402
+ }
403
+ async getCreditHistory() {
404
+ return this.unavailable();
405
+ }
406
+ async getOutstanding() {
407
+ return this.unavailable();
408
+ }
409
+ async getTransactions() {
410
+ return this.unavailable();
411
+ }
412
+ async notifyPayment() {
413
+ return this.unavailable();
414
+ }
415
+ async waitForSettlement() {
416
+ return this.unavailable();
417
+ }
418
+ async closeChannel() {
419
+ return this.unavailable();
420
+ }
421
+ async withdrawCredits() {
422
+ return this.unavailable();
423
+ }
424
+ async submitOperatorConsent() {
425
+ return this.unavailable();
426
+ }
427
+ };
428
+ function createBackendClient(backendUrl) {
429
+ if (!backendUrl) {
430
+ return new UnavailableAiCreditsBackendClient();
431
+ }
432
+ return new ProductionAiCreditsBackendClient(backendUrl);
433
+ }
434
+ async function waitForOperatorConsent(chain, ref) {
435
+ for (let attempt = 0; attempt < BRIDGE_POLL_MAX_ATTEMPTS; attempt++) {
436
+ if (attempt > 0) await sleep(BRIDGE_POLL_INTERVAL_MS);
437
+ const status = await chain.getBuyerOperatorStatus(ref);
438
+ if (status.operatorAccepted) return;
439
+ }
440
+ throw new Error("Operator consent confirmation timeout \u2014 check Base transaction status");
441
+ }
442
+ async function buildAccountView(payer, backend, chain, options = {}) {
443
+ const normalizedPayer = normalizeAddress(payer);
444
+ const [credit, outstanding, history] = await Promise.all([
445
+ backend.getAccountCredit(payer),
446
+ backend.getOutstanding(payer),
447
+ backend.getCreditHistory(payer, { limit: MAX_HISTORY_LIMIT, offset: 0 })
448
+ ]);
449
+ const sessionBuyer = options.buyerAddress && (0, import_viem2.isAddress)(options.buyerAddress) ? normalizeAddress(options.buyerAddress) : null;
450
+ const buyer = sessionBuyer ?? resolveBuyerAddress(history.items);
451
+ const [operator, withdrawableUsd] = buyer ? await Promise.all([
452
+ chain.getBuyerOperatorStatus({ payer: normalizedPayer, buyer }),
453
+ chain.getWithdrawableUsd(buyer)
454
+ ]) : [defaultOperatorStatus(normalizedPayer), "0"];
455
+ return {
456
+ account: normalizedPayer,
457
+ buyer,
458
+ profile: credit.profile,
459
+ operator,
460
+ withdrawableUsd,
461
+ outstandingFundingUsd: outstanding.outstandingFundingUsd,
462
+ outstandingFundingCount: outstanding.count
463
+ };
464
+ }
465
+
466
+ // src/chainClient.ts
467
+ var import_viem3 = require("viem");
468
+
469
+ // src/operatorConsent.ts
470
+ var import_accounts = require("viem/accounts");
471
+ var ANTSEED_DEPOSITS_BASE_ADDRESS = "0x0F7a3a8f4Da01637d1202bb5443fcF7F88F99fD2";
472
+ var SET_OPERATOR_TYPES = {
473
+ SetOperator: [
474
+ { name: "operator", type: "address" },
475
+ { name: "nonce", type: "uint256" }
476
+ ]
477
+ };
478
+ function buildSetOperatorPayload(chainId, depositsAddress, operatorAddress, nonce, domain) {
479
+ return {
480
+ primaryType: "SetOperator",
481
+ domain: {
482
+ name: domain.name,
483
+ version: domain.version,
484
+ chainId,
485
+ verifyingContract: depositsAddress.toLowerCase()
486
+ },
487
+ types: {
488
+ EIP712Domain: [
489
+ { name: "name", type: "string" },
490
+ { name: "version", type: "string" },
491
+ { name: "chainId", type: "uint256" },
492
+ { name: "verifyingContract", type: "address" }
493
+ ],
494
+ ...SET_OPERATOR_TYPES
495
+ },
496
+ message: {
497
+ operator: operatorAddress.toLowerCase(),
498
+ nonce: nonce.toString()
499
+ }
500
+ };
501
+ }
502
+ async function signOperatorConsentFromTypedData(buyerPrivateKey, typedData) {
503
+ const account = (0, import_accounts.privateKeyToAccount)(buyerPrivateKey);
504
+ const types = { ...typedData.types };
505
+ delete types.EIP712Domain;
506
+ return account.signTypedData({
507
+ domain: {
508
+ name: typedData.domain.name,
509
+ version: typedData.domain.version,
510
+ chainId: typedData.domain.chainId,
511
+ verifyingContract: typedData.domain.verifyingContract
512
+ },
513
+ types,
514
+ primaryType: typedData.primaryType,
515
+ message: {
516
+ operator: typedData.message.operator,
517
+ nonce: BigInt(String(typedData.message.nonce))
518
+ }
519
+ });
520
+ }
521
+
522
+ // src/chainClient.ts
523
+ var BASE_CHAIN_ID = 8453;
524
+ var DEFAULT_BASE_RPC_URL = "https://mainnet.base.org";
525
+ var CELO_GD_ANTSEED_VAULT_ADDRESS = "0x4Dd0136b9aabD5823cf0F65d89e8fB882C660885";
526
+ var CELO_GOODID_ADDRESS = "0xC361A6E67822a0EDc17D899227dd9FC50BD62F42";
527
+ var DEFAULT_CELO_RPC_URL = "https://forno.celo.org";
528
+ var CELO_CHAIN = {
529
+ id: 42220,
530
+ name: "Celo",
531
+ nativeCurrency: { name: "Celo", symbol: "CELO", decimals: 18 },
532
+ rpcUrls: {
533
+ default: { http: [DEFAULT_CELO_RPC_URL] },
534
+ public: { http: [DEFAULT_CELO_RPC_URL] }
535
+ }
536
+ };
537
+ var BASE_CHAIN = {
538
+ id: BASE_CHAIN_ID,
539
+ name: "Base",
540
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
541
+ rpcUrls: {
542
+ default: { http: [DEFAULT_BASE_RPC_URL] },
543
+ public: { http: [DEFAULT_BASE_RPC_URL] }
544
+ }
545
+ };
546
+ var CELO_VAULT_ABI = (0, import_viem3.parseAbi)([
547
+ "function gdUsdPerToken(uint128 amount) view returns (uint256)"
548
+ ]);
549
+ var DEPOSITS_ABI = (0, import_viem3.parseAbi)([
550
+ "function getOperator(address buyer) view returns (address)",
551
+ "function getOperatorNonce(address buyer) view returns (uint256)",
552
+ "function eip712Domain() view returns (bytes1 fields, string name, string version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] extensions)"
553
+ ]);
554
+ var FUNDING_VAULT_ABI = (0, import_viem3.parseAbi)([
555
+ "function withdrawablePrincipal(address buyer) view returns (uint256)"
556
+ ]);
557
+ var GOODID_ABI = (0, import_viem3.parseAbi)([
558
+ "function getWhitelistedRoot(address account) view returns (address)"
559
+ ]);
560
+ function normalizeAddress2(address) {
561
+ return address.toLowerCase();
562
+ }
563
+ var ProductionAiCreditsChainClient = class {
564
+ baseClient;
565
+ celoClient;
566
+ fundingVaultAddress;
567
+ celoVaultAddress;
568
+ celoGoodIdAddress;
569
+ depositsAddress;
570
+ constructor(options = {}) {
571
+ const baseRpcUrl = options.baseRpcUrl ?? DEFAULT_BASE_RPC_URL;
572
+ const celoRpcUrl = options.celoRpcUrl ?? DEFAULT_CELO_RPC_URL;
573
+ this.baseClient = (0, import_viem3.createPublicClient)({ chain: BASE_CHAIN, transport: (0, import_viem3.http)(baseRpcUrl) });
574
+ this.fundingVaultAddress = options.fundingVaultAddress;
575
+ this.celoVaultAddress = options.celoVaultAddress;
576
+ this.celoGoodIdAddress = options.celoGoodIdAddress ?? CELO_GOODID_ADDRESS;
577
+ this.depositsAddress = options.depositsAddress ?? ANTSEED_DEPOSITS_BASE_ADDRESS;
578
+ this.celoClient = this.celoVaultAddress || this.celoGoodIdAddress ? (0, import_viem3.createPublicClient)({ chain: CELO_CHAIN, transport: (0, import_viem3.http)(celoRpcUrl) }) : null;
579
+ }
580
+ async isGoodIdVerified(account) {
581
+ if (!this.celoClient || !this.celoGoodIdAddress) return false;
582
+ try {
583
+ const root = await this.celoClient.readContract({
584
+ address: this.celoGoodIdAddress,
585
+ abi: GOODID_ABI,
586
+ functionName: "getWhitelistedRoot",
587
+ args: [normalizeAddress2(account)]
588
+ });
589
+ const rootAddress = String(root).toLowerCase();
590
+ return rootAddress !== "0x0000000000000000000000000000000000000000";
591
+ } catch {
592
+ return false;
593
+ }
594
+ }
595
+ async fetchGdUsdPerToken() {
596
+ if (!this.celoClient || !this.celoVaultAddress) return 15e-4;
597
+ const usd18 = await this.celoClient.readContract({
598
+ address: this.celoVaultAddress,
599
+ abi: CELO_VAULT_ABI,
600
+ functionName: "gdUsdPerToken",
601
+ args: [10n ** 18n]
602
+ });
603
+ return Number(usd18) / 1e18;
604
+ }
605
+ async buildQuote(depositG, streamG) {
606
+ return buildQuoteAmounts(depositG, streamG);
607
+ }
608
+ async getBuyerOperatorStatus(ref) {
609
+ const payer = normalizeAddress2(ref.payer);
610
+ const buyer = normalizeAddress2(ref.buyer);
611
+ const operatorAddress = this.fundingVaultAddress?.toLowerCase();
612
+ if (!operatorAddress) {
613
+ return {
614
+ enabled: false,
615
+ account: payer,
616
+ buyerAddress: buyer,
617
+ currentOperator: "0x0000000000000000000000000000000000000000",
618
+ operatorAccepted: false,
619
+ consentNonce: "0"
620
+ };
621
+ }
622
+ const [currentOperator, consentNonce] = await Promise.all([
623
+ this.baseClient.readContract({
624
+ address: this.depositsAddress,
625
+ abi: DEPOSITS_ABI,
626
+ functionName: "getOperator",
627
+ args: [buyer]
628
+ }),
629
+ this.readOperatorNonce(buyer)
630
+ ]);
631
+ const current = String(currentOperator).toLowerCase();
632
+ return {
633
+ enabled: true,
634
+ account: payer,
635
+ buyerAddress: buyer,
636
+ operatorAddress,
637
+ currentOperator: current,
638
+ operatorAccepted: current === operatorAddress,
639
+ consentNonce: consentNonce.toString()
640
+ };
641
+ }
642
+ async buildOperatorConsentPayload(ref, operatorStatus) {
643
+ const payer = normalizeAddress2(ref.payer);
644
+ const buyer = normalizeAddress2(ref.buyer);
645
+ const status = operatorStatus ?? await this.getBuyerOperatorStatus(ref);
646
+ if (!status.enabled || !status.operatorAddress) {
647
+ return { enabled: false, account: payer, buyerAddress: buyer };
648
+ }
649
+ const domain = await this.readDepositsDomain();
650
+ return {
651
+ enabled: true,
652
+ account: payer,
653
+ buyerAddress: buyer,
654
+ typedData: buildSetOperatorPayload(
655
+ BASE_CHAIN_ID,
656
+ this.depositsAddress,
657
+ status.operatorAddress,
658
+ BigInt(status.consentNonce),
659
+ domain
660
+ )
661
+ };
662
+ }
663
+ async getWithdrawableUsd(buyer) {
664
+ if (!this.fundingVaultAddress) return "0";
665
+ const amount = await this.baseClient.readContract({
666
+ address: this.fundingVaultAddress,
667
+ abi: FUNDING_VAULT_ABI,
668
+ functionName: "withdrawablePrincipal",
669
+ args: [normalizeAddress2(buyer)]
670
+ });
671
+ return amount.toString();
672
+ }
673
+ async readOperatorNonce(buyer) {
674
+ return this.baseClient.readContract({
675
+ address: this.depositsAddress,
676
+ abi: DEPOSITS_ABI,
677
+ functionName: "getOperatorNonce",
678
+ args: [buyer]
679
+ });
680
+ }
681
+ async readDepositsDomain() {
682
+ try {
683
+ const domain = await this.baseClient.readContract({
684
+ address: this.depositsAddress,
685
+ abi: DEPOSITS_ABI,
686
+ functionName: "eip712Domain"
687
+ });
688
+ return { name: String(domain[1]), version: String(domain[2]) };
689
+ } catch {
690
+ return { name: "AntseedDeposits", version: "1" };
691
+ }
692
+ }
693
+ };
694
+ function createChainClient(options = {}) {
695
+ return new ProductionAiCreditsChainClient({
696
+ ...options,
697
+ celoGoodIdAddress: options.celoGoodIdAddress ?? CELO_GOODID_ADDRESS
698
+ });
699
+ }
700
+
701
+ // src/adapter.ts
702
+ var import_react = require("react");
703
+ var import_core = require("@goodwidget/core");
704
+ var import_viem8 = require("viem");
705
+ var import_accounts4 = require("viem/accounts");
706
+
707
+ // src/buyerKeyDerivation.ts
708
+ var import_viem4 = require("viem");
709
+ var import_accounts2 = require("viem/accounts");
710
+ var SECP256K1_ORDER = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;
711
+ function buildBuyerKeyMessage(payerAddress) {
712
+ return `Generate a key for G$ credits from payer wallet of '${payerAddress.toLowerCase()}'`;
713
+ }
714
+ function deriveBuyerPrivateKeyFromSignature(signature) {
715
+ for (let counter = 0; counter < 256; counter++) {
716
+ const hash = counter === 0 ? (0, import_viem4.keccak256)(signature) : (0, import_viem4.keccak256)((0, import_viem4.toBytes)(`${signature}:${counter}`));
717
+ const candidate = BigInt(hash);
718
+ if (candidate <= 0n || candidate >= SECP256K1_ORDER) {
719
+ continue;
720
+ }
721
+ const privateKey = `0x${candidate.toString(16).padStart(64, "0")}`;
722
+ try {
723
+ (0, import_accounts2.privateKeyToAccount)(privateKey);
724
+ return privateKey;
725
+ } catch {
726
+ continue;
727
+ }
728
+ }
729
+ throw new Error("Could not derive a valid buyer key from wallet signature");
730
+ }
731
+
732
+ // src/buyerSignatures.ts
733
+ var import_accounts3 = require("viem/accounts");
734
+ var ANTSEED_BUYER_OPERATOR_DOMAIN = {
735
+ name: "AntseedBuyerOperator",
736
+ version: "1"
737
+ };
738
+ var WITHDRAW_PRINCIPAL_TYPES = {
739
+ WithdrawPrincipal: [
740
+ { name: "buyer", type: "address" },
741
+ { name: "amount", type: "uint256" },
742
+ { name: "recipient", type: "address" },
743
+ { name: "timestamp", type: "uint256" }
744
+ ]
745
+ };
746
+ var REQUEST_CLOSE_TYPES = {
747
+ RequestClose: [
748
+ { name: "channelId", type: "bytes32" },
749
+ { name: "timestamp", type: "uint256" }
750
+ ]
751
+ };
752
+ function normalizeChannelId(channelId) {
753
+ const trimmed = channelId.trim();
754
+ if (!/^0x[0-9a-fA-F]{64}$/.test(trimmed)) return null;
755
+ return trimmed.toLowerCase();
756
+ }
757
+ async function signWithdrawPrincipal(params) {
758
+ const account = (0, import_accounts3.privateKeyToAccount)(params.buyerPrivateKey);
759
+ return account.signTypedData({
760
+ domain: {
761
+ name: ANTSEED_BUYER_OPERATOR_DOMAIN.name,
762
+ version: ANTSEED_BUYER_OPERATOR_DOMAIN.version,
763
+ chainId: BASE_CHAIN_ID,
764
+ verifyingContract: params.fundingVaultAddress
765
+ },
766
+ types: WITHDRAW_PRINCIPAL_TYPES,
767
+ primaryType: "WithdrawPrincipal",
768
+ message: {
769
+ buyer: params.buyer,
770
+ amount: params.amountMicro,
771
+ recipient: params.recipient,
772
+ timestamp: BigInt(params.timestamp)
773
+ }
774
+ });
775
+ }
776
+ async function signRequestClose(params) {
777
+ const account = (0, import_accounts3.privateKeyToAccount)(params.buyerPrivateKey);
778
+ return account.signTypedData({
779
+ domain: {
780
+ name: ANTSEED_BUYER_OPERATOR_DOMAIN.name,
781
+ version: ANTSEED_BUYER_OPERATOR_DOMAIN.version,
782
+ chainId: BASE_CHAIN_ID,
783
+ verifyingContract: params.fundingVaultAddress
784
+ },
785
+ types: REQUEST_CLOSE_TYPES,
786
+ primaryType: "RequestClose",
787
+ message: {
788
+ channelId: params.channelId,
789
+ timestamp: BigInt(params.timestamp)
790
+ }
791
+ });
792
+ }
793
+
794
+ // src/payerSession.ts
795
+ var payerWalletSessions = /* @__PURE__ */ new Map();
796
+ function payerSessionKey(address) {
797
+ return address.toLowerCase();
798
+ }
799
+ function readPayerSession(address) {
800
+ if (!address) return null;
801
+ return payerWalletSessions.get(payerSessionKey(address)) ?? null;
802
+ }
803
+ function patchPayerSession(address, patch) {
804
+ const existing = readPayerSession(address);
805
+ payerWalletSessions.set(payerSessionKey(address), {
806
+ operatorConsented: false,
807
+ ...existing,
808
+ ...patch
809
+ });
810
+ }
811
+ function patchPayerSessionFields(address) {
812
+ const session = readPayerSession(address);
813
+ if (!session) {
814
+ return {
815
+ buyerPrvKey: null,
816
+ operatorConsented: false
817
+ };
818
+ }
819
+ return {
820
+ buyerPubKey: session.buyerPubKey,
821
+ buyerPrvKey: session.buyerPrvKey ?? null,
822
+ operatorConsented: session.operatorConsented
823
+ };
824
+ }
825
+ function addressesMatch(a, b) {
826
+ if (!a || !b) return false;
827
+ return payerSessionKey(a) === payerSessionKey(b);
828
+ }
829
+
830
+ // src/celoPayment.ts
831
+ var import_viem5 = require("viem");
832
+ var G_TOKEN_CELO_ADDRESS = "0x62B8B11039FcfE5aB0C56E502b1C372A3d2a9c7A";
833
+ var CFA_V1_FORWARDER_ADDRESS = "0xcfA132E353cB4E398080B9700609bb008eceB125";
834
+ var CFA_V1_ADDRESS = "0x9d369e78e1a682cE0F8d9aD849BeA4FE1c3bD3Ad";
835
+ var SUPERFLUID_HOST_CELO_ADDRESS = "0xA4Ff07cF81C02CFD356184879D953970cA957585";
836
+ var OPERATION_TYPE_ERC20_APPROVE = 1;
837
+ var OPERATION_TYPE_SUPERFLUID_CALL_AGREEMENT = 201;
838
+ var OPERATION_TYPE_CALL_APP_ACTION = 202;
839
+ var SECONDS_PER_MONTH2 = 30n * 24n * 3600n;
840
+ var CFA_FORWARDER_ABI = (0, import_viem5.parseAbi)([
841
+ "function getFlowInfo(address token, address sender, address receiver) view returns (uint256 lastUpdated, int96 flowrate, uint256 deposit, uint256 owedDeposit)"
842
+ ]);
843
+ var CFA_ABI = (0, import_viem5.parseAbi)([
844
+ "function createFlow(address token, address receiver, int96 flowRate, bytes ctx) returns (bytes newCtx)",
845
+ "function updateFlow(address token, address receiver, int96 flowRate, bytes ctx) returns (bytes newCtx)",
846
+ "function deleteFlow(address token, address sender, address receiver, bytes ctx) returns (bytes newCtx)"
847
+ ]);
848
+ var VAULT_ABI = (0, import_viem5.parseAbi)([
849
+ "function depositFromAction(uint256 amount, bytes data, bytes ctx) returns (bytes newCtx)"
850
+ ]);
851
+ var HOST_ABI = (0, import_viem5.parseAbi)([
852
+ "function batchCall((uint32 operationType, address target, bytes data)[] operations) payable"
853
+ ]);
854
+ var CELO_CHAIN2 = {
855
+ id: 42220,
856
+ name: "Celo",
857
+ nativeCurrency: { name: "Celo", symbol: "CELO", decimals: 18 },
858
+ rpcUrls: { default: { http: ["https://forno.celo.org"] } }
859
+ };
860
+ function isStreamAmountChanged(streamAmountG, currentStreamAmountG) {
861
+ return gToWei(streamAmountG) !== gToWei(currentStreamAmountG ?? "0");
862
+ }
863
+ function monthlyToFlowRate(monthlyAmountG) {
864
+ const monthlyWei = gToWei(monthlyAmountG);
865
+ if (monthlyWei <= 0n) return 0n;
866
+ return monthlyWei / SECONDS_PER_MONTH2;
867
+ }
868
+ function encodeBuyerUserData(buyer) {
869
+ return (0, import_viem5.encodeAbiParameters)([{ type: "address" }], [buyer]);
870
+ }
871
+ function buildApproveOperation(vault, depositWei) {
872
+ return {
873
+ operationType: OPERATION_TYPE_ERC20_APPROVE,
874
+ target: G_TOKEN_CELO_ADDRESS,
875
+ data: (0, import_viem5.encodeAbiParameters)([{ type: "address" }, { type: "uint256" }], [vault, depositWei])
876
+ };
877
+ }
878
+ function buildDepositFromActionOperation(vault, buyer, depositWei) {
879
+ const callData = (0, import_viem5.encodeFunctionData)({
880
+ abi: VAULT_ABI,
881
+ functionName: "depositFromAction",
882
+ args: [depositWei, encodeBuyerUserData(buyer), "0x"]
883
+ });
884
+ return {
885
+ operationType: OPERATION_TYPE_CALL_APP_ACTION,
886
+ target: vault,
887
+ data: callData
888
+ };
889
+ }
890
+ async function buildStreamOperation(publicClient, payer, buyer, vault, streamAmountG) {
891
+ const flowRatePerSecond = monthlyToFlowRate(streamAmountG);
892
+ const userData = encodeBuyerUserData(buyer);
893
+ const flowInfo = await publicClient.readContract({
894
+ address: CFA_V1_FORWARDER_ADDRESS,
895
+ abi: CFA_FORWARDER_ABI,
896
+ functionName: "getFlowInfo",
897
+ args: [G_TOKEN_CELO_ADDRESS, payer, vault]
898
+ });
899
+ const existingFlowRate = flowInfo[1];
900
+ let callData;
901
+ if (flowRatePerSecond <= 0n) {
902
+ if (existingFlowRate <= 0n) {
903
+ throw new Error("No existing stream to cancel");
904
+ }
905
+ callData = (0, import_viem5.encodeFunctionData)({
906
+ abi: CFA_ABI,
907
+ functionName: "deleteFlow",
908
+ args: [G_TOKEN_CELO_ADDRESS, payer, vault, "0x"]
909
+ });
910
+ } else if (existingFlowRate > 0n) {
911
+ callData = (0, import_viem5.encodeFunctionData)({
912
+ abi: CFA_ABI,
913
+ functionName: "updateFlow",
914
+ args: [G_TOKEN_CELO_ADDRESS, vault, flowRatePerSecond, "0x"]
915
+ });
916
+ } else {
917
+ callData = (0, import_viem5.encodeFunctionData)({
918
+ abi: CFA_ABI,
919
+ functionName: "createFlow",
920
+ args: [G_TOKEN_CELO_ADDRESS, vault, flowRatePerSecond, "0x"]
921
+ });
922
+ }
923
+ return {
924
+ operationType: OPERATION_TYPE_SUPERFLUID_CALL_AGREEMENT,
925
+ target: CFA_V1_ADDRESS,
926
+ data: (0, import_viem5.encodeAbiParameters)([{ type: "bytes" }, { type: "bytes" }], [callData, userData])
927
+ };
928
+ }
929
+ async function waitForMinedTransaction(publicClient, hash) {
930
+ const receipt = await publicClient.waitForTransactionReceipt({ hash });
931
+ if (receipt.status === "reverted") {
932
+ throw new Error(`Celo transaction reverted: ${hash}`);
933
+ }
934
+ }
935
+ async function executeCeloPayment(params) {
936
+ const {
937
+ walletClient,
938
+ publicClient,
939
+ payer,
940
+ buyer,
941
+ vault,
942
+ depositAmountG,
943
+ streamAmountG,
944
+ currentStreamAmountG
945
+ } = params;
946
+ const depositWei = gToWei(depositAmountG);
947
+ const hasDeposit = depositWei > 0n;
948
+ const streamChanged = isStreamAmountChanged(streamAmountG, currentStreamAmountG);
949
+ if (!hasDeposit && !streamChanged) {
950
+ throw new Error("Enter a deposit or change the monthly stream amount");
951
+ }
952
+ const operations = [];
953
+ if (hasDeposit) {
954
+ operations.push(buildApproveOperation(vault, depositWei));
955
+ }
956
+ if (streamChanged) {
957
+ operations.push(await buildStreamOperation(publicClient, payer, buyer, vault, streamAmountG));
958
+ }
959
+ if (hasDeposit) {
960
+ operations.push(buildDepositFromActionOperation(vault, buyer, depositWei));
961
+ }
962
+ const txHash = await walletClient.writeContract({
963
+ account: payer,
964
+ chain: CELO_CHAIN2,
965
+ address: SUPERFLUID_HOST_CELO_ADDRESS,
966
+ abi: HOST_ABI,
967
+ functionName: "batchCall",
968
+ args: [operations]
969
+ });
970
+ await waitForMinedTransaction(publicClient, txHash);
971
+ return { txHashes: [txHash] };
972
+ }
973
+
974
+ // src/goodIdVerification.ts
975
+ var import_citizen_sdk = require("@goodsdks/citizen-sdk");
976
+ var import_viem6 = require("viem");
977
+ var CELO_CHAIN_ID = 42220;
978
+ var CELO_CHAIN3 = {
979
+ id: CELO_CHAIN_ID,
980
+ name: "Celo",
981
+ nativeCurrency: { name: "Celo", symbol: "CELO", decimals: 18 },
982
+ rpcUrls: {
983
+ default: { http: ["https://forno.celo.org"] },
984
+ public: { http: ["https://forno.celo.org"] }
985
+ }
986
+ };
987
+ var AVAILABLE_ENVIRONMENTS = import_citizen_sdk.citizenSdkCapabilities.environments;
988
+ async function startGoodIdVerification(params) {
989
+ if (params.chainId !== CELO_CHAIN_ID) {
990
+ throw new Error("Switch to Celo to verify with GoodID");
991
+ }
992
+ const env = params.environment && AVAILABLE_ENVIRONMENTS.includes(params.environment) ? params.environment : "production";
993
+ const transport = (0, import_viem6.custom)(params.provider);
994
+ const publicClient = (0, import_viem6.createPublicClient)({ chain: CELO_CHAIN3, transport });
995
+ const walletClient = (0, import_viem6.createWalletClient)({
996
+ account: params.address,
997
+ chain: CELO_CHAIN3,
998
+ transport
999
+ });
1000
+ const identitySDK = new import_citizen_sdk.IdentitySDK({ publicClient, walletClient, env });
1001
+ const returnUrl = params.returnUrl ?? (typeof window !== "undefined" ? window.location.href : "");
1002
+ const fvLink = await identitySDK.generateFVLink(false, returnUrl, params.chainId);
1003
+ if (typeof window === "undefined") {
1004
+ throw new Error("GoodID verification requires a browser environment");
1005
+ }
1006
+ window.open(fvLink, "_blank", "noopener,noreferrer");
1007
+ }
1008
+ function isUserRejectedWalletRequest(error) {
1009
+ const message = error instanceof Error ? error.message : String(error);
1010
+ return message.includes("User rejected") || message.includes("user rejected") || message.includes("4001") || message.includes("ACTION_REJECTED");
1011
+ }
1012
+
1013
+ // src/paymentErrors.ts
1014
+ function errorMessage(error) {
1015
+ if (error instanceof Error) return error.message;
1016
+ return String(error ?? "");
1017
+ }
1018
+ function looksLikeRawChainError(message) {
1019
+ const lower = message.toLowerCase();
1020
+ return message.includes("\n") || message.length > 160 || lower.includes("request arguments") || lower.includes("contract call") || lower.includes("docs:") || lower.includes("version: viem") || lower.includes("http request failed") || lower.includes("execution reverted") || lower.includes("transaction reverted") || lower.includes("raw call argument");
1021
+ }
1022
+ function isInsufficientGas(message) {
1023
+ const lower = message.toLowerCase();
1024
+ return lower.includes("insufficient funds") || lower.includes("insufficient funds for gas") || lower.includes("insufficient funds for intrinsic transaction cost") || lower.includes("gas required exceeds allowance") || lower.includes("max fee per gas less than block base fee");
1025
+ }
1026
+ function isInsufficientGBalance(message) {
1027
+ const lower = message.toLowerCase();
1028
+ return lower.includes("transfer amount exceeds balance") || lower.includes("exceeds balance") || lower.includes("erc20: transfer amount exceeds balance") || lower.includes("not enough g$");
1029
+ }
1030
+ function mapPaymentError(error) {
1031
+ console.error("[AiCreditsWidget]", error);
1032
+ if (isUserRejectedWalletRequest(error)) {
1033
+ return "Transaction cancelled";
1034
+ }
1035
+ const message = errorMessage(error).trim();
1036
+ if (isInsufficientGas(message)) {
1037
+ return "Not enough CELO for gas";
1038
+ }
1039
+ if (isInsufficientGBalance(message)) {
1040
+ return "Not enough G$ for this payment";
1041
+ }
1042
+ if (message && !looksLikeRawChainError(message)) {
1043
+ return message;
1044
+ }
1045
+ return "Payment failed. Try again.";
1046
+ }
1047
+
1048
+ // src/vaultMinimums.ts
1049
+ var import_viem7 = require("viem");
1050
+ var ONE_G_WEI = 10n ** 18n;
1051
+ var VAULT_MINIMUMS_ABI = (0, import_viem7.parseAbi)([
1052
+ "function minFirstDepositUsd() view returns (uint256)",
1053
+ "function minMonthlyStreamUsd() view returns (uint256)",
1054
+ "function totalDepositedGd(address account) view returns (uint256)",
1055
+ "function gdUsdPerToken(uint128 amount) view returns (uint256)"
1056
+ ]);
1057
+ function formatMinGDisplay(amountWei) {
1058
+ const raw = Number(amountWei) / 1e18;
1059
+ if (!Number.isFinite(raw) || raw <= 0) return "0";
1060
+ if (raw >= 1e3) return Math.ceil(raw).toString();
1061
+ if (raw >= 10) return (Math.ceil(raw * 10) / 10).toFixed(1);
1062
+ return (Math.ceil(raw * 100) / 100).toFixed(2);
1063
+ }
1064
+ function formatMinUsdDisplay(usd) {
1065
+ return formatUsdDisplay(usd, 2);
1066
+ }
1067
+ function parseUsdThreshold(usd) {
1068
+ if (usd === null) return 0;
1069
+ const value = Number.parseFloat(usd);
1070
+ return Number.isFinite(value) && value > 0 ? value : 0;
1071
+ }
1072
+ function getPaymentAmountValidation(params) {
1073
+ const depositG = parseGAmount(params.depositAmount);
1074
+ const streamG = parseGAmount(params.streamAmount);
1075
+ const balance = parseGAmount(params.gBalance ?? "0");
1076
+ const streamChanged = gToWei(params.streamAmount) !== gToWei(params.currentStreamAmount ?? "0");
1077
+ const hasPaymentAction = depositG > 0 || streamChanged;
1078
+ const minDepositUsd = parseUsdThreshold(params.minDepositUsd);
1079
+ const minStreamUsd = parseUsdThreshold(params.minStreamUsd);
1080
+ const depositUsd = params.quote && params.gdUsdPerToken !== null ? Number.parseFloat(quoteDepositPrincipalUsd(params.quote, params.gdUsdPerToken)) : 0;
1081
+ const streamUsd = params.quote && params.gdUsdPerToken !== null ? Number.parseFloat(quoteStreamPrincipalUsd(params.quote, params.gdUsdPerToken)) : 0;
1082
+ const depositBelowMin = depositG > 0 && minDepositUsd > 0 && params.quote !== null && depositUsd < minDepositUsd;
1083
+ const streamBelowMin = streamChanged && streamG > 0 && minStreamUsd > 0 && params.quote !== null && streamUsd < minStreamUsd;
1084
+ const overBalance = depositG > balance;
1085
+ const minsLoaded = params.minStreamUsd !== null;
1086
+ const vaultMinimumsMet = !minsLoaded || !depositBelowMin && !streamBelowMin;
1087
+ return {
1088
+ depositBelowMin,
1089
+ streamBelowMin,
1090
+ overBalance,
1091
+ vaultMinimumsMet,
1092
+ streamChanged,
1093
+ hasPaymentAction
1094
+ };
1095
+ }
1096
+ function getPayDisabledMessage(params) {
1097
+ if (params.canPay) return null;
1098
+ if (!params.minsLoaded) return "Loading vault minimums\u2026";
1099
+ if (params.validation.overBalance) {
1100
+ return "One-time deposit exceeds your G$ balance. Reduce the deposit amount.";
1101
+ }
1102
+ if (params.validation.depositBelowMin && params.minDepositUsd) {
1103
+ return `First deposit must be at least ${formatMinUsdDisplay(params.minDepositUsd)}.`;
1104
+ }
1105
+ if (params.validation.streamBelowMin && params.minStreamUsd) {
1106
+ return `Monthly stream must be at least ${formatMinUsdDisplay(params.minStreamUsd)}.`;
1107
+ }
1108
+ if (params.status !== "quote_ready") {
1109
+ return "Enter a deposit or change the monthly stream amount to continue.";
1110
+ }
1111
+ return "Adjust the amounts to continue.";
1112
+ }
1113
+ function formatUsd18(usd18) {
1114
+ return (Number(usd18) / 1e18).toFixed(2);
1115
+ }
1116
+ async function readGdUsd18(publicClient, vault, gdAmountWei) {
1117
+ if (gdAmountWei <= 0n) return 0n;
1118
+ return publicClient.readContract({
1119
+ address: vault,
1120
+ abi: VAULT_MINIMUMS_ABI,
1121
+ functionName: "gdUsdPerToken",
1122
+ args: [gdAmountWei]
1123
+ });
1124
+ }
1125
+ async function minGdWeiForUsdThreshold(publicClient, vault, minUsd18) {
1126
+ const usdPerOneG = await readGdUsd18(publicClient, vault, ONE_G_WEI);
1127
+ if (usdPerOneG <= 0n) return minUsd18;
1128
+ return (minUsd18 * ONE_G_WEI + usdPerOneG - 1n) / usdPerOneG;
1129
+ }
1130
+ async function fetchVaultPaymentMinimums(publicClient, vault, payer) {
1131
+ const [minFirstDepositUsd, minMonthlyStreamUsd] = await Promise.all([
1132
+ publicClient.readContract({
1133
+ address: vault,
1134
+ abi: VAULT_MINIMUMS_ABI,
1135
+ functionName: "minFirstDepositUsd"
1136
+ }),
1137
+ publicClient.readContract({
1138
+ address: vault,
1139
+ abi: VAULT_MINIMUMS_ABI,
1140
+ functionName: "minMonthlyStreamUsd"
1141
+ })
1142
+ ]);
1143
+ let minDepositUsd = formatUsd18(minFirstDepositUsd);
1144
+ if (payer) {
1145
+ const totalDeposited = await publicClient.readContract({
1146
+ address: vault,
1147
+ abi: VAULT_MINIMUMS_ABI,
1148
+ functionName: "totalDepositedGd",
1149
+ args: [payer]
1150
+ });
1151
+ if (totalDeposited > 0n) {
1152
+ minDepositUsd = null;
1153
+ }
1154
+ }
1155
+ return {
1156
+ minDepositUsd,
1157
+ minStreamUsd: formatUsd18(minMonthlyStreamUsd)
1158
+ };
1159
+ }
1160
+ async function validateVaultPaymentAmounts(params) {
1161
+ const depositG = parseGAmount(params.depositAmount);
1162
+ const streamG = parseGAmount(params.streamAmount);
1163
+ const hasDeposit = depositG > 0;
1164
+ const streamChanged = gToWei(params.streamAmount) !== gToWei(params.currentStreamAmount ?? "0");
1165
+ const hasStreamUpdate = streamChanged && streamG > 0;
1166
+ if (!hasDeposit && !streamChanged) {
1167
+ throw new Error("Enter a deposit or change the monthly stream amount");
1168
+ }
1169
+ const [minFirstDepositUsd, minMonthlyStreamUsd, totalDeposited] = await Promise.all([
1170
+ params.publicClient.readContract({
1171
+ address: params.vault,
1172
+ abi: VAULT_MINIMUMS_ABI,
1173
+ functionName: "minFirstDepositUsd"
1174
+ }),
1175
+ params.publicClient.readContract({
1176
+ address: params.vault,
1177
+ abi: VAULT_MINIMUMS_ABI,
1178
+ functionName: "minMonthlyStreamUsd"
1179
+ }),
1180
+ params.publicClient.readContract({
1181
+ address: params.vault,
1182
+ abi: VAULT_MINIMUMS_ABI,
1183
+ functionName: "totalDepositedGd",
1184
+ args: [params.payer]
1185
+ })
1186
+ ]);
1187
+ if (hasStreamUpdate) {
1188
+ const monthlyWei = gToWei(params.streamAmount);
1189
+ const streamUsd = await readGdUsd18(params.publicClient, params.vault, monthlyWei);
1190
+ if (streamUsd < minMonthlyStreamUsd) {
1191
+ const minWei = await minGdWeiForUsdThreshold(
1192
+ params.publicClient,
1193
+ params.vault,
1194
+ minMonthlyStreamUsd
1195
+ );
1196
+ throw new Error(
1197
+ `Monthly stream must be at least ${formatMinGDisplay(minWei)} G$ (about ${formatMinUsdDisplay(formatUsd18(minMonthlyStreamUsd))} at the current G$ price)`
1198
+ );
1199
+ }
1200
+ }
1201
+ if (hasDeposit && totalDeposited === 0n) {
1202
+ const depositWei = gToWei(params.depositAmount);
1203
+ const depositUsd = await readGdUsd18(params.publicClient, params.vault, depositWei);
1204
+ if (depositUsd < minFirstDepositUsd) {
1205
+ const minWei = await minGdWeiForUsdThreshold(
1206
+ params.publicClient,
1207
+ params.vault,
1208
+ minFirstDepositUsd
1209
+ );
1210
+ throw new Error(
1211
+ `First deposit must be at least ${formatMinGDisplay(minWei)} G$ (about ${formatMinUsdDisplay(formatUsd18(minFirstDepositUsd))} at the current G$ price)`
1212
+ );
1213
+ }
1214
+ }
1215
+ }
1216
+
1217
+ // src/adapter.ts
1218
+ var CELO_CHAIN_ID2 = 42220;
1219
+ var MIN_DEPOSIT_AMOUNT = "1";
1220
+ var CELO_GD_ANTSEED_VAULT_FALLBACK = CELO_GD_ANTSEED_VAULT_ADDRESS;
1221
+ var G_TOKEN_ABI = (0, import_viem8.parseAbi)([
1222
+ "function balanceOf(address account) view returns (uint256)",
1223
+ "function decimals() view returns (uint8)"
1224
+ ]);
1225
+ var CELO_CHAIN4 = {
1226
+ id: CELO_CHAIN_ID2,
1227
+ name: "Celo",
1228
+ nativeCurrency: { name: "Celo", symbol: "CELO", decimals: 18 },
1229
+ rpcUrls: {
1230
+ default: { http: ["https://forno.celo.org"] },
1231
+ public: { http: ["https://forno.celo.org"] }
1232
+ }
1233
+ };
1234
+ var INITIAL_STATE = {
1235
+ status: "disconnected",
1236
+ address: null,
1237
+ chainId: null,
1238
+ gBalance: null,
1239
+ gdUsdPerToken: null,
1240
+ totalCreditUsd: null,
1241
+ isGoodIdVerified: false,
1242
+ buyerPubKey: null,
1243
+ buyerPrvKey: null,
1244
+ operatorConsented: false,
1245
+ operatorAddress: null,
1246
+ minDepositUsd: null,
1247
+ minStreamUsd: null,
1248
+ totalGdDepositedG: null,
1249
+ monthlyStreamG: null,
1250
+ withdrawableUsd: null,
1251
+ depositBonusPercent: DEFAULT_DISCOUNT_CONFIG.depositBonusPercent,
1252
+ streamBonusPercent: DEFAULT_DISCOUNT_CONFIG.streamBonusPercent,
1253
+ error: null,
1254
+ activeTab: "buy"
1255
+ };
1256
+ var WALLET_LOADING_STATE = {
1257
+ gBalance: null,
1258
+ gdUsdPerToken: null,
1259
+ totalCreditUsd: null,
1260
+ isGoodIdVerified: false,
1261
+ minDepositUsd: null,
1262
+ minStreamUsd: null,
1263
+ totalGdDepositedG: null,
1264
+ monthlyStreamG: null,
1265
+ withdrawableUsd: null,
1266
+ operatorAddress: null
1267
+ };
1268
+ function isNonBuyTab(tab) {
1269
+ return tab === "manage" || tab === "history";
1270
+ }
1271
+ function resolveActiveTab(prev, overrides) {
1272
+ if (overrides.activeTab !== void 0) return overrides.activeTab;
1273
+ if (overrides.totalCreditUsd !== void 0 && overrides.totalCreditUsd !== null) {
1274
+ return hasCreditBalance(overrides.totalCreditUsd) ? "manage" : "buy";
1275
+ }
1276
+ return prev.activeTab ?? "buy";
1277
+ }
1278
+ function hasCreditBalance(totalCreditUsd) {
1279
+ return totalCreditUsd !== null && BigInt(totalCreditUsd) > 0n;
1280
+ }
1281
+ function deriveStatus(params) {
1282
+ const {
1283
+ isConnected,
1284
+ chainId,
1285
+ gBalance,
1286
+ buyerPubKey,
1287
+ buyerPrvKey,
1288
+ operatorConsented,
1289
+ currentStatus
1290
+ } = params;
1291
+ if (currentStatus === "payment_pending" || currentStatus === "payment_confirmed" || currentStatus === "payment_failed" || currentStatus === "backend_unavailable") {
1292
+ return currentStatus;
1293
+ }
1294
+ if (currentStatus === "connecting" && gBalance === null) {
1295
+ return "connecting";
1296
+ }
1297
+ if (!isConnected) {
1298
+ return currentStatus === "connecting" ? "connecting" : "disconnected";
1299
+ }
1300
+ if (chainId !== null && chainId !== CELO_CHAIN_ID2) return "unsupported_chain";
1301
+ if (gBalance === null) return "purchase_setup";
1302
+ const balance = Number.parseFloat(gBalance);
1303
+ if (balance <= 0) return "purchase_setup";
1304
+ const minBalance = Number.parseFloat(MIN_DEPOSIT_AMOUNT);
1305
+ if (balance < minBalance) return "insufficient_g_balance";
1306
+ if (operatorConsented && !!buyerPubKey) return "quote_ready";
1307
+ if (!buyerPubKey || !buyerPrvKey || !operatorConsented) return "purchase_setup";
1308
+ return "quote_ready";
1309
+ }
1310
+ function withDerivedStatus(prev, overrides, isConnected = true) {
1311
+ const merged = { ...prev, ...overrides };
1312
+ const status = deriveStatus({
1313
+ isConnected,
1314
+ chainId: merged.chainId,
1315
+ gBalance: merged.gBalance,
1316
+ buyerPubKey: merged.buyerPubKey,
1317
+ buyerPrvKey: merged.buyerPrvKey,
1318
+ operatorConsented: merged.operatorConsented,
1319
+ currentStatus: merged.status
1320
+ });
1321
+ return {
1322
+ ...merged,
1323
+ status,
1324
+ activeTab: resolveActiveTab(prev, overrides)
1325
+ };
1326
+ }
1327
+ function mergeStatePreservingNonBuyTab(prev, overrides) {
1328
+ const nextTab = overrides.activeTab ?? prev.activeTab;
1329
+ if (!isNonBuyTab(prev.activeTab) && !isNonBuyTab(nextTab)) {
1330
+ return withDerivedStatus(prev, overrides, true);
1331
+ }
1332
+ const activeTab = isNonBuyTab(nextTab) ? nextTab : prev.activeTab;
1333
+ const status = deriveStatus({
1334
+ isConnected: true,
1335
+ chainId: overrides.chainId ?? prev.chainId,
1336
+ gBalance: overrides.gBalance ?? prev.gBalance,
1337
+ buyerPubKey: overrides.buyerPubKey ?? prev.buyerPubKey,
1338
+ buyerPrvKey: overrides.buyerPrvKey ?? prev.buyerPrvKey,
1339
+ operatorConsented: overrides.operatorConsented ?? prev.operatorConsented,
1340
+ currentStatus: overrides.status ?? prev.status
1341
+ });
1342
+ return {
1343
+ ...prev,
1344
+ ...overrides,
1345
+ status,
1346
+ activeTab
1347
+ };
1348
+ }
1349
+ function viewToStatePatch(view, enriched, prev, options) {
1350
+ const operatorAccepted = view.operator.operatorAccepted;
1351
+ const totalCreditUsd = enriched.totalCreditUsd;
1352
+ const balanceMode = options?.balanceMode ?? "if_positive";
1353
+ return {
1354
+ totalCreditUsd: balanceMode === "always" || hasCreditBalance(totalCreditUsd) ? totalCreditUsd : prev.totalCreditUsd,
1355
+ isGoodIdVerified: enriched.goodIdVerified,
1356
+ operatorConsented: operatorAccepted,
1357
+ operatorAddress: view.operator.operatorAddress ?? null,
1358
+ withdrawableUsd: view.withdrawableUsd,
1359
+ totalGdDepositedG: enriched.totalGdDepositedG,
1360
+ monthlyStreamG: enriched.monthlyStreamG,
1361
+ ...view.buyer ? { buyerPubKey: view.buyer } : {}
1362
+ };
1363
+ }
1364
+ function mergeSessionFields(prev, sessionPatch, accountPatch, accountSwitched) {
1365
+ const buyerPubKey = sessionPatch.buyerPubKey ?? accountPatch.buyerPubKey ?? (accountSwitched ? null : prev.buyerPubKey);
1366
+ const buyerPrvKey = sessionPatch.buyerPrvKey ?? (accountSwitched ? null : prev.buyerPrvKey);
1367
+ const operatorConsented = accountSwitched ? sessionPatch.operatorConsented ?? accountPatch.operatorConsented ?? false : accountPatch.operatorConsented ?? sessionPatch.operatorConsented ?? prev.operatorConsented;
1368
+ return {
1369
+ buyerPubKey,
1370
+ buyerPrvKey,
1371
+ operatorConsented
1372
+ };
1373
+ }
1374
+ function syncOperatorConsentSession(address, operatorConsented) {
1375
+ if (operatorConsented === void 0) return;
1376
+ patchPayerSession(address, { operatorConsented });
1377
+ }
1378
+ function syncBuyerPubKeySession(address, buyerPubKey) {
1379
+ if (!buyerPubKey) return;
1380
+ const existing = readPayerSession(address);
1381
+ if (existing?.buyerPubKey) return;
1382
+ patchPayerSession(address, { buyerPubKey });
1383
+ }
1384
+ function useAiCreditsAdapter({
1385
+ environment = "production",
1386
+ backendUrl,
1387
+ baseRpcUrl,
1388
+ celoRpcUrl,
1389
+ fundingVaultAddress,
1390
+ vaultAddress,
1391
+ goodIdAddress,
1392
+ goodIdReturnUrl,
1393
+ onPaySuccess,
1394
+ onPayError,
1395
+ backendClient: backendClientOverride,
1396
+ chainClient: chainClientOverride,
1397
+ skipVaultPaymentValidation = false,
1398
+ prepareSettlement
1399
+ }) {
1400
+ const { address, chainId, isConnected, provider, connect } = (0, import_core.useWallet)();
1401
+ const [state, setState] = (0, import_react.useState)(INITIAL_STATE);
1402
+ const configurationError = backendClientOverride || backendUrl ? null : "AI Credits backend is not configured";
1403
+ const providerRef = (0, import_react.useRef)(null);
1404
+ providerRef.current = provider;
1405
+ const goodIdVerifyPendingRef = (0, import_react.useRef)(false);
1406
+ const celoVault = vaultAddress ?? CELO_GD_ANTSEED_VAULT_FALLBACK;
1407
+ const backendClient = (0, import_react.useMemo)(
1408
+ () => backendClientOverride ?? createBackendClient(backendUrl),
1409
+ [backendClientOverride, backendUrl]
1410
+ );
1411
+ const chainClient = (0, import_react.useMemo)(
1412
+ () => chainClientOverride ?? createChainClient({
1413
+ baseRpcUrl,
1414
+ celoRpcUrl,
1415
+ fundingVaultAddress,
1416
+ celoVaultAddress: celoVault,
1417
+ celoGoodIdAddress: goodIdAddress ?? CELO_GOODID_ADDRESS
1418
+ }),
1419
+ [chainClientOverride, baseRpcUrl, celoRpcUrl, fundingVaultAddress, celoVault, goodIdAddress]
1420
+ );
1421
+ (0, import_react.useEffect)(() => {
1422
+ if (!isConnected || !address) {
1423
+ setState((prev) => prev.status === "connecting" ? prev : { ...INITIAL_STATE });
1424
+ return;
1425
+ }
1426
+ if (configurationError) {
1427
+ setState((prev) => ({
1428
+ ...prev,
1429
+ address,
1430
+ chainId,
1431
+ status: "backend_unavailable",
1432
+ error: configurationError
1433
+ }));
1434
+ return;
1435
+ }
1436
+ let cancelled = false;
1437
+ const sessionPatch = patchPayerSessionFields(address);
1438
+ setState((prev) => {
1439
+ if (prev.status === "payment_pending" || prev.status === "payment_confirmed" || prev.status === "payment_failed") {
1440
+ return prev;
1441
+ }
1442
+ const accountSwitched = !addressesMatch(prev.address, address);
1443
+ const buyerFields = mergeSessionFields(prev, sessionPatch, {}, accountSwitched);
1444
+ return withDerivedStatus(
1445
+ prev,
1446
+ {
1447
+ address,
1448
+ chainId,
1449
+ ...buyerFields,
1450
+ ...WALLET_LOADING_STATE,
1451
+ error: null,
1452
+ status: "connecting"
1453
+ },
1454
+ true
1455
+ );
1456
+ });
1457
+ async function loadWalletData() {
1458
+ const publicClient = (0, import_viem8.createPublicClient)({ chain: CELO_CHAIN4, transport: (0, import_viem8.http)() });
1459
+ const balancePromise = Promise.all([
1460
+ publicClient.readContract({
1461
+ address: G_TOKEN_CELO_ADDRESS,
1462
+ abi: G_TOKEN_ABI,
1463
+ functionName: "balanceOf",
1464
+ args: [address]
1465
+ }),
1466
+ publicClient.readContract({
1467
+ address: G_TOKEN_CELO_ADDRESS,
1468
+ abi: G_TOKEN_ABI,
1469
+ functionName: "decimals"
1470
+ })
1471
+ ]);
1472
+ const accountPromise = buildAccountView(address, backendClient, chainClient, {
1473
+ buyerAddress: sessionPatch.buyerPubKey ?? null
1474
+ }).then(async (view) => ({
1475
+ view,
1476
+ enriched: await enrichAccountView(view, chainClient)
1477
+ })).catch(() => null);
1478
+ const minimumsPromise = skipVaultPaymentValidation ? Promise.resolve({
1479
+ minDepositUsd: "1.00",
1480
+ minStreamUsd: "1.00"
1481
+ }) : fetchVaultPaymentMinimums(publicClient, celoVault, address).catch(() => null);
1482
+ const gdUsdPerTokenPromise = chainClient.fetchGdUsdPerToken().catch(() => null);
1483
+ const discountConfigPromise = backendClient.getDiscountConfig().catch(() => null);
1484
+ try {
1485
+ const [[rawBalance, decimals], account, minimums, gdUsdPerToken, discountConfig] = await Promise.all([
1486
+ balancePromise,
1487
+ accountPromise,
1488
+ minimumsPromise,
1489
+ gdUsdPerTokenPromise,
1490
+ discountConfigPromise
1491
+ ]);
1492
+ if (cancelled) return;
1493
+ const patch = {
1494
+ address,
1495
+ chainId,
1496
+ gBalance: (0, import_viem8.formatUnits)(rawBalance, decimals),
1497
+ gdUsdPerToken,
1498
+ minDepositUsd: minimums?.minDepositUsd ?? null,
1499
+ minStreamUsd: minimums?.minStreamUsd ?? null,
1500
+ depositBonusPercent: discountConfig?.depositBonusPercent ?? DEFAULT_DISCOUNT_CONFIG.depositBonusPercent,
1501
+ streamBonusPercent: discountConfig?.streamBonusPercent ?? DEFAULT_DISCOUNT_CONFIG.streamBonusPercent
1502
+ };
1503
+ setState((prev) => {
1504
+ const accountSwitched = !addressesMatch(prev.address, address);
1505
+ const accountPatch = account ? viewToStatePatch(account.view, account.enriched, prev, {
1506
+ balanceMode: "always"
1507
+ }) : {};
1508
+ const buyerFields = mergeSessionFields(prev, sessionPatch, accountPatch, accountSwitched);
1509
+ if (address && accountPatch.operatorConsented !== void 0) {
1510
+ syncOperatorConsentSession(address, accountPatch.operatorConsented);
1511
+ }
1512
+ if (address && account?.view.buyer) {
1513
+ syncBuyerPubKeySession(address, account.view.buyer);
1514
+ }
1515
+ return withDerivedStatus(
1516
+ prev,
1517
+ {
1518
+ ...patch,
1519
+ ...accountPatch,
1520
+ ...buyerFields,
1521
+ ...account ? {} : { activeTab: "buy" }
1522
+ },
1523
+ true
1524
+ );
1525
+ });
1526
+ } catch {
1527
+ if (cancelled) return;
1528
+ setState((prev) => {
1529
+ const accountSwitched = !addressesMatch(prev.address, address);
1530
+ const buyerFields = mergeSessionFields(prev, sessionPatch, {}, accountSwitched);
1531
+ return withDerivedStatus(
1532
+ prev,
1533
+ {
1534
+ address,
1535
+ chainId,
1536
+ gBalance: "0",
1537
+ ...buyerFields,
1538
+ status: chainId !== null && chainId !== CELO_CHAIN_ID2 ? "unsupported_chain" : "purchase_setup"
1539
+ },
1540
+ true
1541
+ );
1542
+ });
1543
+ }
1544
+ }
1545
+ void loadWalletData();
1546
+ return () => {
1547
+ cancelled = true;
1548
+ };
1549
+ }, [isConnected, address, chainId, backendClient, chainClient, celoVault, configurationError]);
1550
+ const handleConnect = (0, import_react.useCallback)(async () => {
1551
+ setState((prev) => withDerivedStatus(prev, { status: "connecting", error: null }, false));
1552
+ try {
1553
+ await connect();
1554
+ } catch {
1555
+ setState((prev) => withDerivedStatus(prev, { status: "disconnected", error: null }, false));
1556
+ return;
1557
+ }
1558
+ setState((prev) => {
1559
+ if (prev.status !== "connecting") return prev;
1560
+ return withDerivedStatus(prev, { status: "disconnected", error: null }, false);
1561
+ });
1562
+ }, [connect]);
1563
+ const handleSwitchChain = (0, import_react.useCallback)(async () => {
1564
+ const prov = providerRef.current;
1565
+ if (!prov) return;
1566
+ await prov.request({
1567
+ method: "wallet_switchEthereumChain",
1568
+ params: [{ chainId: `0x${CELO_CHAIN_ID2.toString(16)}` }]
1569
+ });
1570
+ }, []);
1571
+ const handleGenerateBuyerKey = (0, import_react.useCallback)(async () => {
1572
+ if (!address || !providerRef.current) {
1573
+ setState(
1574
+ (prev) => withDerivedStatus(
1575
+ prev,
1576
+ { error: "Connect your wallet before generating a buyer key" },
1577
+ true
1578
+ )
1579
+ );
1580
+ return;
1581
+ }
1582
+ try {
1583
+ const payerAddress = address;
1584
+ const message = buildBuyerKeyMessage(payerAddress);
1585
+ const walletClient = (0, import_viem8.createWalletClient)({
1586
+ account: payerAddress,
1587
+ chain: CELO_CHAIN4,
1588
+ transport: (0, import_viem8.custom)(providerRef.current)
1589
+ });
1590
+ const signature = await walletClient.signMessage({
1591
+ account: payerAddress,
1592
+ message
1593
+ });
1594
+ const privateKey = deriveBuyerPrivateKeyFromSignature(signature);
1595
+ const account = (0, import_accounts4.privateKeyToAccount)(privateKey);
1596
+ patchPayerSession(payerAddress, {
1597
+ buyerPubKey: account.address,
1598
+ buyerPrvKey: privateKey
1599
+ });
1600
+ setState(
1601
+ (prev) => mergeStatePreservingNonBuyTab(prev, {
1602
+ buyerPubKey: account.address,
1603
+ buyerPrvKey: privateKey,
1604
+ error: null,
1605
+ ...!isNonBuyTab(prev.activeTab) ? { status: "purchase_setup" } : {}
1606
+ })
1607
+ );
1608
+ } catch (err) {
1609
+ setState(
1610
+ (prev) => withDerivedStatus(
1611
+ prev,
1612
+ {
1613
+ error: err instanceof Error ? err.message : "Buyer key generation was rejected"
1614
+ },
1615
+ true
1616
+ )
1617
+ );
1618
+ }
1619
+ }, [address]);
1620
+ const handleSignOperatorConsent = (0, import_react.useCallback)(async () => {
1621
+ const currentState = state;
1622
+ if (!currentState.address || !currentState.buyerPubKey || !currentState.buyerPrvKey) {
1623
+ setState(
1624
+ (prev) => withDerivedStatus(
1625
+ prev,
1626
+ { error: "Generate a buyer key before signing operator consent" },
1627
+ true
1628
+ )
1629
+ );
1630
+ return;
1631
+ }
1632
+ const ref = { payer: currentState.address, buyer: currentState.buyerPubKey };
1633
+ const onNonBuyTab = isNonBuyTab(currentState.activeTab);
1634
+ try {
1635
+ const operatorStatus = await chainClient.getBuyerOperatorStatus(ref);
1636
+ if (!operatorStatus.enabled) {
1637
+ throw new Error("Operator consent is not available");
1638
+ }
1639
+ if (operatorStatus.operatorAccepted) {
1640
+ patchPayerSession(currentState.address, { operatorConsented: true });
1641
+ setState(
1642
+ (prev) => mergeStatePreservingNonBuyTab(prev, {
1643
+ operatorConsented: true,
1644
+ error: null,
1645
+ ...!onNonBuyTab ? { status: "purchase_setup" } : {}
1646
+ })
1647
+ );
1648
+ return;
1649
+ }
1650
+ const payload = await chainClient.buildOperatorConsentPayload(ref, operatorStatus);
1651
+ if (!payload.enabled || !payload.typedData) {
1652
+ throw new Error("Operator consent is not available");
1653
+ }
1654
+ const buyerSig = await signOperatorConsentFromTypedData(
1655
+ currentState.buyerPrvKey,
1656
+ payload.typedData
1657
+ );
1658
+ await backendClient.submitOperatorConsent(ref.buyer, {
1659
+ nonce: operatorStatus.consentNonce,
1660
+ signature: buyerSig
1661
+ });
1662
+ await waitForOperatorConsent(chainClient, ref);
1663
+ patchPayerSession(currentState.address, { operatorConsented: true });
1664
+ setState(
1665
+ (prev) => mergeStatePreservingNonBuyTab(prev, {
1666
+ operatorConsented: true,
1667
+ error: null,
1668
+ ...!onNonBuyTab ? { status: "purchase_setup" } : {}
1669
+ })
1670
+ );
1671
+ } catch (err) {
1672
+ setState((prev) => ({
1673
+ ...prev,
1674
+ error: err instanceof Error ? err.message : "Operator consent signature rejected"
1675
+ }));
1676
+ }
1677
+ }, [state, backendClient, chainClient]);
1678
+ const handleSyncOperatorConsentFromChain = (0, import_react.useCallback)(async () => {
1679
+ const currentState = state;
1680
+ if (!currentState.address || !currentState.buyerPubKey || currentState.operatorConsented) {
1681
+ return;
1682
+ }
1683
+ try {
1684
+ const ref = { payer: currentState.address, buyer: currentState.buyerPubKey };
1685
+ const operatorStatus = await chainClient.getBuyerOperatorStatus(ref);
1686
+ if (!operatorStatus.operatorAccepted) return;
1687
+ patchPayerSession(currentState.address, { operatorConsented: true });
1688
+ const onNonBuyTab = isNonBuyTab(currentState.activeTab);
1689
+ setState(
1690
+ (prev) => mergeStatePreservingNonBuyTab(prev, {
1691
+ operatorConsented: true,
1692
+ error: null,
1693
+ ...!onNonBuyTab ? { status: "purchase_setup" } : {}
1694
+ })
1695
+ );
1696
+ } catch {
1697
+ return;
1698
+ }
1699
+ }, [state, chainClient]);
1700
+ const handleBuildQuote = (0, import_react.useCallback)(
1701
+ async (depositG, streamG) => {
1702
+ const quote = await chainClient.buildQuote(depositG, streamG);
1703
+ if (state.gdUsdPerToken === null) {
1704
+ try {
1705
+ const gdUsdPerToken = await chainClient.fetchGdUsdPerToken();
1706
+ setState((prev) => ({ ...prev, gdUsdPerToken }));
1707
+ } catch {
1708
+ return quote;
1709
+ }
1710
+ }
1711
+ return quote;
1712
+ },
1713
+ [chainClient, state.gdUsdPerToken]
1714
+ );
1715
+ const handlePay = (0, import_react.useCallback)(
1716
+ async (quote) => {
1717
+ const currentState = state;
1718
+ if (!currentState.address || !currentState.buyerPubKey || !providerRef.current) {
1719
+ throw new Error("Connect your wallet and generate a buyer key before paying");
1720
+ }
1721
+ const hasDeposit = Number.parseFloat(quote.depositAmountG) > 0;
1722
+ const streamChanged = isStreamAmountChanged(quote.streamAmountG, currentState.monthlyStreamG);
1723
+ if (!hasDeposit && !streamChanged) {
1724
+ throw new Error("Enter a deposit or change the monthly stream amount");
1725
+ }
1726
+ let gdUsdPerToken = currentState.gdUsdPerToken;
1727
+ try {
1728
+ if (gdUsdPerToken === null) {
1729
+ gdUsdPerToken = await chainClient.fetchGdUsdPerToken();
1730
+ }
1731
+ } catch {
1732
+ setState((prev) => ({
1733
+ ...prev,
1734
+ status: "backend_unavailable",
1735
+ error: "Could not build quote \u2014 check chain connectivity"
1736
+ }));
1737
+ throw new Error("Could not build quote \u2014 check chain connectivity");
1738
+ }
1739
+ if (gdUsdPerToken === null) {
1740
+ throw new Error("Could not build quote \u2014 check chain connectivity");
1741
+ }
1742
+ if (!skipVaultPaymentValidation) {
1743
+ try {
1744
+ const publicClient = (0, import_viem8.createPublicClient)({ chain: CELO_CHAIN4, transport: (0, import_viem8.http)() });
1745
+ await validateVaultPaymentAmounts({
1746
+ publicClient,
1747
+ vault: celoVault,
1748
+ payer: currentState.address,
1749
+ depositAmount: quote.depositAmountG,
1750
+ streamAmount: quote.streamAmountG,
1751
+ currentStreamAmount: currentState.monthlyStreamG
1752
+ });
1753
+ } catch (error) {
1754
+ const message = error instanceof Error ? error.message : "Payment amount below vault minimum";
1755
+ setState((prev) => ({
1756
+ ...prev,
1757
+ status: "payment_failed",
1758
+ error: message
1759
+ }));
1760
+ onPayError?.({
1761
+ address: currentState.address,
1762
+ chainId: CELO_CHAIN_ID2,
1763
+ message
1764
+ });
1765
+ throw error instanceof Error ? error : new Error(message);
1766
+ }
1767
+ }
1768
+ setState((prev) => ({
1769
+ ...prev,
1770
+ gdUsdPerToken,
1771
+ status: "payment_pending",
1772
+ error: null
1773
+ }));
1774
+ try {
1775
+ const vault = celoVault;
1776
+ const payerAddress = currentState.address;
1777
+ const buyerAddress = currentState.buyerPubKey;
1778
+ const publicClient = (0, import_viem8.createPublicClient)({ chain: CELO_CHAIN4, transport: (0, import_viem8.http)() });
1779
+ const walletClient = (0, import_viem8.createWalletClient)({
1780
+ account: payerAddress,
1781
+ chain: CELO_CHAIN4,
1782
+ transport: (0, import_viem8.custom)(providerRef.current)
1783
+ });
1784
+ const accountRef = {
1785
+ payer: currentState.address,
1786
+ buyer: currentState.buyerPubKey
1787
+ };
1788
+ if (prepareSettlement) {
1789
+ const creditUsdMicro2 = quoteTotalUsdMicro(quote, gdUsdPerToken, currentState.isGoodIdVerified, {
1790
+ depositBonusPercent: currentState.depositBonusPercent,
1791
+ streamBonusPercent: currentState.streamBonusPercent
1792
+ });
1793
+ prepareSettlement(accountRef, creditUsdMicro2);
1794
+ }
1795
+ const { txHashes } = await executeCeloPayment({
1796
+ walletClient,
1797
+ publicClient,
1798
+ payer: payerAddress,
1799
+ buyer: buyerAddress,
1800
+ vault,
1801
+ depositAmountG: quote.depositAmountG,
1802
+ streamAmountG: quote.streamAmountG,
1803
+ currentStreamAmountG: currentState.monthlyStreamG
1804
+ });
1805
+ const txHash = txHashes[txHashes.length - 1];
1806
+ setState((prev) => ({
1807
+ ...prev,
1808
+ status: "payment_confirmed"
1809
+ }));
1810
+ let balanceBefore = "0";
1811
+ try {
1812
+ const credit = await backendClient.getAccountCredit(currentState.address);
1813
+ balanceBefore = totalCreditUsdFromProfile(credit.profile);
1814
+ } catch {
1815
+ balanceBefore = "0";
1816
+ }
1817
+ for (const hash of txHashes) {
1818
+ await backendClient.notifyPayment(hash);
1819
+ }
1820
+ const { totalCreditUsd } = await backendClient.waitForSettlement(accountRef, {
1821
+ txHashes,
1822
+ previousBalance: balanceBefore
1823
+ });
1824
+ const creditUsdMicro = (BigInt(totalCreditUsd) - BigInt(balanceBefore || "0")).toString();
1825
+ setState(
1826
+ (prev) => withDerivedStatus(prev, {
1827
+ totalCreditUsd,
1828
+ error: null,
1829
+ activeTab: "manage"
1830
+ })
1831
+ );
1832
+ onPaySuccess?.({
1833
+ address: currentState.address,
1834
+ chainId: CELO_CHAIN_ID2,
1835
+ transactionHash: txHash,
1836
+ buyerPubKey: currentState.buyerPubKey,
1837
+ creditUsdMicro
1838
+ });
1839
+ } catch (error) {
1840
+ const message = mapPaymentError(error);
1841
+ setState((prev) => ({
1842
+ ...prev,
1843
+ status: "payment_failed",
1844
+ error: message
1845
+ }));
1846
+ onPayError?.({
1847
+ address: currentState.address,
1848
+ chainId: CELO_CHAIN_ID2,
1849
+ message
1850
+ });
1851
+ throw new Error(message);
1852
+ }
1853
+ },
1854
+ [
1855
+ state,
1856
+ backendClient,
1857
+ chainClient,
1858
+ celoVault,
1859
+ onPaySuccess,
1860
+ onPayError,
1861
+ prepareSettlement,
1862
+ skipVaultPaymentValidation
1863
+ ]
1864
+ );
1865
+ const handleRefresh = (0, import_react.useCallback)(
1866
+ async (options) => {
1867
+ const currentState = state;
1868
+ if (!currentState.address) return;
1869
+ try {
1870
+ const sessionBuyer = currentState.buyerPubKey ?? patchPayerSessionFields(currentState.address).buyerPubKey ?? null;
1871
+ const [view, discountConfig] = await Promise.all([
1872
+ buildAccountView(currentState.address, backendClient, chainClient, {
1873
+ buyerAddress: sessionBuyer
1874
+ }),
1875
+ backendClient.getDiscountConfig().catch(() => null)
1876
+ ]);
1877
+ const enriched = await enrichAccountView(view, chainClient);
1878
+ setState((prev) => {
1879
+ const accountPatch = viewToStatePatch(view, enriched, prev, {
1880
+ balanceMode: "always"
1881
+ });
1882
+ const sessionFields = mergeSessionFields(
1883
+ prev,
1884
+ patchPayerSessionFields(currentState.address),
1885
+ accountPatch,
1886
+ false
1887
+ );
1888
+ if (accountPatch.operatorConsented !== void 0 && currentState.address) {
1889
+ syncOperatorConsentSession(currentState.address, accountPatch.operatorConsented);
1890
+ }
1891
+ if (currentState.address && view.buyer) {
1892
+ syncBuyerPubKeySession(currentState.address, view.buyer);
1893
+ }
1894
+ const statusSeed = options?.afterGoodIdVerify && prev.status === "payment_failed" ? "quote_ready" : prev.status === "backend_unavailable" ? "purchase_setup" : prev.status;
1895
+ return withDerivedStatus(
1896
+ { ...prev, status: statusSeed },
1897
+ {
1898
+ ...accountPatch,
1899
+ ...sessionFields,
1900
+ activeTab: prev.activeTab,
1901
+ error: null,
1902
+ depositBonusPercent: discountConfig?.depositBonusPercent ?? prev.depositBonusPercent,
1903
+ streamBonusPercent: discountConfig?.streamBonusPercent ?? prev.streamBonusPercent
1904
+ },
1905
+ true
1906
+ );
1907
+ });
1908
+ } catch {
1909
+ setState(
1910
+ (prev) => mergeStatePreservingNonBuyTab(prev, {
1911
+ status: "backend_unavailable",
1912
+ error: "Could not reach backend \u2014 check your connection"
1913
+ })
1914
+ );
1915
+ }
1916
+ },
1917
+ [state, backendClient, chainClient]
1918
+ );
1919
+ const handleVerifyGoodId = (0, import_react.useCallback)(async () => {
1920
+ const currentState = state;
1921
+ if (!currentState.address || !providerRef.current) {
1922
+ setState(
1923
+ (prev) => withDerivedStatus(
1924
+ prev,
1925
+ { error: "Connect your wallet on Celo to verify with GoodID" },
1926
+ true
1927
+ )
1928
+ );
1929
+ return false;
1930
+ }
1931
+ if (currentState.chainId !== CELO_CHAIN_ID2) {
1932
+ setState(
1933
+ (prev) => withDerivedStatus(prev, { error: "Switch to Celo to verify with GoodID" }, true)
1934
+ );
1935
+ return false;
1936
+ }
1937
+ try {
1938
+ await startGoodIdVerification({
1939
+ provider: providerRef.current,
1940
+ address: currentState.address,
1941
+ chainId: CELO_CHAIN_ID2,
1942
+ environment,
1943
+ returnUrl: goodIdReturnUrl
1944
+ });
1945
+ goodIdVerifyPendingRef.current = true;
1946
+ setState((prev) => ({ ...prev, error: null }));
1947
+ return true;
1948
+ } catch (err) {
1949
+ if (isUserRejectedWalletRequest(err)) {
1950
+ return false;
1951
+ }
1952
+ setState(
1953
+ (prev) => withDerivedStatus(
1954
+ prev,
1955
+ {
1956
+ error: err instanceof Error ? err.message : "Could not start GoodID verification"
1957
+ },
1958
+ true
1959
+ )
1960
+ );
1961
+ return false;
1962
+ }
1963
+ }, [state, environment, goodIdReturnUrl]);
1964
+ (0, import_react.useEffect)(() => {
1965
+ if (typeof window === "undefined") return;
1966
+ const onFocus = () => {
1967
+ if (!goodIdVerifyPendingRef.current) return;
1968
+ goodIdVerifyPendingRef.current = false;
1969
+ void handleRefresh({ afterGoodIdVerify: true });
1970
+ };
1971
+ window.addEventListener("focus", onFocus);
1972
+ return () => window.removeEventListener("focus", onFocus);
1973
+ }, [handleRefresh]);
1974
+ const handleCloseChannel = (0, import_react.useCallback)(
1975
+ async (channelIdInput) => {
1976
+ const currentState = state;
1977
+ const channelId = normalizeChannelId(channelIdInput);
1978
+ if (!channelId) {
1979
+ setState((prev) => ({
1980
+ ...prev,
1981
+ error: "Enter a valid channel ID (0x followed by 64 hex characters)"
1982
+ }));
1983
+ return;
1984
+ }
1985
+ if (!currentState.buyerPrvKey) {
1986
+ setState((prev) => ({
1987
+ ...prev,
1988
+ error: "Sign with your payer wallet in Buyer & Operator below to generate the buyer private key before closing a channel"
1989
+ }));
1990
+ return;
1991
+ }
1992
+ if (!fundingVaultAddress) {
1993
+ setState((prev) => ({
1994
+ ...prev,
1995
+ error: "Funding vault address is not configured"
1996
+ }));
1997
+ return;
1998
+ }
1999
+ try {
2000
+ const timestamp = Math.floor(Date.now() / 1e3);
2001
+ const signature = await signRequestClose({
2002
+ buyerPrivateKey: currentState.buyerPrvKey,
2003
+ fundingVaultAddress,
2004
+ channelId,
2005
+ timestamp
2006
+ });
2007
+ await backendClient.closeChannel(channelId, { timestamp, signature });
2008
+ setState((prev) => ({ ...prev, error: null }));
2009
+ } catch (err) {
2010
+ setState((prev) => ({
2011
+ ...prev,
2012
+ error: err instanceof Error ? err.message : "Close channel failed"
2013
+ }));
2014
+ }
2015
+ },
2016
+ [state, backendClient, fundingVaultAddress]
2017
+ );
2018
+ const handleWithdrawCredits = (0, import_react.useCallback)(
2019
+ async (withdrawAmount) => {
2020
+ const currentState = state;
2021
+ if (!currentState.address || !currentState.buyerPubKey) return;
2022
+ if (!currentState.buyerPrvKey) {
2023
+ setState((prev) => ({
2024
+ ...prev,
2025
+ error: "Sign with your payer wallet in Buyer & Operator below to generate the buyer private key before withdrawing funds"
2026
+ }));
2027
+ return;
2028
+ }
2029
+ if (!fundingVaultAddress) {
2030
+ setState((prev) => ({
2031
+ ...prev,
2032
+ error: "Funding vault address is not configured"
2033
+ }));
2034
+ return;
2035
+ }
2036
+ if (!withdrawAmount.trim()) {
2037
+ setState((prev) => ({ ...prev, error: "Enter an amount to withdraw" }));
2038
+ return;
2039
+ }
2040
+ try {
2041
+ const amount = usdDisplayToMicro(withdrawAmount.trim());
2042
+ const withdrawable = BigInt(currentState.withdrawableUsd ?? "0");
2043
+ if (BigInt(amount) <= 0n) {
2044
+ setState((prev) => ({ ...prev, error: "Enter a valid USD amount" }));
2045
+ return;
2046
+ }
2047
+ if (BigInt(amount) > withdrawable) {
2048
+ setState((prev) => ({ ...prev, error: "Amount exceeds withdrawable principal" }));
2049
+ return;
2050
+ }
2051
+ const buyer = currentState.buyerPubKey;
2052
+ const payer = currentState.address;
2053
+ const timestamp = Math.floor(Date.now() / 1e3);
2054
+ const signature = await signWithdrawPrincipal({
2055
+ buyerPrivateKey: currentState.buyerPrvKey,
2056
+ fundingVaultAddress,
2057
+ buyer,
2058
+ amountMicro: BigInt(amount),
2059
+ recipient: payer,
2060
+ timestamp
2061
+ });
2062
+ await backendClient.withdrawCredits(buyer, {
2063
+ amount,
2064
+ recipient: payer,
2065
+ timestamp,
2066
+ signature
2067
+ });
2068
+ setState((prev) => ({ ...prev, error: null }));
2069
+ await handleRefresh();
2070
+ } catch (err) {
2071
+ setState((prev) => ({
2072
+ ...prev,
2073
+ error: err instanceof Error ? err.message : "Withdraw failed"
2074
+ }));
2075
+ }
2076
+ },
2077
+ [state, backendClient, fundingVaultAddress, handleRefresh]
2078
+ );
2079
+ const handleRetry = (0, import_react.useCallback)(async () => {
2080
+ if (configurationError) {
2081
+ setState((prev) => ({
2082
+ ...prev,
2083
+ status: "backend_unavailable",
2084
+ error: configurationError
2085
+ }));
2086
+ return;
2087
+ }
2088
+ await handleRefresh();
2089
+ }, [configurationError, handleRefresh]);
2090
+ const handleSetActiveTab = (0, import_react.useCallback)((tab) => {
2091
+ if (tab === "buy") {
2092
+ setState(
2093
+ (prev) => withDerivedStatus(prev, { activeTab: "buy", status: "purchase_setup", error: null }, true)
2094
+ );
2095
+ return;
2096
+ }
2097
+ setState((prev) => mergeStatePreservingNonBuyTab(prev, { activeTab: tab, error: null }));
2098
+ }, []);
2099
+ const handleStartPurchase = (0, import_react.useCallback)(() => {
2100
+ handleSetActiveTab("buy");
2101
+ }, [handleSetActiveTab]);
2102
+ const actions = (0, import_react.useMemo)(
2103
+ () => ({
2104
+ connect: handleConnect,
2105
+ switchChain: handleSwitchChain,
2106
+ generateBuyerKey: handleGenerateBuyerKey,
2107
+ signOperatorConsent: handleSignOperatorConsent,
2108
+ syncOperatorConsentFromChain: handleSyncOperatorConsentFromChain,
2109
+ buildQuote: handleBuildQuote,
2110
+ pay: handlePay,
2111
+ refresh: handleRefresh,
2112
+ verifyGoodId: handleVerifyGoodId,
2113
+ startPurchase: handleStartPurchase,
2114
+ setActiveTab: handleSetActiveTab,
2115
+ closeChannel: handleCloseChannel,
2116
+ withdrawCredits: handleWithdrawCredits,
2117
+ retry: handleRetry
2118
+ }),
2119
+ [
2120
+ handleConnect,
2121
+ handleSwitchChain,
2122
+ handleGenerateBuyerKey,
2123
+ handleSignOperatorConsent,
2124
+ handleSyncOperatorConsentFromChain,
2125
+ handleBuildQuote,
2126
+ handlePay,
2127
+ handleRefresh,
2128
+ handleVerifyGoodId,
2129
+ handleStartPurchase,
2130
+ handleSetActiveTab,
2131
+ handleCloseChannel,
2132
+ handleWithdrawCredits,
2133
+ handleRetry
2134
+ ]
2135
+ );
2136
+ return { state, actions };
2137
+ }
2138
+
2139
+ // src/AiCreditsWidget.tsx
2140
+ var import_react14 = __toESM(require("react"), 1);
2141
+ var import_core2 = require("@goodwidget/core");
2142
+ var import_ui16 = require("@goodwidget/ui");
2143
+
2144
+ // src/useAiCreditsHistory.ts
2145
+ var import_react2 = require("react");
2146
+ var HISTORY_PAGE_SIZE = 10;
2147
+ var HISTORY_LOOKBACK_DAYS = 90;
2148
+ var HISTORY_SOURCE_OPTIONS = [
2149
+ { id: "deposit", label: "Deposit", defaultChecked: true },
2150
+ { id: "streamUpdate", label: "Stream update", defaultChecked: true },
2151
+ { id: "streamRequest", label: "Stream credit", defaultChecked: true },
2152
+ { id: "streamCron", label: "Stream credit", defaultChecked: true }
2153
+ ];
2154
+ function formatHistoryDateInput(date) {
2155
+ return date.toISOString().slice(0, 10);
2156
+ }
2157
+ function getLast90DaysRange(now = /* @__PURE__ */ new Date()) {
2158
+ const to = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
2159
+ const from = new Date(to);
2160
+ from.setUTCDate(from.getUTCDate() - HISTORY_LOOKBACK_DAYS);
2161
+ return {
2162
+ from: formatHistoryDateInput(from),
2163
+ to: formatHistoryDateInput(to)
2164
+ };
2165
+ }
2166
+ function createDefaultSelectedSources() {
2167
+ return Object.fromEntries(
2168
+ HISTORY_SOURCE_OPTIONS.map((option) => [option.id, option.defaultChecked])
2169
+ );
2170
+ }
2171
+ function toIsoStartOfDay(dateValue) {
2172
+ if (!dateValue) return void 0;
2173
+ const parsed = Date.parse(`${dateValue}T00:00:00.000Z`);
2174
+ if (Number.isNaN(parsed)) return void 0;
2175
+ return new Date(parsed).toISOString();
2176
+ }
2177
+ function toIsoEndOfDay(dateValue) {
2178
+ if (!dateValue) return void 0;
2179
+ const parsed = Date.parse(`${dateValue}T23:59:59.999Z`);
2180
+ if (Number.isNaN(parsed)) return void 0;
2181
+ return new Date(parsed).toISOString();
2182
+ }
2183
+ function useAiCreditsHistory(options) {
2184
+ const { address, backendUrl, environment = "production", backendClient } = options;
2185
+ const defaultRange = (0, import_react2.useMemo)(() => getLast90DaysRange(), []);
2186
+ const [selectedSources, setSelectedSources] = (0, import_react2.useState)(createDefaultSelectedSources);
2187
+ const [statusFilter, setStatusFilter] = (0, import_react2.useState)("all");
2188
+ const [fromDate, setFromDate] = (0, import_react2.useState)(defaultRange.from);
2189
+ const [toDate, setToDate] = (0, import_react2.useState)(defaultRange.to);
2190
+ const [entries, setEntries] = (0, import_react2.useState)([]);
2191
+ const [offset, setOffset] = (0, import_react2.useState)(0);
2192
+ const [hasMore, setHasMore] = (0, import_react2.useState)(false);
2193
+ const [loading, setLoading] = (0, import_react2.useState)(false);
2194
+ const [loadingMore, setLoadingMore] = (0, import_react2.useState)(false);
2195
+ const [error, setError] = (0, import_react2.useState)(null);
2196
+ const activeSources = (0, import_react2.useMemo)(
2197
+ () => HISTORY_SOURCE_OPTIONS.map((option) => option.id).filter((id) => selectedSources[id]),
2198
+ [selectedSources]
2199
+ );
2200
+ const loadHistory = (0, import_react2.useCallback)(
2201
+ async (nextOffset, append) => {
2202
+ if (!address) {
2203
+ setEntries([]);
2204
+ setOffset(0);
2205
+ setHasMore(false);
2206
+ setError(null);
2207
+ setLoading(false);
2208
+ setLoadingMore(false);
2209
+ return;
2210
+ }
2211
+ if (activeSources.length === 0) {
2212
+ setEntries([]);
2213
+ setOffset(0);
2214
+ setHasMore(false);
2215
+ setError(null);
2216
+ setLoading(false);
2217
+ setLoadingMore(false);
2218
+ return;
2219
+ }
2220
+ if (append) setLoadingMore(true);
2221
+ else setLoading(true);
2222
+ setError(null);
2223
+ const client = backendClient ?? createBackendClient(backendUrl);
2224
+ const apiSource = activeSources.length === 1 ? activeSources[0] : void 0;
2225
+ const fundingStatus = statusFilter === "all" ? void 0 : statusFilter;
2226
+ try {
2227
+ const response = await client.getCreditHistory(address, {
2228
+ limit: HISTORY_PAGE_SIZE,
2229
+ offset: nextOffset,
2230
+ source: apiSource,
2231
+ fundingStatus,
2232
+ from: toIsoStartOfDay(fromDate),
2233
+ to: toIsoEndOfDay(toDate)
2234
+ });
2235
+ const pageItems = activeSources.length === 1 ? response.items : response.items.filter((entry) => selectedSources[entry.source]);
2236
+ setEntries((prev) => append ? [...prev, ...pageItems] : pageItems);
2237
+ setOffset(nextOffset);
2238
+ setHasMore(response.hasMore);
2239
+ } catch (err) {
2240
+ if (!append) setEntries([]);
2241
+ setHasMore(false);
2242
+ setError(err instanceof Error ? err.message : "Unable to load credit history");
2243
+ } finally {
2244
+ setLoading(false);
2245
+ setLoadingMore(false);
2246
+ }
2247
+ },
2248
+ [
2249
+ address,
2250
+ backendUrl,
2251
+ environment,
2252
+ backendClient,
2253
+ activeSources,
2254
+ statusFilter,
2255
+ fromDate,
2256
+ toDate,
2257
+ selectedSources
2258
+ ]
2259
+ );
2260
+ (0, import_react2.useEffect)(() => {
2261
+ void loadHistory(0, false);
2262
+ }, [loadHistory]);
2263
+ const setSourceChecked = (0, import_react2.useCallback)((source, checked) => {
2264
+ setSelectedSources((prev) => {
2265
+ if (source === "streamRequest" || source === "streamCron") {
2266
+ return { ...prev, streamRequest: checked, streamCron: checked };
2267
+ }
2268
+ return { ...prev, [source]: checked };
2269
+ });
2270
+ }, []);
2271
+ const reload = (0, import_react2.useCallback)(async () => {
2272
+ await loadHistory(0, false);
2273
+ }, [loadHistory]);
2274
+ const loadMore = (0, import_react2.useCallback)(async () => {
2275
+ await loadHistory(offset + HISTORY_PAGE_SIZE, true);
2276
+ }, [loadHistory, offset]);
2277
+ return {
2278
+ state: {
2279
+ selectedSources,
2280
+ statusFilter,
2281
+ fromDate,
2282
+ toDate,
2283
+ entries,
2284
+ offset,
2285
+ hasMore,
2286
+ loading,
2287
+ loadingMore,
2288
+ error,
2289
+ activeSources
2290
+ },
2291
+ actions: {
2292
+ setSourceChecked,
2293
+ setStatusFilter,
2294
+ setFromDate,
2295
+ setToDate,
2296
+ reload,
2297
+ loadMore
2298
+ }
2299
+ };
2300
+ }
2301
+
2302
+ // src/components/theme/cards.ts
2303
+ var import_ui = require("@goodwidget/ui");
2304
+ var AiCreditsStatusNotice = (0, import_ui.createComponent)(import_ui.Card, {
2305
+ name: "AiCreditsStatusNotice",
2306
+ extends: "Card",
2307
+ backgroundColor: "$backgroundHover",
2308
+ borderWidth: 1,
2309
+ padding: "$3"
2310
+ });
2311
+ var BonusBadgeFrame = (0, import_ui.createComponent)(import_ui.XStack, {
2312
+ name: "BonusBadgeFrame",
2313
+ borderRadius: "$full",
2314
+ paddingHorizontal: "$2",
2315
+ paddingVertical: 2,
2316
+ alignItems: "center",
2317
+ alignSelf: "flex-start",
2318
+ gap: "$1"
2319
+ });
2320
+
2321
+ // src/components/buy/AiCreditsHero.tsx
2322
+ var import_ui2 = require("@goodwidget/ui");
2323
+ var import_jsx_runtime = require("react/jsx-runtime");
2324
+ function AiCreditsHero({ gBalance, isGoodIdVerified }) {
2325
+ const showVerifiedBadge = gBalance !== null && Number.parseFloat(gBalance) > 0 && isGoodIdVerified;
2326
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.Card, { gap: "$4", backgroundColor: "$backgroundHover", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ui2.XStack, { justifyContent: "space-between", alignItems: "flex-start", gap: "$2", children: [
2327
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ui2.YStack, { gap: "$1", flexShrink: 1, children: [
2328
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.Text, { variant: "label", secondary: true, children: "Your G$ Balance" }),
2329
+ gBalance !== null ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.TokenAmount, { token: "G$", amount: gBalance, size: "xl" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.Spinner, { size: "sm" })
2330
+ ] }),
2331
+ showVerifiedBadge && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BonusBadgeFrame, { borderRadius: "$2", backgroundColor: "$backgroundPress", flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ui2.Text, { fontSize: "$2", fontWeight: "700", color: "$primary", children: "GoodID verified" }) })
2332
+ ] }) });
2333
+ }
2334
+
2335
+ // src/components/buy/BuyerKeyPanel.tsx
2336
+ var import_react4 = require("react");
2337
+ var import_ui4 = require("@goodwidget/ui");
2338
+
2339
+ // src/components/shared/styles.ts
2340
+ var monospaceSingleLineStyle = {
2341
+ fontFamily: "monospace",
2342
+ overflow: "hidden",
2343
+ textOverflow: "ellipsis",
2344
+ whiteSpace: "nowrap"
2345
+ };
2346
+ function truncateAddress(address) {
2347
+ return `${address.slice(0, 10)}\u2026${address.slice(-6)}`;
2348
+ }
2349
+ var compactButtonProps = {
2350
+ borderRadius: "$3",
2351
+ height: "$7",
2352
+ paddingHorizontal: "$3"
2353
+ };
2354
+
2355
+ // src/components/shared/useCopyFeedback.ts
2356
+ var import_react3 = require("react");
2357
+ var import_ui3 = require("@goodwidget/ui");
2358
+ function useCopyFeedback() {
2359
+ const [copied, setCopied] = (0, import_react3.useState)(false);
2360
+ const copy = async (text) => {
2361
+ if (!await (0, import_ui3.copyTextToClipboard)(text)) return;
2362
+ setCopied(true);
2363
+ setTimeout(() => setCopied(false), 2e3);
2364
+ };
2365
+ return { copied, copy };
2366
+ }
2367
+
2368
+ // src/components/buy/BuyerKeyPanel.tsx
2369
+ var import_jsx_runtime2 = require("react/jsx-runtime");
2370
+ function BuyerKeyPanel({
2371
+ buyerPubKey,
2372
+ buyerPrvKey,
2373
+ buyerPubKeySaved,
2374
+ onGenerate,
2375
+ onConfirm,
2376
+ embedded = false
2377
+ }) {
2378
+ const { copied: copiedAddress, copy: copyAddress } = useCopyFeedback();
2379
+ const { copied: copiedPrivate, copy: copyPrivate } = useCopyFeedback();
2380
+ const [isPrivateKeyVisible, setIsPrivateKeyVisible] = (0, import_react4.useState)(false);
2381
+ const [isGenerating, setIsGenerating] = (0, import_react4.useState)(false);
2382
+ async function handleGenerate() {
2383
+ setIsGenerating(true);
2384
+ try {
2385
+ await onGenerate();
2386
+ } finally {
2387
+ setIsGenerating(false);
2388
+ }
2389
+ }
2390
+ const Shell = embedded ? import_ui4.YStack : import_ui4.Card;
2391
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(Shell, { gap: "$3", children: [
2392
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.Heading, { level: 5, children: "Buyer Key" }),
2393
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.Text, { children: "Sign a message with your payer wallet to derive a deterministic AntSeed buyer key. Save the private key \u2014 you will need it to authenticate from your developer tools." }),
2394
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_ui4.YStack, { gap: "$3", children: [
2395
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2396
+ import_ui4.Button,
2397
+ {
2398
+ size: "sm",
2399
+ ...compactButtonProps,
2400
+ onPress: handleGenerate,
2401
+ disabled: isGenerating || Boolean(buyerPrvKey),
2402
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.ButtonText, { children: isGenerating ? "Waiting for signature\u2026" : "Sign & Generate Key" })
2403
+ }
2404
+ ),
2405
+ buyerPubKey && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_ui4.YStack, { gap: "$2", children: [
2406
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.Text, { variant: "label", secondary: true, children: "Address (registered on-chain)" }),
2407
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2408
+ import_ui4.XStack,
2409
+ {
2410
+ backgroundColor: "$backgroundMuted",
2411
+ borderRadius: "$2",
2412
+ padding: "$3",
2413
+ justifyContent: "space-between",
2414
+ alignItems: "center",
2415
+ children: [
2416
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.Text, { fontSize: "$2", style: monospaceSingleLineStyle, flex: 1, numberOfLines: 1, children: buyerPubKey }),
2417
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.Button, { size: "sm", variant: "ghost", iconSize: "sm", onPress: () => void copyAddress(buyerPubKey), children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2418
+ import_ui4.Icon,
2419
+ {
2420
+ name: copiedAddress ? "check" : "copy",
2421
+ size: "xs",
2422
+ color: copiedAddress ? "success" : "text"
2423
+ }
2424
+ ) })
2425
+ ]
2426
+ }
2427
+ ),
2428
+ buyerPrvKey && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
2429
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_ui4.XStack, { justifyContent: "space-between", alignItems: "center", children: [
2430
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.Text, { variant: "label", secondary: true, children: "Private Key \u2014 save this securely" }),
2431
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2432
+ import_ui4.Button,
2433
+ {
2434
+ variant: "text",
2435
+ size: "sm",
2436
+ onPress: () => {
2437
+ setIsPrivateKeyVisible((prev) => !prev);
2438
+ },
2439
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.ButtonText, { children: isPrivateKeyVisible ? "Hide" : "Reveal" })
2440
+ }
2441
+ )
2442
+ ] }),
2443
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AiCreditsStatusNotice, { borderColor: "$warning", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.Text, { color: "$warning", fontSize: "$2", children: "\u26A0 Revealing your private key can expose your account. Never share it \u2014 store it in a secure place." }) }),
2444
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2445
+ import_ui4.XStack,
2446
+ {
2447
+ backgroundColor: "$backgroundMuted",
2448
+ borderRadius: "$2",
2449
+ padding: "$3",
2450
+ justifyContent: "space-between",
2451
+ alignItems: "center",
2452
+ children: [
2453
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.Text, { fontSize: "$2", style: monospaceSingleLineStyle, flex: 1, numberOfLines: 1, children: isPrivateKeyVisible ? buyerPrvKey : "\u2022".repeat(Math.min(48, buyerPrvKey.length)) }),
2454
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2455
+ import_ui4.Button,
2456
+ {
2457
+ size: "sm",
2458
+ variant: "ghost",
2459
+ iconSize: "sm",
2460
+ onPress: () => void copyPrivate(buyerPrvKey),
2461
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2462
+ import_ui4.Icon,
2463
+ {
2464
+ name: copiedPrivate ? "check" : "copy",
2465
+ size: "xs",
2466
+ color: copiedPrivate ? "success" : "text"
2467
+ }
2468
+ )
2469
+ }
2470
+ )
2471
+ ]
2472
+ }
2473
+ )
2474
+ ] }),
2475
+ buyerPrvKey && !buyerPubKeySaved && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.Button, { size: "sm", ...compactButtonProps, onPress: onConfirm, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.ButtonText, { children: "I've Saved My Private Key" }) }),
2476
+ buyerPubKeySaved && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_ui4.XStack, { gap: "$2", alignItems: "center", children: [
2477
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.Icon, { name: "check", size: "sm", color: "success" }),
2478
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_ui4.Text, { color: "$success", fontSize: "$2", children: "Key confirmed \u2014 you can proceed" })
2479
+ ] })
2480
+ ] })
2481
+ ] })
2482
+ ] });
2483
+ }
2484
+
2485
+ // src/components/buy/OperatorConsentStep.tsx
2486
+ var import_react5 = require("react");
2487
+ var import_ui5 = require("@goodwidget/ui");
2488
+ var import_jsx_runtime3 = require("react/jsx-runtime");
2489
+ function OperatorConsentStep({
2490
+ buyerPubKey,
2491
+ buyerPrvKey,
2492
+ operatorConsented,
2493
+ onSign,
2494
+ embedded = false
2495
+ }) {
2496
+ const [isSigning, setIsSigning] = (0, import_react5.useState)(false);
2497
+ const canSign = Boolean(buyerPubKey && buyerPrvKey);
2498
+ const Shell = embedded ? import_ui5.YStack : import_ui5.Card;
2499
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(Shell, { gap: "$3", ...!embedded ? { backgroundColor: "$backgroundHover" } : {}, children: [
2500
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_ui5.Heading, { level: 5, children: "Authorize AntSeed Operator" }),
2501
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_ui5.Text, { fontSize: "$2", lineHeight: "$3", children: "Your buyer key signs an EIP-712 SetOperator message. The backend submits it to AntseedDeposits so the funding vault can act as your operator. No gas is required from you." }),
2502
+ buyerPubKey && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_ui5.Text, { fontSize: "$2", lineHeight: "$2", children: [
2503
+ "Buyer address:",
2504
+ " ",
2505
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_ui5.Text, { fontFamily: "$mono", fontSize: "$2", children: truncateAddress(buyerPubKey) })
2506
+ ] }),
2507
+ operatorConsented ? /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_ui5.XStack, { gap: "$2", alignItems: "center", children: [
2508
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_ui5.Icon, { name: "check", size: "sm", color: "success" }),
2509
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_ui5.Text, { color: "$success", children: "Operator consent accepted \u2014 ready to pay" })
2510
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2511
+ import_ui5.Button,
2512
+ {
2513
+ size: "sm",
2514
+ ...compactButtonProps,
2515
+ onPress: () => {
2516
+ setIsSigning(true);
2517
+ void onSign().finally(() => {
2518
+ setIsSigning(false);
2519
+ });
2520
+ },
2521
+ disabled: !canSign || isSigning,
2522
+ children: isSigning ? /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_ui5.XStack, { gap: "$2", alignItems: "center", children: [
2523
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_ui5.ButtonText, { children: "Signing\u2026" }),
2524
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_ui5.Spinner, { size: "sm" })
2525
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_ui5.ButtonText, { children: "Sign Operator Consent" })
2526
+ }
2527
+ )
2528
+ ] });
2529
+ }
2530
+
2531
+ // src/components/buy/AmountPicker.tsx
2532
+ var import_react7 = require("react");
2533
+ var import_ui7 = require("@goodwidget/ui");
2534
+
2535
+ // src/components/shared/tooltips.tsx
2536
+ var import_react6 = require("react");
2537
+ var import_ui6 = require("@goodwidget/ui");
2538
+ var import_jsx_runtime4 = require("react/jsx-runtime");
2539
+ function InfoTooltip({ message }) {
2540
+ const [open, setOpen] = (0, import_react6.useState)(false);
2541
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
2542
+ import_ui6.XStack,
2543
+ {
2544
+ position: "relative",
2545
+ alignItems: "center",
2546
+ cursor: "help",
2547
+ tabIndex: 0,
2548
+ accessibilityLabel: message,
2549
+ onMouseEnter: () => setOpen(true),
2550
+ onMouseLeave: () => setOpen(false),
2551
+ onFocus: () => setOpen(true),
2552
+ onBlur: () => setOpen(false),
2553
+ children: [
2554
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_ui6.Icon, { name: "info", size: "xs", color: "primary" }),
2555
+ open && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(TooltipBubble, { message })
2556
+ ]
2557
+ }
2558
+ );
2559
+ }
2560
+ function TooltipBubble({ message }) {
2561
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
2562
+ import_ui6.YStack,
2563
+ {
2564
+ position: "absolute",
2565
+ bottom: "100%",
2566
+ right: 0,
2567
+ marginBottom: "$1",
2568
+ backgroundColor: "$background",
2569
+ borderWidth: 1,
2570
+ borderColor: "$borderColor",
2571
+ borderRadius: "$2",
2572
+ padding: "$2",
2573
+ maxWidth: 280,
2574
+ zIndex: 100,
2575
+ pointerEvents: "none",
2576
+ children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_ui6.Text, { fontSize: "$1", lineHeight: "$2", color: "$color", children: message })
2577
+ }
2578
+ );
2579
+ }
2580
+ function HoverTooltip({
2581
+ message,
2582
+ children,
2583
+ fullWidth = false
2584
+ }) {
2585
+ const [open, setOpen] = (0, import_react6.useState)(false);
2586
+ if (!message) return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_jsx_runtime4.Fragment, { children });
2587
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
2588
+ import_ui6.XStack,
2589
+ {
2590
+ position: "relative",
2591
+ flexShrink: 0,
2592
+ width: fullWidth ? "100%" : void 0,
2593
+ onMouseEnter: () => setOpen(true),
2594
+ onMouseLeave: () => setOpen(false),
2595
+ onFocus: () => setOpen(true),
2596
+ onBlur: () => setOpen(false),
2597
+ children: [
2598
+ children,
2599
+ open && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(TooltipBubble, { message })
2600
+ ]
2601
+ }
2602
+ );
2603
+ }
2604
+
2605
+ // src/components/buy/AmountPicker.tsx
2606
+ var import_jsx_runtime5 = require("react/jsx-runtime");
2607
+ var DEFAULT_DEPOSIT_AMOUNT = "1";
2608
+ var DEFAULT_STREAM_AMOUNT = "0";
2609
+ function resolveInitialStreamAmount(monthlyStreamG) {
2610
+ if (!monthlyStreamG) return DEFAULT_STREAM_AMOUNT;
2611
+ return parseGAmount(monthlyStreamG) > 0 ? monthlyStreamG : DEFAULT_STREAM_AMOUNT;
2612
+ }
2613
+ function BonusLabel({ label, active }) {
2614
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2615
+ BonusBadgeFrame,
2616
+ {
2617
+ backgroundColor: active ? "$successMuted" : "$warningMuted",
2618
+ borderWidth: 1,
2619
+ borderColor: active ? "$success" : "$warning",
2620
+ children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Text, { fontSize: "$1", fontWeight: "700", lineHeight: 16, color: active ? "$success" : "$warning", children: label })
2621
+ }
2622
+ );
2623
+ }
2624
+ function BonusSummaryValue({
2625
+ quote,
2626
+ gdUsdPerToken,
2627
+ isGoodIdVerified,
2628
+ depositBonusPercent,
2629
+ streamBonusPercent,
2630
+ onVerifyGoodId,
2631
+ isVerifyingGoodId
2632
+ }) {
2633
+ if (!isGoodIdVerified) {
2634
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.XStack, { gap: "$1.5", alignItems: "center", justifyContent: "flex-end", flex: 1, flexShrink: 1, minWidth: 0, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2635
+ import_ui7.Button,
2636
+ {
2637
+ variant: "text",
2638
+ size: "sm",
2639
+ disabled: isVerifyingGoodId,
2640
+ onPress: () => {
2641
+ void onVerifyGoodId();
2642
+ },
2643
+ children: isVerifyingGoodId ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Spinner, { size: "sm" }) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.ButtonText, { fontWeight: "600", children: "Verify to get Bonuses" })
2644
+ }
2645
+ ) });
2646
+ }
2647
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Text, { fontSize: "$2", fontWeight: "700", color: "$success", children: formatMinUsdDisplay(
2648
+ quoteDepositBonusUsd(quote, gdUsdPerToken, isGoodIdVerified, depositBonusPercent)
2649
+ ) + " + " + formatMinUsdDisplay(
2650
+ quoteStreamBonusUsd(quote, gdUsdPerToken, isGoodIdVerified, streamBonusPercent)
2651
+ ) + "/month" });
2652
+ }
2653
+ function AmountPicker({
2654
+ status,
2655
+ gBalance,
2656
+ minDepositUsd,
2657
+ minStreamUsd,
2658
+ monthlyStreamG,
2659
+ gdUsdPerToken,
2660
+ isGoodIdVerified,
2661
+ depositBonusPercent,
2662
+ streamBonusPercent,
2663
+ isPayPending,
2664
+ buildQuote,
2665
+ onPay,
2666
+ onVerifyGoodId,
2667
+ embedded = false
2668
+ }) {
2669
+ const streamSeed = (0, import_react7.useMemo)(() => resolveInitialStreamAmount(monthlyStreamG), [monthlyStreamG]);
2670
+ const [depositAmount, setDepositAmount] = (0, import_react7.useState)(DEFAULT_DEPOSIT_AMOUNT);
2671
+ const [streamAmount, setStreamAmount] = (0, import_react7.useState)(streamSeed);
2672
+ const [quote, setQuote] = (0, import_react7.useState)(null);
2673
+ const [quotePending, setQuotePending] = (0, import_react7.useState)(false);
2674
+ const [isVerifyingGoodId, setIsVerifyingGoodId] = (0, import_react7.useState)(false);
2675
+ const isStreamUpdateFlow = parseGAmount(streamSeed) > 0;
2676
+ (0, import_react7.useEffect)(() => {
2677
+ setStreamAmount(streamSeed);
2678
+ }, [streamSeed]);
2679
+ (0, import_react7.useEffect)(() => {
2680
+ let cancelled = false;
2681
+ setQuotePending(true);
2682
+ void buildQuote(depositAmount, streamAmount).then((nextQuote) => {
2683
+ if (!cancelled) setQuote(nextQuote);
2684
+ }).catch(() => {
2685
+ if (!cancelled) setQuote(null);
2686
+ }).finally(() => {
2687
+ if (!cancelled) setQuotePending(false);
2688
+ });
2689
+ return () => {
2690
+ cancelled = true;
2691
+ };
2692
+ }, [depositAmount, streamAmount, buildQuote]);
2693
+ const depositG = parseGAmount(depositAmount);
2694
+ const streamG = parseGAmount(streamAmount);
2695
+ const depositBonusLabel = isGoodIdVerified ? `+${depositBonusPercent}% bonus` : `Verify for +${depositBonusPercent}%`;
2696
+ const streamBonusLabel = isGoodIdVerified ? `+${streamBonusPercent}% bonus` : `Verify for +${streamBonusPercent}%`;
2697
+ const paymentValidation = (0, import_react7.useMemo)(
2698
+ () => getPaymentAmountValidation({
2699
+ depositAmount,
2700
+ streamAmount,
2701
+ currentStreamAmount: monthlyStreamG,
2702
+ minDepositUsd,
2703
+ minStreamUsd,
2704
+ quote,
2705
+ gdUsdPerToken,
2706
+ gBalance
2707
+ }),
2708
+ [depositAmount, streamAmount, monthlyStreamG, minDepositUsd, minStreamUsd, quote, gdUsdPerToken, gBalance]
2709
+ );
2710
+ const minsLoaded = minStreamUsd !== null;
2711
+ const canPay = status === "quote_ready" && minsLoaded && paymentValidation.hasPaymentAction && paymentValidation.vaultMinimumsMet && !paymentValidation.overBalance && !quotePending && quote !== null;
2712
+ const payDisabledMessage = getPayDisabledMessage({
2713
+ canPay,
2714
+ minsLoaded,
2715
+ status,
2716
+ minDepositUsd,
2717
+ minStreamUsd,
2718
+ validation: paymentValidation
2719
+ });
2720
+ const { depositBelowMin, streamBelowMin, overBalance } = paymentValidation;
2721
+ const depositMinUsdLabel = minDepositUsd !== null ? `Minimum ${formatMinUsdDisplay(minDepositUsd)} for your first deposit` : "One-time deposit (no minimum after first deposit)";
2722
+ const streamMinUsdLabel = isStreamUpdateFlow ? `Current stream \xB7 min ${minStreamUsd !== null ? formatMinUsdDisplay(minStreamUsd) : "\u2026"}/month` : minStreamUsd !== null ? `Minimum ${formatMinUsdDisplay(minStreamUsd)}/month` : "Loading minimum\u2026";
2723
+ const depositPlaceholder = minStreamUsd === null ? "Loading minimum\u2026" : minDepositUsd !== null ? `Min ${formatMinUsdDisplay(minDepositUsd)}` : "0 G$ (optional)";
2724
+ const streamPlaceholder = minStreamUsd === null ? "Loading minimum\u2026" : `Min ${formatMinUsdDisplay(minStreamUsd)}/mo`;
2725
+ const effectiveDepositBonusPercent = getDepositBonusPercent(isGoodIdVerified, depositBonusPercent);
2726
+ const effectiveStreamBonusPercent = getStreamBonusPercent(isGoodIdVerified, streamBonusPercent);
2727
+ const depositEstUsd = quote && gdUsdPerToken !== null && depositG > 0 ? formatUsdWithBonus(
2728
+ quoteDepositPrincipalUsd(quote, gdUsdPerToken),
2729
+ effectiveDepositBonusPercent
2730
+ ) : null;
2731
+ const streamEstUsd = quote && gdUsdPerToken !== null && streamG > 0 ? formatUsdWithBonus(
2732
+ quoteStreamPrincipalUsd(quote, gdUsdPerToken),
2733
+ effectiveStreamBonusPercent
2734
+ ) : null;
2735
+ const usd1ToGLabel = gdUsdPerToken !== null ? formatUsd1ToG(gdUsdPerToken) : null;
2736
+ const Shell = embedded ? import_ui7.YStack : import_ui7.Card;
2737
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(Shell, { gap: "$3", children: [
2738
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.XStack, { justifyContent: "space-between", alignItems: "center", gap: "$2", children: [
2739
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Heading, { level: 5, children: "Buy Credits" }),
2740
+ usd1ToGLabel && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.Text, { fontSize: "$2", secondary: true, flexShrink: 1, textAlign: "right", children: [
2741
+ "US$1 \u2248 ",
2742
+ usd1ToGLabel,
2743
+ " G$"
2744
+ ] })
2745
+ ] }),
2746
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.XStack, { justifyContent: "space-between", alignItems: "center", children: [
2747
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Text, { variant: "label", secondary: true, children: "Your G$ Balance" }),
2748
+ gBalance !== null ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.TokenAmount, { token: "G$", amount: gBalance, size: "sm" }) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Spinner, { size: "sm" })
2749
+ ] }),
2750
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.YStack, { gap: "$1", children: [
2751
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.XStack, { justifyContent: "space-between", alignItems: "center", children: [
2752
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Text, { variant: "label", children: "One-time Deposit (G$)" }),
2753
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(BonusLabel, { label: depositBonusLabel, active: isGoodIdVerified })
2754
+ ] }),
2755
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2756
+ import_ui7.Input,
2757
+ {
2758
+ value: depositAmount,
2759
+ onChangeText: setDepositAmount,
2760
+ placeholder: depositPlaceholder,
2761
+ error: depositBelowMin
2762
+ }
2763
+ ),
2764
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.XStack, { justifyContent: "space-between", alignItems: "center", gap: "$2", children: [
2765
+ depositG > 0 && depositEstUsd ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.Text, { fontSize: "$1", secondary: true, children: [
2766
+ "\u2248 ",
2767
+ depositEstUsd
2768
+ ] }) : depositG > 0 && quotePending ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Spinner, { size: "sm" }) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.YStack, {}),
2769
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Text, { fontSize: "$1", secondary: true, textAlign: "right", flexShrink: 0, children: depositMinUsdLabel })
2770
+ ] })
2771
+ ] }),
2772
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.YStack, { gap: "$1", children: [
2773
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.XStack, { justifyContent: "space-between", alignItems: "center", children: [
2774
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Text, { variant: "label", children: isStreamUpdateFlow ? "Update Monthly Stream (G$)" : "Monthly Stream (G$)" }),
2775
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(BonusLabel, { label: streamBonusLabel, active: isGoodIdVerified })
2776
+ ] }),
2777
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2778
+ import_ui7.Input,
2779
+ {
2780
+ value: streamAmount,
2781
+ onChangeText: setStreamAmount,
2782
+ placeholder: streamPlaceholder,
2783
+ error: streamBelowMin
2784
+ }
2785
+ ),
2786
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.XStack, { justifyContent: "space-between", alignItems: "center", gap: "$2", children: [
2787
+ streamG > 0 && streamEstUsd ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.Text, { fontSize: "$1", secondary: true, children: [
2788
+ "\u2248 ",
2789
+ streamEstUsd,
2790
+ "/month"
2791
+ ] }) : streamG > 0 && quotePending ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Spinner, { size: "sm" }) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.YStack, {}),
2792
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Text, { fontSize: "$1", secondary: true, textAlign: "right", flexShrink: 0, children: streamMinUsdLabel })
2793
+ ] })
2794
+ ] }),
2795
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Separator, {}),
2796
+ quote && gdUsdPerToken !== null && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_jsx_runtime5.Fragment, { children: [
2797
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.XStack, { justifyContent: "space-between", alignItems: "center", children: [
2798
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Text, { variant: "label", children: "Est. credits" }),
2799
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Text, { fontSize: "$2", color: "$primary", fontWeight: "700", children: formatMinUsdDisplay(quoteDepositPrincipalUsd(quote, gdUsdPerToken)) + " + " + formatMinUsdDisplay(quoteStreamPrincipalUsd(quote, gdUsdPerToken)) + "/month" })
2800
+ ] }),
2801
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.XStack, { justifyContent: "space-between", alignItems: "center", gap: "$2", children: [
2802
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Text, { fontSize: "$1", flexShrink: 0, children: "Bonuses" }),
2803
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2804
+ BonusSummaryValue,
2805
+ {
2806
+ quote,
2807
+ gdUsdPerToken,
2808
+ isGoodIdVerified,
2809
+ depositBonusPercent,
2810
+ streamBonusPercent,
2811
+ isVerifyingGoodId,
2812
+ onVerifyGoodId: async () => {
2813
+ setIsVerifyingGoodId(true);
2814
+ try {
2815
+ await onVerifyGoodId();
2816
+ } finally {
2817
+ setIsVerifyingGoodId(false);
2818
+ }
2819
+ }
2820
+ }
2821
+ )
2822
+ ] })
2823
+ ] }),
2824
+ overBalance && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(AiCreditsStatusNotice, { borderColor: "$warning", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Text, { color: "$warning", fontSize: "$2", children: "Deposit amount exceeds your G$ balance. Reduce the deposit amount." }) }),
2825
+ depositBelowMin && minDepositUsd && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(AiCreditsStatusNotice, { borderColor: "$warning", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.Text, { color: "$warning", fontSize: "$2", children: [
2826
+ "First deposit must be at least ",
2827
+ formatMinUsdDisplay(minDepositUsd),
2828
+ "."
2829
+ ] }) }),
2830
+ streamBelowMin && minStreamUsd && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(AiCreditsStatusNotice, { borderColor: "$warning", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.Text, { color: "$warning", fontSize: "$2", children: [
2831
+ "Monthly stream must be at least ",
2832
+ formatMinUsdDisplay(minStreamUsd),
2833
+ "."
2834
+ ] }) }),
2835
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(HoverTooltip, { message: payDisabledMessage, fullWidth: true, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2836
+ import_ui7.Button,
2837
+ {
2838
+ fullWidth: true,
2839
+ size: "sm",
2840
+ ...compactButtonProps,
2841
+ disabled: !canPay || isPayPending,
2842
+ onPress: () => {
2843
+ if (quote) onPay(quote);
2844
+ },
2845
+ children: isPayPending ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_ui7.XStack, { gap: "$2", alignItems: "center", children: [
2846
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.ButtonText, { children: "Buy AI Credits" }),
2847
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.Spinner, { size: "sm" })
2848
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_ui7.ButtonText, { children: "Buy AI Credits" })
2849
+ }
2850
+ ) })
2851
+ ] });
2852
+ }
2853
+
2854
+ // src/components/buy/BuyCreditsFaq.tsx
2855
+ var import_react8 = require("react");
2856
+ var import_ui8 = require("@goodwidget/ui");
2857
+ var import_jsx_runtime6 = require("react/jsx-runtime");
2858
+ var FAQ_ITEMS = [
2859
+ {
2860
+ id: "what-are-credits",
2861
+ question: "What are AI credits?",
2862
+ answer: "AI credits pay for AntSeed-compatible coding tools. GoodDollar only supports purchasing AntSeed AI credits. You buy them with G$ on Celo; AI credits (USD) settle on Base and appear in your Manage tab balance."
2863
+ },
2864
+ {
2865
+ id: "how-to-buy",
2866
+ question: "How do I buy credits?",
2867
+ answer: "Complete the Buy Credits steps: generate a buyer key, sign operator consent, then enter a one-time G$ deposit and/or a monthly G$ stream and confirm one Celo transaction (approve, deposit, and stream changes are batched when needed)."
2868
+ },
2869
+ {
2870
+ id: "deposit-vs-stream",
2871
+ question: "What is a one-time deposit vs a monthly stream?",
2872
+ answer: "A one-time deposit converts G$ into credits right away. A monthly stream sets a G$/month flow rate on Celo; credits are added in real time as G$ streams in, not as a single monthly lump."
2873
+ },
2874
+ {
2875
+ id: "minimums",
2876
+ question: "What are the minimum amounts?",
2877
+ answer: "Your first one-time deposit must be at least US$1.00. If you set a monthly stream, it must be at least US$1.00/month. After your first deposit, there is no minimum for additional one-time deposits.\n\nTo open a new channel to a new provider, you need more than 1 USDC in available credits."
2878
+ },
2879
+ {
2880
+ id: "goodid-bonus",
2881
+ question: "How do GoodID bonuses work?",
2882
+ answer: "With a verified GoodID you receive bonus credits on one-time deposits and monthly streams. The current bonus rates are shown in the Buy Credits form. Without GoodID verification, bonuses do not apply."
2883
+ },
2884
+ {
2885
+ id: "buyer-key",
2886
+ question: "What is the buyer key?",
2887
+ answer: "Your payer wallet pays G$ on Celo. The buyer key is a separate key derived from a payer signature; it manages your AI credits on Base. Save the buyer private key from this session for AI API setup and Manage actions like withdraw."
2888
+ },
2889
+ {
2890
+ id: "operator-consent",
2891
+ question: "Why do I authorize the Gooddollar operator?",
2892
+ answer: "Payer is the wallet that pays G$ on Celo. Buyer is a separate key derived from a payer signature; it owns your AI credit account on Base.\n\nOperator consent is a one-time sign-off so the GoodDollar operator can act as your operator on Base. After you pay G$ on Celo, the operator can fund your credits and handle Base-side actions \u2014 including moving credit funds \u2014 without you paying Base gas. It cannot access your payer wallet or G$ on Celo. Because the operator can act on your Base credit account, you are trusting GoodDollar with that role. You can also withdraw unused principal yourself with your buyer private key."
2893
+ },
2894
+ {
2895
+ id: "when-credits-arrive",
2896
+ question: "When do credits arrive?",
2897
+ answer: "After your Celo payment confirms, credits are funded on Base. Funding usually completes within a short time; check the Manage tab for your updated balance."
2898
+ },
2899
+ {
2900
+ id: "withdraw",
2901
+ question: "What funds can I withdraw?",
2902
+ answer: "You can withdraw unused principal up to the Withdrawable amount shown in Manage. Bonus credits from GoodID are not withdrawable and stay for AI usage only.\n\nWithdrawals are signed with your buyer private key and settled on Base as USD to your payer wallet address \u2014 the same wallet that pays G$ on Celo. Your total credit balance will be higher than the withdrawable amount when bonuses are included."
2903
+ },
2904
+ {
2905
+ id: "api-setup",
2906
+ question: "What is API setup?",
2907
+ answer: "After you have credits, open Manage \u2192 API Setup and copy the commands into your terminal. ANTSEED_IDENTITY_HEX is your buyer private key. it links your purchases to the credit balance your AI tools should use."
2908
+ },
2909
+ {
2910
+ id: "support",
2911
+ question: "Who do I contact for support?",
2912
+ answer: "GoodDollar only supports purchasing AntSeed AI credits through this widget. For post-purchase issues \u2014 including credit usage, channels, providers, or AntSeed tooling \u2014 contact the AntSeed support team on Telegram: https://t.me/antseed"
2913
+ }
2914
+ ];
2915
+ function FaqItem({
2916
+ question,
2917
+ answer,
2918
+ expanded,
2919
+ onToggle
2920
+ }) {
2921
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_ui8.YStack, { gap: "$1", children: [
2922
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
2923
+ import_ui8.XStack,
2924
+ {
2925
+ justifyContent: "space-between",
2926
+ alignItems: "center",
2927
+ gap: "$2",
2928
+ onPress: onToggle,
2929
+ cursor: "pointer",
2930
+ children: [
2931
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_ui8.Text, { fontSize: "$2", fontWeight: "600", flex: 1, children: question }),
2932
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_ui8.Icon, { name: expanded ? "chevron-up" : "chevron-down", size: "xs", color: "muted" })
2933
+ ]
2934
+ }
2935
+ ),
2936
+ expanded && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_ui8.YStack, { gap: "$2", children: answer.split("\n\n").map((paragraph, index) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_ui8.Text, { fontSize: "$2", secondary: true, lineHeight: "$3", children: paragraph }, index)) })
2937
+ ] });
2938
+ }
2939
+ function BuyCreditsFaq() {
2940
+ const [expandedId, setExpandedId] = (0, import_react8.useState)(null);
2941
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_ui8.Card, { gap: "$3", children: [
2942
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_ui8.Heading, { level: 6, children: "FAQ" }),
2943
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_ui8.YStack, { gap: "$3", children: FAQ_ITEMS.map((item, index) => /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_ui8.YStack, { gap: "$3", children: [
2944
+ index > 0 && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_ui8.Separator, {}),
2945
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
2946
+ FaqItem,
2947
+ {
2948
+ question: item.question,
2949
+ answer: item.answer,
2950
+ expanded: expandedId === item.id,
2951
+ onToggle: () => {
2952
+ setExpandedId((current) => current === item.id ? null : item.id);
2953
+ }
2954
+ }
2955
+ )
2956
+ ] }, item.id)) })
2957
+ ] });
2958
+ }
2959
+
2960
+ // src/components/manage/CreditsManagementCard.tsx
2961
+ var import_react9 = require("react");
2962
+ var import_ui9 = require("@goodwidget/ui");
2963
+
2964
+ // src/components/shared/constants.ts
2965
+ var BUYER_KEY_REQUIRED_CLOSE_TOOLTIP = "Sign with your payer wallet in Buyer & Operator below to generate the buyer private key before closing a channel.";
2966
+ var BUYER_KEY_REQUIRED_WITHDRAW_TOOLTIP = "Sign with your payer wallet in Buyer & Operator below to generate the buyer private key before withdrawing funds.";
2967
+ var WITHDRAW_TOOLTIP = "Withdraws principal to your payer wallet (not bonus). Requires the buyer private key from this session.";
2968
+
2969
+ // src/components/manage/CreditsManagementCard.tsx
2970
+ var import_jsx_runtime7 = require("react/jsx-runtime");
2971
+ function StatCell({ label, children }) {
2972
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
2973
+ import_ui9.YStack,
2974
+ {
2975
+ flex: 1,
2976
+ minWidth: "45%",
2977
+ gap: "$1",
2978
+ backgroundColor: "$backgroundHover",
2979
+ borderRadius: "$2",
2980
+ padding: "$2",
2981
+ $gtSm: {
2982
+ minWidth: "28%"
2983
+ },
2984
+ children: [
2985
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.Text, { fontSize: "$1", secondary: true, children: label }),
2986
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.YStack, { justifyContent: "center", children })
2987
+ ]
2988
+ }
2989
+ );
2990
+ }
2991
+ function StatValueText({
2992
+ children,
2993
+ color
2994
+ }) {
2995
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.Text, { fontSize: "$2", fontWeight: "700", color, children });
2996
+ }
2997
+ function formatCompactAmount(amount) {
2998
+ const value = Number.parseFloat(amount);
2999
+ if (!Number.isFinite(value) || value < 0) return "0";
3000
+ return new Intl.NumberFormat("en-US", {
3001
+ notation: "compact",
3002
+ maximumFractionDigits: 2
3003
+ }).format(value);
3004
+ }
3005
+ function formatExactGAmount(amount) {
3006
+ const value = Number.parseFloat(amount);
3007
+ if (!Number.isFinite(value) || value < 0) return "0 G$";
3008
+ return `${new Intl.NumberFormat("en-US", {
3009
+ minimumFractionDigits: 2,
3010
+ maximumFractionDigits: 2
3011
+ }).format(value)} G$`;
3012
+ }
3013
+ function CompactGStatValue({ amount }) {
3014
+ const [open, setOpen] = (0, import_react9.useState)(false);
3015
+ const value = Number.parseFloat(amount);
3016
+ const compact = formatCompactAmount(amount);
3017
+ const exact = formatExactGAmount(amount);
3018
+ const needsExact = Number.isFinite(value) && value >= 1e3;
3019
+ if (!needsExact) {
3020
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(StatValueText, { children: compact });
3021
+ }
3022
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
3023
+ import_ui9.XStack,
3024
+ {
3025
+ position: "relative",
3026
+ cursor: "help",
3027
+ alignItems: "center",
3028
+ tabIndex: 0,
3029
+ accessibilityLabel: exact,
3030
+ onMouseEnter: () => setOpen(true),
3031
+ onMouseLeave: () => setOpen(false),
3032
+ onFocus: () => setOpen(true),
3033
+ onBlur: () => setOpen(false),
3034
+ onPress: () => setOpen((prev) => !prev),
3035
+ children: [
3036
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(StatValueText, { children: compact }),
3037
+ open && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
3038
+ import_ui9.YStack,
3039
+ {
3040
+ position: "absolute",
3041
+ bottom: "100%",
3042
+ left: 0,
3043
+ marginBottom: "$1",
3044
+ backgroundColor: "$background",
3045
+ borderWidth: 1,
3046
+ borderColor: "$borderColor",
3047
+ borderRadius: "$2",
3048
+ padding: "$2",
3049
+ zIndex: 100,
3050
+ pointerEvents: "none",
3051
+ children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.Text, { fontSize: "$1", lineHeight: "$2", color: "$color", whiteSpace: "nowrap", children: exact })
3052
+ }
3053
+ )
3054
+ ]
3055
+ }
3056
+ );
3057
+ }
3058
+ function formatUsdAmount(usdMicro) {
3059
+ const value = Number.parseFloat(formatUsdMicro(usdMicro));
3060
+ if (!Number.isFinite(value) || value < 0) return "0.0000";
3061
+ return new Intl.NumberFormat("en-US", {
3062
+ minimumFractionDigits: 4,
3063
+ maximumFractionDigits: 4
3064
+ }).format(value);
3065
+ }
3066
+ function CreditsManagementCard({ state, actions }) {
3067
+ const [isClosing, setIsClosing] = (0, import_react9.useState)(false);
3068
+ const [isWithdrawing, setIsWithdrawing] = (0, import_react9.useState)(false);
3069
+ const [channelId, setChannelId] = (0, import_react9.useState)("");
3070
+ const [withdrawAmount, setWithdrawAmount] = (0, import_react9.useState)("");
3071
+ const {
3072
+ totalCreditUsd,
3073
+ totalGdDepositedG,
3074
+ monthlyStreamG,
3075
+ gdUsdPerToken,
3076
+ isGoodIdVerified,
3077
+ withdrawableUsd,
3078
+ buyerPrvKey
3079
+ } = state;
3080
+ const monthlyStreamUsdDisplay = (0, import_react9.useMemo)(() => {
3081
+ if (!monthlyStreamG || !gdUsdPerToken) return null;
3082
+ if (Number.parseFloat(monthlyStreamG) <= 0) return null;
3083
+ const quote = { depositAmountG: "0", streamAmountG: monthlyStreamG };
3084
+ const usdMicro = quoteTotalUsdMicro(quote, gdUsdPerToken, isGoodIdVerified, {
3085
+ depositBonusPercent: state.depositBonusPercent,
3086
+ streamBonusPercent: state.streamBonusPercent
3087
+ });
3088
+ if (usdMicro <= 0n) return null;
3089
+ return formatUsdAmount(usdMicro.toString());
3090
+ }, [monthlyStreamG, gdUsdPerToken, isGoodIdVerified, state.depositBonusPercent, state.streamBonusPercent]);
3091
+ const totalCreditDisplay = totalCreditUsd && BigInt(totalCreditUsd) > 0n ? formatUsdAmount(totalCreditUsd) : totalCreditUsd !== null ? formatUsdAmount("0") : null;
3092
+ const withdrawableDisplay = withdrawableUsd !== null ? formatUsdAmount(withdrawableUsd) : null;
3093
+ const hasWithdrawableBalance = withdrawableUsd !== null && BigInt(withdrawableUsd) > 0n;
3094
+ const canClose = Boolean(buyerPrvKey) && Boolean(channelId.trim()) && !isClosing;
3095
+ const canWithdraw = Boolean(buyerPrvKey) && hasWithdrawableBalance && Boolean(withdrawAmount.trim()) && !isWithdrawing;
3096
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_ui9.Card, { gap: "$3", children: [
3097
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.Heading, { level: 6, children: "AI Credits" }),
3098
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_ui9.XStack, { gap: "$4", width: "100%", alignItems: "flex-start", flexWrap: "wrap", children: [
3099
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_ui9.YStack, { gap: "$2", flex: 1, minWidth: 0, children: [
3100
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.Text, { fontSize: "$1", secondary: true, children: "Total Credit (US$)" }),
3101
+ totalCreditDisplay !== null ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.Heading, { level: 5, children: totalCreditDisplay }) : /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.Spinner, { size: "sm" })
3102
+ ] }),
3103
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_ui9.YStack, { gap: "$2", flex: 1, minWidth: 0, children: [
3104
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.Text, { fontSize: "$1", secondary: true, children: "Est. Monthly Credit (US$)" }),
3105
+ monthlyStreamUsdDisplay ? /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_ui9.Heading, { level: 5, color: "$primary", children: [
3106
+ "~",
3107
+ monthlyStreamUsdDisplay
3108
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.Heading, { level: 5, children: "\u2014" })
3109
+ ] })
3110
+ ] }),
3111
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_ui9.XStack, { gap: "$2", width: "100%", flexWrap: "wrap", alignItems: "stretch", children: [
3112
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(StatCell, { label: "Total Deposited (G$)", children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(CompactGStatValue, { amount: totalGdDepositedG ?? "0.00" }) }),
3113
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(StatCell, { label: "Monthly Stream (G$)", children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(CompactGStatValue, { amount: monthlyStreamG ?? "0.00" }) }),
3114
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(StatCell, { label: "Withdrawable (US$)", children: withdrawableDisplay !== null ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(StatValueText, { children: withdrawableDisplay }) : /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.Spinner, { size: "sm" }) })
3115
+ ] }),
3116
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_ui9.YStack, { gap: "$1", children: [
3117
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_ui9.XStack, { gap: "$1", alignItems: "center", children: [
3118
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.Text, { fontSize: "$1", variant: "label", children: "Withdraw" }),
3119
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(InfoTooltip, { message: WITHDRAW_TOOLTIP })
3120
+ ] }),
3121
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_ui9.XStack, { gap: "$2", alignItems: "center", children: [
3122
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.YStack, { flex: 1, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
3123
+ import_ui9.Input,
3124
+ {
3125
+ size: "sm",
3126
+ value: withdrawAmount,
3127
+ onChangeText: setWithdrawAmount,
3128
+ placeholder: hasWithdrawableBalance && withdrawableDisplay ? `Max ${withdrawableDisplay} US$` : "Amount in US$"
3129
+ }
3130
+ ) }),
3131
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(HoverTooltip, { message: !buyerPrvKey ? BUYER_KEY_REQUIRED_WITHDRAW_TOOLTIP : null, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
3132
+ import_ui9.Button,
3133
+ {
3134
+ variant: "outline",
3135
+ size: "sm",
3136
+ minWidth: "$14",
3137
+ flexShrink: 0,
3138
+ disabled: !canWithdraw,
3139
+ ...compactButtonProps,
3140
+ onPress: () => {
3141
+ setIsWithdrawing(true);
3142
+ void Promise.resolve(actions.withdrawCredits(withdrawAmount)).finally(() => {
3143
+ setIsWithdrawing(false);
3144
+ setWithdrawAmount("");
3145
+ });
3146
+ },
3147
+ children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.ButtonText, { children: isWithdrawing ? "Withdrawing\u2026" : "Withdraw" })
3148
+ }
3149
+ ) })
3150
+ ] })
3151
+ ] }),
3152
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_ui9.YStack, { gap: "$1", children: [
3153
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.Text, { fontSize: "$1", variant: "label", children: "Close Channel" }),
3154
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_ui9.XStack, { gap: "$2", alignItems: "center", children: [
3155
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.YStack, { flex: 1, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
3156
+ import_ui9.Input,
3157
+ {
3158
+ size: "sm",
3159
+ value: channelId,
3160
+ onChangeText: setChannelId,
3161
+ placeholder: "0x\u2026 (64 hex chars)"
3162
+ }
3163
+ ) }),
3164
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(HoverTooltip, { message: !buyerPrvKey ? BUYER_KEY_REQUIRED_CLOSE_TOOLTIP : null, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
3165
+ import_ui9.Button,
3166
+ {
3167
+ variant: "outline",
3168
+ size: "sm",
3169
+ minWidth: "$14",
3170
+ flexShrink: 0,
3171
+ disabled: !canClose,
3172
+ ...compactButtonProps,
3173
+ onPress: () => {
3174
+ setIsClosing(true);
3175
+ void Promise.resolve(actions.closeChannel(channelId)).finally(() => {
3176
+ setIsClosing(false);
3177
+ setChannelId("");
3178
+ });
3179
+ },
3180
+ children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_ui9.ButtonText, { children: isClosing ? "Closing\u2026" : "Close" })
3181
+ }
3182
+ ) })
3183
+ ] })
3184
+ ] })
3185
+ ] });
3186
+ }
3187
+
3188
+ // src/components/manage/BuyerOperatorCard.tsx
3189
+ var import_react10 = require("react");
3190
+ var import_ui11 = require("@goodwidget/ui");
3191
+
3192
+ // src/components/shared/AddressView.tsx
3193
+ var import_ui10 = require("@goodwidget/ui");
3194
+ var import_jsx_runtime8 = require("react/jsx-runtime");
3195
+ function AddressView({ label, address }) {
3196
+ const { copied, copy } = useCopyFeedback();
3197
+ return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(import_ui10.YStack, { gap: "$1", children: [
3198
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_ui10.Text, { fontSize: "$1", secondary: true, children: label }),
3199
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
3200
+ import_ui10.XStack,
3201
+ {
3202
+ backgroundColor: "$backgroundMuted",
3203
+ borderRadius: "$2",
3204
+ padding: "$2",
3205
+ justifyContent: "space-between",
3206
+ alignItems: "center",
3207
+ children: [
3208
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
3209
+ import_ui10.Text,
3210
+ {
3211
+ fontSize: "$2",
3212
+ fontFamily: "$mono",
3213
+ flex: 1,
3214
+ numberOfLines: 1,
3215
+ style: monospaceSingleLineStyle,
3216
+ children: truncateAddress(address)
3217
+ }
3218
+ ),
3219
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_ui10.Button, { size: "sm", variant: "ghost", iconSize: "sm", onPress: () => void copy(address), children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_ui10.Icon, { name: copied ? "check" : "copy", size: "xs", color: copied ? "success" : "text" }) })
3220
+ ]
3221
+ }
3222
+ )
3223
+ ] });
3224
+ }
3225
+
3226
+ // src/components/manage/BuyerOperatorCard.tsx
3227
+ var import_jsx_runtime9 = require("react/jsx-runtime");
3228
+ function BuyerOperatorCard({ state, actions }) {
3229
+ const { address, buyerPubKey, buyerPrvKey, operatorConsented } = state;
3230
+ const { copied: copiedPrivate, copy: copyPrivate } = useCopyFeedback();
3231
+ const [isPrivateKeyVisible, setIsPrivateKeyVisible] = (0, import_react10.useState)(false);
3232
+ const [isGenerating, setIsGenerating] = (0, import_react10.useState)(false);
3233
+ const [isSigning, setIsSigning] = (0, import_react10.useState)(false);
3234
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(import_ui11.Card, { gap: "$2", children: [
3235
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_ui11.Heading, { level: 6, children: "Buyer & Operator" }),
3236
+ address && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(AddressView, { label: "Payer", address }),
3237
+ buyerPubKey && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(AddressView, { label: "Buyer", address: buyerPubKey }),
3238
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(import_ui11.XStack, { gap: "$2", alignItems: "stretch", width: "100%", children: [
3239
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
3240
+ import_ui11.Button,
3241
+ {
3242
+ flex: 1,
3243
+ flexBasis: 0,
3244
+ minWidth: 0,
3245
+ size: "sm",
3246
+ ...compactButtonProps,
3247
+ onPress: () => {
3248
+ setIsGenerating(true);
3249
+ void Promise.resolve(actions.generateBuyerKey()).finally(() => setIsGenerating(false));
3250
+ },
3251
+ disabled: isGenerating,
3252
+ children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_ui11.ButtonText, { children: isGenerating ? "Signing\u2026" : "Sign & Generate" })
3253
+ }
3254
+ ),
3255
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
3256
+ import_ui11.Button,
3257
+ {
3258
+ flex: 1,
3259
+ flexBasis: 0,
3260
+ minWidth: 0,
3261
+ size: "sm",
3262
+ ...compactButtonProps,
3263
+ onPress: () => {
3264
+ setIsSigning(true);
3265
+ void Promise.resolve(actions.signOperatorConsent()).finally(() => setIsSigning(false));
3266
+ },
3267
+ disabled: operatorConsented || isSigning || !buyerPrvKey,
3268
+ children: isSigning ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_ui11.Spinner, { size: "sm" }) : /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_ui11.ButtonText, { children: operatorConsented ? "Consented" : "Sign Consent" })
3269
+ }
3270
+ )
3271
+ ] }),
3272
+ buyerPrvKey && /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(import_ui11.YStack, { gap: "$2", children: [
3273
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(import_ui11.XStack, { justifyContent: "space-between", alignItems: "center", children: [
3274
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_ui11.Text, { fontSize: "$1", secondary: true, children: "Buyer Private Key" }),
3275
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
3276
+ import_ui11.Button,
3277
+ {
3278
+ variant: "text",
3279
+ size: "sm",
3280
+ onPress: () => setIsPrivateKeyVisible((prev) => !prev),
3281
+ children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_ui11.ButtonText, { children: isPrivateKeyVisible ? "Hide" : "Reveal" })
3282
+ }
3283
+ )
3284
+ ] }),
3285
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
3286
+ import_ui11.XStack,
3287
+ {
3288
+ backgroundColor: "$backgroundMuted",
3289
+ borderRadius: "$2",
3290
+ padding: "$2",
3291
+ justifyContent: "space-between",
3292
+ alignItems: "center",
3293
+ children: [
3294
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_ui11.Text, { fontSize: "$2", style: monospaceSingleLineStyle, flex: 1, numberOfLines: 1, children: isPrivateKeyVisible ? buyerPrvKey : "\u2022".repeat(Math.min(48, buyerPrvKey.length)) }),
3295
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
3296
+ import_ui11.Button,
3297
+ {
3298
+ size: "sm",
3299
+ variant: "ghost",
3300
+ iconSize: "sm",
3301
+ onPress: () => void copyPrivate(buyerPrvKey),
3302
+ children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
3303
+ import_ui11.Icon,
3304
+ {
3305
+ name: copiedPrivate ? "check" : "copy",
3306
+ size: "xs",
3307
+ color: copiedPrivate ? "success" : "text"
3308
+ }
3309
+ )
3310
+ }
3311
+ )
3312
+ ]
3313
+ }
3314
+ )
3315
+ ] })
3316
+ ] });
3317
+ }
3318
+
3319
+ // src/components/manage/SetupSnippet.tsx
3320
+ var import_react11 = require("react");
3321
+ var import_ui12 = require("@goodwidget/ui");
3322
+ var import_jsx_runtime10 = require("react/jsx-runtime");
3323
+ var ANTSEED_API_DOCS_URL = "https://antseed.com/docs/guides/using-the-api";
3324
+ var setupSnippetLineStyle = {
3325
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
3326
+ fontSize: 13,
3327
+ lineHeight: "20px",
3328
+ wordBreak: "break-word",
3329
+ overflowWrap: "anywhere"
3330
+ };
3331
+ function buildSetupSnippet() {
3332
+ return [
3333
+ "npm install -g @antseed/cli",
3334
+ "",
3335
+ "export ANTSEED_IDENTITY_HEX=<buyer-private-key-hex>",
3336
+ "",
3337
+ "antseed buyer start",
3338
+ "antseed network browse",
3339
+ "antseed buyer connection set --peer <peer-id>"
3340
+ ].join("\n");
3341
+ }
3342
+ function SetupSnippet() {
3343
+ const [expanded, setExpanded] = (0, import_react11.useState)(false);
3344
+ const [copied, setCopied] = (0, import_react11.useState)(false);
3345
+ const snippet = buildSetupSnippet();
3346
+ const copyText = snippet.replace(/\n\n+/g, "\n").trim();
3347
+ const lines = snippet.trim().split("\n");
3348
+ async function handleCopy() {
3349
+ const copied2 = await (0, import_ui12.copyTextToClipboard)(copyText);
3350
+ if (!copied2) return;
3351
+ setCopied(true);
3352
+ setTimeout(() => setCopied(false), 2e3);
3353
+ }
3354
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(import_ui12.Card, { gap: "$2", children: [
3355
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(import_ui12.XStack, { justifyContent: "space-between", alignItems: "center", children: [
3356
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(
3357
+ import_ui12.XStack,
3358
+ {
3359
+ flex: 1,
3360
+ justifyContent: "space-between",
3361
+ alignItems: "center",
3362
+ onPress: () => setExpanded((value) => !value),
3363
+ cursor: "pointer",
3364
+ children: [
3365
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_ui12.Text, { fontSize: "$3", fontWeight: "600", children: "API Setup" }),
3366
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_ui12.Icon, { name: expanded ? "chevron-up" : "chevron-right", size: "xs", color: "muted" })
3367
+ ]
3368
+ }
3369
+ ),
3370
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_ui12.Button, { size: "sm", variant: "ghost", iconSize: "sm", onPress: handleCopy, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_ui12.Icon, { name: copied ? "check" : "copy", size: "xs", color: copied ? "success" : "text" }) })
3371
+ ] }),
3372
+ expanded && /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(import_ui12.YStack, { gap: "$2", children: [
3373
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
3374
+ import_ui12.YStack,
3375
+ {
3376
+ backgroundColor: "$backgroundMuted",
3377
+ borderRadius: "$2",
3378
+ padding: "$3",
3379
+ width: "100%",
3380
+ gap: "$1",
3381
+ children: lines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_ui12.Text, { color: "$text", style: setupSnippetLineStyle, children: line.length > 0 ? line : " " }, index))
3382
+ }
3383
+ ),
3384
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(import_ui12.Text, { fontSize: "$1", secondary: true, children: [
3385
+ "To connect AI tools to the AntSeed AI provider, see the",
3386
+ " ",
3387
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_ui12.Anchor, { href: ANTSEED_API_DOCS_URL, target: "_blank", children: "AntSeed API guide" }),
3388
+ "."
3389
+ ] })
3390
+ ] })
3391
+ ] });
3392
+ }
3393
+
3394
+ // src/components/history/HistoryTab.tsx
3395
+ var import_react12 = require("react");
3396
+ var import_ui13 = require("@goodwidget/ui");
3397
+ var import_jsx_runtime11 = require("react/jsx-runtime");
3398
+ var STATUS_OPTIONS = [
3399
+ { label: "All", value: "all" },
3400
+ { label: "Funded", value: "funded" },
3401
+ { label: "Pending", value: "pending" },
3402
+ { label: "Failed", value: "failed" }
3403
+ ];
3404
+ var SOURCE_PILL_OPTIONS = [
3405
+ { id: "deposit", label: "Deposit" },
3406
+ { id: "streamUpdate", label: "Stream update" },
3407
+ { id: "streamRequest", label: "Stream credit" }
3408
+ ];
3409
+ function sourceLabel(source) {
3410
+ if (source === "deposit") return "G$ Deposit";
3411
+ if (source === "streamUpdate") return "Stream Update";
3412
+ return "Stream Credit";
3413
+ }
3414
+ function formatEntryDate(createdAt) {
3415
+ const date = new Date(createdAt);
3416
+ if (Number.isNaN(date.getTime())) return createdAt;
3417
+ return date.toLocaleDateString("en-US", {
3418
+ month: "short",
3419
+ day: "numeric",
3420
+ year: "numeric"
3421
+ });
3422
+ }
3423
+ function formatGAmount(gdAmountWei) {
3424
+ try {
3425
+ const amountWei = BigInt(gdAmountWei || "0");
3426
+ if (amountWei <= 0n) return null;
3427
+ return `${weiToG(amountWei)} G$`;
3428
+ } catch {
3429
+ return null;
3430
+ }
3431
+ }
3432
+ function formatUsdCredit(usdMicro) {
3433
+ try {
3434
+ const micro = BigInt(usdMicro || "0");
3435
+ if (micro <= 0n) return null;
3436
+ return `+$${formatUsdMicro(usdMicro)}`;
3437
+ } catch {
3438
+ return null;
3439
+ }
3440
+ }
3441
+ function formatUsdValue(usdMicro) {
3442
+ return `$${formatUsdMicro(usdMicro || "0")}`;
3443
+ }
3444
+ function amountLines(entry) {
3445
+ const gAmount = formatGAmount(entry.gdAmountWei);
3446
+ const usdCredit = formatUsdCredit(entry.totalCreditUsd);
3447
+ if (entry.source === "streamUpdate") {
3448
+ const addedG = gAmount ? `+${gAmount}` : null;
3449
+ if (addedG && usdCredit) return { primary: addedG, secondary: usdCredit };
3450
+ if (addedG) return { primary: addedG };
3451
+ if (usdCredit) return { primary: usdCredit };
3452
+ return null;
3453
+ }
3454
+ if (gAmount && usdCredit) return { primary: gAmount, secondary: usdCredit };
3455
+ if (gAmount) return { primary: gAmount };
3456
+ if (usdCredit) return { primary: usdCredit };
3457
+ return null;
3458
+ }
3459
+ function entryDetailRows(entry) {
3460
+ const rows = [
3461
+ { label: "Principal", value: formatUsdValue(entry.principalUsd) },
3462
+ { label: "Bonus", value: formatUsdValue(entry.bonusUsd) }
3463
+ ];
3464
+ if (entry.txHash) rows.push({ label: "Celo tx", value: entry.txHash });
3465
+ if (entry.fundingTxHash) rows.push({ label: "Funding tx", value: entry.fundingTxHash });
3466
+ return rows;
3467
+ }
3468
+ function EntryDetailRow({ label, value }) {
3469
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.XStack, { gap: "$2", alignItems: "flex-start", width: "100%", children: [
3470
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$1", fontWeight: "600", secondary: true, minWidth: 72, flexShrink: 0, children: label }),
3471
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3472
+ import_ui13.Text,
3473
+ {
3474
+ fontSize: "$1",
3475
+ flex: 1,
3476
+ minWidth: 0,
3477
+ style: { wordBreak: "break-all", overflowWrap: "anywhere" },
3478
+ children: value
3479
+ }
3480
+ )
3481
+ ] });
3482
+ }
3483
+ function entryAccent(entry) {
3484
+ if (entry.fundingStatus === "failed") return "$error";
3485
+ if (entry.fundingStatus === "pending") return "$warning";
3486
+ return "$success";
3487
+ }
3488
+ function amountAccent(entry) {
3489
+ if (entry.fundingStatus === "failed") return "$error";
3490
+ if (entry.fundingStatus === "pending") return "$warning";
3491
+ return "$success";
3492
+ }
3493
+ function entryIconName(entry) {
3494
+ if (entry.fundingStatus === "failed") return "alert-circle";
3495
+ if (entry.source === "deposit") return "plus";
3496
+ if (entry.source === "streamUpdate") return "refresh";
3497
+ return "arrow-down";
3498
+ }
3499
+ function entryIconColor(entry) {
3500
+ if (entry.fundingStatus === "failed") return "error";
3501
+ if (entry.fundingStatus === "pending") return "warning";
3502
+ if (entry.source === "streamUpdate") return "primary";
3503
+ return "success";
3504
+ }
3505
+ function entryIconBackground(entry) {
3506
+ if (entry.fundingStatus === "failed") return "$errorMuted";
3507
+ if (entry.fundingStatus === "pending") return "$warningMuted";
3508
+ if (entry.source === "streamUpdate") return "$infoMuted";
3509
+ return "$successMuted";
3510
+ }
3511
+ function statusLabel(status) {
3512
+ return status.toUpperCase();
3513
+ }
3514
+ function sumFilteredGdWei(entries) {
3515
+ return entries.reduce((sum, entry) => {
3516
+ if (entry.source === "streamUpdate") return sum;
3517
+ try {
3518
+ const amount = BigInt(entry.gdAmountWei || "0");
3519
+ return amount > 0n ? sum + amount : sum;
3520
+ } catch {
3521
+ return sum;
3522
+ }
3523
+ }, 0n);
3524
+ }
3525
+ function formatAccumulatedG(amountWei) {
3526
+ const value = Number(amountWei) / 1e18;
3527
+ if (!Number.isFinite(value) || value < 0) return "0.00 G$";
3528
+ return `${new Intl.NumberFormat("en-US", {
3529
+ minimumFractionDigits: 2,
3530
+ maximumFractionDigits: 2
3531
+ }).format(value)} G$`;
3532
+ }
3533
+ function formatShortDate(dateValue) {
3534
+ const date = /* @__PURE__ */ new Date(`${dateValue}T00:00:00.000Z`);
3535
+ if (Number.isNaN(date.getTime())) return dateValue;
3536
+ return date.toLocaleDateString("en-US", {
3537
+ month: "short",
3538
+ day: "numeric",
3539
+ year: "numeric",
3540
+ timeZone: "UTC"
3541
+ });
3542
+ }
3543
+ function escapeCsvValue(value) {
3544
+ if (value.includes(",") || value.includes('"') || value.includes("\n")) {
3545
+ return `"${value.replace(/"/g, '""')}"`;
3546
+ }
3547
+ return value;
3548
+ }
3549
+ function exportEntriesCsv(entries) {
3550
+ if (typeof document === "undefined") return;
3551
+ const headers = [
3552
+ "id",
3553
+ "source",
3554
+ "status",
3555
+ "usdCredit",
3556
+ "gdAmountWei",
3557
+ "createdAt",
3558
+ "txHash",
3559
+ "fundingTxHash"
3560
+ ];
3561
+ const rows = entries.map(
3562
+ (entry) => [
3563
+ entry.id,
3564
+ entry.source,
3565
+ entry.fundingStatus,
3566
+ formatUsdMicro(entry.totalCreditUsd),
3567
+ entry.gdAmountWei,
3568
+ entry.createdAt,
3569
+ entry.txHash ?? "",
3570
+ entry.fundingTxHash ?? ""
3571
+ ].map((value) => escapeCsvValue(String(value))).join(",")
3572
+ );
3573
+ const csv = [headers.join(","), ...rows].join("\n");
3574
+ const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
3575
+ const url = URL.createObjectURL(blob);
3576
+ const anchor = document.createElement("a");
3577
+ anchor.href = url;
3578
+ anchor.download = "ai-credit-history.csv";
3579
+ anchor.click();
3580
+ URL.revokeObjectURL(url);
3581
+ }
3582
+ function CreditHistoryEntryRow({
3583
+ entry,
3584
+ expanded,
3585
+ onToggle
3586
+ }) {
3587
+ const accent = entryAccent(entry);
3588
+ const amountColor = amountAccent(entry);
3589
+ const amounts = amountLines(entry);
3590
+ const detailRows = entryDetailRows(entry);
3591
+ const titleColor = entry.fundingStatus === "failed" ? "$error" : "$color";
3592
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.Card, { gap: "$2", children: [
3593
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
3594
+ import_ui13.XStack,
3595
+ {
3596
+ alignItems: "center",
3597
+ gap: "$3",
3598
+ width: "100%",
3599
+ cursor: "pointer",
3600
+ onPress: onToggle,
3601
+ children: [
3602
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3603
+ import_ui13.YStack,
3604
+ {
3605
+ width: 40,
3606
+ height: 40,
3607
+ borderRadius: "$full",
3608
+ alignItems: "center",
3609
+ justifyContent: "center",
3610
+ backgroundColor: entryIconBackground(entry),
3611
+ flexShrink: 0,
3612
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3613
+ import_ui13.Icon,
3614
+ {
3615
+ name: entryIconName(entry),
3616
+ size: "sm",
3617
+ color: entryIconColor(entry)
3618
+ }
3619
+ )
3620
+ }
3621
+ ),
3622
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.YStack, { flex: 1, gap: "$0.5", minWidth: 0, children: [
3623
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$3", fontWeight: "700", color: titleColor, children: sourceLabel(entry.source) }),
3624
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.XStack, { alignItems: "center", gap: "$1", children: [
3625
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3626
+ import_ui13.YStack,
3627
+ {
3628
+ width: 6,
3629
+ height: 6,
3630
+ borderRadius: "$full",
3631
+ backgroundColor: accent
3632
+ }
3633
+ ),
3634
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$1", fontWeight: "600", color: accent, letterSpacing: 0.4, children: statusLabel(entry.fundingStatus) })
3635
+ ] })
3636
+ ] }),
3637
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.YStack, { alignItems: "flex-end", gap: "$0.5", flexShrink: 0, children: [
3638
+ amounts?.primary ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$3", fontWeight: "700", color: amountColor, children: amounts.primary }) : null,
3639
+ amounts?.secondary ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$2", fontWeight: "600", color: amountColor, children: amounts.secondary }) : null,
3640
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$1", secondary: true, children: formatEntryDate(entry.createdAt) })
3641
+ ] })
3642
+ ]
3643
+ }
3644
+ ),
3645
+ expanded && detailRows.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.YStack, { gap: "$1.5", paddingTop: "$1", children: detailRows.map((row) => /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(EntryDetailRow, { label: row.label, value: row.value }, row.label)) }) : null
3646
+ ] });
3647
+ }
3648
+ function SourceFilterChip({
3649
+ label,
3650
+ selected,
3651
+ onPress
3652
+ }) {
3653
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3654
+ import_ui13.XStack,
3655
+ {
3656
+ tag: "button",
3657
+ role: "checkbox",
3658
+ "aria-checked": selected,
3659
+ cursor: "pointer",
3660
+ alignItems: "center",
3661
+ justifyContent: "center",
3662
+ height: "$7",
3663
+ paddingHorizontal: "$3",
3664
+ borderRadius: "$full",
3665
+ borderWidth: 1,
3666
+ borderColor: selected ? "$primary" : "$borderColor",
3667
+ backgroundColor: selected ? "$infoMuted" : "$backgroundDark",
3668
+ hoverStyle: {
3669
+ opacity: 0.9
3670
+ },
3671
+ pressStyle: {
3672
+ opacity: 0.85
3673
+ },
3674
+ onPress,
3675
+ flexShrink: 0,
3676
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3677
+ import_ui13.Text,
3678
+ {
3679
+ fontSize: "$2",
3680
+ fontWeight: selected ? "700" : "500",
3681
+ color: selected ? "$primary" : "$placeholderColor",
3682
+ userSelect: "none",
3683
+ children: label
3684
+ }
3685
+ )
3686
+ }
3687
+ );
3688
+ }
3689
+ function StatusFilterSelect({
3690
+ value,
3691
+ onValueChange
3692
+ }) {
3693
+ const [open, setOpen] = (0, import_react12.useState)(false);
3694
+ const selected = STATUS_OPTIONS.find((option) => option.value === value);
3695
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.YStack, { flex: 1, minWidth: 0, position: "relative", zIndex: open ? 20 : 1, children: [
3696
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
3697
+ import_ui13.XStack,
3698
+ {
3699
+ tag: "button",
3700
+ role: "combobox",
3701
+ height: "$7",
3702
+ alignItems: "center",
3703
+ justifyContent: "space-between",
3704
+ gap: "$2",
3705
+ paddingHorizontal: "$3",
3706
+ borderRadius: "$3",
3707
+ borderWidth: 1,
3708
+ borderColor: "$borderColor",
3709
+ backgroundColor: "$backgroundDark",
3710
+ cursor: "pointer",
3711
+ onPress: () => setOpen((current) => !current),
3712
+ children: [
3713
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.Text, { fontSize: "$2", color: "$placeholderColor", numberOfLines: 1, flex: 1, children: [
3714
+ "Status: ",
3715
+ selected?.label ?? "All"
3716
+ ] }),
3717
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Icon, { name: open ? "chevron-up" : "chevron-down", size: "xs", color: "muted" })
3718
+ ]
3719
+ }
3720
+ ),
3721
+ open ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3722
+ import_ui13.YStack,
3723
+ {
3724
+ position: "absolute",
3725
+ top: "100%",
3726
+ left: 0,
3727
+ right: 0,
3728
+ marginTop: "$1",
3729
+ borderRadius: "$3",
3730
+ borderWidth: 1,
3731
+ borderColor: "$borderColor",
3732
+ backgroundColor: "$backgroundDark",
3733
+ overflow: "hidden",
3734
+ zIndex: 30,
3735
+ children: STATUS_OPTIONS.map((option) => /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3736
+ import_ui13.XStack,
3737
+ {
3738
+ tag: "button",
3739
+ role: "option",
3740
+ paddingHorizontal: "$3",
3741
+ paddingVertical: "$2",
3742
+ cursor: "pointer",
3743
+ backgroundColor: option.value === value ? "$infoMuted" : "transparent",
3744
+ hoverStyle: { backgroundColor: "$backgroundPress" },
3745
+ onPress: () => {
3746
+ onValueChange(option.value);
3747
+ setOpen(false);
3748
+ },
3749
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3750
+ import_ui13.Text,
3751
+ {
3752
+ fontSize: "$2",
3753
+ fontWeight: option.value === value ? "700" : "500",
3754
+ color: option.value === value ? "$primary" : "$color",
3755
+ children: option.label
3756
+ }
3757
+ )
3758
+ },
3759
+ option.value
3760
+ ))
3761
+ }
3762
+ ) : null
3763
+ ] });
3764
+ }
3765
+ function HistoryTab({ state, actions }) {
3766
+ const {
3767
+ selectedSources,
3768
+ statusFilter,
3769
+ fromDate,
3770
+ toDate,
3771
+ entries,
3772
+ hasMore,
3773
+ loading,
3774
+ loadingMore,
3775
+ error,
3776
+ activeSources
3777
+ } = state;
3778
+ const [expandedEntryId, setExpandedEntryId] = (0, import_react12.useState)(null);
3779
+ const defaultRange = (0, import_react12.useMemo)(() => getLast90DaysRange(), []);
3780
+ const isDefaultRange = fromDate === defaultRange.from && toDate === defaultRange.to;
3781
+ const rangeSummary = isDefaultRange ? `Last ${HISTORY_LOOKBACK_DAYS} days activity` : `${formatShortDate(fromDate)} \u2013 ${formatShortDate(toDate)}`;
3782
+ const accumulatedG = (0, import_react12.useMemo)(
3783
+ () => formatAccumulatedG(sumFilteredGdWei(entries)),
3784
+ [entries]
3785
+ );
3786
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.YStack, { gap: "$3", width: "100%", children: [
3787
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.Card, { gap: "$3", children: [
3788
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.XStack, { alignItems: "flex-start", justifyContent: "space-between", gap: "$2", width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.YStack, { flex: 1, gap: "$0.5", minWidth: 0, children: [
3789
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Heading, { level: 4, children: "AI Credit History" }),
3790
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$1", secondary: true, children: rangeSummary })
3791
+ ] }) }),
3792
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.YStack, { gap: "$1", children: [
3793
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$1", fontWeight: "600", secondary: true, letterSpacing: 0.6, children: "TOTAL ACCUMULATED" }),
3794
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$7", fontWeight: "700", color: "$color", children: accumulatedG })
3795
+ ] })
3796
+ ] }),
3797
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.XStack, { gap: "$2", flexWrap: "wrap", width: "100%", children: SOURCE_PILL_OPTIONS.map((option) => /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3798
+ SourceFilterChip,
3799
+ {
3800
+ label: option.label,
3801
+ selected: selectedSources[option.id],
3802
+ onPress: () => actions.setSourceChecked(option.id, !selectedSources[option.id])
3803
+ },
3804
+ option.id
3805
+ )) }),
3806
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.XStack, { gap: "$2", alignItems: "center", width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3807
+ StatusFilterSelect,
3808
+ {
3809
+ value: statusFilter,
3810
+ onValueChange: actions.setStatusFilter
3811
+ }
3812
+ ) }),
3813
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.XStack, { gap: "$2", width: "100%", children: [
3814
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.YStack, { flex: 1, minWidth: 0, children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3815
+ import_ui13.Input,
3816
+ {
3817
+ size: "sm",
3818
+ type: "date",
3819
+ label: "From",
3820
+ value: fromDate,
3821
+ onChangeText: actions.setFromDate
3822
+ }
3823
+ ) }),
3824
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.YStack, { flex: 1, minWidth: 0, children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3825
+ import_ui13.Input,
3826
+ {
3827
+ size: "sm",
3828
+ type: "date",
3829
+ label: "To",
3830
+ value: toDate,
3831
+ onChangeText: actions.setToDate
3832
+ }
3833
+ ) })
3834
+ ] }),
3835
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.XStack, { alignItems: "center", justifyContent: "space-between", gap: "$2", width: "100%", children: [
3836
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$1", fontWeight: "700", secondary: true, letterSpacing: 0.6, children: "CREDIT HISTORY" }),
3837
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3838
+ import_ui13.XStack,
3839
+ {
3840
+ tag: "button",
3841
+ backgroundColor: "transparent",
3842
+ borderWidth: 0,
3843
+ padding: 0,
3844
+ cursor: entries.length > 0 ? "pointer" : "default",
3845
+ opacity: entries.length > 0 ? 1 : 0.5,
3846
+ hoverStyle: { opacity: entries.length > 0 ? 0.85 : 0.5 },
3847
+ pressStyle: { opacity: entries.length > 0 ? 0.7 : 0.5 },
3848
+ onPress: () => {
3849
+ if (entries.length === 0) return;
3850
+ exportEntriesCsv(entries);
3851
+ },
3852
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$2", fontWeight: "600", color: "$primary", children: "Export CSV" })
3853
+ }
3854
+ )
3855
+ ] }),
3856
+ loading ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Card, { gap: "$2", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.YStack, { alignItems: "center", paddingVertical: "$4", gap: "$2", children: [
3857
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Spinner, { size: "sm" }),
3858
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$2", secondary: true, children: "Loading credit history\u2026" })
3859
+ ] }) }) : error ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Card, { gap: "$2", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_ui13.YStack, { gap: "$2", paddingVertical: "$2", children: [
3860
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { color: "$error", fontSize: "$2", children: error }),
3861
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3862
+ import_ui13.Button,
3863
+ {
3864
+ variant: "outline",
3865
+ size: "sm",
3866
+ alignSelf: "flex-start",
3867
+ ...compactButtonProps,
3868
+ onPress: () => {
3869
+ void actions.reload();
3870
+ },
3871
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.ButtonText, { children: "Retry" })
3872
+ }
3873
+ )
3874
+ ] }) }) : activeSources.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Card, { children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$2", secondary: true, children: "Select at least one source to view history." }) }) : entries.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Card, { children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Text, { fontSize: "$2", secondary: true, children: "No credit history matches these filters." }) }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.YStack, { gap: "$2", width: "100%", children: entries.map((entry) => /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3875
+ CreditHistoryEntryRow,
3876
+ {
3877
+ entry,
3878
+ expanded: expandedEntryId === entry.id,
3879
+ onToggle: () => setExpandedEntryId((current) => current === entry.id ? null : entry.id)
3880
+ },
3881
+ entry.id
3882
+ )) }),
3883
+ !loading && !error && hasMore && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
3884
+ import_ui13.Button,
3885
+ {
3886
+ variant: "outline",
3887
+ size: "sm",
3888
+ alignSelf: "center",
3889
+ disabled: loadingMore,
3890
+ ...compactButtonProps,
3891
+ onPress: () => {
3892
+ void actions.loadMore();
3893
+ },
3894
+ children: [
3895
+ loadingMore ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.Spinner, { size: "sm" }) : null,
3896
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_ui13.ButtonText, { children: loadingMore ? "Loading\u2026" : "Load more" })
3897
+ ]
3898
+ }
3899
+ )
3900
+ ] });
3901
+ }
3902
+
3903
+ // src/components/flow/purchaseFlowUtils.ts
3904
+ function mapStatusToActiveStep(state, buyerPubKeySaved) {
3905
+ if (state.operatorConsented) return "pay";
3906
+ if (!state.buyerPubKey || !state.buyerPrvKey) return "buyer_key";
3907
+ if (!buyerPubKeySaved) return "buyer_key";
3908
+ if (!state.operatorConsented) return "consent";
3909
+ if (state.status === "purchase_setup" || state.status === "quote_ready" || state.status === "payment_pending" || state.status === "payment_confirmed" || state.status === "payment_failed")
3910
+ return "pay";
3911
+ return null;
3912
+ }
3913
+ function getAiCreditsActiveFlowStep(state, buyerPubKeySaved) {
3914
+ return mapStatusToActiveStep(state, buyerPubKeySaved);
3915
+ }
3916
+ function getActiveFlowStepActionLabel(state, step, buyerPubKeySaved) {
3917
+ if (!step) return null;
3918
+ switch (step) {
3919
+ case "buyer_key":
3920
+ if (!state.buyerPubKey) return "Sign & Generate Key";
3921
+ if (!buyerPubKeySaved) return "Continue Buyer Key";
3922
+ return "View Buyer Key";
3923
+ case "consent":
3924
+ return state.operatorConsented ? "View Operator Consent" : "Sign Operator Consent";
3925
+ case "pay":
3926
+ return "Set Amounts & Pay";
3927
+ default:
3928
+ return null;
3929
+ }
3930
+ }
3931
+
3932
+ // src/components/flow/AiCreditsFlowStepper.tsx
3933
+ var import_ui14 = require("@goodwidget/ui");
3934
+ var import_jsx_runtime12 = require("react/jsx-runtime");
3935
+ var STEP_ORDER = ["buyer_key", "consent", "pay"];
3936
+ function AiCreditsFlowStepper({
3937
+ state,
3938
+ buyerPubKeySaved,
3939
+ onStepPress
3940
+ }) {
3941
+ const activeStep = mapStatusToActiveStep(state, buyerPubKeySaved);
3942
+ function getStepStatus(step) {
3943
+ const stepIndex = STEP_ORDER.indexOf(step);
3944
+ if (!activeStep) return "pending";
3945
+ const activeIndex = STEP_ORDER.indexOf(activeStep);
3946
+ if (activeIndex < 0) return "pending";
3947
+ if (stepIndex > activeIndex) return "pending";
3948
+ if (stepIndex < activeIndex) return "completed";
3949
+ if (step === "pay" && state.status === "payment_failed") return "failed";
3950
+ if (step === "pay" && (state.status === "payment_pending" || state.status === "payment_confirmed")) {
3951
+ return "active";
3952
+ }
3953
+ return "ready";
3954
+ }
3955
+ const steps = [
3956
+ {
3957
+ id: "buyer_key",
3958
+ title: "Buyer Key",
3959
+ description: "Generate or provide your AI credits buyer key",
3960
+ status: getStepStatus("buyer_key")
3961
+ },
3962
+ {
3963
+ id: "consent",
3964
+ title: "Operator Consent",
3965
+ description: "Sign permission for the AntseedBuyerOperator",
3966
+ status: getStepStatus("consent")
3967
+ },
3968
+ {
3969
+ id: "pay",
3970
+ title: "Buy Credits",
3971
+ description: state.status === "payment_pending" ? "Transaction submitted\u2026" : state.status === "payment_confirmed" ? "Settling on Base\u2026" : state.status === "payment_failed" ? state.error ?? "Payment failed" : "Confirm the Celo transaction",
3972
+ status: getStepStatus("pay")
3973
+ }
3974
+ ];
3975
+ function handleStepPress(stepId) {
3976
+ const step = steps.find((item) => item.id === stepId);
3977
+ if (!step || step.status === "completed" || step.status === "pending") return;
3978
+ onStepPress?.(stepId);
3979
+ }
3980
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
3981
+ import_ui14.Stepper,
3982
+ {
3983
+ steps,
3984
+ activeStepId: activeStep,
3985
+ onStepPress: onStepPress ? handleStepPress : void 0,
3986
+ header: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_ui14.Heading, { level: 5, secondary: true, children: "Purchase Flow" })
3987
+ }
3988
+ );
3989
+ }
3990
+
3991
+ // src/components/flow/AiCreditsPurchaseFlow.tsx
3992
+ var import_react13 = require("react");
3993
+ var import_ui15 = require("@goodwidget/ui");
3994
+ var import_jsx_runtime13 = require("react/jsx-runtime");
3995
+ function AiCreditsPurchaseFlow({
3996
+ state,
3997
+ actions,
3998
+ isPending,
3999
+ onPay
4000
+ }) {
4001
+ const [buyerPubKeySaved, setBuyerPubKeySaved] = (0, import_react13.useState)(false);
4002
+ const activeStep = getAiCreditsActiveFlowStep(state, buyerPubKeySaved);
4003
+ const [drawerOpen, setDrawerOpen] = (0, import_react13.useState)(false);
4004
+ const [drawerStep, setDrawerStep] = (0, import_react13.useState)(activeStep);
4005
+ const prevActiveStepRef = (0, import_react13.useRef)(null);
4006
+ const goodIdTabPendingRef = (0, import_react13.useRef)(false);
4007
+ (0, import_react13.useEffect)(() => {
4008
+ setBuyerPubKeySaved(false);
4009
+ }, [state.buyerPubKey]);
4010
+ (0, import_react13.useEffect)(() => {
4011
+ if (activeStep !== "consent" || state.operatorConsented) return;
4012
+ if (!state.address || !state.buyerPubKey) return;
4013
+ void actions.syncOperatorConsentFromChain();
4014
+ }, [activeStep, state.operatorConsented, state.address, state.buyerPubKey, actions]);
4015
+ (0, import_react13.useEffect)(() => {
4016
+ if (!activeStep) {
4017
+ setDrawerOpen(false);
4018
+ setDrawerStep(null);
4019
+ prevActiveStepRef.current = null;
4020
+ return;
4021
+ }
4022
+ const previousStep = prevActiveStepRef.current;
4023
+ prevActiveStepRef.current = activeStep;
4024
+ setDrawerStep(activeStep);
4025
+ if (previousStep == null) {
4026
+ setDrawerOpen(false);
4027
+ } else if (previousStep !== activeStep) {
4028
+ setDrawerOpen(true);
4029
+ }
4030
+ }, [activeStep]);
4031
+ (0, import_react13.useEffect)(() => {
4032
+ if (typeof window === "undefined") return;
4033
+ const onFocus = () => {
4034
+ if (!goodIdTabPendingRef.current) return;
4035
+ goodIdTabPendingRef.current = false;
4036
+ if (activeStep === "pay") {
4037
+ setDrawerStep("pay");
4038
+ setDrawerOpen(true);
4039
+ }
4040
+ };
4041
+ window.addEventListener("focus", onFocus);
4042
+ return () => window.removeEventListener("focus", onFocus);
4043
+ }, [activeStep]);
4044
+ const handleVerifyGoodId = (0, import_react13.useCallback)(async () => {
4045
+ try {
4046
+ const started = await actions.verifyGoodId();
4047
+ if (started) {
4048
+ goodIdTabPendingRef.current = true;
4049
+ }
4050
+ } finally {
4051
+ if (activeStep === "pay") {
4052
+ setDrawerStep("pay");
4053
+ setDrawerOpen(true);
4054
+ }
4055
+ }
4056
+ }, [actions, activeStep]);
4057
+ const openDrawer = (0, import_react13.useCallback)(
4058
+ (step) => {
4059
+ if (step !== activeStep && !(step === "pay" && state.status === "payment_failed")) return;
4060
+ setDrawerStep(step);
4061
+ setDrawerOpen(true);
4062
+ },
4063
+ [activeStep, state.status]
4064
+ );
4065
+ const handleStepPress = (0, import_react13.useCallback)(
4066
+ (stepId) => {
4067
+ openDrawer(stepId);
4068
+ },
4069
+ [openDrawer]
4070
+ );
4071
+ const actionLabel = getActiveFlowStepActionLabel(state, activeStep, buyerPubKeySaved);
4072
+ function renderDrawerContent(step) {
4073
+ if (!step) return null;
4074
+ switch (step) {
4075
+ case "buyer_key":
4076
+ return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
4077
+ BuyerKeyPanel,
4078
+ {
4079
+ embedded: true,
4080
+ buyerPubKey: state.buyerPubKey,
4081
+ buyerPrvKey: state.buyerPrvKey ?? null,
4082
+ buyerPubKeySaved,
4083
+ onGenerate: actions.generateBuyerKey,
4084
+ onConfirm: () => setBuyerPubKeySaved(true)
4085
+ }
4086
+ );
4087
+ case "consent":
4088
+ return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
4089
+ OperatorConsentStep,
4090
+ {
4091
+ embedded: true,
4092
+ buyerPubKey: state.buyerPubKey,
4093
+ buyerPrvKey: state.buyerPrvKey ?? null,
4094
+ operatorConsented: state.operatorConsented,
4095
+ onSign: actions.signOperatorConsent
4096
+ }
4097
+ );
4098
+ case "pay":
4099
+ return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
4100
+ AmountPicker,
4101
+ {
4102
+ embedded: true,
4103
+ status: state.status,
4104
+ gBalance: state.gBalance,
4105
+ minDepositUsd: state.minDepositUsd,
4106
+ minStreamUsd: state.minStreamUsd,
4107
+ monthlyStreamG: state.monthlyStreamG,
4108
+ gdUsdPerToken: state.gdUsdPerToken,
4109
+ isGoodIdVerified: state.isGoodIdVerified,
4110
+ depositBonusPercent: state.depositBonusPercent,
4111
+ streamBonusPercent: state.streamBonusPercent,
4112
+ isPayPending: isPending,
4113
+ buildQuote: actions.buildQuote,
4114
+ onPay,
4115
+ onVerifyGoodId: handleVerifyGoodId
4116
+ }
4117
+ );
4118
+ default:
4119
+ return null;
4120
+ }
4121
+ }
4122
+ return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(import_jsx_runtime13.Fragment, { children: [
4123
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
4124
+ AiCreditsFlowStepper,
4125
+ {
4126
+ state,
4127
+ buyerPubKeySaved,
4128
+ onStepPress: handleStepPress
4129
+ }
4130
+ ),
4131
+ !drawerOpen && actionLabel && activeStep && /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
4132
+ import_ui15.Button,
4133
+ {
4134
+ fullWidth: true,
4135
+ size: "sm",
4136
+ ...compactButtonProps,
4137
+ onPress: () => {
4138
+ openDrawer(activeStep);
4139
+ },
4140
+ children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_ui15.ButtonText, { children: actionLabel })
4141
+ }
4142
+ ),
4143
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
4144
+ import_ui15.Drawer,
4145
+ {
4146
+ open: drawerOpen && drawerStep !== null,
4147
+ onClose: () => {
4148
+ setDrawerOpen(false);
4149
+ },
4150
+ height: "full",
4151
+ children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_ui15.ScrollArea, { width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_ui15.YStack, { gap: "$3", paddingBottom: "$4", width: "100%", children: renderDrawerContent(drawerStep) }) })
4152
+ }
4153
+ )
4154
+ ] });
4155
+ }
4156
+
4157
+ // src/AiCreditsWidget.tsx
4158
+ var import_jsx_runtime14 = require("react/jsx-runtime");
4159
+ var CELO_CHAIN_ID3 = 42220;
4160
+ function DisconnectedPanel({
4161
+ onConnect,
4162
+ connecting
4163
+ }) {
4164
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Card, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_ui16.YStack, { gap: "$5", paddingVertical: "$6", alignItems: "center", children: [
4165
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { secondary: true, children: "Connect your wallet to buy AI credits" }),
4166
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
4167
+ import_ui16.CircularActionButton,
4168
+ {
4169
+ label: connecting ? "Connecting..." : "Connect Wallet",
4170
+ pending: connecting,
4171
+ disabled: connecting,
4172
+ onPress: () => {
4173
+ void onConnect();
4174
+ }
4175
+ }
4176
+ )
4177
+ ] }) });
4178
+ }
4179
+ function BuyCreditsPanel({ state, actions, isPending, onPay }) {
4180
+ let content;
4181
+ if (state.status === "unsupported_chain") {
4182
+ content = /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(AiCreditsStatusNotice, { children: [
4183
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.XStack, { gap: "$2", alignItems: "center", children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { color: "$warning", fontWeight: "700", children: "Wrong Network" }) }),
4184
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { secondary: true, children: "Please switch to the Celo network to continue." }),
4185
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
4186
+ import_ui16.Button,
4187
+ {
4188
+ onPress: () => {
4189
+ void actions.switchChain();
4190
+ },
4191
+ children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.ButtonText, { children: "Switch to Celo" })
4192
+ }
4193
+ )
4194
+ ] });
4195
+ } else if (state.status === "payment_failed") {
4196
+ content = /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
4197
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(AiCreditsStatusNotice, { children: [
4198
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { color: "$error", fontWeight: "700", children: "Payment Failed" }),
4199
+ state.error && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { secondary: true, children: state.error })
4200
+ ] }),
4201
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
4202
+ AiCreditsPurchaseFlow,
4203
+ {
4204
+ state,
4205
+ actions,
4206
+ isPending,
4207
+ onPay
4208
+ }
4209
+ )
4210
+ ] });
4211
+ } else if (state.status === "backend_unavailable") {
4212
+ content = /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(AiCreditsStatusNotice, { children: [
4213
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { color: "$warning", fontWeight: "700", children: "Service Unavailable" }),
4214
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { secondary: true, children: "The AI credits service is temporarily unavailable. Your wallet has not been charged." }),
4215
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
4216
+ import_ui16.Button,
4217
+ {
4218
+ onPress: () => {
4219
+ void actions.retry();
4220
+ },
4221
+ children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.ButtonText, { children: "Retry" })
4222
+ }
4223
+ )
4224
+ ] });
4225
+ } else if (state.status === "insufficient_g_balance") {
4226
+ content = /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
4227
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
4228
+ AiCreditsHero,
4229
+ {
4230
+ gBalance: state.gBalance,
4231
+ isGoodIdVerified: state.isGoodIdVerified
4232
+ }
4233
+ ),
4234
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(AiCreditsStatusNotice, { children: [
4235
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { color: "$warning", fontWeight: "700", children: "Insufficient G$ Balance" }),
4236
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { secondary: true, children: "You need at least 1 G$ to purchase AI credits. Top up your wallet and try again." })
4237
+ ] })
4238
+ ] });
4239
+ } else if (state.status === "payment_pending" || state.status === "payment_confirmed") {
4240
+ const message = state.status === "payment_pending" ? "Transaction submitted \u2014 waiting for confirmation\u2026" : "Payment confirmed \u2014 settling credits on Base\u2026";
4241
+ content = /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
4242
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Card, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_ui16.YStack, { gap: "$4", alignItems: "center", padding: "$4", children: [
4243
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Spinner, { size: "lg" }),
4244
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { center: true, secondary: true, children: message })
4245
+ ] }) }),
4246
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(AiCreditsFlowStepper, { state, buyerPubKeySaved: true })
4247
+ ] });
4248
+ } else {
4249
+ content = /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
4250
+ state.address && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
4251
+ AiCreditsHero,
4252
+ {
4253
+ gBalance: state.gBalance,
4254
+ isGoodIdVerified: state.isGoodIdVerified
4255
+ }
4256
+ ),
4257
+ state.error && /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(AiCreditsStatusNotice, { children: [
4258
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { color: "$error", fontWeight: "700", children: "Request Failed" }),
4259
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { secondary: true, children: state.error })
4260
+ ] }),
4261
+ state.gBalance !== null && Number.parseFloat(state.gBalance) <= 0 && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(AiCreditsStatusNotice, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { secondary: true, children: "You need G$ before you can buy AI credits." }) }),
4262
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
4263
+ AiCreditsPurchaseFlow,
4264
+ {
4265
+ state,
4266
+ actions,
4267
+ isPending,
4268
+ onPay
4269
+ }
4270
+ )
4271
+ ] });
4272
+ }
4273
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_ui16.YStack, { gap: "$4", children: [
4274
+ content,
4275
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(BuyCreditsFaq, {})
4276
+ ] });
4277
+ }
4278
+ function ManagePanel({
4279
+ state,
4280
+ actions
4281
+ }) {
4282
+ const [refreshing, setRefreshing] = import_react14.default.useState(false);
4283
+ const handleRefresh = async () => {
4284
+ setRefreshing(true);
4285
+ try {
4286
+ await actions.refresh();
4287
+ } finally {
4288
+ setRefreshing(false);
4289
+ }
4290
+ };
4291
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_ui16.YStack, { gap: "$3", width: "100%", children: [
4292
+ state.error && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(AiCreditsStatusNotice, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { color: "$error", fontSize: "$2", children: state.error }) }),
4293
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(CreditsManagementCard, { state, actions }),
4294
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(BuyerOperatorCard, { state, actions }),
4295
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(SetupSnippet, {}),
4296
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_ui16.YStack, { gap: "$2", width: "100%", alignItems: "center", children: [
4297
+ state.error && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Text, { color: "$error", fontSize: "$2", textAlign: "center", children: state.error }),
4298
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
4299
+ import_ui16.Button,
4300
+ {
4301
+ variant: "outline",
4302
+ size: "sm",
4303
+ alignSelf: "stretch",
4304
+ gap: "$2",
4305
+ disabled: refreshing,
4306
+ ...compactButtonProps,
4307
+ onPress: () => {
4308
+ void handleRefresh();
4309
+ },
4310
+ children: [
4311
+ refreshing ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Spinner, { size: "sm" }) : /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.Icon, { name: "refresh", size: "sm", color: "muted" }),
4312
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.ButtonText, { children: refreshing ? "Refreshing\u2026" : "Refresh Balance" })
4313
+ ]
4314
+ }
4315
+ )
4316
+ ] })
4317
+ ] });
4318
+ }
4319
+ function AiCreditsInner({
4320
+ environment,
4321
+ backendUrl,
4322
+ baseRpcUrl,
4323
+ celoRpcUrl,
4324
+ fundingVaultAddress,
4325
+ vaultAddress,
4326
+ goodIdAddress,
4327
+ adapterFactory,
4328
+ adapterOptions,
4329
+ onPaySuccess,
4330
+ onPayError
4331
+ }) {
4332
+ const defaultAdapter = useAiCreditsAdapter({
4333
+ environment,
4334
+ backendUrl,
4335
+ baseRpcUrl,
4336
+ celoRpcUrl,
4337
+ fundingVaultAddress,
4338
+ vaultAddress,
4339
+ goodIdAddress,
4340
+ onPaySuccess,
4341
+ onPayError,
4342
+ backendClient: adapterOptions?.backendClient,
4343
+ chainClient: adapterOptions?.chainClient,
4344
+ skipVaultPaymentValidation: adapterOptions?.skipVaultPaymentValidation,
4345
+ prepareSettlement: adapterOptions?.prepareSettlement
4346
+ });
4347
+ const activeAdapter = (0, import_react14.useMemo)(
4348
+ () => adapterFactory ? adapterFactory({ environment, backendUrl }) : defaultAdapter,
4349
+ [adapterFactory, environment, backendUrl, defaultAdapter]
4350
+ );
4351
+ const { state, actions } = activeAdapter;
4352
+ const history = useAiCreditsHistory({
4353
+ address: state.address,
4354
+ backendUrl,
4355
+ environment,
4356
+ backendClient: adapterOptions?.backendClient
4357
+ });
4358
+ const handlePay = (0, import_react14.useCallback)(
4359
+ async (quote) => {
4360
+ const toastId = (0, import_ui16.createToast)({
4361
+ message: "Submitting Celo transaction\u2026",
4362
+ status: "pending",
4363
+ duration: 0
4364
+ });
4365
+ try {
4366
+ await actions.pay(quote);
4367
+ (0, import_ui16.updateToast)(toastId, {
4368
+ message: "Credits added successfully!",
4369
+ status: "success",
4370
+ duration: 4e3
4371
+ });
4372
+ } catch (err) {
4373
+ (0, import_ui16.updateToast)(toastId, {
4374
+ message: err instanceof Error ? err.message : state.error ?? "Payment failed. Try again.",
4375
+ status: "error",
4376
+ duration: 4e3
4377
+ });
4378
+ }
4379
+ },
4380
+ [actions, state.error]
4381
+ );
4382
+ const isPending = state.status === "payment_pending" || state.status === "payment_confirmed";
4383
+ const handleTabChange = (0, import_react14.useCallback)(
4384
+ (tabId) => {
4385
+ actions.setActiveTab(tabId);
4386
+ },
4387
+ [actions]
4388
+ );
4389
+ const buyPanel = /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
4390
+ BuyCreditsPanel,
4391
+ {
4392
+ state,
4393
+ actions,
4394
+ isPending,
4395
+ onPay: (quote) => {
4396
+ void handlePay(quote);
4397
+ }
4398
+ }
4399
+ );
4400
+ if (state.status === "disconnected" || state.status === "connecting") {
4401
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.YStack, { gap: "$3", padding: "$3", width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(DisconnectedPanel, { onConnect: actions.connect, connecting: state.status === "connecting" }) });
4402
+ }
4403
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_ui16.YStack, { gap: "$3", padding: "$3", width: "100%", children: [
4404
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
4405
+ import_ui16.WidgetTabs,
4406
+ {
4407
+ tabs: [
4408
+ { id: "buy", label: "Buy Credits" },
4409
+ { id: "manage", label: "Manage" },
4410
+ { id: "history", label: "History" }
4411
+ ],
4412
+ activeTab: state.activeTab,
4413
+ onTabChange: handleTabChange,
4414
+ chainId: state.chainId ?? CELO_CHAIN_ID3
4415
+ }
4416
+ ),
4417
+ state.activeTab === "manage" ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(ManagePanel, { state, actions }) : state.activeTab === "history" ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(HistoryTab, { state: history.state, actions: history.actions }) : buyPanel
4418
+ ] });
4419
+ }
4420
+ function AiCreditsWidget({
4421
+ provider,
4422
+ connectOverride,
4423
+ environment = "production",
4424
+ backendUrl,
4425
+ baseRpcUrl,
4426
+ celoRpcUrl,
4427
+ fundingVaultAddress,
4428
+ vaultAddress,
4429
+ goodIdAddress,
4430
+ themeOverrides,
4431
+ config,
4432
+ defaultTheme = "dark",
4433
+ onPaySuccess,
4434
+ onPayError,
4435
+ adapterFactory,
4436
+ adapterOptions,
4437
+ testId
4438
+ }) {
4439
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
4440
+ import_core2.GoodWidgetProvider,
4441
+ {
4442
+ provider,
4443
+ connectOverride,
4444
+ config,
4445
+ themeOverrides,
4446
+ defaultTheme,
4447
+ children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_ui16.YStack, { backgroundColor: "$background", width: "100%", "data-testid": testId, children: [
4448
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
4449
+ AiCreditsInner,
4450
+ {
4451
+ environment,
4452
+ backendUrl,
4453
+ baseRpcUrl,
4454
+ celoRpcUrl,
4455
+ fundingVaultAddress,
4456
+ vaultAddress,
4457
+ goodIdAddress,
4458
+ adapterFactory,
4459
+ adapterOptions,
4460
+ onPaySuccess,
4461
+ onPayError
4462
+ }
4463
+ ),
4464
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_ui16.ToastContainer, {})
4465
+ ] })
4466
+ }
4467
+ );
4468
+ }
4469
+
4470
+ // src/mocked/chainClient.ts
4471
+ var mockOperatorAcceptedBuyers = /* @__PURE__ */ new Set();
4472
+ function normalizeAddress3(address) {
4473
+ return address.toLowerCase();
4474
+ }
4475
+ function markMockOperatorConsent(buyer) {
4476
+ mockOperatorAcceptedBuyers.add(normalizeAddress3(buyer));
4477
+ }
4478
+ var MockAiCreditsChainClient = class {
4479
+ operatorAccepted;
4480
+ gdUsdPerToken;
4481
+ goodIdVerified;
4482
+ constructor(options = {}) {
4483
+ this.operatorAccepted = options.operatorAccepted ?? false;
4484
+ this.gdUsdPerToken = options.gdUsdPerToken ?? 15e-4;
4485
+ this.goodIdVerified = options.goodIdVerified ?? false;
4486
+ }
4487
+ async isGoodIdVerified() {
4488
+ return this.goodIdVerified;
4489
+ }
4490
+ async fetchGdUsdPerToken() {
4491
+ return this.gdUsdPerToken;
4492
+ }
4493
+ async buildQuote(depositG, streamG) {
4494
+ return buildQuoteAmounts(depositG, streamG);
4495
+ }
4496
+ async getBuyerOperatorStatus(ref) {
4497
+ const payer = normalizeAddress3(ref.payer);
4498
+ const buyer = normalizeAddress3(ref.buyer);
4499
+ const operatorAddress = "0x0000000000000000000000000000000000000004";
4500
+ const operatorAccepted = this.operatorAccepted || mockOperatorAcceptedBuyers.has(buyer);
4501
+ return {
4502
+ enabled: true,
4503
+ account: payer,
4504
+ buyerAddress: buyer,
4505
+ operatorAddress,
4506
+ currentOperator: operatorAccepted ? operatorAddress : "0x0000000000000000000000000000000000000000",
4507
+ operatorAccepted,
4508
+ consentNonce: "0"
4509
+ };
4510
+ }
4511
+ async buildOperatorConsentPayload(ref, operatorStatus) {
4512
+ const status = operatorStatus ?? await this.getBuyerOperatorStatus(ref);
4513
+ if (!status.enabled || !status.operatorAddress) {
4514
+ return {
4515
+ enabled: false,
4516
+ account: normalizeAddress3(ref.payer),
4517
+ buyerAddress: normalizeAddress3(ref.buyer)
4518
+ };
4519
+ }
4520
+ return {
4521
+ enabled: true,
4522
+ account: normalizeAddress3(ref.payer),
4523
+ buyerAddress: normalizeAddress3(ref.buyer),
4524
+ typedData: buildSetOperatorPayload(
4525
+ BASE_CHAIN_ID,
4526
+ ANTSEED_DEPOSITS_BASE_ADDRESS,
4527
+ status.operatorAddress,
4528
+ BigInt(status.consentNonce),
4529
+ { name: "AntseedDeposits", version: "1" }
4530
+ )
4531
+ };
4532
+ }
4533
+ async getWithdrawableUsd() {
4534
+ return "0";
4535
+ }
4536
+ };
4537
+
4538
+ // src/mocked/backendClient.ts
4539
+ var MOCK_DELAY_MS = 600;
4540
+ var DEFAULT_HISTORY_LIMIT2 = 20;
4541
+ var MAX_HISTORY_LIMIT2 = 100;
4542
+ function sleep2(ms) {
4543
+ return new Promise((resolve) => setTimeout(resolve, ms));
4544
+ }
4545
+ function normalizeAddress4(address) {
4546
+ return address.toLowerCase();
4547
+ }
4548
+ function paginateGdCredits(entries, options = {}) {
4549
+ let result = [...entries].sort((a, b) => {
4550
+ const byCreated = b.createdAt.localeCompare(a.createdAt);
4551
+ return byCreated !== 0 ? byCreated : b.id.localeCompare(a.id);
4552
+ });
4553
+ if (options.source) result = result.filter((entry) => entry.source === options.source);
4554
+ if (options.fundingStatus) result = result.filter((entry) => entry.fundingStatus === options.fundingStatus);
4555
+ if (options.from) {
4556
+ const fromMs = Date.parse(options.from);
4557
+ result = result.filter((entry) => Date.parse(entry.createdAt) >= fromMs);
4558
+ }
4559
+ if (options.to) {
4560
+ const toMs = Date.parse(options.to);
4561
+ result = result.filter((entry) => Date.parse(entry.createdAt) <= toMs);
4562
+ }
4563
+ const limit = options.limit === void 0 ? DEFAULT_HISTORY_LIMIT2 : Math.min(Math.max(1, Math.floor(options.limit)), MAX_HISTORY_LIMIT2);
4564
+ const offset = Math.max(0, Math.floor(options.offset ?? 0));
4565
+ return {
4566
+ account: "",
4567
+ items: result.slice(offset, offset + limit),
4568
+ total: result.length,
4569
+ limit,
4570
+ offset,
4571
+ hasMore: offset + limit < result.length
4572
+ };
4573
+ }
4574
+ function createDemoHistory(account) {
4575
+ const normalized = normalizeAddress4(account);
4576
+ return [
4577
+ {
4578
+ id: "demo-deposit-1",
4579
+ account: normalized,
4580
+ rootAccount: normalized,
4581
+ source: "deposit",
4582
+ gdAmountWei: "440000000000000000000",
4583
+ totalCreditUsd: "6600",
4584
+ principalUsd: "6000",
4585
+ bonusUsd: "600",
4586
+ fundingStatus: "funded",
4587
+ txHash: "0xdemo01",
4588
+ logIndex: 0,
4589
+ createdAt: "2026-06-25T14:30:00.000Z",
4590
+ streamUpdateMonth: "2026-06",
4591
+ buyerAddress: normalized
4592
+ },
4593
+ {
4594
+ id: "demo-stream-update-1",
4595
+ account: normalized,
4596
+ rootAccount: normalized,
4597
+ source: "streamUpdate",
4598
+ gdAmountWei: "10000000000000000000",
4599
+ totalCreditUsd: "0",
4600
+ principalUsd: "0",
4601
+ bonusUsd: "0",
4602
+ fundingStatus: "funded",
4603
+ txHash: "0xdemo02",
4604
+ logIndex: 0,
4605
+ createdAt: "2026-06-24T12:00:00.000Z",
4606
+ streamUpdateMonth: "2026-06",
4607
+ buyerAddress: normalized
4608
+ },
4609
+ {
4610
+ id: "demo-stream-request-1",
4611
+ account: normalized,
4612
+ rootAccount: normalized,
4613
+ source: "streamRequest",
4614
+ gdAmountWei: "8000000000000000000",
4615
+ totalCreditUsd: "1200",
4616
+ principalUsd: "1000",
4617
+ bonusUsd: "200",
4618
+ fundingStatus: "pending",
4619
+ txHash: "0xdemo03",
4620
+ logIndex: 0,
4621
+ createdAt: "2026-06-23T09:15:00.000Z",
4622
+ streamUpdateMonth: "2026-06",
4623
+ buyerAddress: normalized
4624
+ },
4625
+ {
4626
+ id: "demo-stream-cron-1",
4627
+ account: normalized,
4628
+ rootAccount: normalized,
4629
+ source: "streamCron",
4630
+ gdAmountWei: "5000000000000000000",
4631
+ totalCreditUsd: "900",
4632
+ principalUsd: "750",
4633
+ bonusUsd: "150",
4634
+ fundingStatus: "funded",
4635
+ createdAt: "2026-06-22T08:00:00.000Z",
4636
+ streamUpdateMonth: "2026-06",
4637
+ buyerAddress: normalized
4638
+ }
4639
+ ];
4640
+ }
4641
+ var MockAiCreditsBackendClient = class {
4642
+ activeRef = null;
4643
+ lastCreditUsd = 0n;
4644
+ accountStates = /* @__PURE__ */ new Map();
4645
+ getState(payer) {
4646
+ const key = normalizeAddress4(payer);
4647
+ if (!this.accountStates.has(key)) {
4648
+ this.accountStates.set(key, {
4649
+ principalUsd: 0n,
4650
+ bonusUsd: 0n,
4651
+ transactions: createDemoHistory(key),
4652
+ rootAccount: key
4653
+ });
4654
+ }
4655
+ return this.accountStates.get(key);
4656
+ }
4657
+ async getDiscountConfig() {
4658
+ await sleep2(MOCK_DELAY_MS);
4659
+ return { ...DEFAULT_DISCOUNT_CONFIG };
4660
+ }
4661
+ buildProfile(payer) {
4662
+ const state = this.getState(payer);
4663
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4664
+ const outstanding = state.transactions.filter((entry) => entry.fundingStatus === "pending" || entry.fundingStatus === "failed").reduce((sum, entry) => sum + BigInt(entry.totalCreditUsd), 0n);
4665
+ return {
4666
+ account: normalizeAddress4(payer),
4667
+ rootAccount: state.rootAccount,
4668
+ createdAt: now,
4669
+ updatedAt: now,
4670
+ totalGdDepositedWei: "0",
4671
+ totalPrincipalUsd: state.principalUsd.toString(),
4672
+ totalBonusUsd: state.bonusUsd.toString(),
4673
+ totalGDStreamedWei: "0",
4674
+ totalOutstandingFundingUsd: outstanding.toString(),
4675
+ streamFlowRateWeiPerSecond: "0"
4676
+ };
4677
+ }
4678
+ async getAccountCredit(payer) {
4679
+ await sleep2(MOCK_DELAY_MS);
4680
+ const profile = this.buildProfile(payer);
4681
+ return { account: profile.account, profile };
4682
+ }
4683
+ async getCreditHistory(payer, options = {}) {
4684
+ await sleep2(MOCK_DELAY_MS);
4685
+ return { ...paginateGdCredits(this.getState(payer).transactions, options), account: normalizeAddress4(payer) };
4686
+ }
4687
+ async getOutstanding(payer) {
4688
+ await sleep2(MOCK_DELAY_MS);
4689
+ const pending = this.getState(payer).transactions.filter(
4690
+ (entry) => entry.fundingStatus === "pending" || entry.fundingStatus === "failed"
4691
+ );
4692
+ return {
4693
+ outstandingFundingUsd: pending.reduce((sum, entry) => sum + BigInt(entry.totalCreditUsd || "0"), 0n).toString(),
4694
+ count: pending.length
4695
+ };
4696
+ }
4697
+ async getTransactions(payer, options = {}) {
4698
+ const history = await this.getCreditHistory(payer, {
4699
+ fundingStatus: options.status,
4700
+ limit: options.limit,
4701
+ offset: options.cursor ? Number(options.cursor) || 0 : 0
4702
+ });
4703
+ return { account: history.account, transactions: history.items };
4704
+ }
4705
+ prepareSettlement(ref, creditUsd) {
4706
+ this.activeRef = { payer: normalizeAddress4(ref.payer), buyer: normalizeAddress4(ref.buyer) };
4707
+ this.lastCreditUsd = creditUsd;
4708
+ }
4709
+ async notifyPayment(txHash) {
4710
+ await sleep2(MOCK_DELAY_MS);
4711
+ const ref = this.activeRef;
4712
+ if (!ref) return { txHash, events: [] };
4713
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4714
+ const entry = {
4715
+ id: `${txHash}:0`,
4716
+ account: ref.payer,
4717
+ rootAccount: ref.payer,
4718
+ source: "deposit",
4719
+ gdAmountWei: "0",
4720
+ totalCreditUsd: this.lastCreditUsd.toString(),
4721
+ principalUsd: this.lastCreditUsd.toString(),
4722
+ bonusUsd: "0",
4723
+ fundingStatus: "pending",
4724
+ txHash,
4725
+ logIndex: 0,
4726
+ createdAt: now,
4727
+ streamUpdateMonth: now.slice(0, 7),
4728
+ buyerAddress: ref.buyer
4729
+ };
4730
+ const state = this.getState(ref.payer);
4731
+ if (!state.transactions.find((item) => item.id === entry.id)) state.transactions.unshift(entry);
4732
+ return { txHash, events: [entry] };
4733
+ }
4734
+ async waitForSettlement(ref) {
4735
+ await sleep2(MOCK_DELAY_MS);
4736
+ const state = this.getState(ref.payer);
4737
+ for (const entry of state.transactions) {
4738
+ if (entry.fundingStatus !== "pending") continue;
4739
+ entry.fundingStatus = "funded";
4740
+ state.principalUsd += BigInt(entry.principalUsd);
4741
+ state.bonusUsd += BigInt(entry.bonusUsd);
4742
+ }
4743
+ return { totalCreditUsd: totalCreditUsdFromProfile(this.buildProfile(ref.payer)) };
4744
+ }
4745
+ async closeChannel(channelId) {
4746
+ await sleep2(MOCK_DELAY_MS);
4747
+ return { channelId, action: "close", bridge: { enabled: true, txHash: "0xmock" } };
4748
+ }
4749
+ async withdrawCredits(buyer, body) {
4750
+ await sleep2(MOCK_DELAY_MS);
4751
+ return { account: buyer, amountUsd: body.amount, bridge: { enabled: true, txHash: "0xmock" } };
4752
+ }
4753
+ async submitOperatorConsent(buyer) {
4754
+ await sleep2(MOCK_DELAY_MS);
4755
+ const normalizedBuyer = normalizeAddress4(buyer);
4756
+ markMockOperatorConsent(normalizedBuyer);
4757
+ return { buyer: normalizedBuyer, bridge: { enabled: true, txHash: "0xmock" } };
4758
+ }
4759
+ };
4760
+
4761
+ // src/mocked/AiCreditsMockWidget.tsx
4762
+ var import_jsx_runtime15 = require("react/jsx-runtime");
4763
+ function MockAiCreditsWidget(props) {
4764
+ const backendClient = (0, import_react15.useMemo)(() => new MockAiCreditsBackendClient(), []);
4765
+ const chainClient = (0, import_react15.useMemo)(() => new MockAiCreditsChainClient(), []);
4766
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
4767
+ AiCreditsWidget,
4768
+ {
4769
+ ...props,
4770
+ environment: "development",
4771
+ adapterOptions: {
4772
+ backendClient,
4773
+ chainClient,
4774
+ skipVaultPaymentValidation: true,
4775
+ prepareSettlement: (ref, creditUsd) => backendClient.prepareSettlement(ref, creditUsd)
4776
+ }
4777
+ }
4778
+ );
4779
+ }
4780
+ // Annotate the CommonJS export names for ESM import in node:
4781
+ 0 && (module.exports = {
4782
+ MockAiCreditsBackendClient,
4783
+ MockAiCreditsChainClient,
4784
+ MockAiCreditsWidget
4785
+ });
4786
+ //# sourceMappingURL=index.cjs.map