[Blockchain] Entering the world of web3 - how DApp can quickly access the wall

In web3, the wall is an identifier for you to enter the blockchain. The walls used by each user are not nearly the same, so it is necessary to access more walls. From the perspective of users, if it is not necessary, I don't want to download additional wall. So today we will talk about how DApp can quickly access the wall.

1. Based on wagmi

1.1 There are many wall connections built in wagmi , which can be accessed quickly


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 There is also a built-in injection method in wagmi, which can be quickly accessed


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'
  }

Reference link: https://wagmi.sh/react/connectors/injected

1.3 wagmi combined with Web3Modal to access custom wall


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}`);

In this way, you can set up multiple wall instances and use Wagmi SDK and Web3Modal to connect different providers to realize the function of multi- wall management.

2. Based on Rainbow Kit

    RainbowKit is an open source JavaScript library that provides some convenience methods for interacting with Rainbow walls in Web3 Dapps.

        Rainbow wall is an Ethereum-based mobile wall application that supports Ethereum, ERC-20 tokens, and other assets on Ethereum-compatible chains. Rainbow wall also supports decentralized applications on Ethereum, and users can interact with these applications directly from the wall.

RainbowKit provides the following features:

  • Get user wall address
  • Open Dapp in Rainbow wall
  • Send ERC-20 token transaction
  • Send an Ethereum transaction
  • Get the asset balance in the user's wall

With RainbowKit, you can easily connect your Web3 Dapp to the Rainbow wall, and allow users to interact with your Dapp using the assets in the Rainbow wall.

The source code of RainbowKit is available on GitHub, and you can check out its documentation for detailed usage and examples.

Reference address: https://www.rainbowkit.com/docs/custom-wallets

The following is the wall effect based on wagmi access , and the list can be developed by yourself (if the wall exists in the plug-in , the corresponding wall will pop up , if it does not exist, jump to the corresponding page to download)


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. The process of DApp accessing the wall

To connect your Dapp to Web3 wall, you need to complete the following steps:

1. Install the Ethers.js library: Ethers.js is a JavaScript library that provides an API for interacting with the Ethereum network. You can install it via npm, or import it using a <script> tag in your HTML page.

2. Connect to the Ethereum node: In Ethers.js, connecting to the Ethereum node is done by creating a Provider object. You can use the ethers.providers.JsonRpcProvider class to connect to Ethereum nodes. You need to specify the HTTP or WebSocket address of an Ethereum node, and the network ID to use.


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

3. Get the user's wall address: To get the user's wall address, you can use the provider.getSigner() method to get a Signer object, and then use the signer.getAddress() method to get the user's wall address.

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

4. Send a transaction: To send a transaction to the Ethereum network, you need to create a Transaction object and sign it with the user's wall address. You can then send the transaction to the network using the provider.sendTransaction() method.


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);
  });

The above is a simple process of Dapp accessing Web3 wall.

Reference document: https://learnblockchain.cn/ethers_v5/

Guess you like

Origin blog.csdn.net/qq_23334071/article/details/130179657