主页 > 安卓手机怎么下载imtoken > 基于以太的 Dapps 的 21 个常用实用函数

基于以太的 Dapps 的 21 个常用实用函数

安卓手机怎么下载imtoken 2023-12-18 05:08:50

钱包工具相关的metamask介绍

Metamask 是 Chrome 和 Firefox 的浏览器扩展,它允许用户安全地维护他们的以太坊账户和私钥,并使用他们的账户与使用 Web3.js 的网站进行交互(如果你没用过以太坊私钥格式,你肯定会) 想要安装 - 这样你的浏览器就可以使用 Web3.js,然后你就可以与任何与以太坊区块链通信的网站进行交互)**

作为开发人员以太坊私钥格式,如果您希望用户通过浏览器中的网站与您的 DApp 交互(就像我们在 CryptoZombies 游戏中所做的那样),您肯定会希望与 Metamask 兼容。

注意:Metamask 默认使用 Infura 的服务器作为 web3 提供者。 就像我们上面做的一样。 但它也让用户可以选择自己的 Web3 提供商。 所以使用 Metamask 的 web3 provider,你把选择权交给了用户,你不用自己操心。

小狐狸显示状态——已连接钱包的状态

连接钱包地址:

是否安装metamsk

/**
 * @description: check metamsk
 * @param {*}
 * @return {bool}
 */
export function isMetaMask() {
  const { ethereum } = window;
  return Boolean(ethereum && ethereum.isMetaMask);
}

获取chainid

/**
 * @description: 获取chainid
 * @param {*}
 * @return {*}
 */
async function getChainId() {
  const { ethereum } = window;
  try {
    const chainId = await ethereum.request({
      method: "eth_chainId"
    });
    handleNewChain(chainId);
  } catch (err) {
    console.error(err);
  }
}

主动切换到以太坊网络

/**
 * @description: Switch to the primary network (may be deprecated in the future)
 * @param {*}
 * @return {*}
 */
async function switchToEthereum() {
  try {
    await window.ethereum.request({
      method: "wallet_switchEthereumChain",
      params: [
        {
          chainId: "0x1"
        }
      ]
    });
  } catch (error) {
    console.log(error);
  }
}

主动切换到其余链配置

/**
 * @description: Switch to the rest of the network (mainly used)
 * @param {*} findChain

以太坊与以太基金_以太坊私钥格式_以太经典和以太坊统一

* @return {*} */ async function switchToOtherNetwork(findChain) { const data = []; data.push(findChain); console.log(findChain, "switchNetwork"); try { await window.ethereum.request({ method: "wallet_addEthereumChain", params: data // [{XXXXX}] is Array }); } catch (error) { console.log(error); } }

监控链上钱包配置

/**
 * @description: handelConnectInfo
 * @param {*} info
 * @return {*}
 */
function handelConnectInfo(info) {
  console.log(info, "handelConnectInfo");
}
/**
 * @description: handleDisConnect
 * @param {*} disconnect
 * @return {*}
 */
function handleDisConnect(disconnect) {
  console.log(disconnect, "handleDisConnect");
}
/**
 * @description: handleNewAccount
 * @param {*} account
 * @return {*}
 */
function handleNewAccount(account) {
  updateAccount(account[0]);
}
/**
 * @description: handelNewMessage
 * @param {*} msg
 * @return {*}
 */
function handelNewMessage(msg) {
  console.log(msg, "handelNewMessage");
}
/**
 * @description: monitor metamsk
 * @param {*}

以太坊私钥格式_以太经典和以太坊统一_以太坊与以太基金

* @return {*} */ function _listeningMetamsk() { const { ethereum } = window; ethereum.on("chainChanged", handleNewChain); ethereum.on("accountsChanged", handleNewAccount); ethereum.on("message", handelNewMessage); ethereum.on("connect", throttle(handelConnectInfo, 1000)); ethereum.on("disconnect", throttle(handleDisConnect, 1000)); }

将自定义令牌添加到元掩码

// metmask提供的可以直接在memask中添加自定义代币的方法
async function addToken() {
      let contractAddress = getContractAddress();
      window.ethereum
        .request({
          method: "wallet_watchAsset",
          params: {
            type: "ERC20",
            options: {
              address: contractAddress.IPISTR,
              symbol: "IPISTR",
              decimals: 18,
              image: "https://i.loli.net/2021/08/12/BNYGAD9RZUl6nch.png"
            }
          }
        })
        .then(success => {
          if (success) {
            Message.success("IPISTR Token added successfully!");
          } else {
            Message.error("Something went wrong.");
          }
        })
        .catch(console.error);
    }

综合示例——连接钱包

export async function getMetamskConnect() {
  if (!isMetaMask()) {
    openUrl("https://metamask.io/", "install metamsk");
  }
  if (window.ethereum) {
    window.provider = window.ethereum;
    try {
      let accounts = await window.ethereum.request({
        method: "eth_requestAccounts"
      });
      await updateAccount(accounts[0]);
    } catch (error) {
      console.warn("Please authorize to access tour account");

以太坊私钥格式_以太经典和以太坊统一_以太坊与以太基金

} } await getChainId(); //获取chanid参数 _listeningMetamsk(); }

综合示例——交换网络

参考

解决方案

/**
 * @description: switch or add rpcNetwork
 * @param {*} id chan_id(16)
 * @return {*}
 */
export async function switchNetwork(id) {
  let findChain = nativeMetamaskMap.find(v => v.chainId === id);
  if (!window.ethereum) {
    Message.warning("Please install metamsk");
    return;
  }
  if (!findChain) {
    Message.warning("The current website does not support the chain");
    return;
  }
  if (id === "0x1") {
    switchToEthereum();
  } else {
    switchToOtherNetwork(findChain);
  }
}
/**
 * @description: matemask config
 * @param {*}
 * @return {*}
 */
export const nativeMetamaskMap = [
  {
    chainId: "0x1",
    chainName: "Ethereum Mainnet",
    nativeCurrency: {
      name: "Ether",
      symbol: "ETH",
      decimals: 18
    },
    rpcUrls: ["https://mainnet.infura.io/v3/"],
    blockExplorerUrls: ["https://etherscan.io/"]
  },
  {
    chainId: "0x80",
    chainName: "huobi Network",
    nativeCurrency: {
      name: "HT",
      symbol: "HT",
      decimals: 18
    },

以太经典和以太坊统一_以太坊与以太基金_以太坊私钥格式

rpcUrls: ["https://http-mainnet-node.huobichain.com"], blockExplorerUrls: ["https://hecoinfo.com"] }, { chainId: "0x38", chainName: "Binance Smart Chain", nativeCurrency: { name: "BNB", symbol: "BNB", decimals: 18 }, rpcUrls: ["https://bsc-dataseed.binance.org/"], blockExplorerUrls: ["https://bscscan.com/"] }, { chainId: "0x61", chainName: "BSC-Test-Network", nativeCurrency: { name: "BNB", symbol: "BNB", decimals: 18 }, rpcUrls: ["https://data-seed-prebsc-2-s3.binance.org:8545"], blockExplorerUrls: ["https://testnet.bscscan.com"] }, { chainId: "0x539", chainName: "Local-Test-Network", nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 }, rpcUrls: ["https://mainnet.infura.io/v3/"], blockExplorerUrls: ["https://etherscan.io/"] } ];

钱包连接

WalletConnect 是一组由 WalletConnect Foundation 支持的开源协议,WalletConnect Foundation 是一个同名的非营利组织。 WalletConnect 拥有强大的开发团队。 团队负责人 Pedro Gomes 曾是 Web 端全栈工程师(ETH DeFi 入门级产品)。 2018年离职,全职致力于WalletConnect的开发,现已开源。 协议。 WalletConnect开源协议主要用于端到端加密,提高数字钱包的易用性,给用户更轻松、更安全的体验。

基本依赖

import WalletConnect from "@walletconnect/client";
import QRCodeModal from "@walletconnect/qrcode-modal";

激活主动连接——弹出二维码

const getWallectConnect = async () => {
    // bridge url
    const bridge = "https://bridge.walletconnect.org";
    // create new connector
    const connector = new WalletConnect({ bridge, qrcodeModal: QRCodeModal });
    walletconnect.connector = connector;
    // check if already connected
    if (!connector.connected) {
      // create new session
      await connector.createSession();

以太坊与以太基金_以太经典和以太坊统一_以太坊私钥格式

if (localStorage.metamskconnect) delete localStorage.metamskconnect; } // subscribe to events await subscribeToEvents(); };

断开链接

const onDisconnect = () => {
    walletconnect.walletconnect = null;
  };

事件监听器

const subscribeToEvents = () => {
    const { connector } = walletconnect;
    if (!connector) {
      return;
    }
    connector.on("session_update", async (error, payload) => {
      console.log(`connector.on("session_update")`, payload);
      if (error) {
        throw error;
      }
      const { chainId, accounts } = payload.params[0];
      onSessionUpdate(accounts, chainId);
    });
    connector.on("connect", (error, payload) => {
      console.log(`connector.on("connect")`);
      if (error) {
        throw error;
      }
      onConnect(payload);
    });
    connector.on("disconnect", (error, payload) => {
      console.log("%c%s", "color: #ffa640", payload);
      Message.warning("wallectconnect disconnect");
      if (error) {
        throw error;
      }
      onDisconnect();
    });
    if (connector.connected) {
      const { chainId, accounts } = connector;
      onSessionUpdate(accounts, chainId);
    }
    walletconnect.connector = connector;
  };

本文参与登联社区写作激励计划,好文章好收益,欢迎正在阅读的你加入。