mango-ui-v2/hooks/useWallet.tsx

79 lines
2.1 KiB
TypeScript
Raw Normal View History

2021-04-02 11:26:21 -07:00
import { useEffect } from 'react'
import Wallet from '@project-serum/sol-wallet-adapter'
import useLocalStorageState from './useLocalStorageState'
import useMangoStore from '../stores/useMangoStore'
2021-04-11 21:17:23 -07:00
import { notify } from '../utils/notifications'
export const WALLET_PROVIDERS = [
{ name: 'sollet.io', url: 'https://www.sollet.io' },
]
const ENDPOINT = process.env.CLUSTER ? process.env.CLUSTER : 'mainnet-beta'
2021-04-02 11:26:21 -07:00
export default function useWallet() {
const setMangoStore = useMangoStore((state) => state.set)
const { current: wallet, connected } = useMangoStore((state) => state.wallet)
const endpoint = useMangoStore((state) => state.connection.endpoint)
2021-04-09 17:01:00 -07:00
const fetchWalletBalances = useMangoStore(
(s) => s.actions.fetchWalletBalances
)
const [savedProviderUrl] = useLocalStorageState(
'walletProvider',
'https://www.sollet.io'
)
2021-04-02 11:26:21 -07:00
const providerUrl = savedProviderUrl
? savedProviderUrl
: 'https://www.sollet.io'
2021-04-02 11:26:21 -07:00
useEffect(() => {
if (wallet) return
2021-04-02 11:26:21 -07:00
console.log('creating wallet', endpoint)
2021-04-02 11:26:21 -07:00
const newWallet = new Wallet(providerUrl, ENDPOINT)
setMangoStore((state) => {
2021-04-02 11:26:21 -07:00
state.wallet.current = newWallet
})
2021-04-10 08:52:31 -07:00
// eslint-disable-next-line
2021-04-02 11:26:21 -07:00
}, [endpoint])
useEffect(() => {
2021-04-02 11:26:21 -07:00
if (!wallet) return
wallet.on('connect', () => {
setMangoStore((state) => {
2021-04-02 11:26:21 -07:00
state.wallet.connected = true
})
2021-04-11 21:17:23 -07:00
notify({
message: 'Wallet connected',
description:
'Connected to wallet ' +
wallet.publicKey.toString().substr(0, 5) +
'...' +
wallet.publicKey.toString().substr(-5),
})
})
wallet.on('disconnect', () => {
setMangoStore((state) => {
2021-04-02 11:26:21 -07:00
state.wallet.connected = false
state.marginAccounts = []
state.selectedMarginAccount.current = null
2021-04-02 11:26:21 -07:00
})
2021-04-11 21:17:23 -07:00
notify({
type: 'info',
message: 'Disconnected from wallet',
})
})
return () => {
wallet.disconnect()
setMangoStore((state) => {
2021-04-02 11:26:21 -07:00
state.wallet.connected = false
})
}
}, [wallet])
2021-04-09 17:01:00 -07:00
useEffect(() => {
fetchWalletBalances()
}, [connected, fetchWalletBalances])
2021-04-02 11:26:21 -07:00
return { wallet, connected }
}