-
Notifications
You must be signed in to change notification settings - Fork 112
/
useSignedHandle.ts
71 lines (63 loc) · 1.93 KB
/
useSignedHandle.ts
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
import { useState, useCallback, Dispatch, SetStateAction } from 'react'
import { useActiveWeb3React } from '.'
// sign handle based on data format from EIP-712
// based on twitter handle, return signature and message signing function
// return setter function to reset signature if needed
export function useSignedHandle(twitterHandle: string | undefined): {
sig: string | undefined
signMessage: () => void
setSig: Dispatch<SetStateAction<string | undefined>>
error: string | undefined
} {
// get signer and account to sign data with
const { library, account } = useActiveWeb3React()
// store and set signature
const [sig, setSig] = useState<string | undefined>()
// mark errors
const [error, setError] = useState<string | undefined>()
const signMessage = useCallback(() => {
// reset error
setError(undefined)
if (!library && account) {
return
}
const EIP712Domain = [
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
]
const domain = {
name: 'Sybil Verifier',
version: '1',
}
const Permit = [{ name: 'username', type: 'string' }]
const message = { username: twitterHandle }
const data = JSON.stringify({
types: {
EIP712Domain,
Permit,
},
domain,
primaryType: 'Permit',
message,
})
/**
* Need to use personal_sign as eth typed data is not
* supported by most hardware wallets yet.
*/
if (account) {
//format as hex
const message = new Buffer(data).toString('hex')
// need to manually prefix with 0x for wallet connect
library
?.send('personal_sign', ['0x' + message, account])
.catch((error) => {
console.log(error)
setError('Error signing message')
})
.then((sig) => {
setSig(sig)
})
}
}, [account, library, twitterHandle])
return { sig, signMessage, setSig, error }
}