[ブロックチェーン] web3 の世界に入る - DApp が壁にすばやくアクセスする方法

web3では、ウォールはブロックチェーンに入る為の識別子です.各ユーザーが使用するウォールはほぼ同じではないので、より多くのウォールにアクセスする必要があります.追加の壁をダウンロードしたくありません。今日は、DApp が壁にすばやくアクセスする方法について説明します。

1.wagmiベース

1.1 wagmi には多くの壁接続が組み込まれており、すぐにアクセスできます


import { MetaMaskConnector } from 'wagmi/connectors/metaMask'
import { CoinbaseWalletConnector } from 'wagmi/connectors/coinbaseWallet'
import { LedgerConnector } from 'wagmi/connectors/ledger'
import { WalletConnectConnector } from 'wagmi/connectors/walletConnect'
import { SafeConnector } from 'wagmi/connectors/safe'

import { createClient, configureChains, mainnet, goerli } from 'wagmi'
import { bsc, bscTestnet } from 'wagmi/chains'
const { chains, provider, webSocketProvider } = configureChains(
    [goerli, mainnet, bscTestnet, bsc, arbitrum],
    [alchemyProvider({ apiKey: AlchemyApiKey }), publicProvider()]
)

export const client = createClient({
    autoConnect: true,
    connectors: [
        new MetaMaskConnector({ chains }),
        new CoinbaseWalletConnector({
            options: {
                appName: 'CoinbaseWallet',
                jsonRpcUrl: 'https://eth-mainnet.alchemyapi.io/v2/yourAlchemyId',
            },
        }),
        new LedgerConnector({
            chains
        }),
        new WalletConnectConnector({
            chains,
            options: {}
        }),
        new SafeConnector({
            chains,
            options: {},
        })
    ],
    provider,
    webSocketProvider
})

 1.2 wagmiには組み込みのインジェクションメソッドもあり、すぐにアクセスできます


import { InjectedConnector } from 'wagmi/connectors/injected'

import { createClient, configureChains, mainnet, goerli } from 'wagmi'
import { bsc, bscTestnet } from 'wagmi/chains'
const { chains, provider, webSocketProvider } = configureChains(
    [goerli, mainnet, bscTestnet, bsc, arbitrum],
    [alchemyProvider({ apiKey: AlchemyApiKey }), publicProvider()]
)

export const client = createClient({
    autoConnect: true,
    connectors: [
        // 内置自定义参数
        new InjectedConnector({
            chains,
            options: {
                name: 'BitKeep',
                getProvider: () =>
                    typeof window !== 'undefined' ? window.isBitKeep : undefined,
            },
        })
    ],
    provider,
    webSocketProvider
})

// 内置主流的wall
const getName = (provider: Ethereum) => {
    if (provider.isApexWallet) return 'Apex Wallet'
    if (provider.isAvalanche) return 'Core Wallet'
    if (provider.isBackpack) return 'Backpack'
    if (provider.isBifrost) return 'Bifrost Wallet'
    if (provider.isBitKeep) return 'BitKeep'
    if (provider.isBitski) return 'Bitski'
    if (provider.isBraveWallet) return 'Brave Wallet'
    if (provider.isCoinbaseWallet) return 'Coinbase Wallet'
    if (provider.isDawn) return 'Dawn Wallet'
    if (provider.isExodus) return 'Exodus'
    if (provider.isFrame) return 'Frame'
    if (provider.isFrontier) return 'Frontier Wallet'
    if (provider.isGamestop) return 'GameStop Wallet'
    if (provider.isHyperPay) return 'HyperPay Wallet'
    if (provider.isKuCoinWallet) return 'KuCoin Wallet'
    if (provider.isMathWallet) return 'MathWallet'
    if (provider.isOkxWallet || provider.isOKExWallet) return 'OKX Wallet'
    if (provider.isOneInchIOSWallet || provider.isOneInchAndroidWallet)
      return '1inch Wallet'
    if (provider.isOpera) return 'Opera'
    if (provider.isPhantom) return 'Phantom'
    if (provider.isPortal) return 'Ripio Portal'
    if (provider.isRabby) return 'Rabby'
    if (provider.isRainbow) return 'Rainbow'
    if (provider.isStatus) return 'Status'
    if (provider.isTally) return 'Taho'
    if (provider.isTokenPocket) return 'TokenPocket'
    if (provider.isTokenary) return 'Tokenary'
    if (provider.isTrust || provider.isTrustWallet) return 'Trust Wallet'
    if (provider.isXDEFI) return 'XDEFI Wallet'
    if (provider.isZerion) return 'Zerion'
    if (provider.isMetaMask) return 'MetaMask'
  }

参考リンク:https://wagmi.sh/react/connectors/injected

1.3 wagmi と Web3Modal を組み合わせてカスタムウォールにアクセス


import { MultiWallet, Wallet, EthereumChainId, EthereumNetwork } from '@wagmi/wallet';
import { InjectedConnector } from '@wagmi/connectors/injected';
import Web3Modal from 'web3modal';

// 创建第一个wall实例
const wallet1 = new Wallet({
  chainId: EthereumChainId.MAINNET,
  network: EthereumNetwork.MAINNET,
  provider: new InjectedConnector(),
});

// 创建第二个wall实例
const wallet2 = new Wallet({
  chainId: EthereumChainId.MAINNET,
  network: EthereumNetwork.MAINNET,
  provider: new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/your-project-id'),
});

// 创建多wall实例
const multiWallet = new MultiWallet([wallet1, wallet2]);

// 初始化 Web3Modal
const web3Modal = new Web3Modal({
  cacheProvider: true,
  providerOptions: {
    injected: {
      display: {
        name: 'Wagmi Wallet',
        description: 'Connect to your Wagmi wallet',
      },
      package: '@wagmi/connectors/injected',
      options: {
        network: EthereumChainId.MAINNET,
      },
    },
  },
});

// 连接指定的wall
async function connectWallet(index: number) {
  const provider = await web3Modal.connect();
  await multiWallet.connectWallet(index, provider);
}

// 使用第一个wall实例
await connectWallet(0);
const wallet1Address = await wallet1.getAddress();
console.log(`Wallet 1 address: ${wallet1Address}`);

// 使用第二个wall实例
await connectWallet(1);
const wallet2Address = await wallet2.getAddress();
console.log(`Wallet 2 address: ${wallet2Address}`);

このように、複数のウォールインスタンスを設定し、Wagmi SDK と Web3Modal を使用して異なるプロバイダーを接続することで、マルチウォール管理の機能を実現できます

2. レインボーキットベース

    RainbowKit は、Web3 Dapps で Rainbow ウォールを操作するための便利なメソッドを提供するオープン ソースの JavaScript ライブラリです。

        レインボー ウォールは、イーサリアム、ERC-20 トークン、およびイーサリアム互換チェーン上のその他の資産をサポートする、イーサリアム ベースのモバイル ウォール アプリケーションです。レインボー ウォールはイーサリアム上の分散型アプリケーションもサポートしており、ユーザーはこれらのアプリケーションをウォールから直接操作できます。

RainbowKit は次の機能を提供します。

  • ユーザーウォールアドレスを取得する
  • レインボーウォールでDappを開く
  • ERC-20 トークン トランザクションを送信する
  • イーサリアム トランザクションを送信する
  • ユーザーのウォールの資産残高を取得する

RainbowKit を使用すると、Web3 Dapp を Rainbow ウォールに簡単に接続し、ユーザーが Rainbow ウォールのアセットを使用して Dapp を操作できるようになります。

RainbowKit のソース コードは GitHub で入手できます。詳細な使用方法と例については、ドキュメントを参照してください。

参考アドレス:https://www.rainbowkit.com/docs/custom-wallets

以下はwagmi accessに基づくウォールエフェクトで、リストは自分で開発可能です(プラグインにウォールが存在する場合は対応するウォールがポップアップし、存在しない場合は対応するページにジャンプしてダウンロードします) )


const getUrlByType = id => {
      const obj = {
          metaMask: 'https://metamask.io/download/',
          safe: 'https://www.safepal.com/download'
      }
      return (id && obj[id]) || 'did'
  }

  // 点击wall的方法
  const handleConnectAsync = connector => {
      if (!connector.connector.ready) {
          window.open(getUrlByType(connector.connector.id), '_target')
          return
      }
      const signToLogin = async () => {
          dispatch('setVisibleWalletList', '0')

          const { address } = getAccount()
          const msg = `Welcome to Doaverse!`
          const signMessage = await getSigMessageService(msg)
          if (!signMessage) return
          console.log('signMessage...', signMessage)
          await loginWalletCb(msg, signMessage)
          dispatch('setIsLogout', '0')
          emitter.emit('header:loginSuccess')
      }
      if (isConnected) {
          // wall端记录状态已连接,直接请求签名
          signToLogin()
      }
      connectAsync(connector).then(signToLogin)
  }

3. DAppがウォールにアクセスするプロセス

Dapp を Web3 ウォールに接続するには、次の手順を完了する必要があります。

1. Ethers.js ライブラリをインストールします。Ethers.js は、Ethereum ネットワークと対話するための API を提供する JavaScript ライブラリです。npm 経由でインストールするか、HTML ページで <script> タグを使用してインポートできます。

2. イーサリアム ノードへの接続: Ethers.js では、プロバイダー オブジェクトを作成することによって、イーサリアム ノードへの接続が行われます。ethers.providers.JsonRpcProvider クラスを使用して、Ethereum ノードに接続できます。Ethereum ノードの HTTP または WebSocket アドレスと、使用するネットワーク ID を指定する必要があります。


// 连接到以太坊主网
const provider = new ethers.providers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID', 1);

3. ユーザーのウォール アドレスを取得する: ユーザーのウォール アドレスを取得するには、provider.getSigner() メソッドを使用して Signer オブジェクトを取得してから、signer.getAddress() メソッドを使用してユーザーのウォール アドレスを取得します。

const signer = provider.getSigner();
const userAddress = await signer.getAddress();

4. トランザクションの送信: イーサリアム ネットワークにトランザクションを送信するには、トランザクション オブジェクトを作成し、ユーザーのウォール アドレスで署名する必要があります。その後、 provider.sendTransaction() メソッドを使用してトランザクションをネットワークに送信できます。


const tx = {
  from: userAddress,
  to: '0x123...',
  value: ethers.utils.parseEther('1'),
  gasLimit: 21000,
  gasPrice: ethers.utils.parseUnits('10', 'gwei'),
  nonce: await provider.getTransactionCount(userAddress)
};

const signedTx = await signer.signTransaction(tx);

provider.sendTransaction(signedTx)
  .then(receipt => {
    console.log('Transaction receipt:', receipt);
  });

上記は、Dapp が Web3 ウォールにアクセスする簡単なプロセスです。

参考資料:https://learnblockchain.cn/ethers_v5/

おすすめ

転載: blog.csdn.net/qq_23334071/article/details/130179657