2022-02-22 06:40:55 +00:00
|
|
|
import { ReactNode, useCallback, useMemo, useRef, useState } from 'react';
|
2022-02-23 05:05:39 +00:00
|
|
|
import { VegaKeyExtended, VegaWalletContextShape } from '.';
|
2022-02-22 23:06:35 +00:00
|
|
|
import { VegaConnector } from './connectors';
|
|
|
|
import { VegaWalletContext } from './context';
|
2022-02-22 06:40:55 +00:00
|
|
|
|
|
|
|
interface VegaWalletProviderProps {
|
|
|
|
children: ReactNode;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const VegaWalletProvider = ({ children }: VegaWalletProviderProps) => {
|
2022-02-23 05:05:39 +00:00
|
|
|
const [publicKeys, setPublicKeys] = useState<VegaKeyExtended[] | null>(null);
|
2022-02-22 06:40:55 +00:00
|
|
|
const connector = useRef<VegaConnector | null>(null);
|
|
|
|
|
|
|
|
const connect = useCallback(async (c: VegaConnector) => {
|
|
|
|
connector.current = c;
|
|
|
|
try {
|
2022-02-23 05:05:39 +00:00
|
|
|
const res = await connector.current.connect();
|
2022-02-23 19:24:30 +00:00
|
|
|
|
|
|
|
if (!res) {
|
|
|
|
console.log('connect failed', res);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-02-23 05:05:39 +00:00
|
|
|
const publicKeysWithName = res.map((pk) => {
|
|
|
|
const nameMeta = pk.meta?.find((m) => m.key === 'name');
|
|
|
|
return {
|
|
|
|
...pk,
|
|
|
|
name: nameMeta?.value ? nameMeta.value : 'None',
|
|
|
|
};
|
|
|
|
});
|
|
|
|
setPublicKeys(publicKeysWithName);
|
2022-02-22 06:40:55 +00:00
|
|
|
} catch (err) {
|
2022-02-23 05:39:12 +00:00
|
|
|
console.error(err);
|
2022-02-22 06:40:55 +00:00
|
|
|
}
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
const disconnect = useCallback(async () => {
|
|
|
|
try {
|
2022-02-22 23:06:35 +00:00
|
|
|
await connector.current?.disconnect();
|
2022-02-22 06:40:55 +00:00
|
|
|
setPublicKeys(null);
|
|
|
|
connector.current = null;
|
|
|
|
} catch (err) {
|
2022-02-23 05:39:12 +00:00
|
|
|
console.error(err);
|
2022-02-22 06:40:55 +00:00
|
|
|
}
|
|
|
|
}, []);
|
|
|
|
|
2022-02-23 05:05:39 +00:00
|
|
|
const contextValue = useMemo<VegaWalletContextShape>(() => {
|
2022-02-22 06:40:55 +00:00
|
|
|
return {
|
|
|
|
publicKeys,
|
|
|
|
connect,
|
|
|
|
disconnect,
|
|
|
|
connector: connector.current,
|
|
|
|
};
|
2022-02-23 19:24:30 +00:00
|
|
|
}, [publicKeys, connect, disconnect, connector]);
|
2022-02-22 06:40:55 +00:00
|
|
|
|
|
|
|
return (
|
|
|
|
<VegaWalletContext.Provider value={contextValue}>
|
|
|
|
{children}
|
|
|
|
</VegaWalletContext.Provider>
|
|
|
|
);
|
|
|
|
};
|