-
Notifications
You must be signed in to change notification settings - Fork 22
/
keplr.ts
53 lines (45 loc) · 1.23 KB
/
keplr.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
import { Keplr, Window as KeplrWindow } from '@keplr-wallet/types'
declare global {
interface Window extends KeplrWindow {}
}
// Suggest a token to the user.
export const suggestToken = async (chainId: string, address: string) =>
(await getKeplrFromWindow())
?.suggestToken(chainId, address)
.then(() => true)
.catch(() => false)
export const getKeplrFromWindow: () => Promise<
Keplr | undefined
> = async () => {
if (typeof window === 'undefined') {
return
}
const keplr = (window as KeplrWindow).keplr
if (keplr) {
return keplr
}
if (document.readyState === 'complete') {
if (keplr) {
return keplr
} else {
throw new Error('Keplr not found')
}
}
return new Promise((resolve, reject) => {
const documentStateChange = (event: Event) => {
if (
event.target &&
(event.target as Document).readyState === 'complete'
) {
const keplr = (window as KeplrWindow).keplr
if (keplr) {
resolve(keplr)
} else {
reject(new Error('Keplr not found'))
}
document.removeEventListener('readystatechange', documentStateChange)
}
}
document.addEventListener('readystatechange', documentStateChange)
})
}