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

页面调用效果图 官方示例

相关推荐
FrancyZhou1 天前
【12】智能合约开发入门
区块链·智能合约
电报号dapp1191 天前
Sui链开发:技术架构与生态实践深度解析(2025年最新进展)
架构·去中心化·区块链·智能合约
weex_213341 天前
WEEX交易所安全教學:如何應對剪切板被劫持駭客攻擊?
区块链
电报号dapp1192 天前
NFT质押:数字资产的价值裂变与收益体系深度解析
游戏·去中心化·区块链·智能合约
FrancyZhou2 天前
【11】子网
区块链
qiquandongkh2 天前
期权帮|股指期货多单和空单有什么区别?
大数据·金融·区块链
静语金科媛3 天前
供应链金融的学习梳理
区块链·供应链
没落英雄3 天前
在 EDU Chain 上创建 Fungible Token
web3·智能合约
微wx笑3 天前
伦敦金库彻底断供的连锁反应推演(截至2025年02月22日)
区块链
Minner-Scrapy3 天前
区块链共识机制详解
去中心化·区块链·共识算法·web app