小狐狸JSON-RPC:钱包连接,断开连接,监听地址改变

发布于:2024-03-29 ⋅ 阅读:(15) ⋅ 点赞:(0)

detect-metamask
创建连接,并监听钱包切换

一、连接钱包,切换地址(监听地址切换),断开连接

  1. 使用npm安装 @metamask/detect-provider在您的项目目录中:
npm i @metamask/detect-provider
import detectEthereumProvider from "@metamask/detect-provider";
async onLoad() {
	if (typeof window.ethereum !== "undefined") {
	    console.log("MetaMask 已安装!");
	}
	this.provider = await detectEthereumProvider();
	this.provider.request({
		method: "eth_accounts"
	}).then(this.handleAccountsChanged).catch((err) => {
		console.error(err);
	});
	this.provider.on("accountsChanged", this.handleAccountsChanged);
},
methods: {
	// 这个方法,只在钱包APP内可以监听到地址切换,浏览器不行。
	handleAccountsChanged(accounts) {
		console.log('监听', accounts);
		if (accounts.length === 0) {
			console.log("请连接到MetaMask");
		} else if (accounts[0] !== this.address) {
			console.log('地址发生更换', this.address);
			this.address = accounts[0];
		}
	},
	// 连接钱包
	async getAccount() {
		// 1.向用户请求连接钱包,弹出钱包选择账户
		let res = await window.ethereum.request({
			"method": "wallet_requestPermissions",
			"params": [{
				"eth_accounts": {}
			}]
		}).catch((err) => {
			// User rejected the request. (用户拒绝了请求。)
			console.log(err.message);
		});
		if(res){
			// 2.选择地址并确认
			let accounts = await this.provider.request({
				method: "eth_requestAccounts"
			}).catch((err) => {
				if (err.code === 4001) {
					console.log("请连接到MetaMask.");
				} else {
					console.error(err);
				}
			});
			this.address = accounts[0]; // 当前钱包地址
		}
	},
	// 关闭连接,仅适用于浏览器扩展。
	async closeAccount() {
		var res = await window.ethereum.request({
			"method": "wallet_revokePermissions",
			"params": [{
				"eth_accounts": {}
			}]
		});
		this.address = ''
		console.log('连接已断开', res);
	},
}

实现的效果图:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

本文含有隐藏内容,请 开通VIP 后查看