forked from Cookie-Jar-DAO/cookie-jar-v3
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseJarCreation.ts
More file actions
533 lines (466 loc) · 13 KB
/
useJarCreation.ts
File metadata and controls
533 lines (466 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { decodeEventLog, isAddress, parseEther } from "viem";
import {
useAccount,
useChainId,
useWaitForTransactionReceipt,
useWriteContract,
} from "wagmi";
import { contractAddresses, isV2Chain } from "@/config/supported-networks";
import { cookieJarFactoryAbi } from "@/generated";
import { cookieJarFactoryV1Abi } from "@/lib/blockchain/cookie-jar-v1-abi";
import { ETH_ADDRESS } from "@/lib/blockchain/token-utils";
import { useToast } from "../app/useToast";
import {
buildV2CreateCookieJarArgs,
getAccessConfigValidationError,
} from "./createV2CreateArgs";
import {
AccessType,
NFTType,
WithdrawalTypeOptions,
jarCreationSchema,
type JarCreationFormData,
type ProtocolConfig,
} from "./schemas/jarCreationSchema";
// Re-export for backward compatibility (used by StepContent, page, etc.)
export { AccessType, WithdrawalTypeOptions, NFTType };
export type { ProtocolConfig, JarCreationFormData };
/**
* Custom hook for Cookie Jar creation workflow.
*
* Manages form state via React Hook Form + Zod, contract interactions,
* transaction lifecycle, and step validation for the multi-step wizard.
*/
export const useJarCreation = () => {
const router = useRouter();
const { isConnected, address } = useAccount();
const chainId = useChainId();
const { toast } = useToast();
const queryClient = useQueryClient();
// ── Form state (replaces 30+ individual useState calls) ──
// Cast needed: @hookform/resolvers@3.3 types expect Zod 3.22 internals,
// but bun resolved to Zod 3.25 which has incompatible _parse signature.
// Runtime behavior is identical — this is purely a type-level conflict.
const form = useForm<JarCreationFormData>({
resolver: zodResolver(jarCreationSchema as any),
defaultValues: {
jarName: "",
jarOwnerAddress: "0x0000000000000000000000000000000000000000",
supportedCurrency: ETH_ADDRESS,
metadata: "",
imageUrl: "",
externalLink: "",
showCustomCurrency: false,
customCurrencyAddress: "",
withdrawalOption: WithdrawalTypeOptions.Fixed,
fixedAmount: "0",
maxWithdrawal: "0",
withdrawalInterval: "0",
strictPurpose: true,
emergencyWithdrawalEnabled: true,
oneTimeWithdrawal: false,
accessType: AccessType.Allowlist,
nftAddresses: [],
nftTypes: [],
protocolConfig: { accessType: "Allowlist" },
enableCustomFee: false,
customFee: "",
streamingEnabled: false,
requireStreamApproval: true,
maxStreamRate: "1.0",
minStreamDuration: "1",
autoSwapEnabled: false,
},
mode: "onTouched",
});
// ── Non-form state ──
const [isFormError, setIsFormError] = useState(false);
const [formErrors, setFormErrors] = useState<string[]>([]);
const [_isCreating, setIsCreating] = useState(false);
const [newJarPreview, setNewJarPreview] = useState<{
address: string;
name: string;
currency: string;
} | null>(null);
// ── Contract interaction ──
const {
writeContract,
data: hash,
error: createError,
isPending,
} = useWriteContract();
const {
isLoading: isWaitingForTx,
isSuccess: txConfirmed,
data: receipt,
} = useWaitForTransactionReceipt({ hash });
const factoryAddress = contractAddresses.cookieJarFactory[chainId] as
| `0x${string}`
| undefined;
const isV2Contract = isV2Chain(chainId);
// ── Helpers ──
const parseAmount = (amount: string) => {
try {
return parseEther(amount || "0");
} catch {
return parseEther("0");
}
};
// ── Step validation ──
// These read from form.getValues() instead of individual state variables.
// Cross-field conditional logic stays here because Zod can't handle
// cross-step superRefine with RHF's trigger().
const validateStep1 = useCallback((): {
isValid: boolean;
errors: string[];
} => {
const {
jarName,
jarOwnerAddress,
supportedCurrency,
showCustomCurrency,
customCurrencyAddress,
} = form.getValues();
const errors: string[] = [];
if (!jarName.trim()) {
errors.push("Jar name is required");
}
if (jarOwnerAddress && !isAddress(jarOwnerAddress)) {
errors.push("Jar owner address must be a valid Ethereum address");
}
if (!isAddress(supportedCurrency)) {
if (showCustomCurrency && customCurrencyAddress) {
if (!isAddress(customCurrencyAddress)) {
errors.push("Custom currency must be a valid contract address");
}
} else if (supportedCurrency !== ETH_ADDRESS) {
errors.push("Valid currency address is required");
}
}
return { isValid: errors.length === 0, errors };
}, [form]);
const validateStep2 = useCallback((): {
isValid: boolean;
errors: string[];
} => {
const { withdrawalOption, fixedAmount, maxWithdrawal, withdrawalInterval } =
form.getValues();
const errors: string[] = [];
if (withdrawalOption === WithdrawalTypeOptions.Fixed) {
if (!fixedAmount || parseFloat(fixedAmount) <= 0) {
errors.push("Fixed withdrawal amount must be greater than 0");
}
} else {
if (!maxWithdrawal || parseFloat(maxWithdrawal) <= 0) {
errors.push("Maximum withdrawal amount must be greater than 0");
}
}
if (!withdrawalInterval || parseInt(withdrawalInterval, 10) <= 0) {
errors.push("Withdrawal interval must be greater than 0 days");
}
return { isValid: errors.length === 0, errors };
}, [form]);
const validateStep3 = useCallback((): {
isValid: boolean;
errors: string[];
} => {
const values = form.getValues();
const { accessType, nftAddresses } = values;
const errors: string[] = [];
if (accessType === AccessType.NFTGated) {
if (nftAddresses.length === 0) {
errors.push(
"At least one NFT address is required for NFT-gated access",
);
}
for (const addr of nftAddresses) {
if (!isAddress(addr)) {
errors.push(`NFT address is not a valid Ethereum address`);
break;
}
}
}
const accessValidationError = getAccessConfigValidationError(values);
if (accessValidationError) {
errors.push(accessValidationError);
}
return { isValid: errors.length === 0, errors };
}, [form]);
const validateStep4 = useCallback((): {
isValid: boolean;
errors: string[];
} => {
const { enableCustomFee, customFee } = form.getValues();
const errors: string[] = [];
if (enableCustomFee) {
if (
!customFee ||
parseFloat(customFee) < 0 ||
parseFloat(customFee) > 100
) {
errors.push("Custom fee must be between 0 and 100 percent");
}
}
return { isValid: errors.length === 0, errors };
}, [form]);
const validateAll = useCallback((): {
isValid: boolean;
errors: string[];
} => {
const step1 = validateStep1();
const step2 = validateStep2();
const step3 = validateStep3();
const step4 = validateStep4();
const allErrors = [
...step1.errors,
...step2.errors,
...step3.errors,
...step4.errors,
];
return { isValid: allErrors.length === 0, errors: allErrors };
}, [validateStep1, validateStep2, validateStep3, validateStep4]);
// ── Form submission ──
const confirmSubmit = useCallback(() => {
const values = form.getValues();
const { isValid, errors } = validateAll();
if (!isValid) {
setFormErrors(errors);
setIsFormError(true);
return;
}
setFormErrors([]);
setIsFormError(false);
const effectiveNftAddresses =
values.accessType === AccessType.NFTGated ? values.nftAddresses : [];
const effectiveNftTypes =
values.accessType === AccessType.NFTGated ? values.nftTypes : [];
const finalMetadata = isV2Contract
? JSON.stringify({
version: "2.0",
name: values.jarName,
description: values.metadata,
image: values.imageUrl,
external_url: values.externalLink,
})
: values.jarName || values.metadata || "Cookie Jar";
try {
if (!factoryAddress) {
throw new Error(
`No contract address found for the current network (Chain ID: ${chainId}). Please switch to a supported network.`,
);
}
if (isV2Contract) {
const args = buildV2CreateCookieJarArgs({
values: {
...values,
nftAddresses: effectiveNftAddresses,
nftTypes: effectiveNftTypes,
},
metadata: finalMetadata,
parseAmount,
});
writeContract({
address: factoryAddress,
abi: cookieJarFactoryAbi,
functionName: "createCookieJar",
args,
});
} else {
writeContract({
address: factoryAddress,
abi: cookieJarFactoryV1Abi,
functionName: "createCookieJar",
args: [
values.jarOwnerAddress as `0x${string}`,
values.supportedCurrency as `0x${string}`,
values.accessType,
effectiveNftAddresses as readonly `0x${string}`[],
effectiveNftTypes,
values.withdrawalOption,
parseAmount(values.fixedAmount),
parseAmount(values.maxWithdrawal),
BigInt(values.withdrawalInterval || "0"),
values.strictPurpose,
values.emergencyWithdrawalEnabled,
values.oneTimeWithdrawal,
[] as readonly `0x${string}`[],
finalMetadata,
],
});
}
setIsCreating(true);
} catch (error) {
console.error("Error creating jar:", error);
toast({
title: "Transaction Failed",
description:
error instanceof Error
? error.message
: "An unknown error occurred",
variant: "destructive",
});
}
}, [
form,
validateAll,
isV2Contract,
factoryAddress,
chainId,
writeContract,
toast,
]);
// ── Confetti ──
const triggerConfetti = async () => {
try {
const confettiModule = await import("canvas-confetti");
const confetti = confettiModule.default;
confetti({
particleCount: 100,
spread: 70,
origin: { y: 0.6 },
});
} catch (error) {
console.log("Confetti animation failed:", error);
}
};
// ── Effects ──
// Handle successful transaction
useEffect(() => {
if (txConfirmed && receipt) {
const values = form.getValues();
queryClient.invalidateQueries({
queryKey: ["cookie-jar-factory", chainId, factoryAddress],
});
toast({
title: "Cookie Jar Created!",
description:
"Your new jar has been deployed successfully. Visit /jars to see it in the list!",
});
triggerConfetti();
try {
let jarAddress: string | null = null;
if (receipt.logs && receipt.logs.length > 0) {
for (const log of receipt.logs) {
try {
const eventName = isV2Contract
? ("JarCreated" as const)
: ("CookieJarCreated" as const);
const decodedLog = decodeEventLog({
abi: isV2Contract
? cookieJarFactoryAbi
: cookieJarFactoryV1Abi,
data: log.data,
topics: log.topics,
eventName,
});
if (decodedLog.eventName === "JarCreated") {
jarAddress = (decodedLog.args as any)?.jarAddress;
break;
}
if (decodedLog.eventName === "CookieJarCreated") {
jarAddress = (decodedLog.args as any)?.cookieJarAddress;
break;
}
} catch {
// Log is not the expected jar-created event, checking next
}
}
}
if (jarAddress && isAddress(jarAddress)) {
setNewJarPreview({
address: jarAddress,
name: values.jarName || "New Cookie Jar",
currency: values.supportedCurrency,
});
setTimeout(() => {
router.push(`/jar/${jarAddress}`);
}, 1000);
setIsCreating(false);
form.reset();
return;
}
setTimeout(() => {
router.push("/jars");
}, 500);
} catch (error) {
console.error("Error extracting jar address:", error);
setTimeout(() => {
router.push("/jars");
}, 500);
}
setIsCreating(false);
form.reset();
}
}, [
txConfirmed,
receipt,
router,
isV2Contract,
toast,
form,
queryClient,
chainId,
factoryAddress,
]);
// Handle transaction error
useEffect(() => {
if (createError) {
console.error("Transaction error:", createError);
toast({
title: "Transaction Failed",
description: createError.message || "Failed to create cookie jar",
variant: "destructive",
});
setIsCreating(false);
setIsFormError(true);
}
}, [createError, toast]);
// Sync wallet address to form
useEffect(() => {
if (isConnected && address) {
form.setValue("jarOwnerAddress", address);
}
}, [isConnected, address, form]);
// Reset v2-only fields when switching to v1 chain
useEffect(() => {
if (!isV2Contract) {
form.setValue("accessType", AccessType.Allowlist);
form.setValue("enableCustomFee", false);
form.setValue("customFee", "");
}
}, [isV2Contract, form]);
return {
// RHF form instance — wrap in <FormProvider {...form}>
form,
// Transaction state
isCreating: isPending,
isWaitingForTx,
txConfirmed,
receipt,
createError,
// Error state
isFormError,
formErrors,
// Preview
newJarPreview,
// Actions
confirmSubmit,
resetForm: () => form.reset(),
// Per-step validation
validateStep1,
validateStep2,
validateStep3,
validateStep4,
validateAll,
// Constants
ETH_ADDRESS,
factoryAddress,
isV2Contract,
};
};