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

页面调用效果图 官方示例

相关推荐
Rockbean8 天前
10分钟智能合约:进阶实战-7.2 Foundry开发环境
web3·智能合约·solidity
davidrevo10 天前
Solidity 学习总结:核心特性与实战指南
web3
Rockbean11 天前
10分钟智能合约:进阶实战-6.4 使合约拒绝服务
web3·智能合约·solidity
Rockbean11 天前
10分钟智能合约:进阶实战-6.3 重入攻击提取资金
web3·智能合约·solidity
木西13 天前
实战:基于 Solidity 0.8.27 与 OpenZeppelin V5 构建多链恶搞代币(以 SPX6900 为例)
web3·智能合约·solidity
m0_3801671414 天前
面向开发者的Top10加密货币数据API(2026年最新)
大数据·人工智能·区块链
2601_9594801514 天前
Moneta Markets亿汇:“比特币高位修复风险偏好”
区块链
m0_3801671415 天前
加密货币价格 API、市场数据 API 与 分析 API 有什么区别?
人工智能·ai·区块链
LedgerNinja15 天前
AEGET:提升决策效率,助力交易者建立清晰的交易体系
区块链
2601_9619633815 天前
Spring Boot集成电子签章的7个典型问题与解决方案:从入门到生产级实践
大数据·人工智能·spring boot·python·区块链·智能合约