-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathform.tsx
More file actions
221 lines (197 loc) · 7.54 KB
/
form.tsx
File metadata and controls
221 lines (197 loc) · 7.54 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
'use client'
import * as React from 'react'
import { Label } from '@/components/ui/label'
import { EXAMPLE_TXS, INTERPRETER_REPO } from '@/app/data'
import { useLocalStorage } from 'usehooks-ts'
import { PlayIcon } from '@radix-ui/react-icons'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { useRouter } from 'next/navigation'
import { DecodedTransaction } from '@3loop/transaction-decoder'
import type { Interpretation } from '@/lib/interpreter-server'
import CodeBlock from '@/components/ui/code-block'
import { NetworkSelect } from '@/components/ui/network-select'
import { fallbackInterpreter, getInterpreter } from '@3loop/transaction-interpreter'
import { ExampleTransactions } from '@/components/ui/examples'
interface FormProps {
chainID: number
decoded?: DecodedTransaction
currentHash?: string
error?: string
}
const PATH = 'interpret'
export default function DecodingForm({ decoded, currentHash, chainID, error }: FormProps) {
const [result, setResult] = React.useState<Interpretation>()
const [persistedSchema, setSchema] = useLocalStorage(decoded?.toAddress ?? 'unknown', '')
const [isInterpreting, setIsInterpreting] = React.useState(false)
const [userAddress, setUserAddress] = React.useState<string>('')
const matchingExample = React.useMemo(() => {
return Object.values(EXAMPLE_TXS)
.flatMap((categoryTxs) => categoryTxs)
.find((tx) => tx.hash.toLowerCase() === currentHash?.toLowerCase())
}, [currentHash])
const schema = React.useMemo(() => {
if (persistedSchema !== '') return persistedSchema
if (decoded?.toAddress == null) return null
const schema = getInterpreter(decoded)
if (schema != null) return schema
return fallbackInterpreter
}, [decoded, persistedSchema])
const router = useRouter()
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
const hash = (e.target as any).hash.value
router.push(`/${PATH}/${chainID}/${hash}`)
}
const onRun = React.useCallback(() => {
if (schema && decoded != null) {
const newInterpreter = {
id: decoded.toAddress ?? 'unknown',
schema: schema,
}
setIsInterpreting(true)
setResult(undefined)
// Call server-side API to run interpreter (avoids CORS issues)
fetch('/api/interpret', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
decodedTx: decoded,
interpreter: newInterpreter,
interpretAsUserAddress: userAddress || undefined,
}),
})
.then((response) => response.json())
.then((res) => {
setResult(res)
})
.catch((error) => {
setResult({
tx: decoded,
interpretation: null,
error: error.message || 'Failed to interpret transaction',
})
})
.finally(() => {
setIsInterpreting(false)
})
}
}, [schema, decoded, userAddress])
// Set user address from example if available
React.useEffect(() => {
if (matchingExample && (matchingExample as any).interpretAsUserAddress) {
setUserAddress((matchingExample as any).interpretAsUserAddress)
}
}, [matchingExample])
// Run the interpreter on page load
React.useEffect(() => {
if (schema && decoded != null && result == null) {
onRun()
}
}, [schema, decoded, result, onRun])
const interpreterSourceLink = React.useMemo(() => {
return matchingExample?.interpreter
? `${INTERPRETER_REPO}/interpreters/${matchingExample?.interpreter}.ts`
: INTERPRETER_REPO
}, [matchingExample])
return (
<div className="grid h-full items-stretch gap-6 grid-cols-1 lg:grid-cols-[1fr_200px]">
<div className="md:order-1 flex flex-col space-y-4">
<form onSubmit={onSubmit}>
<div className="flex w-full lg:items-center gap-2 flex-col lg:flex-row">
<div>
<NetworkSelect
defaultValue={chainID.toString()}
onValueChange={(value) => {
const hash = currentHash || ''
router.push(`/${PATH}/${value}/${hash}`)
}}
/>
</div>
<Input
className="flex-1"
id="hash"
name="hash"
placeholder={`Paste Ethereum transaction hash or click on examples`}
defaultValue={currentHash}
/>
<div className="flex gap-2">
<Button type="submit" className="flex-1">
Decode
</Button>
<Button variant={'outline'} onClick={onRun} type="button" className="flex-1" disabled={isInterpreting}>
<PlayIcon className="mr-2 h-4 w-4" />
{isInterpreting ? 'Interpreting...' : 'Interpret'}
</Button>
</div>
</div>
<div className="flex w-full lg:items-center gap-2 flex-col lg:flex-row mt-2">
<Input
className="flex-1"
id="userAddress"
name="userAddress"
placeholder="Optional: interpret as user address"
value={userAddress}
onChange={(e) => setUserAddress(e.target.value)}
/>
</div>
</form>
{error ? (
<div className="text-red-500 p-4 bg-red-50 rounded-md whitespace-pre-line">{error}</div>
) : (
<div className="grid gap-6 grid-cols-1 lg:grid-cols-2 h-full">
<div className="flex flex-col gap-2 lg:col-span-2 min-h-[40vh] lg:min-h-[initial]">
<Label>
Interpretation:{' '}
<a
href={interpreterSourceLink}
target="_blank"
rel="noopener noreferrer"
className="text-xs text-blue-500 hover:underline"
>
(Source Code)
</a>
</Label>
<CodeBlock
language="javascript"
value={schema ?? ''}
onChange={(value) => setSchema(value)}
lineNumbers={true}
readonly={false}
/>
</div>
<div className="flex flex-col gap-2 min-h-[40vh] lg:min-h-[initial]">
<Label>Decoded transaction:</Label>
<CodeBlock language="json" value={JSON.stringify(decoded, null, 2)} readonly={true} lineNumbers={false} />
</div>
<div className="flex flex-col gap-2 min-h-[40vh] lg:min-h-[initial]">
<div className="flex flex-row justify-between items-center">
<Label>Result:</Label>
</div>
{isInterpreting ? (
<div className="flex items-center justify-center p-8 border rounded-md">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 mx-auto mb-2"></div>
<p className="text-sm text-gray-600">Interpreting transaction...</p>
</div>
</div>
) : (
<CodeBlock
language="json"
value={result?.error ? result?.error : JSON.stringify(result?.interpretation, null, 2)}
readonly={true}
lineNumbers={false}
/>
)}
</div>
</div>
)}
</div>
<div className="md:order-2">
<ExampleTransactions path={PATH} />
</div>
</div>
)
}