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

实现的效果图:


相关推荐
web3.088899914 分钟前
天猫API接口详解:商品详情与关键词搜索商品指南及代码示例
python·json
liulilittle1 小时前
TCP BBR 拥塞控制模块编译
网络·网络协议·tcp/ip
wangl_922 小时前
Modbus RTU 与 Modbus TCP 深入指南-功能码与数据模型
网络·网络协议·tcp/ip·tcp·modbus·rtu
wangl_923 小时前
Modbus RTU 与 Modbus TCP 深入指南-性能分析与优化
网络·网络协议·tcp/ip·tcp·modbus·rtu
源远流长jerry4 小时前
Linux 网络收包机制:从网卡到 Socket 的完整路径
linux·运维·服务器·网络·网络协议·tcp/ip
上海云盾安全满满5 小时前
选择接入高防IP后,源机是否还要带有防护
网络·网络协议·tcp/ip
treesforest7 小时前
IP地理位置精准查询:从城市级到街道级的定位技术深度解析
大数据·网络·网络协议·tcp/ip·安全·网络安全·ip
哼?~8 小时前
再谈UDP协议
网络·网络协议·udp
IPHWT 零软网络8 小时前
OM200G-A融合通信IP-PBX:国产化架构下的高可靠政企通信解决方案
网络协议·tcp/ip·架构
路溪非溪8 小时前
BLE MESH基础知识总结
网络·网络协议·智能路由器·射频工程