小狐狸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);
	},
}

实现的效果图:


相关推荐
FPGA_Linuxer2 天前
FPGA 40 DAC线缆和光模块带光纤实现40G UDP差异
网络协议·fpga开发·udp
real 12 天前
传输层协议UDP
网络·网络协议·udp
hsjkdhs3 天前
网络编程之UDP广播与粘包问题
网络·网络协议·udp
yzx9910133 天前
接口协议全解析:从HTTP到gRPC,如何选择适合你的通信方案?
网络·人工智能·网络协议·flask·pygame
板鸭〈小号〉3 天前
UDP-Server(3)chat聊天室
网络·网络协议·udp
Martin-Luo3 天前
Vue3 通过json配置生成查询表单
javascript·vue.js·json
星尘库3 天前
后端json数据反序列化枚举类型不匹配的错误
json
BXCQ_xuan3 天前
软件工程实践四:MyBatis-Plus 教程(连接、分页、查询)
spring boot·mysql·json·mybatis
王维志3 天前
LiteDB详解
数据库·后端·mongodb·sqlite·c#·json·database
weixin_456904273 天前
使用HTTPS 服务在浏览器端使用摄像头的方式解析
网络协议·http·https