-
Notifications
You must be signed in to change notification settings - Fork 128
/
index.tsx
73 lines (59 loc) · 1.69 KB
/
index.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
import { createContext, useState, useEffect, useContext, useMemo, ReactElement } from 'react';
import SafeAppsSDK, { Opts as SDKOpts, SafeInfo } from '@safe-global/safe-apps-sdk';
type SafeReactSDKContext = {
sdk: SafeAppsSDK;
connected: boolean;
safe: SafeInfo;
};
const SafeContext = createContext<SafeReactSDKContext | undefined>(undefined);
interface Props {
loader?: ReactElement;
opts?: SDKOpts;
children: React.ReactNode;
}
export const SafeProvider: React.FC<Props> = ({ loader = null, opts, children }) => {
const [sdk] = useState(() => new SafeAppsSDK(opts));
const [connected, setConnected] = useState(false);
const [safe, setSafe] = useState<SafeInfo>({
safeAddress: '',
chainId: 1,
threshold: 1,
owners: [],
isReadOnly: true,
});
const contextValue = useMemo(() => ({ sdk, connected, safe }), [sdk, connected, safe]);
useEffect(() => {
let active = true;
const fetchSafeInfo = async () => {
try {
const safeInfo = await sdk.safe.getInfo();
if (!active) {
return;
}
setSafe(safeInfo);
setConnected(true);
} catch (err) {
if (!active) {
return;
}
setConnected(false);
}
};
fetchSafeInfo();
return () => {
active = false;
};
}, [sdk]);
if (!connected && loader) {
return loader;
}
return <SafeContext.Provider value={contextValue}>{children}</SafeContext.Provider>;
};
export const useSafeAppsSDK = (): SafeReactSDKContext => {
const value = useContext(SafeContext);
if (value === undefined) {
throw new Error('You probably forgot to put <SafeProvider>.');
}
return value;
};
export default SafeProvider;