BestLidamao
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# 一文读懂MetaMask Snap,极速开发你的第一个AI Snap ### 前言 #### Metamask Snap是什么? 前几天Consensys 宣布向公众推出 MetaMask Snaps 的首个版本。据官网说明,MetaMask Snaps 是由第三方开发人员创建的功能,MetaMask 用户可以将其直接安装到他们的钱包中。 目前官方已经公布了35款可用的snap,并发布了snap应用商店 [https://snaps.metamask.io/](https://snaps.metamask.io/) ![](https://hackmd.io/_uploads/ryGJF-zy6.png) #### Metamask Snap 初体验 为了方便演示,接下来的视频中我们讲讲解交易洞察的demo是如何工作的,[本文交易洞察部分案例体验网址](https://insights.pages.dev/) <iframe width="560" height="315" src="https://www.youtube.com/embed/BHK8WDRWE9Y?si=QV3LvOOXELlrKZ91" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> 以下将会用一个视频来介绍安装流程 Snap 通过 npm 平台来托管和分发,用户点击安装后小狐狸自动加载包并添加到snap列表中.MetaMask官方将会通过一个whitelist来控制snap是否可以安装(审计过的), <iframe width="560" height="315" src="https://www.youtube.com/embed/LhTJFWYdbgA?si=hzXjkLFIIZK4YO8t" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> 我们可以在视频中看到 <img style="width:70%" src="https://hackmd.io/_uploads/S1zvVo-Jp.png" alt="install snap"/> 1. 获取以太坊provider,实际上是获取当前RPC以便确认所处链 2. 获取网络请求,也就是snap调用第三方api的能力 3. 获取交易内容,插件就是通过这个能力读取用户的交易data 由此看来 Snap 对权限的控制是相对较细的,同时对安全性也采取了相当重视的态度.整体采用最小权限的思路来设计,需要用户在安装前了解并确认。 接下来我们分析一下 snap 的安全性和设计 #### Snap是安全的吗? 目前来看Snap的安全性非常高 1. Snaps 采用 Agoric 团队的 Hardened JavaScript (又称 Secure EcmaScript ,是 Agoric 团队开发的 JS 框架)作为其"完全虚拟化"沙盒方案,Agoric 的脚本语言允许 MetaMask 限制对全局 JS API 的访问,并将不受信任的代码与应用程序的其他部分分开。因此 Snap 只能访问一组有限的权限,且由用户在安装时确定。通过这一系列举措为 Snap 提供了必要的安全基础。 2. 明确的用户授权,在 Snap 安装时已经明确显示所有可能的授权. 用户可以根据Snap的来源来决策是否安装 3. 代码必须开源,成为官方认可的snap必须代码开源,通过社区的力量大大降低snap自带恶意代码的可能性 4. 专业的安全审核,目前软件中心的Snap都经过第三方安全公司的代码审计. 也只有通过审核的Snap才能被发布。 这大大提高了Snap的安全可信度,其中就包括大家都非常熟悉的慢雾 <img src="https://hackmd.io/_uploads/H1O50-7Ja.png" alt="notify" style="height:300px"/> 以下是由慢雾审核的几个snap审计信息 1. [Unipass](https://snaps.metamask.io/snap/npm/unipasswallet/unipass-snap/) 2. [btcsnap](https://snaps.metamask.io/snap/npm/btcsnap/) 3. [Riskdetect-snap](https://snaps.metamask.io/snap/npm/goplus/riskdetect-snap/) #### MetaMask Snap为什么重要? Snap似乎是MetaMask近期最大的开发重心,实际上2022年年底左右就有一批开发者在进行snap开发了 基于目前公布的三大API: 1. Interoperability(互操作性),允许开发者基于metamask开发其他链钱包 2. Transaction Insights(交易洞察),允许开发者在用户交易发起前获取交易data,从而分析交易是否存在风险 3. Notifications(通知),通过snap直接推送消息给用户(不过这里似乎需要网站支持,略微有点鸡肋) ![](https://hackmd.io/_uploads/HJsaxwkyp.png) 提供了这些API的MetaMask实际上已经成为类似开放平台一样的产品.类比微信小程序,凭借MetaMask巨大的用户流量入口,Snap势必成为下一个开发风口 #### Span的几个特性简单介绍 `snap_notify`:notify接口可以在 MetaMask 或浏览器中显示通知。snap可以通过这个接口向用户直接发送消息,具体如下图所示 <img src="https://hackmd.io/_uploads/H1ZhIiZkT.png" alt="notify" style="width:50%"/> `Transaction Insights`:当用户与智能合约进行交互时,snap就会收到onTransaction事件,MetaMask 会将未签名的原始交易传递给 onTransaction 处理程序方法,snap可以在交易的二次确认页面返回一个界面,并且自定义显示内容 <img src="https://hackmd.io/_uploads/B1DMcobJ6.png" alt="Insight" style="height:300px"/> `Dialog`:Dialog能力将允许snap直接弹出一个独立窗口,实现类似传统Alert/Confirm/Prompt弹窗能力(如下图) <img src="https://hackmd.io/_uploads/ByAEOoWkp.png" alt="Insight" style="height:300px"/> #### MetaMask Snap暂时无法实现什么样的功能? 限制于安全性等原因,Snap目前不支持第三方前端框架,只提供了比较少数的UIKit,以下仍然是用insight做示例,展示所有开发者可以调用的ui组件库 <img src="https://hackmd.io/_uploads/SJ4pnyG1p.png" alt="Insight" style="height:300px"/> 如图所示,目前上线的只有Heading(大文字),Text(小文字),Panel(卡片且只能用一次),Divider(分割线),Copyable(点击复制)和小部分Markdown子集( **bold** 和 _italic_),所以说构建可交互似乎暂时无法实现,也无法使用内嵌html来实现交互操作 用户可以点击或者输入内容的方法,似乎只有调用上文中的Dialog能力 不过在官方Discord中提问后,官方声称这些都是出于安全性的考虑,并将会在接下来的版本中放开。 ### 本章小总结 以上分析那么多,不如直接入手开发一款snap,从而更加深入了解如何快速上手 本文将介绍如何使用**transaction insight**能力来开发一款 **基于chatgpt的全自动AI智能合约审计Snap** ## 开始BUIDL #### 梳理思路 众所周知,大部分用户在绝大多数情况下其实并不知道正在交互的智能合约到底是什么,主要包括如下几个问题 1. 交易的合约是否是钓鱼网站替换的合约 2. 交易的合约是否是一个可升级合约 3. 智能合约是否是一个刚被部署还没有多少人验证过的合约 4. 交易的合约是否开源 更别提对于普通用户来说犹如天书一般的Solidity语言 这时其实非常适合Transaction Insight功能 使用一些传统手段检测上面的几个问题,然后使用AI来对智能合约做一个比较浅显的**安全性审计** 哪怕能解决80%的问题,也能避免大量用户被钓鱼合约欺骗 #### 准备开发环境 **下载钱包** 首先需要安装MetaMask Flask [MetaMask Flask官网](https://metamask.io/flask/) ![](https://hackmd.io/_uploads/H1kcLOJk6.png) MetaMask Flask 是一个以开发人员为中心的 MetaMask 扩展发行版,主要用于新功能预览以及实验性功能开发 这里使用Flask主要是方便我们开发的snap能本地即时预览 > 建议安装后先暂时关掉小狐狸钱包以及其他浏览器钱包,会冲突 **创建账户** 安装钱包后就像正常创建MetaMask钱包一样创建一个新钱包(记住要保存好助记词) 接下来我们需要给新创建的钱包中充值一些测试币,测试币可以通过以下几个水龙头获取 - [Sepolia](https://sepoliafaucet.com/) - [Goerli](https://goerlifaucet.com/) - [Linea](https://faucet.goerli.linea.build/) 本文讲的snap使用的是goerli,所以下文以goerli为主 **创建Snap模板** 因为要做Transaction Insight,所以我们可以fork一个官方的Template 按照官方文档,首先使用`@metamask/create-snap`这个CLI来创建一个新的snap项目 ``` yarn create @metamask/snap transaction-insights-snap ``` 或者 ``` npm create @metamask/snap transaction-insights-snap ``` 然后 ``` cd transaction-insights-snap ``` #### 文件结构 snap的主要文件在`./packages/snap`中,文件目录结构如下 <img src="https://hackmd.io/_uploads/SkgwyZG16.png" alt="notify" style="height:300px"/> snap的配置文件被放在`snap.mainfest.json`中 snap的主体文件为`./src/index.ts` #### 启用权限 首先需要启用权限,首先我们在snap.mainfest.json中新增如下三条 ```json "initialPermissions": { "endowment:transaction-insight": {},//交易洞察 "endowment:ethereum-provider": {},//获取rpc "endowment:network-access": {}//请求网络 } ``` mainfest文件中还可以修改`description`和`proposedName`来修改项目的描述和名称 #### 获取交易 接下来本案例中只需要修改`index.ts`文件即可完成全部功能,[GitHub完整地址](https://github.com/LidamaoHub/insights) 接下来完成基础的框架(snap最近在快速更新,本段代码在写文时可以运行) ```typescript! import { OnTransactionHandler, OnRpcRequestHandler } from '@metamask/snaps-types';//首先需要引入snap-types类文件 import { heading, panel, text, copyable, divider } from '@metamask/snaps-ui';//引入snap ui部分组件 export const onTransaction: OnTransactionHandler = async ({ transaction }) => { //作为一个小的snap demo,且完成交易洞察,首先需要获取到用户的交易data // 此处transaction包含了to(合约地址),data(交互数据)等值 // 以下是UI部分代码 return { content: panel( [ text( "普通文本" ), heading("标题文本"), text("正文文本"), divider(),//分割线 text( "**粗体文本**", ), text( "_斜体文本_", ), copyable( `https://contract-info.pages.dev`, )//点击后复制的交互组件 ]) }; }; ``` 更多的内容请参考[MetaMask Snap开发者文档](https://docs.metamask.io/snaps/)完成更复杂的snap产品。 在Snap的文件中使用了一个自建的第三方服务AI审计,以下是核心代码 ```python= prompt = f"Please audit the following smart contract and point out any loopholes or deficiencies in this contract:{code}" messages = [ {"role": "system", "content": "imagine you are samczsun, you specialize in auditing and reversing smart contracts,Please limit your answer to 1000 characters"}, {"role": "system", "content": "You will not repeat questions in your answers"}, ] messages.append({"role": "user", "content": prompt}) completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=messages, max_tokens=1024, n=1, stop=None, temperature=0, stream=True ) for chunk in completion: if "content" in chunk["choices"][0]["delta"]: a = chunk["choices"][0]["delta"]["content"] answer+=a ``` 当前Transaction Insight运行效果请见本文第一个演示视频 ### 开发者支持 如果你能够跑通以上样例,那么恭喜你已经成为一个合格的Snap入门开发者! MetaMask官方也有一个专门的MetaMask Grants DAO,通过赠款计划资助 MetaMask 生态系统中高价值项目的开发来激励开发者 MMG是一项由员工主导的实验性计划,向全球外部开发人员发放赠款,以在 MetaMask 生态系统中构建有影响力的体验。 目前只要是能丰富MetaMask生态的项目都可以申请官方的MMG( MetaMask Grant ),当前MetaMask Grants DAO 每年的预算为 240 万美元。 [当前已通过的Grant列表](https://metamaskgrants.org/latest-grantees) 特别值得一提的是,LXDAO的MobyMask很荣幸的作为早期项目申请到了MetaMask Grant <img src="https://hackmd.io/_uploads/H1ybUPmkp.png" alt="Insight" style="height:300px"/> 具体的提案参考:[snapshot链接](https://snapshot.org/#/heart.mmgdao.eth/proposal/0xc5b54ea4a9b7e426e06432735716eb0d401ef93fd0d8fca6b88ceeea8caecd93) ### 结语 目前MetaMask Snap仍在快速迭代的,未来也将会兼容更多内容甚至是形成类似小程序商店那样的巨大生态,不可小觑 MetaMask作为引领行业的钱包,它开放的姿态将促进整个生态的进步。开发者如果能抓住Snap这一机遇,也将有机会做出影响力产品。让我们拭目以待Snap带来的下一个突破性创新。 最后,感谢您的文章,相信这有助于让更多人了解MetaMask Snap的发展现状。 如果你是开发者,请一定不要错过 也请继续关注[LXDAO](https://lxdao.io/),我们将在后续产出更多MetaMask Snap相关文章,敬请期待!

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully