Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compatibility with Alchemy Web3, a wrapper around Web3.js #23

Open
guillermodlpa opened this issue Dec 28, 2021 · 0 comments
Open

Compatibility with Alchemy Web3, a wrapper around Web3.js #23

guillermodlpa opened this issue Dec 28, 2021 · 0 comments

Comments

@guillermodlpa
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant