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

页面调用效果图 官方示例

相关推荐
旋生万物18 小时前
全息编码:从 CRC 到 Merkle Tree 到区块链的统一视角
区块链·#人工智能·#后端开发·#软件工程·#数据结构与算法·#云原生·#分布式系统
ZDGJ60991 天前
国际期货交易中如何选择交易时机?
区块链
MuMuMu12232 天前
越华环保集团碳惠小屋:物联网 + 区块链,构建碳普惠终端数据可信与隐私保护体系
物联网·区块链
IvorySQL3 天前
PostgreSQL 日报| PgBouncer 修复三个 CVE 漏洞(10 月 15 日)
数据库·postgresql·区块链
十二同学啊3 天前
反洗钱体系详解:KYC、风险评级、交易监控与可疑交易报告
web3·区块链·智能合约
海宇大数据3 天前
零信任架构实战:基于海宇公安二要素认证即时版构建自动化证券账户实名鉴权网关
人工智能·架构·自动化·区块链
磐链科技3 天前
DApp技术架构全面解析:从区块链底层、前后端开发到链上数据交互体系设计
架构·区块链
ZDGJ60994 天前
国际期货交易时段流动性影响因素
区块链
IvorySQL4 天前
PostgreSQL 日报| pg_vectorsearch 开源向量搜索发布(10 月 14 日)
数据库·人工智能·postgresql·开源·区块链