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