Config

coderljw 2024-10-13 DAPP
  • 区块链
  • DAPP
  • Config
大约 2 分钟

# 1. config

import { defineConfig } from 'umi'

export default defineConfig({
  chainWebpack: (config, { webpack }) => {
    config.plugin('IgnorePlugin').use(webpack.IgnorePlugin, [
      {
        resourceRegExp: /^electron$/,
      },
    ])
  },
})
1
2
3
4
5
6
7
8
9
10
11
  • 配置测试网/主网,chainId 要以 16 进制表示。
import { defineConfig } from 'umi'

export default defineConfig({
  define: {
    'process.env.CHAIN': {
      chainId: `0x${(97).toString(16)}`,
      chainName: 'Binance Smart Chain Testnet',
      nativeCurrency: {
        name: 'Binance Chain Native Token',
        symbol: 'tBNB',
        decimals: 18,
      },
      rpcUrls: [
        'https://data-seed-prebsc-1-s1.binance.org:8545',
        'https://data-seed-prebsc-2-s1.binance.org:8545',
        'https://data-seed-prebsc-1-s2.binance.org:8545',
        'https://data-seed-prebsc-2-s2.binance.org:8545',
        'https://data-seed-prebsc-1-s3.binance.org:8545',
        'https://data-seed-prebsc-2-s3.binance.org:8545',
      ],
      blockExplorerUrls: ['https://testnet.bscscan.com/'],
      iconUrls: ['https://testnet.bscscan.com/images/favicon.ico'],
    },
  },
})
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

# 2. app.ts

  • 配置 library,注入 web3-react。
import React from 'react'
import Web3 from 'web3'
import { Web3ReactProvider } from '@web3-react/core'

function getLibrary(provider: any) {
  const library = new Web3(provider)
  library.pollingInterval = 12000
  return library
}

export function rootContainer(container: React.ReactNode) {
  return React.createElement(Web3ReactProvider, { getLibrary }, container)
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 3. ConnectChain.tsx

import { useState, useEffect, useRef } from 'react'
import { useIntl, useModel } from 'umi'
import { useWeb3React, UnsupportedChainIdError } from '@web3-react/core'
import { injected, walletconnect } from '@/web3/connectors'
import {
  useEagerConnect,
  useErrorMessage,
  useInactiveListener,
} from '@/web3/hooks'
import { useUser, useSyncCallback } from '@/hooks'
import storage from '@/utils/storage'
import { ACCESS_TOKEN } from '@/utils/types'
import InstallModal from './InstallModal'
import Web3Modal from './Web3Modal'
import AccountInfo from './AccountInfo'
import Button from '../Button'
import styles from './index.less'

const ConnectChain = () => {
  // 快速连接
  const triedEager = useEagerConnect()
  useInactiveListener(!triedEager)

  const { isLogin } = useModel('useLogin')
  const { activate, deactivate, active, error, account } = useWeb3React()
  const { login, layout, loading } = useUser()
  const { formatMessage } = useIntl()

  const currentError = useRef()
  const prevAccount = useRef()
  const documentHiddenAccount = useRef()
  const [documentHidden, setDocumentHidden] = useState(false)

  // 1: 安装MetaMask提示, 2: 连接钱包, 3: 账户信息
  const [visible, setVisible] = useState(0)
  const showErrorMessage = useErrorMessage()

  // 快速登录
  // useEffect(() => {
  //   !isLogin && injectedConnect(true)
  // }, [])

  // 监听账户切换
  useEffect(() => {
    if (
      prevAccount.current &&
      account &&
      prevAccount.current !== account &&
      isLogin &&
      !document.hidden
    ) {
      login()
    }

    return () => {
      prevAccount.current = account
    }
  }, [account])

  // 若在其他网站切换账户,回到页面时,让其重新登录
  useEffect(() => {
    if (
      !documentHidden &&
      isLogin &&
      documentHiddenAccount.current &&
      documentHiddenAccount.current !== account
    ) {
      login()
    }
  }, [documentHidden])

  // 提示错误
  useEffect(() => {
    currentError.current = error
    error && showErrorMessage(error)
  }, [error])

  // 若在其他网站切换为不支持的网络,回到页面时,让其切换为支持的网络
  useEffect(() => {
    document.addEventListener('visibilitychange', async () => {
      setDocumentHidden(document.hidden)
      documentHiddenFn()

      const isAuthorized = await injected.isAuthorized()
      const token = storage.get(ACCESS_TOKEN)
      const { ethereum } = window as any

      if (
        document.hidden ||
        !(
          isAuthorized &&
          token &&
          ethereum?.isMetaMask &&
          currentError.current instanceof UnsupportedChainIdError
        )
      )
        return

      await activate(injected)
      try {
        await ethereum.request({
          method: 'wallet_switchEthereumChain',
          params: [{ chainId: process.env.CHAIN.chainId }],
        })
      } catch (switchError: any) {
        if (switchError.code === 4902) {
          try {
            await ethereum.request({
              method: 'wallet_addEthereumChain',
              params: [process.env.CHAIN],
            })
          } catch (addError) {}
        }
      }
    })
  }, [])

  // 存储页面隐藏时的账户
  const documentHiddenFn = useSyncCallback(() => {
    if (isLogin && document.hidden) {
      documentHiddenAccount.current = account
    }
  })

  // 小心闭包
  const connected = useSyncCallback(async () => {
    if (active) login()
  })

  // 连接MetaMask
  const injectedConnect = async isFirst => {
    const { ethereum } = window as any
    if (!ethereum?.isMetaMask) return isFirst ? false : setVisible(1)

    setVisible(0)
    await deactivate()
    await activate(injected)

    try {
      await ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: process.env.CHAIN.chainId }],
      })
    } catch (switchError: any) {
      if (switchError.code === 4902) {
        try {
          await ethereum.request({
            method: 'wallet_addEthereumChain',
            params: [process.env.CHAIN],
          })
        } catch (addError) {}
      }
    }

    connected()
  }

  // 连接WalletConnect协议钱包
  const walletConnect = async () => {
    setVisible(0)
    await deactivate()
    await activate(walletconnect)
    connected()
  }

  const disConnect = async () => {
    setVisible(0)
    await deactivate()
    layout()
  }

  return (
    <>
      <section className={styles.connect}>
        <Button
          loading={loading}
          onClick={() => {
            if (isLogin) return setVisible(3)
            setVisible(2)
          }}
          className={styles.button}
        >
          {isLogin ? (
            <span className={styles.address}>{account}</span>
          ) : (
            formatMessage({ id: 'connect' })
          )}
        </Button>
      </section>

      <InstallModal visible={visible === 1} hidden={() => setVisible(0)} />

      <Web3Modal
        visible={visible === 2}
        hidden={() => setVisible(0)}
        injectedConnect={() => injectedConnect(false)}
        walletConnect={walletConnect}
      />

      <AccountInfo
        visible={visible === 3}
        hidden={() => setVisible(0)}
        disConnect={disConnect}
      />
    </>
  )
}

export default ConnectChain
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
以父之名
周杰伦.mp3