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

实现的效果图:


相关推荐
凌波粒1 小时前
什么是 MCP(模型上下文协议)
人工智能·网络协议·aigc
XMYX-02 小时前
28 - Go JSON 数据操作
开发语言·golang·json
Ether IC Verifier3 小时前
TCP/IP四层协议详解与以太网包发送过程
网络·网络协议·tcp/ip·计算机网络·dpu
heimeiyingwang5 小时前
【架构实战】RPC框架Dubbo3.0:高性能Java通信之道
java·rpc·架构
Ether IC Verifier6 小时前
CPU/GPU/NPU/DPU功能详解与AI应用分析
网络·人工智能·网络协议·tcp/ip·计算机网络·dpu
lunzi_08269 小时前
《图解HTTP》--第3章 HTTP报文内的HTTP信息
网络·网络协议·http
Promise微笑10 小时前
Geo专家于磊:Json-LD优化实战SOP与双核四驱体系
大数据·人工智能·重构·json
专注VB编程开发20年11 小时前
json和python元组,列表,字典对比
开发语言·python·json·php
Shota Kishi11 小时前
ERPC 在 Solana RPC 中集成 Pyth Hermes 兼容的 Price API:从架构到调用的技术解析
网络协议·rpc·架构
念越11 小时前
HTTPS 安全内核:对称与非对称加密的博弈,数字证书一战定局
java·网络·网络协议·安全·https