-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathRegistration.tsx
More file actions
425 lines (388 loc) · 13.9 KB
/
Copy pathRegistration.tsx
File metadata and controls
425 lines (388 loc) · 13.9 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
import Head from 'next/head'
import { useCallback, useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import styled, { css } from 'styled-components'
import { match, P } from 'ts-pattern'
import { useAccount, useChainId } from 'wagmi'
import { Dialog, Helper, Typography } from '@ensdomains/thorin'
import { BaseLinkWithHistory } from '@app/components/@atoms/BaseLink'
import { InnerDialog } from '@app/components/@atoms/InnerDialog'
import { ProfileRecord } from '@app/constants/profileRecordOptions'
import { useContractAddress } from '@app/hooks/chain/useContractAddress'
import { hasValidPrimaryName } from '@app/hooks/ensjs/public/primaryNameUtils'
import { usePrimaryName } from '@app/hooks/ensjs/public/usePrimaryName'
import { useIsEthRegistrarControllerActive } from '@app/hooks/registration/useIsEthRegistrarControllerActive'
import { useNameDetails } from '@app/hooks/useNameDetails'
import { useReferrer } from '@app/hooks/useReferrer'
import useRegistrationReducer from '@app/hooks/useRegistrationReducer'
import { useResolverExists } from '@app/hooks/useResolverExists'
import { useRouterWithHistory } from '@app/hooks/useRouterWithHistory'
import { Content } from '@app/layouts/Content'
import { useTransactionFlow } from '@app/transaction-flow/TransactionFlowProvider'
import { sendEvent } from '@app/utils/analytics/events'
import { getReferrerHex } from '@app/utils/referrer'
import { isLabelTooLong, secondsToYears } from '@app/utils/utils'
import RegistrationDisabledBanner from './RegistrationDisabledBanner'
import Complete from './steps/Complete'
import Info from './steps/Info'
import Pricing from './steps/Pricing/Pricing'
import Profile from './steps/Profile/Profile'
import Transactions from './steps/Transactions'
import { BackObj, PaymentMethod, RegistrationStepData } from './types'
import { useMoonpayRegistration } from './useMoonpayRegistration'
const ViewProfileContainer = styled.div(
({ theme }) => css`
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-end;
margin-bottom: -${theme.space['3']};
padding: 0 ${theme.space['4']};
& > a {
transition: all 0.15s ease-in-out;
&:hover {
filter: brightness(1.05);
transform: translateY(-1px);
}
}
@media (min-width: ${theme.breakpoints.sm}px) {
margin-bottom: 0;
padding: 0;
}
`,
)
type Props = {
nameDetails: ReturnType<typeof useNameDetails>
isLoading: boolean
}
const StyledInnerDialog = styled(InnerDialog)(
({ theme }) => css`
height: 85vh;
max-height: 85vh;
margin: -${theme.space['4']};
width: calc(100% + 2 * ${theme.space['4']});
gap: 0;
overflow: hidden;
border-top-left-radius: ${theme.radii['3xLarge']};
border-top-right-radius: ${theme.radii['3xLarge']};
@media (min-width: ${theme.breakpoints.sm}px) {
height: 90vh;
max-height: 720px;
width: calc(80vw - 2 * ${theme.space['6']});
max-width: ${theme.space['128']};
margin: -${theme.space['6']};
border-bottom-left-radius: ${theme.radii['3xLarge']};
border-bottom-right-radius: ${theme.radii['3xLarge']};
}
`,
)
const MoonPayHeader = styled.div(
({ theme }) => css`
width: 100%;
background-color: ${theme.colors.greySurface};
color: ${theme.colors.greyPrimary};
padding: ${theme.space['4']};
`,
)
const MoonPayIFrame = styled.iframe(
({ theme }) => css`
max-width: 590px; /* Prevent moonpay iframe from going into modal mode */
padding: ${theme.space['2']};
background-color: #fff;
@media (prefers-color-scheme: dark) {
background-color: #1c1c1e;
}
`,
)
const Registration = ({ nameDetails, isLoading }: Props) => {
const { t } = useTranslation('register')
const router = useRouterWithHistory()
const chainId = useChainId()
const { address } = useAccount()
const primary = usePrimaryName({ address })
const referrer = useReferrer()
const referrerHex = getReferrerHex(referrer)
const selected = useMemo(
() => ({ name: nameDetails.normalisedName, address: address!, chainId, referrer: referrerHex }),
[address, chainId, nameDetails.normalisedName, referrerHex],
)
const { normalisedName, beautifiedName = '' } = nameDetails
const defaultResolverAddress = useContractAddress({ contract: 'ensPublicResolver' })
const { data: resolverExists, isLoading: resolverExistsLoading } = useResolverExists({
address: defaultResolverAddress,
name: normalisedName,
})
const { data: isControllerActive, isLoading: isControllerActiveLoading } =
useIsEthRegistrarControllerActive()
const isRegistrationDisabled = isControllerActive === false
const labelTooLong = isLabelTooLong(normalisedName)
const { dispatch, item } = useRegistrationReducer(selected)
const step = item.queue[item.stepIndex]
const keySuffix = `${nameDetails.normalisedName}-${address}`
const commitKey = `commit-${keySuffix}`
const registerKey = `register-${keySuffix}`
const { cleanupFlow } = useTransactionFlow()
const {
moonpayUrl,
initiateMoonpayRegistrationMutation,
hasMoonpayModal,
setHasMoonpayModal,
moonpayTransactionStatus,
} = useMoonpayRegistration(dispatch, normalisedName, selected, item)
const pricingCallback = ({
seconds,
reverseRecord,
paymentMethodChoice,
estimatedTotal,
ethPrice,
durationType,
}: RegistrationStepData['pricing']) => {
sendEvent('register:pricing', {
// eslint-disable-next-line @typescript-eslint/naming-convention
ens_name: normalisedName,
duration: seconds,
// eslint-disable-next-line @typescript-eslint/naming-convention
estimated_total: estimatedTotal ?? 0n,
// eslint-disable-next-line @typescript-eslint/naming-convention
eth_price: ethPrice ?? 0n,
// eslint-disable-next-line @typescript-eslint/naming-convention
payment_method: paymentMethodChoice,
// eslint-disable-next-line @typescript-eslint/naming-convention
add_reverse_record: reverseRecord,
})
if (paymentMethodChoice === PaymentMethod.moonpay) {
initiateMoonpayRegistrationMutation.mutate(secondsToYears(seconds))
return
}
dispatch({
name: 'setPricingData',
payload: { seconds, reverseRecord, durationType },
selected,
})
dispatch({
name: 'setReferrer',
payload: referrerHex,
selected,
})
if (!item.queue.includes('profile')) {
// if profile is not in queue, set the default profile data
dispatch({
name: 'setProfileData',
payload: {
records: [{ key: 'eth', group: 'address', type: 'addr', value: address! }],
clearRecords: resolverExists,
resolverAddress: defaultResolverAddress,
},
selected,
})
if (reverseRecord) {
// if reverse record is selected, add the profile step to the queue
dispatch({
name: 'setQueue',
payload: ['pricing', 'profile', 'info', 'transactions', 'complete'],
selected,
})
}
}
// If profile is in queue and reverse record is selected, make sure that eth record is included and is set to address
if (item.queue.includes('profile') && reverseRecord) {
const recordsWithoutEth = item.records.filter((record) => record.key !== 'eth')
const newRecords: ProfileRecord[] = [
{ key: 'eth', group: 'address', type: 'addr', value: address! },
...recordsWithoutEth,
]
dispatch({ name: 'setProfileData', payload: { records: newRecords }, selected })
}
dispatch({ name: 'increaseStep', selected })
}
const profileCallback = ({
records,
resolverAddress,
back,
}: RegistrationStepData['profile'] & BackObj) => {
if (!back) {
sendEvent('register:profile', {
// eslint-disable-next-line @typescript-eslint/naming-convention
ens_name: normalisedName,
// eslint-disable-next-line @typescript-eslint/naming-convention
profile_records: records,
// eslint-disable-next-line @typescript-eslint/naming-convention
resolver_address: resolverAddress,
})
}
dispatch({ name: 'setProfileData', payload: { records, resolverAddress }, selected })
dispatch({ name: back ? 'decreaseStep' : 'increaseStep', selected })
}
const genericCallback = ({ back }: BackObj) => {
dispatch({ name: back ? 'decreaseStep' : 'increaseStep', selected })
}
const infoCallback = ({ back }: BackObj) => {
if (!back) {
sendEvent('register:info', {
// eslint-disable-next-line @typescript-eslint/naming-convention
ens_name: normalisedName,
})
}
genericCallback({ back })
}
const transactionsCallback = useCallback(
({ back, resetSecret }: BackObj & { resetSecret?: boolean }) => {
if (resetSecret) {
dispatch({ name: 'resetSecret', selected })
}
genericCallback({ back })
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[selected],
)
const infoProfileCallback = () => {
sendEvent('register:back', {
// eslint-disable-next-line @typescript-eslint/naming-convention
ens_name: normalisedName,
// eslint-disable-next-line @typescript-eslint/naming-convention
from_step: 'info',
// eslint-disable-next-line @typescript-eslint/naming-convention
to_step: 'profile',
})
dispatch({
name: 'setQueue',
payload: ['pricing', 'profile', 'info', 'transactions', 'complete'],
selected,
})
}
/**
* This is called when the user starts the commit transaction
*/
const onStart = () => {
dispatch({ name: 'setStarted', selected })
}
const onComplete = (toProfile: boolean) => {
router.push(toProfile ? `/profile/${normalisedName}` : '/')
}
useEffect(() => {
const handleRouteChange = (e: string) => {
if (e !== router.asPath && step === 'complete') {
dispatch({ name: 'clearItem', selected })
cleanupFlow(commitKey)
cleanupFlow(registerKey)
}
}
router.events.on('routeChangeComplete', handleRouteChange)
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dispatch, step, selected, router.asPath])
const onDismissMoonpayModal = () => {
if (moonpayTransactionStatus === 'waitingAuthorization') {
return
}
setHasMoonpayModal(false)
}
return (
<>
<Head>
<title>{t('title', { name: beautifiedName })}</title>
</Head>
<Content
noTitle
title={beautifiedName}
hideHeading={step === 'complete'}
loading={
labelTooLong
? false
: isLoading || primary.isLoading || resolverExistsLoading || isControllerActiveLoading
}
singleColumnContent
inlineHeading
>
{{
header: nameDetails.expiryDate && (
<ViewProfileContainer>
<BaseLinkWithHistory href={`/expired-profile/${normalisedName}`} passHref>
<a>
<Typography color="accent" weight="bold">
{t('wallet.viewProfile', { ns: 'common' })}
</Typography>
</a>
</BaseLinkWithHistory>
</ViewProfileContainer>
),
trailing: match([labelTooLong, isRegistrationDisabled, step])
.with([true, P._, P._], () => <Helper alert="error">{t('error.nameTooLong')}</Helper>)
.with([false, true, P._], () => <RegistrationDisabledBanner name={normalisedName} />)
.with([false, false, 'pricing'], () => (
<Pricing
name={normalisedName}
beautifiedName={beautifiedName}
gracePeriodEndDate={nameDetails.gracePeriodEndDate}
resolverExists={resolverExists}
callback={pricingCallback}
isPrimaryLoading={primary.isLoading}
hasPrimaryName={hasValidPrimaryName(primary.data)}
registrationData={item}
moonpayTransactionStatus={moonpayTransactionStatus}
initiateMoonpayRegistrationMutation={initiateMoonpayRegistrationMutation}
/>
))
.with([false, false, 'profile'], () => (
<Profile
name={normalisedName}
resolverExists={resolverExists}
registrationData={item}
callback={profileCallback}
/>
))
.with([false, false, 'info'], () => (
<Info
name={normalisedName}
registrationData={item}
callback={infoCallback}
onProfileClick={infoProfileCallback}
/>
))
.with([false, false, 'transactions'], () => (
<Transactions
name={normalisedName}
registrationData={item}
onStart={onStart}
callback={transactionsCallback}
/>
))
.with([false, false, 'complete'], () => (
<Complete
name={normalisedName}
beautifiedName={beautifiedName}
callback={onComplete}
registrationData={item}
isMoonpayFlow={item.isMoonpayFlow}
/>
))
.exhaustive(),
}}
</Content>
<Dialog
open={hasMoonpayModal}
variant="blank"
onDismiss={onDismissMoonpayModal}
onClose={onDismissMoonpayModal}
>
<StyledInnerDialog>
<MoonPayHeader>
<Typography fontVariant="bodyBold" color="grey">
{t('steps.info.moonpayModalHeader')}
</Typography>
</MoonPayHeader>
<MoonPayIFrame
title="Moonpay Checkout"
width="100%"
height="100%"
src={moonpayUrl}
id="moonpayIframe"
/>
</StyledInnerDialog>
</Dialog>
</>
)
}
export default Registration