Web3-Onboard
前提条件
- 一个基本的前端项目环境(React、Vue 或纯 Javascript)
- 安装了 bitget wallet 的浏览器
步骤
1. 安装 Web3 Onboard
通过 yarn 或 npm 安 Web3 Onboard。在项目的根目录运行以下命令
npm
sh
npm i @web3-onboard/core @web3-onboard/bitget
npm i @web3-onboard/core @web3-onboard/bitget
yarn
sh
yarn add @web3-onboard/core @web3-onboard/bitget
yarn add @web3-onboard/core @web3-onboard/bitget
2. 项目中引入和配置 Web3 Onboard
在你的前端项目中,创建一个配置用于初始化 Web3 Onboard,例如在一个 React 应用中,你可以这样做:
jsx
import Onboard from "@web3-onboard/core";
import bitgetWalletModule from "@web3-onboard/bitget";
function App() {
const bitgetWallet = bitgetWalletModule();
// 初始化 Onboard
const onboard = Onboard({
// ... other Onboard options
wallets: [
bitgetWallet,
//... other wallets
],
});
return (
<div className="App">
<button onclick={connectWallet}>Connect Bitget wallet</button>
</div>
);
}
export default App;
import Onboard from "@web3-onboard/core";
import bitgetWalletModule from "@web3-onboard/bitget";
function App() {
const bitgetWallet = bitgetWalletModule();
// 初始化 Onboard
const onboard = Onboard({
// ... other Onboard options
wallets: [
bitgetWallet,
//... other wallets
],
});
return (
<div className="App">
<button onclick={connectWallet}>Connect Bitget wallet</button>
</div>
);
}
export default App;
3.链接钱包
创建一个按钮,当用户点击时,调用 Web3 Onboard 以链接钱包
js
const connectWallet = async () => {
const wallets = await onboard.connectWallet();
console.log(wallets);
};
const connectWallet = async () => {
const wallets = await onboard.connectWallet();
console.log(wallets);
};
4. 前端界面
在你的前端应用的适当位置,添加一个按钮用于触发钱包链接:
html
<button onclick={connectWallet}>Connect Bitget wallet</button>
<button onclick={connectWallet}>Connect Bitget wallet</button>
5.监听钱包状态
js
onboard.state.select("wallets").subscribe((wallets) => {
if (wallets.length > 0) {
console.log("Wallet is connected");
} else {
console.log("Wallet is disconnected");
}
});
onboard.state.select("wallets").subscribe((wallets) => {
if (wallets.length > 0) {
console.log("Wallet is connected");
} else {
console.log("Wallet is disconnected");
}
});