mango-ui-v2/hooks/useWallet.tsx

77 lines
2.3 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 { notify } from './notifications'
import useLocalStorageState from './useLocalStorageState'
import useMangoStore from '../stores/useMangoStore'
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)
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
})
}, [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
})
console.log('connected!')
// const walletPublicKey = wallet.publicKey.toBase58()
// const keyToDisplay =
// walletPublicKey.length > 20
// ? `${walletPublicKey.substring(0, 7)}.....${walletPublicKey.substring(
// walletPublicKey.length - 7,
// walletPublicKey.length
// )}`
// : walletPublicKey
// notify({
// message: 'Wallet update',
// description: 'Connected to wallet ' + keyToDisplay,
// })
})
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
})
// notify({
// message: 'Wallet update',
// description: 'Disconnected from wallet',
// })
// localStorage.removeItem('feeDiscountKey')
})
return () => {
wallet.disconnect()
setMangoStore((state) => {
2021-04-02 11:26:21 -07:00
state.wallet.connected = false
})
}
}, [wallet])
2021-04-02 11:26:21 -07:00
return { wallet, connected }
}