@0xsequence/web3modal 中文文档教程

发布于 3年前 浏览 29 项目主页 更新于 3年前

Web3Modal

适用于所有钱包的单一 Web3 / Ethereum 提供商解决方案

Introduction

Web3Modal 是一个易于使用的库,可帮助开发人员通过简单的可自定义配置在其应用程序中添加对多个提供商的支持。

默认情况下,Web3Modal 库支持注入的提供程序,例如 (MetamaskDapperGnosis SafeFrame、Web3 浏览器等) 和 WalletConnect,您还可以轻松配置库以支持 PortisFortmaticSquarelink TorusAuthereumD'CENT 钱包Venly

Preview

您可以在以下位置测试该库:https://web3modal.com/

preview

Projects using web3modal

打开 PR 以将您的项目添加到列表中!

Related Efforts

Usage

  1. Install Web3Modal NPM package
npm install --save web3modal

# OR

yarn add web3modal
  1. Install Provider packages
/* See Provider Options Section */
  1. Then you can add Web3Modal to your Dapp as follows
import Web3 from "web3";
import Web3Modal from "web3modal";

const providerOptions = {
  /* See Provider Options Section */
};

const web3Modal = new Web3Modal({
  network: "mainnet", // optional
  cacheProvider: true, // optional
  providerOptions // required
});

const provider = await web3Modal.connect();

const web3 = new Web3(provider);

Using with ethers.js

import { ethers } from "ethers";
import Web3Modal from "web3modal";

const providerOptions = {
  /* See Provider Options Section */
};

const web3Modal = new Web3Modal({
  network: "mainnet", // optional
  cacheProvider: true, // optional
  providerOptions // required
});

const instance = await web3Modal.connect();

const provider = new ethers.providers.Web3Provider(instance);
const signer = provider.getSigner();

Using in vanilla JavaScript

您也可以使用老式网页 JavaScript 中的模态。

首先从发布中获取 Web3modal 捆绑的 JavaScript

在您的 HTML 中包含该包后,您可以在您的网页上使用它:

//  You have to refer to default since it was bundled for ESModules
// but after that the documentation will be the same

const Web3Modal = window.Web3Modal.default;
const providerOptions = {
  /* See Provider Options Section */
};

const web3Modal = new Web3Modal({
  network: "mainnet", // optional
  cacheProvider: true, // optional
  providerOptions // required
});

const provider = await web3Modal.connect();

查看完整的 vanilla JavaScript 示例应用程序。

Provider Events

您应该订阅与 EIP-1193 标准兼容的提供商事件。

// Subscribe to accounts change
provider.on("accountsChanged", (accounts: string[]) => {
  console.log(accounts);
});

// Subscribe to chainId change
provider.on("chainChanged", (chainId: number) => {
  console.log(chainId);
});

// Subscribe to provider connection
provider.on("connect", (info: { chainId: number }) => {
  console.log(info);
});

// Subscribe to provider disconnection
provider.on("disconnect", (error: { code: number; message: string }) => {
  console.log(error);
});

Provider Options

这些是 Web3Modal 可用的所有提供程序以及如何配置它们的提供程序选项:

API

class Web3Modal {
  cachedProvider: string;
  connect(): Promise<any>;
  connectTo(id: string): Promise<any>;
  toggleModal(): Promise<void>;
  on(event: string, callback: SimpleFunction): SimpleFunction;
  off(event: string, callback?: SimpleFunction): void;
  clearCachedProvider(): void;
  setCachedProvider(): void;
  updateTheme(theme: string | ThemeColors): Promise<void>;
}

Utils

function getInjectedProvider(): IProviderInfo | null;
function getInjectedProviderName(): string | null;

function getProviderInfo(provider: any): IProviderInfo;
function getProviderInfoByName(name: string | null): IProviderInfo;
function getProviderInfoById(id: string | null): IProviderInfo;
function getProviderInfoByCheck(check: string | null): IProviderInfo;

Types

interface IProviderInfo {
  id: string;
  type: string;
  check: string;
  name: string;
  logo: string;
  description?: string;
  package?: {
    required?: string[];
  };
}

type ThemeColors = {
  background: string;
  main: string;
  secondary: string;
  border: string;
  hover: string;
};

type SimpleFunction = (input?: any) => void;

Custom Themes

默认启用的主题是 light 但也可以通过将选项 theme 设置为 < code>dark,如下所示:

const web3Modal = new Web3Modal({
  ...otherOptions,
  theme: "dark"
});

完全自定义的主题也可以通过使用以下具有有效 css 颜色值的参数传递一个对象来实现:

const web3Modal = new Web3Modal({
  ...otherOptions,
  theme: {
    background: "rgb(39, 49, 56)",
    main: "rgb(199, 199, 199)",
    secondary: "rgb(136, 136, 136)",
    border: "rgba(195, 195, 195, 0.14)",
    hover: "rgb(16, 26, 32)"
  }
});

此外,您还可以在实例化后通过调用以下方法更新模态主题:

await web3Modal.updateTheme("dark");

// OR

await web3Modal.updateTheme({
  background: "rgb(39, 49, 56)",
  main: "rgb(199, 199, 199)",
  secondary: "rgb(136, 136, 136)",
  border: "rgba(195, 195, 195, 0.14)",
  hover: "rgb(16, 26, 32)"
});

Custom Display

这是可能的自定义每个提供商的显示以更改名称、描述和徽标。 这些选项作为提供者选项的一部分可用,如下

const providerOptions = {
  // Example with injected providers
  injected: {
    display: {
      logo: "data:image/gif;base64,INSERT_BASE64_STRING",
      name: "Injected",
      description: "Connect with the provider in your Browser"
    },
    package: null
  },
  // Example with WalletConnect provider
  walletconnect: {
    display: {
      logo: "data:image/gif;base64,INSERT_BASE64_STRING",
      name: "Mobile",
      description: "Scan qrcode with your mobile wallet"
    },
    package: WalletConnectProvider,
    options: {
      infuraId: "INFURA_ID" // required
    }
  }
};

所示您只能更改其中一个显示选项,您无需填写所有 3 个选项,例如:

const providerOptions = {
  walletconnect: {
    display: {
      name: "Mobile"
    },
    package: WalletConnectProvider,
    options: {
      infuraId: "INFURA_ID" // required
    }
  }
};

Custom Provider

如果您想包含 Web3Modal 尚不支持的提供者,我们建议您按照我们的“添加提供商”说明中的简单五个步骤提交 PR

如果仍需要将自定义提供商添加到您的 Web3Modal 集成,您可以使用以 custom- 为前缀的键将其添加到提供者选项中,并且您需要包含显示选项和连接器处理程序,如下所示

import ExampleProvider from "example-provider";

const providerOptions = {
  "custom-example": {
    display: {
      logo: "data:image/gif;base64,INSERT_BASE64_STRING",
      name: "Example Provider",
      description: "Connect to your example provider account"
    },
    package: ExampleProvider,
    options: {
      apiKey: "EXAMPLE_PROVIDER_API_KEY"
    },
    connector: async (ProviderPackage, options) => {
      const provider = new ProviderPackage(options);

      await provider.enable();

      return provider;
    }
  }
};

Connect to specific provider

如果您想连接特定的提供者,可以使用该方法connectTo 并使用特定的 id。 示例:

import Web3 from "web3";
import Web3Modal from "web3modal";

const providerOptions = {
  /* See Provider Options Section */
};

const web3Modal = new Web3Modal({
  network: "mainnet", // optional
  cacheProvider: true, // optional
  providerOptions // required
});

const provider = await web3Modal.connectTo("walletconnect");

const web = new Web3(provider);

Optional Flags

Disable Injected Provider

默认情况下设置为 false 并且 Web3Modal 始终将 InjectedProvider 作为选项显示给用户(如果可用)。 但是,如果需要,您可以将其作为可选标志禁用:

const web3Modal = new Web3Modal({ disableInjectedProvider: true });

Cache Provider

默认情况下设置为 false 并且 Web3Modal 将始终要求用户在触发 onConnect 事件之前选择提供者选项。 但是,您可以启用缓存最后选择的提供程序。 示例:

const web3Modal = new Web3Modal({ cacheProvider: true });

如果您希望重置缓存的提供程序,您可以调用以下方法:

web3Modal.clearCachedProvider();

如果您希望连接到 cachedProvider,您只需执行以下操作:

if (web3Modal.cachedProvider) {
  await web3Modal.connect();
}

Adding a new provider

是否要将您的提供程序添加到 Web3Modal? 支持的提供程序的所有逻辑都位于 src/providers 目录中。 要添加新的,请按照以下步骤此处

Migrating from Web3Connect

如果您在使用 Web3Connect 之前可以查看有关如何使用 Web3Modal 和处理重大更改的迁移说明 这里

Contributions

欢迎贡献代码❤️❤️❤️!

如果你想支持一个新的提供者,请向 repo 提交一个问题或者 fork 这个 repo 并创建一个 pull要求。

您可以加入我们的 discord 进一步讨论 https://discordapp.com/invite/YGnSX9y

License

MIT

Web3Modal

A single Web3 / Ethereum provider solution for all Wallets

Introduction

Web3Modal is an easy-to-use library to help developers add support for multiple providers in their apps with a simple customizable configuration.

By default Web3Modal Library supports injected providers like (Metamask, Dapper, Gnosis Safe, Frame, Web3 Browsers, etc) and WalletConnect, You can also easily configure the library to support Portis, Fortmatic, Squarelink, Torus, Authereum, D'CENT Wallet and Venly.

Preview

You can test the library on: https://web3modal.com/

preview

Projects using web3modal

Open a PR to add your project to the list!

Related Efforts

Usage

  1. Install Web3Modal NPM package
npm install --save web3modal

# OR

yarn add web3modal
  1. Install Provider packages
/* See Provider Options Section */
  1. Then you can add Web3Modal to your Dapp as follows
import Web3 from "web3";
import Web3Modal from "web3modal";

const providerOptions = {
  /* See Provider Options Section */
};

const web3Modal = new Web3Modal({
  network: "mainnet", // optional
  cacheProvider: true, // optional
  providerOptions // required
});

const provider = await web3Modal.connect();

const web3 = new Web3(provider);

Using with ethers.js

import { ethers } from "ethers";
import Web3Modal from "web3modal";

const providerOptions = {
  /* See Provider Options Section */
};

const web3Modal = new Web3Modal({
  network: "mainnet", // optional
  cacheProvider: true, // optional
  providerOptions // required
});

const instance = await web3Modal.connect();

const provider = new ethers.providers.Web3Provider(instance);
const signer = provider.getSigner();

Using in vanilla JavaScript

You can use the modal from the old fashioned web page JavaScript as well.

First get a Web3modal bundled JavaScript from Releases.

After including the bundle in your HTML, you can use it on your web page:

//  You have to refer to default since it was bundled for ESModules
// but after that the documentation will be the same

const Web3Modal = window.Web3Modal.default;
const providerOptions = {
  /* See Provider Options Section */
};

const web3Modal = new Web3Modal({
  network: "mainnet", // optional
  cacheProvider: true, // optional
  providerOptions // required
});

const provider = await web3Modal.connect();

See the full vanilla JavaScript example application.

Provider Events

You should subscribe to provider events compatible with EIP-1193 standard.

// Subscribe to accounts change
provider.on("accountsChanged", (accounts: string[]) => {
  console.log(accounts);
});

// Subscribe to chainId change
provider.on("chainChanged", (chainId: number) => {
  console.log(chainId);
});

// Subscribe to provider connection
provider.on("connect", (info: { chainId: number }) => {
  console.log(info);
});

// Subscribe to provider disconnection
provider.on("disconnect", (error: { code: number; message: string }) => {
  console.log(error);
});

Provider Options

These are all the providers available with Web3Modal and how to configure their provider options:

API

class Web3Modal {
  cachedProvider: string;
  connect(): Promise<any>;
  connectTo(id: string): Promise<any>;
  toggleModal(): Promise<void>;
  on(event: string, callback: SimpleFunction): SimpleFunction;
  off(event: string, callback?: SimpleFunction): void;
  clearCachedProvider(): void;
  setCachedProvider(): void;
  updateTheme(theme: string | ThemeColors): Promise<void>;
}

Utils

function getInjectedProvider(): IProviderInfo | null;
function getInjectedProviderName(): string | null;

function getProviderInfo(provider: any): IProviderInfo;
function getProviderInfoByName(name: string | null): IProviderInfo;
function getProviderInfoById(id: string | null): IProviderInfo;
function getProviderInfoByCheck(check: string | null): IProviderInfo;

Types

interface IProviderInfo {
  id: string;
  type: string;
  check: string;
  name: string;
  logo: string;
  description?: string;
  package?: {
    required?: string[];
  };
}

type ThemeColors = {
  background: string;
  main: string;
  secondary: string;
  border: string;
  hover: string;
};

type SimpleFunction = (input?: any) => void;

Custom Themes

The theme enabled by default is light but dark theme is also available by setting the option theme to dark, as follows:

const web3Modal = new Web3Modal({
  ...otherOptions,
  theme: "dark"
});

Completely custom themes are also available by passing an object instead with the following parameters with valid css colors values:

const web3Modal = new Web3Modal({
  ...otherOptions,
  theme: {
    background: "rgb(39, 49, 56)",
    main: "rgb(199, 199, 199)",
    secondary: "rgb(136, 136, 136)",
    border: "rgba(195, 195, 195, 0.14)",
    hover: "rgb(16, 26, 32)"
  }
});

Addtionally you can also update the modal theme after instantiated by calling the following method:

await web3Modal.updateTheme("dark");

// OR

await web3Modal.updateTheme({
  background: "rgb(39, 49, 56)",
  main: "rgb(199, 199, 199)",
  secondary: "rgb(136, 136, 136)",
  border: "rgba(195, 195, 195, 0.14)",
  hover: "rgb(16, 26, 32)"
});

Custom Display

It's possible to customize the display of each provider to change the name, description and logo. These options are available as part of the provider options as following

const providerOptions = {
  // Example with injected providers
  injected: {
    display: {
      logo: "data:image/gif;base64,INSERT_BASE64_STRING",
      name: "Injected",
      description: "Connect with the provider in your Browser"
    },
    package: null
  },
  // Example with WalletConnect provider
  walletconnect: {
    display: {
      logo: "data:image/gif;base64,INSERT_BASE64_STRING",
      name: "Mobile",
      description: "Scan qrcode with your mobile wallet"
    },
    package: WalletConnectProvider,
    options: {
      infuraId: "INFURA_ID" // required
    }
  }
};

You can change only one of the display options, you are not required to fill all 3 options, example:

const providerOptions = {
  walletconnect: {
    display: {
      name: "Mobile"
    },
    package: WalletConnectProvider,
    options: {
      infuraId: "INFURA_ID" // required
    }
  }
};

Custom Provider

If you would like to include a provider that isn't supported yet on Web3Modal, we would recommend you submit a PR following the simple five steps in our "Adding Providers" instructions

If still need to add a custom provider to your Web3Modal integration, you can add it to the provider options with a key prefixed with custom- and you will need to include the display options and connector handler as follows

import ExampleProvider from "example-provider";

const providerOptions = {
  "custom-example": {
    display: {
      logo: "data:image/gif;base64,INSERT_BASE64_STRING",
      name: "Example Provider",
      description: "Connect to your example provider account"
    },
    package: ExampleProvider,
    options: {
      apiKey: "EXAMPLE_PROVIDER_API_KEY"
    },
    connector: async (ProviderPackage, options) => {
      const provider = new ProviderPackage(options);

      await provider.enable();

      return provider;
    }
  }
};

Connect to specific provider

In case you want to connect a specific provider, you can use the method connectTo and use the specific id. Example:

import Web3 from "web3";
import Web3Modal from "web3modal";

const providerOptions = {
  /* See Provider Options Section */
};

const web3Modal = new Web3Modal({
  network: "mainnet", // optional
  cacheProvider: true, // optional
  providerOptions // required
});

const provider = await web3Modal.connectTo("walletconnect");

const web = new Web3(provider);

Optional Flags

Disable Injected Provider

By default is set to false and Web3Modal always displays InjectedProvider as an option to the user if available. However you can disable it as an optional flag if you desire:

const web3Modal = new Web3Modal({ disableInjectedProvider: true });

Cache Provider

By default is set to false and Web3Modal will always require the user to choose a provider option before triggering the onConnect event. However you can enable caching the last chosen provider. Example:

const web3Modal = new Web3Modal({ cacheProvider: true });

If you wish to reset the cached provider you can call the following method:

web3Modal.clearCachedProvider();

If you wish to connect to the cachedProvider you can simply do the following:

if (web3Modal.cachedProvider) {
  await web3Modal.connect();
}

Adding a new provider

Do you want to add your provider to Web3Modal? All logic for supported providers lives inside the src/providers directory. To add a new follow the following steps here

Migrating from Web3Connect

If you were using Web3Connect before you can check the migration instructions for how to use Web3Modal and handle breaking changes here

Contributions

Code contributions are welcome ❤️❤️❤️!

If you wish to support a new provider submit a issue to the repo or fork this repo and create a pull request.

You can join to our discord to further discuss https://discordapp.com/invite/YGnSX9y

License

MIT

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文