MetaMask Snaps - 为插件钱包写插件

  • Confucian
  • 更新于 2023-10-13 16:11
  • 阅读 860

介绍官网:https://metamask.io/snaps/ MetaMask是EVM系最著名的浏览器插件钱包,而Snaps则是其一个新功能——为MetaMask做扩展,进而为用户提供多样化/定制化服务

MetaMask-Snaps-Banner.png

介绍

官网:https://metamask.io/snaps/

Extend the functionality of MetaMask

MetaMask 是 EVM 系最著名的浏览器插件钱包,而 Snaps 则是其一个新功能——为 MetaMask 做扩展,进而为用户提供多样化/定制化服务

截止到 2023 年 6 月,MetaMask 是唯一一家支持自定义插件的钱包提供商

功能

使用 Snaps 可以支持以下功能:

  • 增加新的 API
  • 支持各种不同的区块链协议:支持非 EVM 系区块链
  • 修改现有功能/信息:对话框、提醒
  • 展示交易信息:能够访问区块链节点
  • 定时任务:用户周期性操作
  • 访问互联网
  • 自定义 UI

开发

开发者文档:https://docs.metamask.io/snaps/

想要开发 MetaMask Snaps 需要使用 MetaMask Flask 钱包,也就是 MetaMask 的开发者版本。除此之外,还需要本地安装 Node.js 与 Yarn 环境

注意:MetaMask 和 MetaMask Flask 不能在同一个浏览器中同时启用,最好将 MetaMask Flask 安装到另一个未安装 MetaMask 的浏览器上

脚手架初始化参考 官方 QuickStart

我们开发功能主要对 packages/snap/src/index.ts 来进行修改

import { OnRpcRequestHandler } from '@metamask/snaps-types';
import { panel, text } from '@metamask/snaps-ui';

/**
 * Handle incoming JSON-RPC requests, sent through `wallet_invokeSnap`.
 *
 * @param args - The request handler args as object.
 * @param args.origin - The origin of the request, e.g., the website that
 * invoked the snap.
 * @param args.request - A validated JSON-RPC request object.
 * @returns The result of `snap_dialog`.
 * @throws If the request method is not valid for this snap.
 */
export const onRpcRequest: OnRpcRequestHandler = ({ origin, request }) => {
  switch (request.method) {
    case 'hello':
      return snap.request({
        method: 'snap_dialog',
        params: {
          type: 'confirmation',
          content: panel([
            text(`Hello, **${origin}**!`),
            text('This custom confirmation is just for display purposes.'),
            text(
              'But you can edit the snap source code to make it do something, if you want to!',
            ),
          ]),
        },
      });
    default:
      throw new Error('Method not found.');
  }
};

网站页面的配置在 packages/site 路径下

官方教程

官方提供一些功能教程,比如预估 gas 和展示交易信息

我参考 官方教程 尝试了开发预估 gas 的 Snap

repo: https://github.com/Confucian-e/gas-estimation-snap

它主要是通过联网访问第三方 API 获取当前 gas fee

需要在 packages/snap/snap.manifest.json 中的 initialPermissions 下添加 "endowment:network-access": {} 这个许可来访问网络,进而访问第三方 API

然后在 packages/snap/src/index.ts 中增加相关逻辑代码即可响应并展示给用户

snaps-gas-estimation.png

点赞 1
收藏 1
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
Confucian
Confucian
0xDa6E...5500
Keep Learning