|
| 1 | +import { sleep } from '@/utils/common'; |
| 2 | +import { Chain, WindowProvider } from 'wagmi'; |
| 3 | +import { InjectedConnector } from 'wagmi/connectors/injected'; |
| 4 | +import { BINANCE_WEB3_WALLET_ID, BINANCE_WEB3_WALLET_NAME, isBinanceWeb3Wallet } from '.'; |
| 5 | +import { isMobile } from '@/base/utils/mobile'; |
| 6 | + |
| 7 | +export type BinanceWeb3WalletConnectorOptions = Required< |
| 8 | + ConstructorParameters<typeof InjectedConnector> |
| 9 | +>[0]['options']; |
| 10 | + |
| 11 | +export interface CustomConstructorParams { |
| 12 | + chains?: Chain[]; |
| 13 | + options?: BinanceWeb3WalletConnectorOptions; |
| 14 | +} |
| 15 | + |
| 16 | +export class BinanceWeb3WalletConnector extends InjectedConnector { |
| 17 | + public id = BINANCE_WEB3_WALLET_ID; |
| 18 | + protected shimDisconnectKey = `${this.id}.shimDisconnect`; |
| 19 | + |
| 20 | + constructor(props: CustomConstructorParams) { |
| 21 | + const { chains, options: _options } = props ?? {}; |
| 22 | + |
| 23 | + const options = { |
| 24 | + name: BINANCE_WEB3_WALLET_NAME, |
| 25 | + shimDisconnect: true, |
| 26 | + getProvider, |
| 27 | + ..._options, |
| 28 | + }; |
| 29 | + |
| 30 | + if (typeof window !== 'undefined' && isMobile() && isBinanceWeb3Wallet()) { |
| 31 | + (window.ethereum as any)?.enable?.(); |
| 32 | + } |
| 33 | + |
| 34 | + super({ |
| 35 | + chains, |
| 36 | + options, |
| 37 | + }); |
| 38 | + } |
| 39 | + |
| 40 | + public async getProvider(): Promise<WindowProvider | undefined> { |
| 41 | + await sleep(); |
| 42 | + return this.options.getProvider(); |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +function getProvider() { |
| 47 | + if (typeof window === 'undefined') return; |
| 48 | + |
| 49 | + if (isMobile()) { |
| 50 | + return window.ethereum; |
| 51 | + } |
| 52 | + |
| 53 | + // Desktop: use Binance Web3 Wallet browser extension |
| 54 | + return window.binancew3w?.ethereum; |
| 55 | +} |
0 commit comments