/
CertificationForm.tsx
448 lines (425 loc) · 16.9 KB
/
CertificationForm.tsx
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
import { useState } from 'react'
import { Lock, Token } from '@unlock-protocol/types'
import { MetadataFormData } from '~/components/interface/locks/metadata/utils'
import { BsArrowLeft as ArrowBackIcon } from 'react-icons/bs'
import { FormProvider, useForm, useWatch } from 'react-hook-form'
import {
Button,
Disclosure,
Input,
TextBox,
ToggleSwitch,
ImageUpload,
Select,
} from '@unlock-protocol/ui'
import { useConfig } from '~/utils/withConfig'
import { useAuth } from '~/contexts/AuthenticationContext'
import { networkDescription } from '~/components/interface/locks/Create/elements/CreateLockForm'
import { SelectCurrencyModal } from '~/components/interface/locks/Create/modals/SelectCurrencyModal'
import { CryptoIcon } from '@unlock-protocol/crypto-icon'
import { useImageUpload } from '~/hooks/useImageUpload'
import { BalanceWarning } from '~/components/interface/locks/Create/elements/BalanceWarning'
import { NetworkWarning } from '~/components/interface/locks/Create/elements/NetworkWarning'
import { getAccountTokenBalance } from '~/hooks/useAccount'
import { Web3Service } from '@unlock-protocol/unlock-js'
import { useQuery } from '@tanstack/react-query'
import { useRouter } from 'next/router'
import { useAvailableNetworks } from '~/utils/networks'
// TODO replace with zod, but only once we have replaced Lock and MetadataFormData as well
export interface NewCertificationForm {
network: number
lock: Omit<Lock, 'address' | 'key'>
currencySymbol: string
unlimitedQuantity: boolean
metadata: Partial<MetadataFormData>
}
interface FormProps {
onSubmit: (data: NewCertificationForm) => void
}
export const CertificationForm = ({ onSubmit }: FormProps) => {
const { networks } = useConfig()
const { account } = useAuth()
const networkOptions = useAvailableNetworks()
const network = networkOptions[0]?.value
const [isFree, setIsFree] = useState(true)
const [unlimitedQuantity, setUnlimitedQuantity] = useState(true)
const [allowPurchase, setAllowPurchase] = useState(false)
const [forever, setForever] = useState(true)
const [isCurrencyModalOpen, setCurrencyModalOpen] = useState(false)
const { mutateAsync: uploadImage, isLoading: isUploading } = useImageUpload()
const router = useRouter()
const methods = useForm<NewCertificationForm>({
mode: 'onChange',
shouldUnregister: false,
defaultValues: {
network,
unlimitedQuantity: true,
lock: {
name: 'My Certification',
expirationDuration: undefined,
maxNumberOfKeys: undefined,
currencyContractAddress: null,
keyPrice: '0',
},
currencySymbol: networks[network!].nativeCurrency.symbol,
metadata: {
external_url: '',
description: 'This certification was created using Unlock Protocol.',
image: '',
certification: {
certification_issuer: 'My company',
},
},
},
})
const {
control,
register,
setValue,
formState: { errors },
watch,
} = methods
const details = useWatch({
control,
})
const DescDescription = () => (
<p>
Provide a description for the certification. This will be part of the NFT
metadata.{' '}
<a
className="text-brand-ui-primary hover:underline"
target="_blank"
rel="noopener noreferrer"
href="https://www.markdownguide.org/cheat-sheet"
>
Markdown is supported.
</a>
</p>
)
const { data: balance, isLoading: isLoadingBalance } = useQuery(
['getBalance', account, network],
async () => {
return await getAccountTokenBalance(Web3Service, account!, null, network!)
}
)
const noBalance = balance && parseFloat(balance) === 0 && !isLoadingBalance
const NetworkDescription = () => {
return (
<p>
This is the network on which your certification contract will be
deployed.{' '}
{details.network && <>{networkDescription(details.network)}</>}
</p>
)
}
const metadataImage = watch('metadata.image')
return (
<FormProvider {...methods}>
<div className="grid grid-cols-[50px_1fr_50px] items-center mb-4">
<Button variant="borderless" aria-label="arrow back">
<ArrowBackIcon
size={20}
className="cursor-pointer"
onClick={() => router.back()}
/>
</Button>
<h1 className="text-xl font-bold text-center text-brand-dark">
Creating Certification
</h1>
</div>
<form className="mb-6" onSubmit={methods.handleSubmit(onSubmit)}>
<div className="grid gap-6">
<Disclosure label="Basic Information" defaultOpen>
<p className="mb-5">
All of these fields can also be adjusted later.
</p>
<div className="grid grid-cols-2 gap-4">
<div>
<ImageUpload
description="This illustration will be used for the NFT certificate. Use 512 by 512 pixels for best results."
isUploading={isUploading}
preview={metadataImage!}
onChange={async (fileOrFileUrl: any) => {
if (typeof fileOrFileUrl === 'string') {
setValue('metadata.image', fileOrFileUrl)
} else {
const items = await uploadImage(fileOrFileUrl[0])
const image = items?.[0]?.publicUrl
if (!image) {
return
}
setValue('metadata.image', image)
}
}}
/>
</div>
<div className="grid gap-3">
<Input
{...register('lock.name', {
required: {
value: true,
message: 'Name is required',
},
})}
type="text"
placeholder="Name"
label="Certification name"
description={
'Enter the program or course name that was completed by the recipient of the certification.'
}
error={errors.lock?.name?.message}
/>
<TextBox
{...register('metadata.description', {
required: {
value: true,
message: 'Please add a description for your certificate',
},
})}
label="Description"
placeholder="Write description here."
description={<DescDescription />}
rows={4}
error={errors.metadata?.description?.message as string}
/>
<Input
{...register('metadata.certification.certification_issuer', {
required: {
value: true,
message: 'Please add an issuer name',
},
})}
label="Official name of the issuer"
description="This is part of NFT metadata."
error={
// @ts-expect-error Property 'certification_issuer' does not exist on type 'FieldError | Merge<FieldError, FieldErrorsImpl<any>>'.
errors.metadata?.certification?.certification_issuer
?.message as string
}
/>
<Input
{...register('metadata.external_url')}
label="External URL"
description="Include a link to the organization that performed the certification. This will be included in the NFT metadata."
error={errors.metadata?.external_url?.message as string}
/>
<div>
<div className="flex items-center justify-between">
<label className="px-1 mb-2 text-base" htmlFor="">
Certification duration (in days)
</label>
<ToggleSwitch
title="Forever"
enabled={forever}
setEnabled={setForever}
onChange={(enabled) => {
if (enabled) {
setValue('lock.expirationDuration', undefined as any)
}
}}
/>
</div>
<Input
disabled={forever}
type="number"
error={errors.lock?.expirationDuration?.message as string}
{...register('lock.expirationDuration', {
valueAsNumber: true,
required: {
value: !forever,
message: 'Please add a duration',
},
})}
/>
</div>
</div>
</div>
</Disclosure>
<Disclosure label="Network" defaultOpen>
<div className="grid gap-6">
<Select
onChange={(newValue) => {
setValue('network', Number(newValue))
setValue('lock.currencyContractAddress', null)
setValue(
'currencySymbol',
networks[newValue].nativeCurrency.symbol
)
}}
options={networkOptions}
label="Network"
defaultValue={network}
description={<NetworkDescription />}
/>
<NetworkWarning network={details.network} />
<div className="mb-4">
{noBalance && (
<BalanceWarning
network={details.network!}
balance={parseFloat(balance)}
/>
)}
</div>
</div>
</Disclosure>
<Disclosure label="Price & Quantity" defaultOpen>
<div className="grid gap-6">
<p>These settings can also be changed later.</p>
<div className="flex flex-col gap-0.5">
<div className="flex items-center justify-between">
<label className="px-1 mb-2 text-base">
Can certifications be purchased?
</label>
<ToggleSwitch
enabled={allowPurchase}
setEnabled={setAllowPurchase}
onChange={(enable: boolean) => {
if (!enable) {
setValue('lock.maxNumberOfKeys', 0, {
shouldValidate: true,
})
setValue('lock.keyPrice', '0', {
shouldValidate: true,
})
}
}}
/>
</div>
<span className="text-sm text-gray-600">
{`By default you certification can't be purchased.
If enabled, and there is enough capacity user can buy the certification.`}
</span>
</div>
{allowPurchase && (
<>
<div className="relative flex flex-col gap-4">
<div className="flex items-center justify-between">
<label className="px-1 mb-2 text-base" htmlFor="">
Currency & Price:
</label>
<ToggleSwitch
title="Free"
enabled={isFree}
setEnabled={setIsFree}
onChange={(enable: boolean) => {
if (enable) {
setValue('lock.keyPrice', '0', {
shouldValidate: true,
})
}
}}
/>
</div>
<div className="relative">
<SelectCurrencyModal
isOpen={isCurrencyModalOpen}
setIsOpen={setCurrencyModalOpen}
network={Number(details.network)}
onSelect={(token: Token) => {
setValue(
'lock.currencyContractAddress',
token.address
)
setValue('currencySymbol', token.symbol)
}}
/>
<div className="grid grid-cols-2 gap-2 justify-items-stretch">
<div className="flex flex-col gap-1.5">
<div
onClick={() => setCurrencyModalOpen(true)}
className="box-border flex items-center flex-1 w-full gap-2 pl-4 text-base text-left transition-all border border-gray-400 rounded-lg shadow-sm cursor-pointer hover:border-gray-500 focus:ring-gray-500 focus:border-gray-500 focus:outline-none"
>
<CryptoIcon symbol={details.currencySymbol!} />
<span>{details.currencySymbol}</span>
</div>
<div className="pl-1"></div>
</div>
<div className="relative">
<Input
type="number"
autoComplete="off"
placeholder="0.00"
min="0"
step="any"
disabled={isFree}
{...register('lock.keyPrice', {
valueAsNumber: true,
required: {
value: !isFree,
message: 'This value is required',
},
})}
/>
{errors?.lock?.keyPrice?.message && (
<span className="absolute -mb-4 text-sm text-red-500">
{errors?.lock?.keyPrice?.message}
</span>
)}
</div>
</div>
</div>
</div>
<div>
<div className="flex items-center justify-between">
<label className="px-1 mb-2 text-base" htmlFor="">
Number of certifications for sale
</label>
<ToggleSwitch
disabled={!allowPurchase}
title="Unlimited"
enabled={unlimitedQuantity}
setEnabled={setUnlimitedQuantity}
onChange={(enable: boolean) => {
if (enable) {
setValue('lock.maxNumberOfKeys', undefined)
}
setValue('unlimitedQuantity', enable)
}}
/>
</div>
<Input
{...register('lock.maxNumberOfKeys', {
valueAsNumber: true,
min: 0,
required: {
value: !unlimitedQuantity,
message: 'This value is required',
},
})}
disabled={unlimitedQuantity || !allowPurchase}
autoComplete="off"
step={1}
pattern="\d+"
type="number"
placeholder="Number of certifications for sale"
description={
'This is the maximum number of certifications available.'
}
error={errors?.lock?.maxNumberOfKeys?.message}
/>
</div>
</>
)}
</div>
</Disclosure>
<div className="flex flex-col justify-center gap-6">
{Object.keys(errors).length > 0 && (
<div className="px-2 text-red-600">
Please make sure you complete all the required fields.
</div>
)}
<Button
disabled={Object.keys(errors).length > 0}
className="w-full"
>
Save & Deploy
</Button>
<span className="text-base text-center">
You can always change any detail after the contract is deployed.
</span>
</div>
</div>
</form>
</FormProvider>
)
}