Erik Marks
    • 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
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

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

      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.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      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
    • Note Insights New
    • Engagement control
    • Make a copy
    • 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 Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy 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
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

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

    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.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    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
    3
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Getting Started with MetaMask Snaps _Devcon VI Workshop_ Kudos to [@Mrtenz](https://github.com/Mrtenz) for the Snap implementation. ## Resources - [Snaps landing page](https://metamask.io/snaps) - [Snaps documentation](https://docs.metamask.io/guide/snaps.html) - [Snaps discussion board](https://github.com/MetaMask/snaps-monorepo/discussions) - [Template snap monorepo](https://github.com/MetaMask/template-snap-monorepo) - [Completed workshop code](https://github.com/rekmarks/devcon-2022-snap/tree/completed) ## Before We Begin 1. Ensure that you have the following dependencies: - A Chromium browser or Firefox - `git` - [Node.js](https://nodejs.org/en/) `^16.0.0` - [`yarn`](https://yarnpkg.com/getting-started/install) - `yarn` can also be installed after cloning the repository, see below. 2. Install [MetaMask Flask](https://metamask.io/flask/). - _During Devcon VI, a prerelease build of MetaMask Flask was required, but this is no longer the case._ 3. Add an existing secret recovery phrase that you aren't afraid to lose, or create a new one. ## The Workshop Our goal is to create a snap that decodes contract call function names and parameters using the [4byte API](https://www.4byte.directory/docs/) and [`@metamask/abi-utils`](https://npmjs.com/package/@metamask/abi-utils). 1. Create a new GitHub repository using the [template snap monorepo](https://github.com/MetaMask/template-snap-monorepo). - This template contains two workspaces, one for the snap and one for the website / dapp that will serve as its user interface. - `git clone` your new repository. - Run `yarn install` at the monorepo root. - If you do not already have `yarn` installed, you can start the installation by directly running `.yarn/releases/yarn-3.2.1.cjs install` from the monorepo root. 2. Boot the snap and website by running `yarn start` at the monorepo root. - This will set up live reloading for both the snap and the website. 3. Install the example snap by clicking `Connect` on the website, then try out its functionality by clicking `Send message`. - The snap will be executed by MetaMask in a sandboxed environment and display a confirmation. 4. Rewrite the snap to use the transaction insights API. - In `snap.manifest.json`, replace the `snap_confirm` permission with `endowment:transaction-insight`. - In `index.ts`, replace the `onRpcRequest` handler with an `onTransaction` handler. Make sure it is exported. - We will add some basic validation. Add [`@metamask/utils`](https://npmjs.com/package/@metamask/utils) as a dependency of your snap and import it in your snap's `index.ts` file. 5. Customize the website to suit your snap, and rewrite the `Send message` logic to create an Ethereum transaction instead. - Don't forget to add logic for requesting Ethereum accounts so that you are able to submit transactions to MetaMask. - You can use the address from `TransactionConstants` as the recipient address. See [Transaction Snippets](#Transaction-Snippets) below. 6. Click `Reconnect` in the UI to reinstall the snap, then click `Send message` to observe your "decoded transaction". 7. Call the 4byte API from within your snap. - Snaps do not get network access by default. Add `endowment:network-access` to your snap's permissions. - Copy the [4byte Snippet](#4byte-Snippet) below for the API URL and some helpful types. - Return some of the data from 4byte as an "insight" so we know that it works. 8. Finally, decode the parameters using [`@metamask/abi-utils`](https://npmjs.com/package/@metamask/abi-utils). - Add `@metamask/abi-utils` as a dependency of your snap and import it in your snap's `index.ts` file. - Copy the `normalizeAbiValue` function from the [Value Normalizer Snippet](#Value-Normalizer-Snippet) and paste it into your snap's `index.ts` file. - Extract the parameter types, decode them using `@metamaks/abi-utils`, and return your your completed insights. ### Transaction Snippets We will demonstrate our snap's functionality by decoding some mock contract transactions that we create. You can of course try some contract interactions on your own as well. ```typescript enum TransactionConstants { // The address of an arbitrary contract that will reject any transactions it receives Address = '0x08A8fDBddc160A7d5b957256b903dCAb1aE512C5', // Some example encoded contract transaction data UpdateWithdrawalAccount = '0x83ade3dc00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000200000000000000000000000047170ceae335a9db7e96b72de630389669b334710000000000000000000000006b175474e89094c44da98b954eedeac495271d0f', UpdateMigrationMode = '0x2e26065e0000000000000000000000000000000000000000000000000000000000000000', UpdateCap = '0x85b2c14a00000000000000000000000047170ceae335a9db7e96b72de630389669b334710000000000000000000000000000000000000000000000000de0b6b3a7640000', } ``` ```typescript // A function that sends contract transactions export const sendContractTransaction = async (data: string) => { // Get the user's account from MetaMask. const [from] = (await window.ethereum.request({ method: 'eth_requestAccounts', })) as string[]; // Send a transaction to MetaMask. await window.ethereum.request({ method: 'eth_sendTransaction', params: [ { from, to: TransactionConstants.Address, value: '0x0', data, }, ], }); }; ``` ### 4byte Snippet We will use the [4byte API](https://www.4byte.directory/docs/) in our Snap. Here is a snippet with some constants: ```typescript // The API endpoint to get a list of functions by 4 byte signature. const API_ENDPOINT = 'https://www.4byte.directory/api/v1/signatures/?hex_signature='; /* eslint-disable camelcase */ type FourByteSignature = { id: number; created_at: string; text_signature: string; hex_signature: string; bytes_signature: string; }; /* eslint-enable camelcase */ ``` ### Value Normalizer Snippet ```typescript /** * The ABI decoder returns certain which are not JSON serializable. This * function converts them to strings. * * @param value - The value to convert. * @returns The converted value. */ function normalizeAbiValue(value: unknown): Json { if (Array.isArray(value)) { return value.map(normalizeAbiValue); } if (value instanceof Uint8Array) { return bytesToHex(value); } if (typeof value === 'bigint') { return value.toString(); } return value as Json; } ```

    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
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    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