generated from scio-labs/inkathon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuse-accurast.tsx
78 lines (65 loc) · 2.27 KB
/
use-accurast.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
import { useEffect, useMemo, useState } from 'react'
import { AcurastClient } from '@acurast/dapp'
import { env } from '@/config/environment'
const DEV_WSS = env.ACCU_DEV_WSS
export const useAccurast = () => {
const [acurastClient, setAcurastClient] = useState<any>(null)
const [id, setId] = useState<string>('')
const [keyPair, setKeyPair] = useState()
const [message, setMessage] = useState()
useEffect(() => {
const init = async () => {
const acurast = new AcurastClient(DEV_WSS)
setAcurastClient(acurast)
const keyPair = await crypto.subtle.generateKey(
{
name: 'ECDSA',
namedCurve: 'P-256',
},
true,
['sign'],
)
const [privateKeyRaw, publicKeyRaw] = await Promise.all([
// @ts-expect-error can't find the argument that matches call
crypto.subtle
.exportKey('jwk', keyPair.privateKey)
.then((jwk) => Buffer.from(jwk.d, 'base64')),
crypto.subtle
.exportKey('raw', keyPair.publicKey)
.then((arrayBuffer) => Buffer.from(arrayBuffer)),
])
const publicKeyCompressedSize = (publicKeyRaw.length - 1) / 2
const publicKeyCompressed = Buffer.concat([
new Uint8Array([publicKeyRaw[2 * publicKeyCompressedSize] % 2 ? 3 : 2]),
publicKeyRaw.subarray(1, publicKeyCompressedSize + 1),
])
const publicKeyHash = await crypto.subtle.digest('SHA-256', publicKeyCompressed)
setId(Buffer.from(publicKeyHash.slice(0, 16)).toString('hex'))
setKeyPair({
// @ts-expect-error allow
privateKey: privateKeyRaw.toString('hex'),
publicKey: publicKeyRaw.toString('hex'),
})
return () => {
acurast.close()
}
}
init()
}, [])
const send = (recipient: any, payload: any) => {
acurastClient.send(recipient, payload)
}
useEffect(() => {
if (acurastClient) {
acurastClient.onMessage((message: any) => {
setMessage({
// @ts-expect-error allow
sender: Buffer.from(message.sender).toString('hex'),
recipient: Buffer.from(message.recipient).toString('hex'),
payload: Buffer.from(message.payload).toString('hex'),
})
})
}
}, [acurastClient])
return { id, keyPair, message, send }
}