Eric Bishard
    • 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
4
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# A Guide to EIP-6963 for React Developers This article will fast track your understanding of EIP-6963 (Multi-Wallet Injected Provider Discovery), answer questions about how to implement in your React dAPp. Just want to see the code? Below is the example code in ViteJS (React + TypeScript) if you'd like to skip the chit chat: GitHub Repo: [vite-react-ts-eip-6963](https://github.com/MetaMask/vite-react-ts-eip-6963) This example code implements EIP-6963 for detecting multiple injected providers (browser installed wallets (Externally Owned Accounts)). Follow along as we explore the interfaces outlined in the EIP, learn about listening to `eip6963:announceProvider` events and storing and distinguishing between the various returned providers for their use anywhere in our dApp. [Skip to "What Developers Need to Know"](#What-Developers-Need-to-Know) The feeling of victory every time I complete a difficult level in [geometry dash meldown](https://geometrydashmeltdown.io) is extremely satisfying, and this is the motivation that helps me continue to challenge myself. A preview of what we will build: ![EIP-6963 React Demo](https://imgur.com/j79GvQ9.gif) ## The EIP-6963 Abstract > An alternative discovery mechanism to `window.ethereum` for [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) providers which **_supports discovering multiple injected Wallet Providers_** in a web page using Javascript’s window events. Before trying to understand any EIP, read and fully understand the [abstract](https://eips.ethereum.org/EIPS/eip-6963#abstract) (Quoted above), [motivation](https://eips.ethereum.org/EIPS/eip-6963#motivation), and do a full read through even if there are aspects that you don't understand. > Note: If you don't understand any part, you can get further information through sites like Ethereum Magicians ([EIP-6963 MIPD](https://ethereum-magicians.org/t/eip-6963-multi-injected-provider-discovery/14076)) where you can get additional context from the authors and the community on most EIPs. It will also be helpful to familiarize yourself [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193). The most important line from the [EIP-6963 abstract](https://eips.ethereum.org/EIPS/eip-6963#abstract) is: **_"An alternative discovery mechanism to `window.ethereum` for EIP-1193 providers"_** Immediately this tells me that EIP-6963's Multi Injected Provider Discovery proposal introduces a different approach for **discovering and interacting with EIP-1193 providers)** in contrast to the existing method relying on the `window.ethereum` object. As a developer with `window.ethereum` littered throughout my dapps and the UX issues that come with the older approach, they have my attention. Hopefully this info helps to frame our thinking as we progress through the EIP and start to implement this improved way of detecting our users installed wallets. ## Issues Predating EIP-6963 In Ethereum dApps, wallets traditionally expose their APIs using a JavaScript object known as 'the Provider.' The initial EIP created to standardize this interface was EIP-1193, and conflicts have risen among different wallet implementations. While EIP-1193 aimed to establish a common convention, the user experience suffered due to race conditions caused by wallets injecting their providers (clobbering) the `window`'s (Ethereum object). This has been a huge criticism of Web3 UX and its shortcomings around wallet discovery, onboarding and connection. These race conditions resulted in multiple wallet extensions enabled in the same browser having conflicts, where the last injected provider takes precedence. EIP-5749 attempted to solve this issue with a `window.evmprovider` solution, and was a step in the right direction, but ultimately was not adopted by enough wallets to solve our UX issues. This is where we end up with EIP 6963 bringing a standard to propose a way of doing Multi Injected Provider Discovery and wallets are taking notice and most have implemented this new standard. [List of wallets that support EIP-6963](https://github.com/WalletConnect/EIP6963/blob/master/src/utils/constants.ts) ## What Developers Need to Know As a developer, the first thing you should do in order to get familiar with [EIP-6963](https://eips.ethereum.org/EIPS/eip-6963), is to understand the initial motive, basic description, and more importantly the types, interfaces and logic needed to implement this new approach. ## Implementing EIP-6963 in a ViteJS React + TS Application The Provider MUST implement and expose the interfaces defined in the EIP. Let's review them real quick, i have also provided links to each section of the original EIP for reference. [Provider Info](https://eips.ethereum.org/EIPS/eip-6963#provider-info) > Each Wallet Provider will be announced with the following interface: ```ts= /** * Represents the assets needed to display a wallet */ interface EIP6963ProviderInfo { uuid: string; name: string; icon: string; rdns: string; } ``` [Provider Detail](https://eips.ethereum.org/EIPS/eip-6963#provider-detail) > used as a composition interface to announce a Wallet Provider and related metadata about the Wallet Provider ```ts= interface EIP6963ProviderDetail { info: EIP6963ProviderInfo; provider: EIP1193Provider; } ``` [Announce](https://eips.ethereum.org/EIPS/eip-6963#announce-and-request-events) > The `EIP6963AnnounceProviderEvent` interface MUST be a `CustomEvent` object with a `type` property containing a string value of `eip6963:announceProvider` and a detail property with an object value of type `EIP6963ProviderDetail`. ```ts= // Announce Event dispatched by a Wallet interface EIP6963AnnounceProviderEvent extends CustomEvent { type: "eip6963:announceProvider"; detail: EIP6963ProviderDetail; } ``` [Request Events](https://eips.ethereum.org/EIPS/eip-6963#announce-and-request-events) > The `EIP6963RequestProviderEvent` interface MUST be an Event object with a type property containing a string value of `eip6963:requestProvider`. ```ts= // Request Event dispatched by a DApp interface EIP6963RequestProviderEvent extends Event { type: "eip6963:requestProvider"; } ``` With these interfaces understood, we can spin up a ViteJS React + TypeScript application and update the `src/vite-env.d.ts` with those interfaces and the addition of an `EIP1193Provider`: ### vite-env.d.ts ```ts= /// <reference types="vite/client" /> interface EIP6963ProviderInfo { walletId: string; uuid: string; name: string; icon: string; } // Represents the structure of an Ethereum provider based on the EIP-1193 standard. interface EIP1193Provider { isStatus?: boolean; host?: string; path?: string; sendAsync?: (request: { method: string, params?: Array<unknown> }, callback: (error: Error | null, response: unknown) => void) => void send?: (request: { method: string, params?: Array<unknown> }, callback: (error: Error | null, response: unknown) => void) => void request: (request: { method: string, params?: Array<unknown> }) => Promise<unknown> } interface EIP6963ProviderDetail { info: EIP6963ProviderInfo; provider: EIP1193Provider; } // This type represents the structure of an event dispatched by a wallet to announce its presence based on EIP-6963. type EIP6963AnnounceProviderEvent = { detail:{ info: EIP6963ProviderInfo, provider: EIP1193Provider } } ``` These interfaces and types provide a structured and standardized way to handle Ethereum wallet providers, facilitating the integration of EIP-6963. The definitions offer clear specifications for the information expected from wallet providers, promoting consistency and interoperability. We can then create a `hooks` directory and add the two following files: ### store.tsx ```ts= declare global{ interface WindowEventMap { "eip6963:announceProvider": CustomEvent } } let providers: EIP6963ProviderDetail[] = [] export const store = { value: ()=>providers, subscribe: (callback: ()=>void)=>{ function onAnnouncement(event: EIP6963AnnounceProviderEvent){ if(providers.map(p => p.info.uuid).includes(event.detail.info.uuid)) return providers = [...providers, event.detail] callback() } window.addEventListener("eip6963:announceProvider", onAnnouncement); window.dispatchEvent(new Event("eip6963:requestProvider")); return ()=>window.removeEventListener("eip6963:announceProvider", onAnnouncement) } } ``` About this store: - Defines a global event type for EIP-6963 provider announcements. - Manages an external store (providers) that holds the state of detected wallet providers. - Subscribes to the "eip6963:announceProvider" event and updates the external store when a new provider is announced. - Provides the value function to access the current state and the subscribe function to subscribe to changes in the external store. ### useSyncProviders.tsx ```ts= import { useSyncExternalStore } from "react"; import { store } from "./store"; export const useSyncProviders = ()=> useSyncExternalStore(store.subscribe, store.value, store.value) ``` Utilizes the `useSyncExternalStore` hook to synchronize the local state with the external store defined in `store.tsx`. In the next component `DiscoverWalletProviders`, the `useSyncProviders` hook is called to get the synchronized state. The `providers` variable now holds the current state of the external store `store.value`. The `DiscoverWalletProviders` component uses this state to dynamically render buttons for each detected wallet provider. Next we will add a component in the `src/components` directory. ### DiscoverWalletProviders.tsx ```ts= import { useState } from 'react' import { useSyncProviders } from '../hooks/useSyncProviders' import { formatAddress } from '~/utils' export const DiscoverWalletProviders = () => { const [selectedWallet, setSelectedWallet] = useState<EIP6963ProviderDetail>() const [userAccount, setUserAccount] = useState<string>('') const providers = useSyncProviders() const handleConnect = async(providerWithInfo: EIP6963ProviderDetail)=> { const accounts = await providerWithInfo.provider .request({method:'eth_requestAccounts'}) .catch(console.error) if(accounts?.[0]){ setSelectedWallet(providerWithInfo) setUserAccount(accounts?.[0]) } } return ( <> <h2>Wallets Detected:</h2> <div> { providers.length > 0 ? providers?.map((provider: EIP6963ProviderDetail)=>( <button key={provider.info.uuid} onClick={()=>handleConnect(provider)} > <img src={provider.info.icon} alt={provider.info.name} /> <div>{provider.info.name}</div> </button> )) : <div> there are no Announced Providers </div> } </div> <hr /> <h2>{ userAccount ? "" : "No " }Wallet Selected</h2> { userAccount && <div> <div> <img src={selectedWallet.info.icon} alt={selectedWallet.info.name} /> <div>{selectedWallet.info.name}</div> <div>({formatAddress(userAccount)})</div> </div> </div> } </> ) } ``` In the code above, as soon as the page is rendered we are logging the providers that we have detected. See lline 11. We can loop over these providers and create a button for each one, this button will be used to call `eth_requestAccounts`. Finally we can render this coomponent in `src/App.tsx` ### App.tsx ```ts= import './App.css' import { DiscoverWalletProviders } from './components/DiscoverWalletProviders' function App() { return ( <> <DiscoverWalletProviders/> </> ) } export default App ``` In summary, these files enable integration of EIP-6963 in a ViteJS (React + TypeScript) application. The interfaces and types are defined, the synchronization between components is taken care of by the `useSyncProviders` hook, and the external store `store.tsx` manages the state of detected wallet providers. With these few steps we have implemented EIP-6963 into a React application utilizing the TypeScript interfaces outlined in the EIP. At a basic level, that's it. You can see the source code here: [vite-react-ts-eip-6963 ](https://github.com/MetaMask/vite-react-ts-eip-6963) ## Third Party Library Support The easiest way for developers building in Web3 to start using EIP-6963 (Multi Injected Provider Discovery) is by taking advantage of Third Party connection libraries (convenience libraries) that already support it. At the time of this writing, here is the list: - [Wagmi 2+](https://wagmi.sh) - [Web3Modal 3+](https://docs.walletconnect.com/web3modal/about) - [MIPD Store](https://github.com/wevm/mipd) - [RainbowKit](https://www.rainbowkit.com) - [Web3Onboard](https://onboard.blocknative.com) If you are building Wallet Connection Libraries you will be happy to know that incorporating MetaMask's SDK will ensure that the connection to MetaMask supports EIP-6963 for the detection of the MetaMask extension and MetaMask Flask wallets. You can get the injected providers using Wagmi's [MIPD Store](https://github.com/wevm/mipd) With Vanilla JS and React examples. ## The MetaMask SDK The MetaMask SDK not only supports EIP-6963 on its own for detecting (only) MetaMask, but is also being integrated into Web3 Onboard and WAGMI v2.0. The SDKs integration of EIP-6963 is for the efficient discovery and connection with the MetaMask Extension. This enhancement is pivotal in streamlining the user experience and promoting seamless interactions with the Ethereum blockchain. ### MetaMask SDK Automatic Detection The MetaMask JS SDK now automatically checks for the presence of the MetaMask Extension that supports EIP-6963. This eliminates the need for manual configuration or detection methods, thereby simplifying the initial setup process for developers and users alike. Conflict Resolution: By adhering to the standards set by EIP-6963, the SDK unambiguously identifies and connects to the MetaMask Extension. This approach effectively resolves potential conflicts that might arise with other wallet extensions, ensuring a more stable and reliable interaction for users. ## Backwards compatibility Dapps that do not support EIP-6963 can still detect MetaMask using the `window.ethereum` provider. However, we recommend adding support to improve the user experience for multiple installed wallets. Read more about [EIP-6963 backwards compatibility](https://eips.ethereum.org/EIPS/eip-6963#backwards-compatibility). ## Resources for Reading on EIP-6963 [NextJS Version of this same App by the Wallet Connect team](https://github.com/WalletConnect/EIP6963) [Overview of EIP-6963: A Possible Solution for Multiple Wallet Conflict](https://mundus.dev/tpost/76iu0k1ot1-overview-of-eip-6963-a-possible-solution) [EIP-6963](https://eips.ethereum.org/EIPS/eip-6963) [EIP-6963 Standardizes Your Browser Wallet Experience](https://www.youtube.com/watch?v=SWmknCUwr3Y&t=281s) ## Additional Demos and Information - [WalletConnect created a NextJS example similar to the demo we are building](https://github.com/WalletConnect/EIP6963) - [Boidushya (DevRel at WalletConnect) created a greatTwitter Thread](https://twitter.com/boidushya/status/1714389971778552128)

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