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

页面调用效果图 官方示例

相关推荐
木西4 天前
揭秘 Web3 隐私社交标杆:CocoCat 的核心架构与智能合约实现
web3·智能合约·solidity
木西5 天前
深度拆解 Grass 模式:基于 EIP-712 与 DePIN 架构的奖励分发系统实现
web3·智能合约·solidity
kida_yuan5 天前
【以太来袭】4. Geth 原理与解析
区块链
blockcoach7 天前
刘教链|金融市场中的物理学规律:平方根定律
区块链
Black_mario7 天前
Web3 时代的“伯克希尔”时刻:解析 Jason Hitchcock 与 Greenlane 的 Berachain 主权财库之路
web3
碳链价值7 天前
吴忌寒清仓比特币背后
区块链
blockcoach7 天前
刘教链|BTC的时光机
区块链
China_Yanhy7 天前
入职 Web3 运维日记 · 第 14 日:铸造无形钥匙 —— OIDC 与 CI/CD 施工实录
运维·web3
lsrsyx8 天前
TEBBIT:以安全、创新与服务,重塑您的数字资产交易体验
安全·区块链