use-metamask icon indicating copy to clipboard operation
use-metamask copied to clipboard

Compatibility with Alchemy Web3, a wrapper around Web3.js

Open guillermodlpa opened this issue 3 years ago • 0 comments

Hi there! I'm developing a project using Alchemy Web3, a wrapper around Web3.js. See the Alchemy Web3 docs for more context: https://docs.alchemy.com/alchemy/documentation/alchemy-web3

I encountered a roadblock when combining it with use-metamask, so I open this issue to:

  1. Confirm if this assessment is correct, or I missed something!
  2. Offer a workaround.
  3. Suggest the workaround to be documented, or a code change to account for this scenario.

Context

The connect function of use-metamask expects to receive an object that can be instantiated with new. Link to connect's source code

Screen Shot 2021-12-29 at 00 01 00

Working example using web3 or ethers:

import Web3 from "web3"; // or import { ethers } from "ethers";

const { connect, metaState } = useMetamask();
connect(Web3); // or connect(ethers.providers.Web3Provider);

Problem

Alchemy Web3 offers a factory function to instantiate the Web3 provider, as opposed to letting programmers create it using the new keyword. Passing that web3 instance to the connect function of useMetamask doesn't work.

// Doesn't work, throws an error
import { createAlchemyWeb3 } from '@alch/alchemy-web3';

const web3 = createAlchemyWeb3('https://eth-mainnet.alchemyapi.io/<api-key>');

connect(web3); // throws an error

Error stack trace:

Screen Shot 2021-12-29 at 00 05 49

Workaround

Create a constructor that returns the existing instance, and pass it to connect:

const web3 = createAlchemyWeb3('https://eth-mainnet.alchemyapi.io/<api-key>');

function Web3Wrapper() {
  return web3;
}

const { connect, metaState } = useMetamask();
connect(Web3Wrapper);

For more context, here is where I'm applying the workaround in my project. Note that the project is unfinished.

Next steps

If I didn't miss anything, I would propose documenting this workaround on the README, for having better developer experience. Depending on how common the factory function pattern is across libraries, it might make sense to update the connect function.

Cheers

guillermodlpa avatar Dec 28 '21 23:12 guillermodlpa