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

Use wagmi context for Balances and UniversalKitProvider components #14

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

lukema95
Copy link

@lukema95 lukema95 commented Aug 22, 2024

Relevant issue: #12

The reason for this issue is that components in universalkit cannot inherit the context of WagmiProvider from the template, which is strange as it should normally be possible.

If all the components in universal were defined within the template, this problem wouldn't exist. There could be multiple reasons causing this issue.

I've tried several methods but found that none of them could solve the problem, such as unifying the React version or using dynamic imports for components in universalkit. No matter what I did, the context of WagmiProvider in the template would be lost after passing it to components in universalkit, meaning hooks like useAccount from wagmi couldn't be used in universalkit.

A simpler and effective solution is to pass the context through parameters:

  1. Use React.forwardRef and useContext, instead of directly using wagmi hooks, pass necessary functions and data via props. The advantage is direct use of WagmiContext without needing to pass each hook separately.

  2. Provide an option for library components that allows users to manually inject the context of WagmiProvider. The advantage is flexibility, allowing users to selectively override certain Wagmi hooks.

I'm currently using the second method, which is more flexible. If we understand the cause of this problem in the future, we can fix it without changing the code, just reverting to the previous usage without passing any hook context.

After modification, to apply it to the template, you only need to manually inject hooks to override the default hooks. The implementation of Provider in template/web that needs to be modified is as follows:

export const Providers = ({ children }: { children: React.ReactNode }) => {
  const [mounted, setMounted] = useState(false);
  useEffect(() => {
    setMounted(true);
  }, []);
  if (!mounted) return null;
  // add hooks
  const wagmiContextValue = {
    useAccount: useAccount as any,
    useChainId: useChainId as any,
    useWalletClient: useWalletClient as any,
  };
  return (
    <WagmiProvider config={config}>
      <QueryClientProvider client={queryClient}>
        <NextThemesProvider
          attribute="class"
          defaultTheme="system"
          enableSystem
          disableTransitionOnChange
        >
          <ThemeProvider>
            <UniversalKitProvider wagmiContextValue={wagmiContextValue}>
              {children}
            </UniversalKitProvider>
          </ThemeProvider>
        </NextThemesProvider>
      </QueryClientProvider>
    </WagmiProvider>
  );
};

If you want to use the Balances component in template/web/Page.tsx:

const Page = () => {
  const wagmiContextValue = {
    useAccount: useAccount as any,
    useChainId: useChainId as any,
    useWalletClient: useWalletClient as any,
  };
  return (
    <div className="m-4">
      <div className="flex justify-end gap-2 mb-10">
        <ConnectBitcoin />
        <ConnectButton label="Connect EVM" showBalance={false} />
      </div>
      <div className="flex justify-center">
        <div className="w-[400px]">
          <Balances wagmiContextValue={wagmiContextValue} />
        </div>
      </div>
    </div>
  );
};

Copy link
Contributor

coderabbitai bot commented Aug 22, 2024

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@lukema95 lukema95 changed the title Use wagmi context for Balances and UniversalKitProvider Use wagmi context for Balances and UniversalKitProvider components Aug 22, 2024
@fadeev
Copy link
Member

fadeev commented Aug 22, 2024

The second option is exactly where I started in the first version of the library: having to pass values from wagmi's useAccount() and useChainId().

https://github.com/zeta-chain/docs/blob/v91/src/pages/developers/frontend/universalkit.mdx

This is messy, because it adds lines upon lines of config. And since components need more than 2 props on average, it just makes the onboarding too complicated.

@fadeev
Copy link
Member

fadeev commented Aug 22, 2024

The problem is RainbowKit. If we throw away RainbowKit from the template, UniversalKit components work fine. RainbowKit for some reason cannot inherit wagmi if it's initialized inside UniversalKitProvider.

@fadeev
Copy link
Member

fadeev commented Aug 22, 2024

But of course if we throw away RainbowKit, we can't connect to the wallet. I'll try a few things, like including RainbowKit provider inside the UniversalKit to see if it helps.

@fadeev
Copy link
Member

fadeev commented Aug 22, 2024

I think I figured it out 😂 The solution is stupid, but it kind of works.

@lukema95 throw away any mention of RainbowKit from template. Remove RainbowKitProvider, remove the Connect button.

Providers file in the template looks like this now:

export const Providers = ({ children }: { children: React.ReactNode }) => {
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) return null;

  return (
    <UniversalKitProvider config={config} client={queryClient}>
      <NextThemesProvider
        attribute="class"
        defaultTheme="system"
        enableSystem
        disableTransitionOnChange
      >
        {children}
      </NextThemesProvider>
    </UniversalKitProvider>
  );
};

Put RainbowKitProvider inside UniversalKit like so:

export const UniversalKitProvider = ({
  children,
  config,
  client,
  zetaChainConfig,
}: {
  children: ReactNode;
  config?: any;
  client: any;
  zetaChainConfig?: any;
}) => {
  return (
    <WagmiProvider config={config || { autoConnect: true }}>
      <QueryClientProvider client={client}>
        <BitcoinWalletProvider>
          <ZetaChainClientProvider zetaChainConfig={zetaChainConfig}>
            <RainbowKitProvider>{children}</RainbowKitProvider>
          </ZetaChainClientProvider>
        </BitcoinWalletProvider>
      </QueryClientProvider>
    </WagmiProvider>
  );
};

Create a new component RainbowKitConnectButton inside UniversalKit that just has the RainbowKit button. Use this button in the template:

import { RainbowKitConnectButton } from "@zetachain/universalkit"

Should work.

Apparently, RainbowKit is very particular about having wagmi inside the same project it's in.

@fadeev
Copy link
Member

fadeev commented Aug 22, 2024

The downside is that now the template can't use wagmi hooks 😔

@fadeev
Copy link
Member

fadeev commented Aug 22, 2024

Why the hell doesn't wagmi propagate from a parent provider?

@fadeev
Copy link
Member

fadeev commented Aug 22, 2024

Maybe just having two wagmis nested is ok, I need to think about it.

@lukema95
Copy link
Author

Maybe just having two wagmis nested is ok, I need to think about it.

Can't we just use RainbowKit?

@fadeev
Copy link
Member

fadeev commented Aug 24, 2024

Maybe just having two wagmis nested is ok, I need to think about it.

Can't we just use RainbowKit?

wdym? From what I can tell, UniversalKit components only work if wagmi is instantiated in the same project (wagmi is in UniversalKit). RainbowKit is the same: the connect button has to be in the same project as RainbowKit provider and wagmi.

If we move wagmi inside UniversalKit, both RainbowKit and UniversalKit components will work. However, if a user decides to use wagmi inside the template, they will have to add wagmi to the template (second wagmi).

The burning question is. If wagmi is instantiated inside UniversalKitProvider, why can't the template use that wagmi. Why doesn't wagmi propagate to the template.

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

Successfully merging this pull request may close these issues.

2 participants