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