multisig-ui/src/components/WalletProvider.tsx

69 lines
1.7 KiB
TypeScript
Raw Normal View History

2021-04-22 12:16:15 -07:00
import React, {
PropsWithChildren,
ReactElement,
ReactNode,
useMemo,
useContext,
2021-04-22 22:05:29 -07:00
} from "react";
import { useSelector } from "react-redux";
import { Connection, ConfirmOptions } from "@solana/web3.js";
2021-04-22 12:16:15 -07:00
// @ts-ignore
2021-04-22 22:05:29 -07:00
import Wallet from "@project-serum/sol-wallet-adapter";
import { Program, Provider } from "@project-serum/anchor";
2021-04-22 22:05:29 -07:00
import { State as StoreState } from "../store/reducer";
import MultisigIdl from "../idl";
2021-04-22 12:16:15 -07:00
export function useWallet(): WalletContextValues {
const w = useContext(WalletContext);
if (!w) {
2021-04-22 22:05:29 -07:00
throw new Error("Missing wallet context");
2021-04-22 12:16:15 -07:00
}
2021-04-22 22:05:29 -07:00
// @ts-ignore
2021-04-22 12:16:15 -07:00
return w;
}
const WalletContext = React.createContext<null | WalletContextValues>(null);
type WalletContextValues = {
wallet: Wallet;
multisigClient: Program;
};
export default function WalletProvider(
2021-04-22 22:05:29 -07:00
props: PropsWithChildren<ReactNode>
2021-04-22 12:16:15 -07:00
): ReactElement {
const { walletProvider, network } = useSelector((state: StoreState) => {
return {
walletProvider: state.common.walletProvider,
network: state.common.network,
};
});
2021-04-22 22:05:29 -07:00
const { wallet, multisigClient } = useMemo(() => {
2021-04-22 12:16:15 -07:00
const opts: ConfirmOptions = {
2021-04-22 22:05:29 -07:00
preflightCommitment: "recent",
commitment: "recent",
2021-04-22 12:16:15 -07:00
};
const connection = new Connection(network.url, opts.preflightCommitment);
const wallet = new Wallet(walletProvider, network.url);
const provider = new Provider(connection, wallet, opts);
const multisigClient = new Program(
MultisigIdl,
network.multisigProgramId,
2021-04-22 22:05:29 -07:00
provider
2021-04-22 12:16:15 -07:00
);
return {
wallet,
multisigClient,
};
}, [walletProvider, network]);
return (
2021-04-22 22:05:29 -07:00
<WalletContext.Provider value={{ wallet, multisigClient }}>
2021-04-22 12:16:15 -07:00
{props.children}
</WalletContext.Provider>
);
}