使用WalletConnect Web3Modal v3 链接钱包基础教程

我使用的是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 进行注册创建

页面调用效果图 官方示例

相关推荐
lsrsyx2 小时前
TEBBIT 交易所:在数字资产时代构筑信任与性能的新标杆
区块链
小明的小名叫小明5 小时前
Aave协议(3)
区块链·defi
Zoey的笔记本5 小时前
构建去中心化协作引擎:基于开源框架的Web3团队项目管理实践
开源·web3·区块链
Sui_Network7 小时前
Sui 2025 年终回顾:Sui 技术栈篇
大数据·人工智能·科技·去中心化·区块链
Dream Algorithm8 小时前
RWA : Real World Asset
大数据·区块链
Yyyyy123jsjs18 小时前
外汇Tick数据交易时段详解与Python实战分析
人工智能·python·区块链
Wnq1007220 小时前
去中心化控制系统搭建与实施方案
去中心化·区块链
DICOM医学影像1 天前
13. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 进阶篇 - sepolia测试网
区块链·solidity·以太坊·web3.0·sepolia·hardhat
小明的小名叫小明1 天前
Aave协议(2)
架构·区块链·defi
Wnq100721 天前
去中心化的 CORBA 架构
架构·去中心化·区块链