-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathpeers.$peerId.tsx
521 lines (498 loc) · 17.5 KB
/
peers.$peerId.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
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
import {
json,
type ActionFunctionArgs,
type LoaderFunctionArgs
} from '@remix-run/node'
import {
Form,
Outlet,
useActionData,
useFormAction,
useLoaderData,
useNavigation,
useSubmit
} from '@remix-run/react'
import { type FormEvent, useRef, useState } from 'react'
import { z } from 'zod'
import { DangerZone, PageHeader } from '~/components'
import {
ConfirmationDialog,
type ConfirmationDialogRef
} from '~/components/ConfirmationDialog'
import { Button, ErrorPanel, Input, PasswordInput } from '~/components/ui'
import { deletePeer, getPeer, updatePeer } from '~/lib/api/peer.server'
import { messageStorage, setMessageAndRedirect } from '~/lib/message.server'
import {
peerGeneralInfoSchema,
peerHttpInfoSchema,
uuidSchema
} from '~/lib/validate.server'
import type { ZodFieldErrors } from '~/shared/types'
import { formatAmount } from '~/shared/utils'
import { checkAuthAndRedirect } from '../lib/kratos_checks.server'
import { EditableTable } from '~/components/ui/EditableTable'
export async function loader({ request, params }: LoaderFunctionArgs) {
const cookies = request.headers.get('cookie')
await checkAuthAndRedirect(request.url, cookies)
const peerId = params.peerId
const result = z.string().uuid().safeParse(peerId)
if (!result.success) {
throw json(null, { status: 400, statusText: 'Invalid peer ID.' })
}
const peer = await getPeer({ id: result.data })
if (!peer) {
throw json(null, { status: 400, statusText: 'Peer not found.' })
}
return json({ peer })
}
export default function ViewPeerPage() {
const { peer } = useLoaderData<typeof loader>()
const response = useActionData<typeof action>()
const formAction = useFormAction()
const [formData, setFormData] = useState<FormData>()
const submit = useSubmit()
const navigation = useNavigation()
const dialogRef = useRef<ConfirmationDialogRef>(null)
const isSubmitting = navigation.state === 'submitting'
const currentPageAction = isSubmitting && navigation.formAction === formAction
const submitHandler = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()
setFormData(new FormData(event.currentTarget))
dialogRef.current?.display()
}
const onConfirm = () => {
if (formData) {
submit(formData, { method: 'post' })
}
}
return (
<div className='pt-4 flex flex-col space-y-4'>
<div className='flex flex-col rounded-md bg-offwhite px-6'>
{/* Peer General Info */}
<PageHeader>
<div>
{peer.name ? (
<h4>
Name:{' '}
<span className='text-sm sm:text-base font-semibold'>
{peer.name}
</span>
</h4>
) : null}
</div>
<Button aria-label='go back to peers page' to='/peers'>
Go to peers page
</Button>
</PageHeader>
<div className='grid grid-cols-1 py-3 gap-6 md:grid-cols-3 border-b border-pearl'>
{/* Peer General Info*/}
<div className='col-span-1 pt-3'>
<h3 className='text-lg font-medium'>General Information</h3>
<p className='text-sm'>
Created at {new Date(peer.createdAt).toLocaleString()}
</p>
<ErrorPanel errors={response?.errors.general.message} />
</div>
<div className='md:col-span-2 bg-white rounded-md shadow-md'>
<Form method='post' replace preventScrollReset>
<fieldset disabled={currentPageAction}>
<div className='w-full p-4 space-y-3'>
<Input type='hidden' name='id' value={peer.id} />
<Input
label='Peer ID'
value={peer.id}
placeholder='Peer ID'
disabled
readOnly
/>
<Input
name='name'
label='Name'
defaultValue={peer.name ?? ''}
placeholder='Peer name'
error={response?.errors.general.fieldErrors.name}
description={
<>
The name of the{' '}
<a
className='default-link'
href='https://rafiki.dev/concepts/interledger-protocol/peering/'
>
peer
</a>
.
</>
}
/>
<Input
name='staticIlpAddress'
label='Static ILP Address'
defaultValue={peer.staticIlpAddress}
placeholder='ILP Address'
required
error={
response?.errors.general.fieldErrors.staticIlpAddress
}
description={
<>
{"The peer's "}
<a
className='default-link'
href='https://interledger.org/developers/rfcs/ilp-addresses/'
>
address on the Interledger network.
</a>
</>
}
/>
<Input
type='number'
name='maxPacketAmount'
defaultValue={
peer.maxPacketAmount ? peer.maxPacketAmount : ''
}
label='Max Packet Amount'
placeholder='Max Packet Amount'
error={response?.errors.general.fieldErrors.maxPacketAmount}
description={
<>
The maximum amount of value that can be sent in a single{' '}
<a
className='default-link'
href='https://interledger.org/developers/rfcs/stream-protocol/#35-packets-and-frames'
>
Interledger STREAM Packet
</a>
.
</>
}
/>
</div>
<div className='flex justify-end p-4'>
<Button
aria-label='save general information'
type='submit'
name='intent'
value='general'
>
{currentPageAction ? 'Saving ...' : 'Save'}
</Button>
</div>
</fieldset>
</Form>
</div>
</div>
{/* Peer General Info - END */}
{/* Peer HTTP Info */}
<div className='grid grid-cols-1 py-3 gap-6 md:grid-cols-3 border-b border-pearl'>
<div className='col-span-1 pt-3'>
<h3 className='text-lg font-medium'>HTTP Information</h3>
<ErrorPanel errors={response?.errors.http.message} />
</div>
<div className='md:col-span-2 bg-white rounded-md shadow-md'>
<Form method='post' replace preventScrollReset>
<fieldset disabled={currentPageAction}>
<div className='w-full p-4 space-y-3'>
<Input type='hidden' name='id' value={peer.id} />
<EditableTable
name='incomingAuthTokens'
label='Incoming Auth Tokens'
options={(peer.incomingTokens || []).map((token) => ({
label: token,
value: token,
canDelete: true,
canEdit: true
}))}
error={response?.errors.http.fieldErrors.incomingAuthTokens}
description={
<>
List of valid tokens to accept when receiving{' '}
<a
className='default-link'
href='https://rafiki.dev/concepts/interledger-protocol/connector/#incoming-http'
>
incoming ILP packets from the peer.
</a>
</>
}
/>
<PasswordInput
name='outgoingAuthToken'
label='Outgoing Auth Token'
placeholder='Outgoing HTTP Auth Token'
required
defaultValue={peer.http.outgoing.authToken}
error={response?.errors.http.fieldErrors.outgoingAuthToken}
description={
<>
List of valid tokens to present when sending{' '}
<a
className='default-link'
href='https://rafiki.dev/concepts/interledger-protocol/connector/#outgoing-http'
>
outgoing ILP packets to the peer.
</a>
</>
}
/>
<Input
name='outgoingEndpoint'
label='Outgoing Endpoint'
placeholder='Outgoing HTTP Endpoint'
required
defaultValue={peer.http.outgoing.endpoint}
error={response?.errors.http.fieldErrors.outgoingEndpoint}
description={
<>
Endpoint on the peer to which{' '}
<a
className='default-link'
href='https://rafiki.dev/concepts/interledger-protocol/connector/#outgoing-http'
>
outgoing ILP packets
</a>{' '}
will be sent.
</>
}
/>
</div>
<div className='flex justify-end p-4'>
<Button
aria-label='save http information'
type='submit'
name='intent'
value='http'
>
{currentPageAction ? 'Saving ...' : 'Save'}
</Button>
</div>
</fieldset>
</Form>
</div>
</div>
{/* Peer HTTP Info - END */}
{/* Peer Asset Info */}
<div className='grid grid-cols-1 py-3 gap-6 md:grid-cols-3 border-b border-pearl'>
<div className='col-span-1 pt-3'>
<h3 className='text-lg font-medium'>Asset Information</h3>
</div>
<div className='md:col-span-2 bg-white rounded-md shadow-md'>
<div className='w-full p-4 gap-4 grid grid-cols-1 lg:grid-cols-3'>
<div>
<p className='font-medium'>Code</p>
<p className='mt-1'>{peer.asset.code}</p>
</div>
<div>
<p className='font-medium'>Scale</p>
<p className='mt-1'>{peer.asset.scale}</p>
</div>
<div>
<p className='font-medium'>Withdrawal threshold</p>
<p className='mt-1'>
{peer.asset.withdrawalThreshold ?? 'No withdrawal threshhold'}
</p>
</div>
</div>
<div className='flex justify-end p-4'>
<Button
aria-label='go to asset page'
type='button'
to={`/assets/${peer.asset.id}`}
>
View asset
</Button>
</div>
</div>
</div>
{/* Peer Asset Info - END */}
{/* Peer Liquidity Info */}
<div className='grid grid-cols-1 py-3 gap-6 md:grid-cols-3 border-b border-pearl'>
<div className='col-span-1 pt-3'>
<h3 className='text-lg font-medium'>Liquidity Information</h3>
</div>
<div className='md:col-span-2 bg-white rounded-md shadow-md'>
<div className='w-full p-4 flex justify-between items-center'>
<div>
<p className='font-medium'>Amount</p>
<p className='mt-1'>
{formatAmount(peer.liquidity ?? '0', peer.asset.scale)}{' '}
{peer.asset.code}
</p>
</div>
<div className='flex space-x-4'>
<Button
aria-label='deposit peer liquidity page'
preventScrollReset
type='button'
to={`/peers/${peer.id}/deposit-liquidity`}
>
Deposit liquidity
</Button>
<Button
aria-label='withdraw peer liquidity page'
preventScrollReset
type='button'
to={`/peers/${peer.id}/withdraw-liquidity`}
>
Withdraw liquidity
</Button>
</div>
</div>
</div>
</div>
{/* Peer Liquidity Info - END */}
{/* DELETE PEER - Danger zone */}
<DangerZone title='Delete Peer'>
<Form method='post' onSubmit={submitHandler}>
<Input type='hidden' name='id' value={peer.id} />
<Input type='hidden' name='intent' value='delete' />
<Button type='submit' intent='danger' aria-label='delete peer'>
Delete peer
</Button>
</Form>
</DangerZone>
</div>
<ConfirmationDialog
ref={dialogRef}
onConfirm={onConfirm}
title='Delete Peer'
keyword={peer.name || 'delete peer'}
confirmButtonText='Delete this peer'
/>
<Outlet />
</div>
)
}
export async function action({ request }: ActionFunctionArgs) {
const actionResponse: {
errors: {
general: {
fieldErrors: ZodFieldErrors<typeof peerGeneralInfoSchema>
message: string[]
}
http: {
fieldErrors: ZodFieldErrors<typeof peerHttpInfoSchema>
message: string[]
}
}
} = {
errors: {
general: {
fieldErrors: {},
message: []
},
http: {
fieldErrors: {},
message: []
}
}
}
const session = await messageStorage.getSession(request.headers.get('cookie'))
const formData = await request.formData()
const intent = formData.get('intent')
formData.delete('intent')
switch (intent) {
case 'general': {
const result = peerGeneralInfoSchema.safeParse(
Object.fromEntries(formData)
)
if (!result.success) {
actionResponse.errors.general.fieldErrors =
result.error.flatten().fieldErrors
return json({ ...actionResponse }, { status: 400 })
}
const response = await updatePeer({
...result.data,
...(result.data.maxPacketAmount
? { maxPacketAmount: result.data.maxPacketAmount }
: { maxPacketAmount: undefined })
})
if (!response?.peer) {
actionResponse.errors.general.message = [
'Could not update peer. Please try again!'
]
return json({ ...actionResponse }, { status: 400 })
}
break
}
case 'http': {
const formDataEntries = Object.fromEntries(formData)
const result = peerHttpInfoSchema.safeParse({
...formDataEntries,
incomingAuthTokens: formDataEntries.incomingAuthTokens
? formDataEntries.incomingAuthTokens.toString().split(',')
: []
})
if (!result.success) {
actionResponse.errors.http.fieldErrors =
result.error.flatten().fieldErrors
return json({ ...actionResponse }, { status: 400 })
}
const response = await updatePeer({
id: result.data.id,
http: {
...(result.data.incomingAuthTokens
? {
incoming: {
authTokens: result.data.incomingAuthTokens
}
}
: {}),
outgoing: {
endpoint: result.data.outgoingEndpoint,
authToken: result.data.outgoingAuthToken
}
}
})
if (!response?.peer) {
actionResponse.errors.general.message = [
'Could not update peer. Please try again!'
]
return json({ ...actionResponse }, { status: 400 })
}
break
}
case 'delete': {
const result = uuidSchema.safeParse(Object.fromEntries(formData))
if (!result.success) {
return setMessageAndRedirect({
session,
message: {
content: 'Invalid peer ID.',
type: 'error'
},
location: '.'
})
}
const response = await deletePeer({ input: { id: result.data.id } })
if (!response?.success) {
return setMessageAndRedirect({
session,
message: {
content: 'Could not delete peer.',
type: 'error'
},
location: '.'
})
}
return setMessageAndRedirect({
session,
message: {
content: 'Peer was deleted.',
type: 'success'
},
location: '/peers'
})
}
default:
throw json(null, { status: 400, statusText: 'Invalid intent.' })
}
return setMessageAndRedirect({
session,
message: {
content: 'Peer information was updated.',
type: 'success'
},
location: '.'
})
}