使用 Web3Modal 2.0 套件連接多種加密貨幣錢包

前置作業

首先,在 WalletConnect 服務註冊一個帳號,並且新增一個專案,然後將 Project ID 複製起來。

實作

建立專案。

1
2
mkdir web3modal-example
cd web3modal-example

建立 package.json 檔。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"name": "web3modal-v2-example",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@wagmi/core": "^0.9.4",
"@web3modal/ethereum": "^2.1.1",
"@web3modal/html": "^2.1.1",
"ethers": "^5.7.2"
},
"devDependencies": {
"vite": "^4.1.1"
}
}

安裝依賴套件。

1
npm i --force

新增 index.html 檔。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>HTML Example</title>
</head>
<body>
<div id="app">
<w3m-core-button></w3m-core-button>
<button id="sign-button">Sign</button>
</div>
<script type="module" src="main.js"></script>
</body>
</html>

新增 main.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
import { configureChains, createClient, signMessage, getAccount } from '@wagmi/core'
import { goerli, mainnet } from '@wagmi/core/chains'
import { EthereumClient, modalConnectors, walletConnectProvider } from '@web3modal/ethereum'
import { Web3Modal } from '@web3modal/html'

// define constants
const projectId = 'your-project-id'
const chains = [mainnet, goerli]

// configure wagmi client
const { provider } = configureChains(chains, [walletConnectProvider({ projectId })])
const wagmiClient = createClient({
autoConnect: true,
connectors: [
...modalConnectors({ appName: 'web3Modal', chains })
],
provider
})

// create ethereum and modal clients
const ethereumClient = new EthereumClient(wagmiClient, chains)
export const web3Modal = new Web3Modal(
{
projectId
},
ethereumClient
)

web3Modal.subscribeModal(({ open }) => {
const account = getAccount()
console.log(account)
})

document.getElementById('sign-button').onclick = async () => {
const signature = await signMessage({
message: 'Hello, World!'
})
console.log(signature)
}

啟動網頁伺服器。

1
npm run dev

點選按鈕以連接錢包。

範例專案

下載範例專案。

1
git clone [email protected]:WalletConnect/web3modal.git

安裝依賴套件。

1
yarn

建立所有的 .env.local 檔。

1
2
3
cp ./examples/laboratory/.env.local.example ./examples/laboratory/.env.local
cp ./examples/react/.env.local.example ./examples/react/.env.local
cp ./examples/react-standalone/.env.local.example ./examples/react-standalone/.env.local

修改所有的 .env.local 檔。

1
NEXT_PUBLIC_PROJECT_ID="your-project-id"

編譯資源。

1
yarn build

啟動網頁,以 html 範例為例。

1
yarn dev:html

程式碼

參考資料