-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseBinanceDeprecated.js
106 lines (83 loc) · 2.85 KB
/
useBinanceDeprecated.js
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { useState, useCallback, useEffect } from "react";
import { BscConnector } from '@binance-chain/bsc-connector'
import useError from "./useError";
import { config } from "../config"
import useSmartContract from "./useSmartContract";
// imports
const { BinanceChain } = window
export const bsc = new BscConnector({
supportedChainIds: [config.chainId]
})
const isInstalled = () => {
return !!BinanceChain
};
const isChainIdCorrect = async () => {
const chainId = await BinanceChain.request({ method: 'eth_chainId' });
return chainId == config.chainId ? true : false
}
const useBinance = () => {
const [account, setAccount] = useState();
const [errorBinance, setError, withErrorHandler] = useError();
const connectWallet = async (cb) => {
if (!isInstalled()) {
if(navigator.userAgent.indexOf("Firefox") != -1 ) window.open("https://addons.mozilla.org/ru/firefox/addon/binance-chain/")
else window.open('https://chrome.google.com/webstore/detail/binance-wallet/fhbohimaelbohpjbbldcngcnapndodjp', '_blank')
return
}
if (!localStorage.getItem("account")) setError("Connect your wallet")
if(!await isChainIdCorrect()) {
setError("Select testnet")
return;
};
await bsc.activate();
const account = await bsc.getAccount();
cb?.(config.chainId, account);
};
const connectBinance = async () => {
await connectWallet(( chainId, account) => {
localStorage.setItem("wallet", "binance")
handleChainChanged(chainId);
handleAccountsChanged(account);
});
};
const handleAccountsChanged = useCallback(
(account) => {
if (account) {
setAccount(account);
localStorage.setItem("account", account)
// window.location.reload()
} else disconnectBinance()
},
[]
);
const handleChainChanged = useCallback(
(hexChainId) => {
window.location.reload()
},
[]
);
useEffect(()=>{
return () => {
setError("")
}
}, [errorBinance])
const disconnectBinance = useCallback(() => {
localStorage.removeItem('wallet')
localStorage.removeItem('account')
window.location.reload()
}, []);
useEffect(() => {
let wallet = localStorage.getItem('wallet')
if (!BinanceChain?.on || !wallet) return;
BinanceChain.on('accountsChanged', handleAccountsChanged)
BinanceChain.on("chainChanged", disconnectBinance);
BinanceChain.on("disconnect", disconnectBinance);
}, [BinanceChain, handleAccountsChanged, disconnectBinance]);
return {
account,
connectBinance,
disconnectBinance,
errorBinance
};
};
export default useBinance;