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