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

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

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

  1. 使用npm安装 @metamask/detect-provider在您的项目目录中:

    npm i @metamask/detect-provider

js 复制代码
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);
	},
}

实现的效果图:


相关推荐
小高Baby@16 分钟前
JSON、bind、form
数据结构·json
..过云雨34 分钟前
五种IO模型与非阻塞IO
网络·网络协议·tcp/ip
源远流长jerry1 小时前
dpdk之kni处理dns案例
linux·网络·网络协议·ubuntu·ip
阿蒙Amon2 小时前
TypeScript学习-第11章:配置文件(tsconfig.json)
学习·typescript·json
南墙上的石头5 小时前
docker日常使用命令汇总
docker·容器·rpc
db_murphy5 小时前
知识篇 | net.ipv4.ip_forward 参数
网络·网络协议·tcp/ip
Vect__5 小时前
TCP Socket编程详解
网络协议·tcp/ip·php
B2_Proxy6 小时前
如何使用代理服务解决“您的 ASN 被阻止”错误:全面策略分析
网络·爬虫·网络协议·tcp/ip·安全·代理模式
一起养小猫6 小时前
Flutter for OpenHarmony 进阶:Timer组件与倒计时系统深度解析
android·网络·笔记·flutter·json·harmonyos
Hello.Reader6 小时前
Rocket 0.5 响应体系Responder、流式输出、WebSocket 与 uri! 类型安全 URI
websocket·网络协议·安全·rust·rocket