我使用的是vue+ethers
官方文档:WalletConnect
1.安装
js
yarn add @web3modal/ethers ethers
或者
npm install @web3modal/ethers ethers
2.引用
新建一个js文件,在main.js中引入,初始化配置sdk
js
import {
createWeb3Modal,
defaultConfig,
} from "@web3modal/ethers5/vue";
// 1. Get projectId
const projectId = import.meta.env.VITE_PROJECT_ID;
// 2. Set chains
const mainnet = {
chainId: 1,
name: 'Ethereum',
currency: 'ETH',
explorerUrl: 'https://etherscan.io',
rpcUrl: 'https://cloudflare-eth.com'
};
// 3. Create modal
const metadata = {
name: 'My Website',
description: 'My Website description',
url: 'https://mywebsite.com',
icons: ['https://avatars.mywebsite.com/']
}
createWeb3Modal({
ethersConfig: defaultConfig({ metadata }),
chains: [mainnet],
projectId
})
获取 address
chainId
isConnected
相关信息
js
import { useWeb3ModalAccount } from "@web3modal/ethers5/vue";
// 一定要先初始化完成才能调用获取到
const { address, chainId, isConnected } = useWeb3ModalAccount();
const getWalletInfo = () => {
console.log({
address,
chainId,
isConnected
})
// 获取更改后的相关操作....
};
// 这里可以使用 watch 监听钱包变化
watch(
() => address.value,
() => {
getWalletInfo();
}
);
调用签名
js
import { useWeb3ModalSigner } from "@web3modal/ethers5/vue";
// 一定要先初始化完成才能调用获取到
const { signer } = useWeb3ModalSigner();
const onSignMessage = async ()=> {
try {
const signature = await signer.value.signMessage("Hello Web3Modal Ethers");
console.log('签名信息',signature);
} catch (error) {
console.log("签名失败", error);
}
}
以上调用方法可以自己结合使用, 具体可以参考官方文档
3.网络组件 点这里看文档
初始化引用之后再调用
html
<w3m-button />
<w3m-account-button />
<w3m-connect-button />
<w3m-network-button />
4.自定义组合 点这里看文档
html
<script setup>
import { useWeb3Modal } from "@web3modal/ethers5/vue";
const { open } = useWeb3Modal();
</script>
<van-button round type="primary" @click="open()">
<span v-if="userStore.address !== ''">
{{ userStore.address) }}
</span>
<span v-else>Connect Wallet</span>
</van-button>
结尾
projectId
可以到 WalletConnect Cloud 进行注册创建
页面调用效果图 官方示例