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

实现的效果图:


相关推荐
AI视觉网奇7 分钟前
ue http 请求学习笔记
网络·网络协议·http
集智飞行16 分钟前
mavros udp url
网络·网络协议·udp
FreeBuf_17 分钟前
攻击者伪造Jackson JSON库入侵Maven中央仓库
java·json·maven
一颗青果7 小时前
HTTP协议详解
linux·网络·网络协议·http
晚枫歌F14 小时前
TCP协议详解
网络·网络协议·tcp/ip
秋42714 小时前
防火墙基本介绍与使用
linux·网络协议·安全·网络安全·架构·系统安全
sweet丶15 小时前
扩展了解DNS放大攻击:原理、影响与防御
网络协议·安全
科技块儿16 小时前
我应该如何选择并使用IP数据库评估不同地区的定位精度(⊙_⊙?)
网络·网络协议·tcp/ip
少莫千华17 小时前
【Web API】RESTful API接口规范
前端·后端·json·api·restful·rest
万粉变现经纪人18 小时前
如何解决 pip install SSL 报错 ValueError: check_hostname requires server_hostname 问题
网络·python·网络协议·beautifulsoup·bug·ssl·pip