-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.jsx
432 lines (406 loc) · 10.4 KB
/
App.jsx
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
import {
Button, Stack, Heading, Text, useDisclosure,
Modal, ModalOverlay, ModalContent, ModalHeader,
ModalCloseButton, ModalBody, FormControl,
FormLabel, Select, ModalFooter, IconButton,
Image, Tooltip,
} from '@chakra-ui/react'
import {
HashRouter as Router, Switch, Route,
} from 'react-router-dom'
import { useState, useEffect, useMemo } from 'react'
import { ethers } from 'ethers'
import { createNftDidUrl } from 'nft-did-resolver'
import { create as createIPFS } from 'ipfs-http-client'
import Publish from './Publish'
import New from './New'
import Landing from './Landing'
import addresses from './contract/addresses.json'
import ABI from './contract/abi/VideosERC1155.json'
import { ifSet } from './utils'
import IPFSLogo from './images/IPFS.svg'
import Metamask from './images/metamask.svg'
import Connected from './images/connected.svg'
const { VideosERC1155 } = addresses
const chains = {
mumbai: {
id: 80001,
name: 'Polygon’s Mumbai Testnet',
rpc: 'https://rpc-mumbai.maticvigil.com',
currency: {
name: 'Matic',
symbol: 'MATIC',
decimals: 18,
},
explorer: 'https://mumbai.polygonscan.com',
},
rinkeby: {
id: 4,
name: 'Rinkeby Testnet',
rpc: process.env.RINKEBY_RPC_URL,
currency: {
name: 'ETH',
symbol: 'Ξ',
decimals: 18,
},
explorer: 'https://rinkeby.etherscan.io',
}
}
const desiredChain = chains.rinkeby
const IPFSSettings = ({
ipfsURL, setIPFSURL, open, closeIPFSSettings,
}) => {
const [url, setURL] = useState(
process.env.IPFS_API_URL
?? ipfsURL
?? 'https://ipfs.infura.io:5001'
)
const save = (evt) => {
evt.preventDefault()
setIPFSURL(url)
closeIPFSSettings()
}
return (
<Modal
size="xl"
{...{ isOpen: open, onClose: closeIPFSSettings }}
>
<ModalOverlay/>
<ModalContent as="form" onSubmit={save}>
<ModalHeader
textOverflow="ellipsis"
overflow="hidden"
whiteSpace="nowrap"
>IPFS Settings</ModalHeader>
<ModalCloseButton/>
<ModalBody pb={6}>
<FormControl mt={4}>
<FormLabel>
<Text
as="acronym"
title="Interplanetary Filesystem"
>
IPFS
</Text>
{' '}API Host
</FormLabel>
<Select
value={url}
onChange={({ target: { value } }) => {
setURL(value)
}}
>
<option value="http:https://localhost:5001">
http:https://localhost:5001 (requires allowing CORS permission)
</option>
<option
value="https://ipfs.infura.io:5001"
>
https://ipfs.infura.io:5001
</option>
</Select>
</FormControl>
</ModalBody>
<ModalFooter>
<Button
colorScheme="red"
onClick={closeIPFSSettings}
>Cancel</Button>
<Button
type="submit"
colorScheme="blue" ml={3}
>Save</Button>
</ModalFooter>
</ModalContent>
</Modal>
)
}
export default () => {
const [access, setAccess] = useState({})
const [nftDID, setNFTDID] = useState(null)
const [address, setAddress] = useState(null)
const [chain, setChain] = (
useState({ name: 'Undefined' })
)
const [provider, setProvider] = useState(null)
const [contract, setContract] = useState(null)
const [ipfsURL, setIPFSURL] = useState('')
const {
isOpen: open,
onOpen: openIPFSSettings,
onClose: closeIPFSSettings,
} = useDisclosure()
const network = async () => {
if(chain.id !== desiredChain.id) {
const chainId = (
`0x${desiredChain.id.toString(16)}`
)
try {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId }],
})
} catch(error) {
if(error.code === 4902) { // not added
try {
await ethereum.request({
method: 'wallet_addEthereumChain',
params: [{
chainId,
chainName: desiredChain.name,
rpcUrls: [desiredChain.rpc],
nativeCurrency: (
desiredChain.currency
),
blockExplorerUrls: [
desiredChain.explorer
],
}],
})
} catch(addError) {
console.error('Add Error', addError)
}
}
}
}
setProvider(
new ethers.providers.Web3Provider(
window.ethereum
)
)
}
const ipfs = useMemo(() => {
const regex = (
/^((https?):\/\/)?([^:/]+)?(:(\d+))?(.*)$/i
)
const match = ipfsURL.match(regex)
if(!match) {
toast({
title: 'Malformed URL',
description: `"${ipfsURL}" did not match expression "${regex.toString()}"`,
status: 'error',
duration: 12000,
isClosable: true,
})
} else {
const protocol = ifSet(match[2]) ?? 'http'
const host = ifSet(match[3]) ?? 'localhost'
const port = parseInt(ifSet(match[5]) ?? 5001)
const config = { host, port, protocol }
if(host.includes('infura')) {
const id = process.env.INFURA_IPFS_PROJECT_ID
if(!id) {
toast({
title: 'Missing Infura Credential',
description: 'Expected $INFURA_IPFS_PROJECT_ID to be set.',
status: 'error',
duration: 10000,
isClosable: true,
})
}
const secret = process.env.INFURA_IPFS_SECRET
if(!secret) {
toast({
title: 'Missing Infura Credential',
description: 'Expected $INFURA_IPFS_SECRET to be set.',
status: 'error',
duration: 10000,
isClosable: true,
})
}
const auth = (
'Basic '
+ (
Buffer.from(id + ':' + secret)
.toString('base64')
)
)
config.headers = {
authorization: auth,
}
}
return createIPFS(config)
}
}, [ipfsURL])
const connect = async () => {
const [address] = (
await window.ethereum.request({
method: 'eth_requestAccounts',
params: [{}],
})
)
setAddress(address)
setProvider(
new ethers.providers.Web3Provider(
window.ethereum
)
)
}
const disconnect = () => {
setAddress(null)
setProvider(null)
}
useEffect(() => {
console.log('LIS')
window.ethereum.on(
'connect',
(arg) => {
console.info('CONN!', arg)
connect()
}
)
}, [])
useEffect(() => {
const listen = async () => {
provider.on(
'network',
({ chainId: id, name }) => {
setChain({ id, name })
},
)
window.ethereum.on(
'chainChanged',
async (arg) => {
const provider = (
new ethers.providers.Web3Provider(
window.ethereum
)
)
const { chainId: id, name } = (
await provider.getNetwork()
)
setChain({ id, name })
},
)
window.ethereum.on(
'accountsChanged',
([addr]) => setAddress(addr),
)
window.ethereum.on(
'disconnect',
() => setProvider(null),
)
return () => {
provider.off('network')
window.ethereum.removeListener('accountsChanged')
window.ethereum.removeListener('chainChanged')
window.ethereum.removeListener('disconnected')
}
}
if(provider) {
listen()
}
}, [provider])
useEffect(() => {
if(provider) {
setContract(
new ethers.Contract(
VideosERC1155, ABI, provider.getSigner()
)
)
}
}, [provider])
useEffect(() => {
const cache = async () => {
const id = await contract.PUBLIC_ACCESS()
setAccess((old) => ({ ...old, public: id }))
}
if(contract && chain.id === desiredChain.id) {
cache()
}
}, [contract, chain.id, desiredChain.id])
useEffect(() => {
if(access.public) {
setNFTDID(createNftDidUrl({
chainId: `eip155:${desiredChain.id}`,
namespace: 'erc1155',
contract: VideosERC1155.toLowerCase(),
tokenId: access.public.toString(),
}))
}
}, [access.public])
const ConnectButton = ({ ...props }) => {
let bg = 'darkorange'
let label = 'Disconnect'
let src = Connected
let colorScheme = 'orange'
let onClick = disconnect
if(!provider) {
bg = 'darkgreen'
label = 'Connect Your Wallet'
src = Metamask
colorScheme = 'green'
onClick = connect
}
return (
<Tooltip
hasArrow placement="left"
{...{ bg, label }}
>
<Button
{...{ colorScheme, onClick, ...props }}
opacity={0.5} p="0.25em 0.5em"
position="fixed" right="0.5em" top="0.5em"
_hover={{
opacity: 1, borderRadius: 'lg',
}}
>
<Image
h={50} w={50} {...{ src }}
/>
</Button>
</Tooltip>
)
}
if(provider && chain.id !== desiredChain.id) {
return (
<Stack maxW={30 * 16} m="auto" mt={10}>
<Heading textAlign="center">
On the chain <q>{chain.name}</q> when {desiredChain.name} is desired.
</Heading>
<Button onClick={network}>
Switch
</Button>
</Stack>
)
}
const IPFSButton = ({ ...props }) => {
const { maxW, maxH } = props
return (
<Tooltip label="Configure IPFS" hasArrow>
<IconButton
aria-label="Configure IPFS"
icon={
<Image
{...{ maxW, maxH }}
src={IPFSLogo}
/>
}
onClick={openIPFSSettings}
{...props}
/>
</Tooltip>
)
}
return (
<Router>
<IPFSSettings {...{
ipfsURL, setIPFSURL, open, closeIPFSSettings,
}}/>
<Switch>
<Route exact path="/new">
<New {...{ IPFSButton, ipfs, ConnectButton }}/>
</Route>
<Route path="/publish">
<Publish {...{
nftDID, access, contract, address, provider,
IPFSButton, ConnectButton,
}}/>
</Route>
<Route path="/">
<Landing/>
</Route>
</Switch>
</Router>
)
}