Problem with initializing Metamask SDK

Hello,

I am trying to integrate MetaMask into my application but I have come across a problem I’m having a lot of issues with solving.

I try to initialize the sdk client in a client component inside of Next.js because I want to make transactions via the MetaMask extension, but I keep getting this error as soon client starts to get initialized.

The error starts with this import trace and then there is a really long string of imports that pretty much crashes my app.

Does anyone have any suggestions on how I should handle this? I am confused because at first it was working fine, but then stopped working, the window object also cannot recognize the ethereum property, so window.ethereum doesn’t work.

@metamask/sdk version: 0.31.0

Any help would be appreciated :slight_smile:

ERROR:

Import trace for requested module:
./node_modules/@metamask/sdk/dist/browser/es/metamask-sdk.js.map
./node_modules/@metamask/sdk/dist/browser/es/ lazy ^\.\/.*$ namespace object
./node_modules/@metamask/sdk/dist/browser/es/metamask-sdk.js
./src/app/[locale]/(users)/(game)/game/metamask/page.tsx

My code:

'use client'

import MetaMaskSDK from '@metamask/sdk'

import { Button } from '@/components/ui/button'

const MMSDK = new MetaMaskSDK({
    dappMetadata: {
        name: 'My app',
        url: 'https://my-app.com',
    },
    preferDesktop: true,
    extensionOnly: true,
    // checkInstallationOnAllCalls: true,
})

const Metamask = () => {
    const initializeTransaction = async () => {
        try {
            const metamaskProvider = MMSDK.getProvider()

            console.log('Initializing transaction!')

            if (!metamaskProvider) throw new Error('No Metamask provider!')

            const data = (await metamaskProvider.request({
                method: 'eth_requestAccounts',
                params: [],
            })) as string[]

            if (!data || data.length === 0)
                throw new Error('No accounts returned from MetaMask.')

            const gas = (21000).toString(16)
            const gasPriceInWei = (20 * 10 ** 9).toString(16)

            const valueToSend = 0.001

            const valueInWei = (valueToSend * 10 ** 18).toString(16)

            const transactionParameters = {
                to: 'my-address',
                from: data[0],
                gas: `0x${gas}`,
                value: `0x${valueInWei}`,
                data: '0x',
                gasPrice: `0x${gasPriceInWei}`,
            }

            const transactionResponse = await metamaskProvider.request({
                method: 'eth_sendTransaction',
                params: [transactionParameters],
            })

            console.log('transactionResponse', transactionResponse)
        } catch (error) {
            console.log(error)
        }
    }

    const disconnectFromMetamask = async () => {
        await MMSDK.terminate()
    }

    const connectToMetamask = async () => {
        try {
            console.log('Initializing MetaMask SDK connection...')

             if (!window.ethereum || !window.ethereum.isMetaMask) {
                 console.log('MetaMask not installed!')
             }

            const accounts = await MMSDK.connect()

            const provider = MMSDK.getProvider()

            if (!provider) {
                console.error(
                    'MetaMask provider not available. Please ensure MetaMask is installed.'
                )
                return
            }

            console.log('MetaMask SDK connected.')

            // Explicitly request accounts to trigger the connection modal
            const connectedAccounts = (await provider.request({
                method: 'eth_requestAccounts',
            })) as string[]

            if (connectedAccounts && connectedAccounts.length > 0) {
                console.log('Connected accounts:', connectedAccounts)
                return connectedAccounts[0] // Return the first connected account
            } else {
                console.error('No accounts returned from MetaMask.')
            }
        } catch (error) {
            console.log(error)
        }
    }
    return (
        <div className="flex items-center gap-4">
            <Button onClick={() => disconnectFromMetamask()}>Disconnect</Button>
            <Button onClick={() => connectToMetamask()}>
                Connect to metamask
            </Button>
            <Button onClick={() => initializeTransaction()}>
                Initialize transaction{' '}
            </Button>
        </div>
    )
}

export default Metamask

1 Like

I found a solution. The problem was with the newest version of the MetaMask SDK “0.31.0”, there might be some kind of bug in this version so what I did was rollback to version “0.30.1” and now it works fine.

1 Like

Hi great thanks for the update :raised_hands:t2: Could you please mark it as solution, thank you again