1.0.16 • Published 10 months ago

@b-ee/web3-connect v1.0.16

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

Web3-Connect

Easy way to connect users to Decentralized Applications.

English | Ukrainian

✨ Features

  • Connection of Multiple Wallets and Accounts: Enable your app users to link several wallets and multiple accounts inside each wallet simultaneously.
  • Support for Multiple Chains: Enable users to easily switch between different networks and chains.
  • Wallet Management Center: A persistent interface for managing wallet connections and networks, with a responsive version designed for mobile devices.
  • Real-time Notifications: Receive immediate transaction notifications for all transaction states on the connected wallet addresses.
  • Standardization of Wallet Providers: All wallet modules provide a provider that conforms to the specifications of EIP-1193, EIP-1102, EIP-3085 and EIP-3326 specifications.
  • Dynamic Loading: To support multiple wallets in your app, you need many dependencies. Web3Connect loads a wallet and its dependencies dynamically only when the user selects it, resulting in minimal bandwidth usage.

☀️ License

MIT

🖥 Environment Support

  • Angular ^15.0.0
  • Server-side Rendering

📦 Installation

We recommend using @angular/cli to install. It not only makes development easier, but also allows you to take advantage of the rich ecosystem of angular packages and tooling.

$ ng new PROJECT_NAME
$ cd PROJECT_NAME
$ ng add @b-ee/web3-connect

More information about @angular/cli here.

You can also install @b-ee/web3-connect with npm or yarn

$ npm install @b-ee/web3-connect
$ yarn add @b-ee/web3-connect

🔨 Usage

Import the component modules you want to use into your app.module.ts file and feature modules.

import {Web3ConnectModule} from "@b-ee/web3-connect";

@NgModule({
  imports: [ Web3ConnectModule ]
})
export class AppModule {
}

Then initialize in your app:

import {Init, injectedModule} from "@b-ee/web3-connect";

const MAINNET_RPC_URL = 'https://mainnet.infura.io/v3/<INFURA_KEY>'

@Component({
  selector: 'app-root',
  template: `
     <web3-connect></web3-connect>
     <button (click)="connect()">Connect Wallet</button>
  `,
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  private injected = injectedModule();

  private web3Connect = Init({
    wallets: [this.injected],
    chains: [
      {
        id: '0x1',
        token: 'ETH',
        label: 'Ethereum Mainnet',
        rpcUrl: MAINNET_RPC_URL
      }
    ]
  })

  async connect(): Promise<void> {
    const wallets = await this.web3Connect.connectWallet();
    console.log(wallets);
  }
}

🔨 Chains

An array of Chains that your app supports:

type Chain = {
  id: ChainId // hex encoded string, eg '0x1' for Ethereum Mainnet
  namespace?: 'evm' // string indicating chain namespace. Defaults to 'evm' but will allow other chain namespaces in the future
  // PLEASE NOTE: Some wallets require an rpcUrl, label, and token for actions such as adding a new chain.
  // It is recommended to include rpcUrl, label, and token for full functionality.
  rpcUrl?: string // Recommended to include. Used for network requests.
  label?: string // Recommended to include. Used for display, eg Ethereum Mainnet.
  token?: TokenSymbol // Recommended to include. The native token symbol, eg ETH, BNB, MATIC.
  color?: string // the color used to represent the chain and will be used as a background for the icon
  icon?: string // the icon to represent the chain
  publicRpcUrl?: string // an optional public RPC used when adding a new chain config to the wallet
  blockExplorerUrl?: string // also used when adding a new config to the wallet
  secondaryTokens?: SecondaryTokens[] // An optional array of tokens (max of 5) to be available to the dapp in the app state object per wallet within the wallet account and displayed in Account Center (if enabled)
}

interface SecondaryTokens {
  /**
   * Required - The onchain address of the token associated
   * with the chain it is entered under
   */
  address: string
  /**
   * An optional svg or url string for the icon of the token.
   * If an svg is used ensure the height/width is set to 100%
   */
  icon?: string
}

🔨 AppMetaData

An object that defines your app:

type AppMetadata = {
  // app name
  name: string
  // SVG icon string, with height or width (whichever is larger) set to 100% or a valid image URL
  // note: if using an emoji make sure to send base64 string
  // Note: `icon` is displayed on both mobile AND desktop. If `logo`
  // below is provided then `icon` displays on mobile and `logo` on desktop
  icon: string
  // Optional wide format logo (ie icon and text) to be displayed in the sidebar of connect modal. Defaults to icon if not provided
  // Note: This will ONLY display on desktop. It is best used with wide format logos. Use `icon` for standard 40x40 icons.
  logo?: string
  // description of app
  description?: string
  // url to a getting started guide for app
  gettingStartedGuide?: string
  // url that points to more information about app
  explore?: string
  // if your app only supports injected wallets and when no injected wallets detected, recommend the user to install some
  recommendedInjectedWallets?: RecommendedInjectedWallets[]
  // allows for dapps to require users to agree to TOS and privacy policy before connecting a wallet
  agreement?: TermsOfServiceAgreementOptions | null
}

type TermsOfServiceAgreementOptions = {
  // user agrees with exact version of terms and privacy policy
  version: string
  // url that points to the Terms & Conditions of the dapp
  termsUrl?: string
  // url that points to the Privacy policy of the dapp
  privacyUrl?: string
}

type RecommendedInjectedWallets = {
  name: string // display name
  url: string // link to download wallet
}

🔨 Locale

An object that defines the display text for different locales. Can also be used to override the default text. To override the default text, pass in an object for the en locale.

type Locale = string // eg 'en', 'ua'

const updateLanguage = (locale: Locale): void => {
  this.web3Connect.state.actions.updateAppMetadata.setLocale(locale);
}

🌗 Theme

To set the color theme of web3-connect to one of the available native themes, import Init from '@b-ee/web3-connect' and pass the theme as a string to the 'theme' init option.

type Theme = ThemingMap | BuiltInThemes | 'system'

type BuiltInThemes = 'dark' | 'light'

type ThemingMap = {
  '--b-ee-background-color'?: string
  '--b-ee-foreground-color'?: string
  '--b-ee-text-color'?: string
  '--b-ee-border-color'?: string
  '--b-ee-action-color'?: string
  '--b-ee-border-radius'?: string
  '--b-ee-font-family'?: string
}

Send Transaction

This API call will return a promise that resolves to the transaction hash (if 'sendTransaction' resolves the transaction hash and is successful), the internal notification id (if no 'sendTransaction' function is provided) or return nothing if an error occurs or 'sendTransaction' is not provided or doesn't resolve to a string.

Example:

const balanceValue = Object.values(balance)[0]
// if using ethers v6 this is:
// ethersProvider = new ethers.BrowserProvider(wallet.provider, 'any')
const ethersProvider = new ethers.providers.Web3Provider(provider, 'any')

const signer = ethersProvider.getSigner()
const txDetails = {
  to: toAddress,
  value: 100000000000000
}

const sendTransaction = () => {
  return signer.sendTransaction(txDetails).then((tx) => tx.hash)
}

const gasPrice = () => ethersProvider.getGasPrice().then((res) => res.toString())

const estimateGas = () => {
  return ethersProvider.estimateGas(txDetails).then((res) => res.toString())
}
const transactionHash = await this.web3Connect.state.actions.preflightNotifications({
  sendTransaction,
  gasPrice,
  estimateGas,
  balance: balanceValue,
  txDetails: txDetails
})
console.log(transactionHash)

🔨 Buffer

Buffer polyfill It seems some component or dependency requires Node's Buffer. Include this in yore polyfills.ts

(window as any).global = window;
global.Buffer = global.Buffer || require('buffer').Buffer;
global.process = require('process');

⌨️ Development

$ git clone git@github.com:bee-io/web3-connect.git
$ cd web3-connect
$ yarn install
$ npm run demo

Browser would open automatically.

🤝 Contributing

PRs Welcome

We welcome all contributions. You can submit any ideas as pull requests or as GitHub issues.

If you're new to posting issues, we ask that you read How To Ask Questions The Smart Way (This guide does not provide actual support services for this project!), How to Ask a Question in Open Source Community and How to Report Bugs Effectively prior to posting. Well written bug reports help us help you!

JetBrains

We list some users here, if your company or product uses @b-ee/web3-connect, let us know here!

Love @b-ee/web3-connect? Give our repo a star :star: :arrow_up:.