michielpost / MetaMask.Blazor

Use MetaMask with Blazor WebAssembly
MIT License
44 stars 21 forks source link
blazor blazor-webassembly dapps ethereum metamask

MetaMask.Blazor

Use MetaMask with Blazor WebAssembly

This library provides an easy helper to use MetaMask with Blazor WebAssembly.

Live Demo

Real world implementation, login with MetaMask: SkyDocs

How to use

See included Blazor sample app.

Install: MetaMask.Blazor on NuGet

Register in Program.cs:

builder.Services.AddMetaMaskBlazor();

Inject the MetaMaskService in your Razor page

@using MetaMask.Blazor
@inject IMetaMaskService MetaMaskService

or class when using a .razor.cs file:

[Inject]
public IMetaMaskService MetaMaskService { get; set; } = default!;

Use the MetaMaskService:

Check if the user has MetaMask installed:

bool hasMetaMask = await MetaMaskService.HasMetaMask();

Check if the user has previously connected to your site.

bool isSiteConnected = await MetaMaskService.IsSiteConnected();

Initialize a new connection with MetaMask

try
{
    await MetaMaskService.ConnectMetaMask();
}
catch (UserDeniedException)
{
   //Handle "User Denied" case;
}

This can throw exceptions if the user decides to not allow the connection.

Once there is a connection, you can use other method calls like:

Events

Listen to events: await MetaMaskService.ListenToEvents();

You can subscribe to two events:

Reference

Acknowledgements

Development of MetaMask.Blazor has been made possible with a grant from The Graph.