Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions packages/metamask/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# @web3-onboard/metamask

## Wallet module for connecting MetaMask Wallet SDK to web3-onboard
## Wallet module for connecting MetaMask Connect EVM to web3-onboard
The MetaMask Web3-Onboard module provides a reliable, secure, and seamless connection from your dapp to the MetaMask browser extension and MetaMask Mobile.
See [MetaMask SDK Developer Docs](https://docs.metamask.io/wallet/how-to/connect/set-up-sdk/)

This module uses [MetaMask Connect EVM](https://docs.metamask.io/metamask-connect/evm/) (`@metamask/connect-evm`) under the hood — the successor to the legacy `@metamask/sdk`. The integration surface for `@web3-onboard/metamask` is unchanged: the legacy options below are mapped to their MetaMask Connect EVM equivalents internally so existing dapps keep working without code changes.

![MetaMask SDK ConnectionFlow](https://github.com/blocknative/web3-onboard/blob/develop/assets/metaMaskSDK-connect.gif?raw=true 'MetaMask SDK ConnectionFlow')

Expand All @@ -12,22 +13,35 @@ See [MetaMask SDK Developer Docs](https://docs.metamask.io/wallet/how-to/connect

### If using this package with the `@web3-onboard/injected-wallets` module
_When utilizing this package alongside the `@web3-onboard/injected-wallets` module, ensure to list this package prior to the initialized injected-wallets module within the wallets list of the Web3-Onboard init._
_This order prioritizes the SDK when a MetaMask browser wallet is detected, allowing the SDK to take precedence._
_This order prioritizes the MetaMask Connect EVM client when a MetaMask browser wallet is detected, allowing it to take precedence._

## Options

```typescript
// For a complete list of options check https://docs.metamask.io/wallet/how-to/connect/set-up-sdk/
// All fields are optional. Legacy MetaMaskSDK option names are accepted for
// backwards compatibility and mapped to MetaMask Connect EVM internally.
interface MetaMaskSDKOptions {
dappMetadata: {
dappMetadata?: {
url?: string;
name?: string;
iconUrl?: string;
base64Icon?: string;
},
};
/**
* If MetaMask browser extension is detected, directly use it without prompting the user.
* If MetaMask browser extension is detected, prefer it over the mobile flow.
* Mapped to `ui.preferExtension`.
*/
extensionOnly?: boolean;
/** Mapped to `ui.headless`. */
headless?: boolean;
/** Used to populate `api.supportedNetworks` via `getInfuraRpcUrls`. */
infuraAPIKey?: string;
/** Merged into `api.supportedNetworks`. */
readonlyRPCMap?: Record<string, string>;
/** Mapped to `mobile.preferredOpenLink`. */
openDeeplink?: (deeplink: string) => void;
/** Mapped to `mobile.useDeeplink`. */
useDeeplink?: boolean;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
```

Expand Down
6 changes: 3 additions & 3 deletions packages/metamask/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@web3-onboard/metamask",
"version": "2.2.1",
"description": "MetaMask SDK wallet module for connecting to Web3-Onboard. Web3-Onboard makes it simple to connect Ethereum hardware and software wallets to your dapp. Features standardised spec compliant web3 providers for all supported wallets, framework agnostic modern javascript UI with code splitting, CSS customization, multi-chain and multi-account support, reactive wallet state subscriptions and real-time transaction state change notifications.",
"version": "2.3.0",
"description": "MetaMask Connect EVM wallet module for connecting to Web3-Onboard. Web3-Onboard makes it simple to connect Ethereum hardware and software wallets to your dapp. Features standardised spec compliant web3 providers for all supported wallets, framework agnostic modern javascript UI with code splitting, CSS customization, multi-chain and multi-account support, reactive wallet state subscriptions and real-time transaction state change notifications.",
"keywords": [
"Ethereum",
"Web3",
Expand Down Expand Up @@ -58,7 +58,7 @@
"typescript": "^5.2.2"
},
"dependencies": {
"@metamask/sdk": "^0.32.0",
"@metamask/connect-evm": "^1.0.0",
"@web3-onboard/common": "^2.4.1"
},
"engines": {
Expand Down
209 changes: 159 additions & 50 deletions packages/metamask/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,95 +1,204 @@
import type { WalletInit } from '@web3-onboard/common'
import type { MetaMaskSDK, MetaMaskSDKOptions } from '@metamask/sdk'
import type { createEIP1193Provider } from '@web3-onboard/common'
import type {
createEVMClient as CreateEVMClientFn,
getInfuraRpcUrls as GetInfuraRpcUrlsFn,
MetamaskConnectEVM
} from '@metamask/connect-evm'

/**
* Legacy MetaMask SDK options that this module continues to accept for
* backwards compatibility. Each field is mapped to its
* `@metamask/connect-evm` equivalent inside `getInterface` so callers can
* upgrade transparently without changing their integration code.
*/
export type MetaMaskSDKOptions = {
dappMetadata?: {
name?: string
url?: string
iconUrl?: string
base64Icon?: string
}
/** Maps to `ui.preferExtension` in `@metamask/connect-evm`. */
extensionOnly?: boolean
/** Maps to `ui.headless` in `@metamask/connect-evm`. */
headless?: boolean
/** Used to populate `api.supportedNetworks` via `getInfuraRpcUrls`. */
infuraAPIKey?: string
/** Merged into `api.supportedNetworks`. */
readonlyRPCMap?: Record<string, string>
/** Maps to `mobile.preferredOpenLink`. */
openDeeplink?: (deeplink: string) => void
/** Maps to `mobile.useDeeplink`. */
useDeeplink?: boolean
// Allow legacy/forward-compat fields (e.g. `i18nOptions`, `_source`,
// `enableAnalytics`) without a type error. They are silently ignored.
[key: string]: unknown
}

type EvmClientOptions = Parameters<typeof CreateEVMClientFn>[0]

type ImportSDK = {
createEIP1193Provider: typeof createEIP1193Provider
MetaMaskSDKConstructor: typeof MetaMaskSDK
type ConnectEvmImports = {
createEVMClient: typeof CreateEVMClientFn
getInfuraRpcUrls: typeof GetInfuraRpcUrlsFn
}
Comment thread
0xFirekeeper marked this conversation as resolved.

const loadImports = async () => {
if (importPromise) {
return await importPromise
}
let importPromise: Promise<ConnectEvmImports> | null = null
let client: MetamaskConnectEVM | null = null

const loadImports = async (): Promise<ConnectEvmImports> => {
const mmConnect = await import('@metamask/connect-evm')

const { createEIP1193Provider } = await import('@web3-onboard/common')
const importedSDK = await import('@metamask/sdk')
const MetaMaskSDKConstructor =
const createEVMClient =
// @ts-ignore — handle both ESM and CJS default-export shapes
mmConnect.createEVMClient || mmConnect.default?.createEVMClient

const getInfuraRpcUrls =
// @ts-ignore
importedSDK.MetaMaskSDK || importedSDK.default.MetaMaskSDK
mmConnect.getInfuraRpcUrls || mmConnect.default?.getInfuraRpcUrls

if (!MetaMaskSDKConstructor) {
throw new Error('Error importing and initializing MetaMask SDK')
if (!createEVMClient) {
throw new Error('Error importing and initializing @metamask/connect-evm')
}

return { createEIP1193Provider, MetaMaskSDKConstructor }
return { createEVMClient, getInfuraRpcUrls }
}

let importPromise: Promise<ImportSDK> | null = null
let sdk: MetaMaskSDK | null = null

function metamask({
options
}: {
options: Partial<MetaMaskSDKOptions>
}): WalletInit {
return () => {
importPromise = loadImports().catch(error => {
importPromise = importPromise ?? loadImports().catch(error => {
throw error
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated

return {
label: 'MetaMask',
getIcon: async () => (await import('./icon.js')).default,
getInterface: async ({ appMetadata }) => {
sdk = (window as any).mmsdk || sdk // Prevent conflict with existing mmsdk instances

if (sdk) {
// Prevent re-initializing instance as it causes issues with MetaMask sdk mobile provider.
// Reuse the existing client/provider if we have already initialized
// it. Re-initializing would needlessly reset state and historically
// caused issues with the MetaMask mobile provider.
if (client) {
const existingProvider = client.getProvider()
attachDisconnectShim(existingProvider)
return {
provider: sdk.getProvider() as any,
instance: sdk
provider: existingProvider as any,
instance: client
}
}

const { name, icon } = appMetadata || {}
const base64 = window.btoa(icon || '')
const appLogoUrl = `data:image/svg+xml;base64,${base64}`
const imports = await importPromise

if (!imports?.MetaMaskSDKConstructor) {
throw new Error('Error importing and initializing MetaMask SDK')
if (!imports?.createEVMClient) {
throw new Error(
'Error importing and initializing @metamask/connect-evm'
)
}

const { MetaMaskSDKConstructor } = imports
const { createEVMClient, getInfuraRpcUrls } = imports

const { name, icon } = appMetadata || {}
const base64 = window.btoa(icon || '')
const appLogoUrl = `data:image/svg+xml;base64,${base64}`

sdk = new MetaMaskSDKConstructor({
...options,
dappMetadata: {
name: options.dappMetadata?.name || name || '',
url: options.dappMetadata?.url || window.location.origin,
base64Icon: appLogoUrl
},
_source: 'web3-onboard'
const evmOptions = mapLegacyOptions({
options,
getInfuraRpcUrls,
fallbackName: name,
fallbackBase64Icon: appLogoUrl
})

await sdk.init()
const provider = sdk.getProvider()
client = await createEVMClient(evmOptions)

if (provider) {
;(provider as any).disconnect = () => {
sdk?.terminate()
}
}

const provider = client.getProvider()
attachDisconnectShim(provider)

return {
provider,
instance: sdk
provider: provider as any,
instance: client
}
}
}
}
}

function attachDisconnectShim(provider: unknown): void {
// Web3-Onboard expects a `disconnect` method on the provider so it can
// tear down the wallet session when the user disconnects from the dapp.
// The MetaMask Connect EVM client exposes this via `client.disconnect()`.
;(provider as { disconnect?: () => void }).disconnect = () => {
void client?.disconnect()
}
}

function mapLegacyOptions({
options,
getInfuraRpcUrls,
fallbackName,
fallbackBase64Icon
}: {
options: Partial<MetaMaskSDKOptions>
getInfuraRpcUrls: typeof GetInfuraRpcUrlsFn
fallbackName?: string
fallbackBase64Icon: string
}): EvmClientOptions {
const supportedNetworks: Record<string, string> = {
...(typeof options.infuraAPIKey === 'string' && options.infuraAPIKey
? getInfuraRpcUrls({ infuraApiKey: options.infuraAPIKey })
: {}),
...(options.readonlyRPCMap ?? {})
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const evmOptions: EvmClientOptions = {
dapp: {
name: options.dappMetadata?.name || fallbackName || '',
url: options.dappMetadata?.url || window.location.origin,
// Mirror the legacy module's behavior: the rendered web3-onboard logo
// (`appLogoUrl`) is always used as the dapp icon, just like the old
// `MetaMaskSDK` integration that always set `base64Icon: appLogoUrl`.
base64Icon: fallbackBase64Icon
},
// `api.supportedNetworks` is required by `createEVMClient`. Pass the
// merged Infura + custom RPC map (or an empty object when neither is
// provided — the client still works, with read-only requests routed
// through MetaMask's default transport).
api: { supportedNetworks: supportedNetworks as Record<`0x${string}`, string> }
}

if (
typeof options.headless === 'boolean' ||
typeof options.extensionOnly === 'boolean'
) {
evmOptions.ui = {
...(typeof options.headless === 'boolean'
? { headless: options.headless }
: {}),
// `extensionOnly: true` semantically meant "prefer the extension when
// available" in the legacy SDK, which is exactly what
// `ui.preferExtension` controls in `@metamask/connect-evm`.
...(typeof options.extensionOnly === 'boolean'
? { preferExtension: options.extensionOnly }
: {})
}
}

if (
typeof options.openDeeplink === 'function' ||
typeof options.useDeeplink === 'boolean'
) {
evmOptions.mobile = {
...(typeof options.openDeeplink === 'function'
? { preferredOpenLink: options.openDeeplink }
: {}),
...(typeof options.useDeeplink === 'boolean'
? { useDeeplink: options.useDeeplink }
: {})
}
}

return evmOptions
}

export default metamask
Loading
Loading