reactjs 如何在react项目中集成Phantom钱包?

kh212irz  于 2022-11-29  发布在  React
关注(0)|答案(1)|浏览(168)

实际上我很想把幻影钱包整合到我的自定义手网站中。因为我是第一次使用Web3,我刚刚使用了Metamask,不确定Solana和幻影钱包是什么。

z9smfwbn

z9smfwbn1#

编写提供程序,然后使用此提供程序 Package 您的应用程序(a A):

import {
  ConnectionProvider,
  WalletProvider,
} from '@solana/wallet-adapter-react'
import { WalletModalProvider } from '@solana/wallet-adapter-react-ui'
import { PhantomWalletAdapter } from '@solana/wallet-adapter-wallets'
import { useMemo } from 'react'

const WalletConnectionProvider = ({ children }) => {
  const endpoint = useMemo(() => 'https://api.devnet.solana.com', [])

  const wallets = useMemo(() => [new PhantomWalletAdapter()], [])

  return (
    <ConnectionProvider endpoint={endpoint}>
      <WalletProvider wallets={wallets} autoConnect>
        <WalletModalProvider>{children}</WalletModalProvider>
      </WalletProvider>
    </ConnectionProvider>
  )
}

export default WalletConnectionProvider

或者以连接到window.ethereum的方式手动检查window.solana

const isWalletConnected = async () => {
    try {
      const { solana } = window;
      if (solana) {
        if (solana.isPhantom) {
          console.log("phantom wallet found");
          // When using this flag, Phantom will only connect and emit a connect event if the application is trusted. Therefore, this can be safely called on page load for new users, as they won't be bothered by a pop-up window even if they have never connected to Phantom before.
          // if user already connected, { onlyIfTrusted: true }
          const response = await solana.connect({ onlyIfTrusted: false });
          console.log(
            "public key",
            response.publicKey.toString()
          );
          setWalletAddress(response.publicKey.toString());
        } else {
          alert("Please install phantom wallet");
        }
      }
    } catch (error) {
      console.log(error);
    }
  };

相关问题