Giter Club home page Giter Club logo

alchemy-web3's Introduction

Alchemy Web3

Web3 client extended with Alchemy and browser provider integration.

Introduction

Alchemy Web3 provides website authors with a drop-in replacement for the web3.js Ethereum API client. It produces a client matching that of web3.js, but brings multiple advantages to make use of Alchemy API:

  • Uses Alchemy or an injected provider as needed. Most requests will be sent through Alchemy, but requests involving signing and sending transactions are sent via a browser provider like Metamask or Trust Wallet if the user has it installed, or via a custom provider specified in options.

  • Easy access to Alchemy's higher level API. The client exposes methods to call Alchemy's exclusive features.

  • Automatically retries on rate limited requests. If Alchemy returns a 429 response (rate limited), automatically retry after a short delay. This behavior is configurable.

  • Robust WebSocket subscriptions which don't miss events if the WebSocket needs to be reconnected.

Alchemy Web3 is designed to require minimal configuration so you can start using it in your app right away.

Installation

With Yarn:

yarn add @alch/alchemy-web3

Or with NPM:

npm install @alch/alchemy-web3

You will also need an Alchemy account to access the Alchemy API. If you don't have one yet, contact Alchemy to request one.

Usage

Basic Usage

Create the client by importing the function createAlchemyWeb3 and then passing it your Alchemy app's URL and optionally a configuration object.

import { createAlchemyWeb3 } from "@alch/alchemy-web3";

// Using HTTPS
const web3 = createAlchemyWeb3(
  "https://eth-mainnet.alchemyapi.io/jsonrpc/<api-key>",
);

or

// Using WebSockets
const web3 = createAlchemyWeb3(
  "wss://eth-mainnet.ws.alchemyapi.io/ws/<api-key>",
);

You can use any of the methods described in the web3.js API and they will send requests to Alchemy:

// Many web3.js methods return promises.
web3.eth.getBlock("latest").then(block => {
  /* … */
});

web3.eth
  .estimateGas({
    from: "0xge61df…",
    to: "0x087a5c…",
    data: "0xa9059c…",
    gasPrice: "0xa994f8…",
  })
  .then(gasAmount => {
    /* … */
  });

With a Browser Provider

If the user has a provider in their browser available at window.ethereum, then any methods which involve user accounts or signing will automatically use it. This provider might be injected by Metamask, Trust Wallet, or other browsers or browser extensions if the user has them installed. For example, the following will use a provider from the user's browser:

web3.eth.getAccounts().then(accounts => {
  web3.eth.sendTransaction({
    from: accounts[0],
    to: "0x6A823E…",
    value: "1000000000000000000",
  });
});

Note on using Metamask

As just discussed, Metamask will automatically be used for accounts and signing if it is installed. However, for this to work you must first request permission from the user to access their accounts in Metamask. This is a security restriction required by Metamask: details can be found here.

To enable the use of Metamask, you must call ethereum.enable(). An example of doing so is as follows:

if (window.ethereum) {
  ethereum
    .enable()
    .then(accounts => {
      // Metamask is ready to go!
    })
    .catch(reason => {
      // Handle error. Likely the user rejected the login.
    });
} else {
  // The user doesn't have Metamask installed.
}

Note that doing so will display a Metamask dialog to the user if they have not already seen it and accepted, so you may choose to wait to enable Metamask until the user is about to perform an action which requires it. This is also why Alchemy Web3 will not automatically enable Metamask on page load.

With a custom provider

You may also choose to bring your own provider for writes rather than relying on one being present in the browser environment. To do so, use the writeProvider option when creating your client:

const web3 = createAlchemyWeb3(ALCHEMY_URL, { writeProvider: provider });

Your provider should expose at least one of sendAsync() or send(), as specified in EIP 1193.

You may swap out the custom provider at any time by calling the setWriteProvider() method:

web3.setWriteProvider(provider);

You may also disable the write provider entirely by passing a value of null.

Automatic Retries

If Alchemy Web3 encounters a rate limited response, it will automatically retry the request after a short delay. This behavior can be configured by passing the following options when creating your client. To disable retries, set maxRetries to 0.

maxRetries

The number of times the client will attempt to resend a rate limited request before giving up. Default: 3.

retryInterval

The minimum time waited between consecutive retries, in milliseconds. Default: 1000.

retryJitter

A random amount of time is added to the retry delay to help avoid additional rate errors caused by too many concurrent connections, chosen as a number of milliseconds between 0 and this value. Default: 250.

Sturdier WebSockets

Alchemy Web3 brings multiple improvements to ensure correct WebSocket behavior in cases of temporary network failure or dropped connections. As with any network connection, you should not assume that a WebSocket will remain open forever without interruption, but correctly handling dropped connections and reconnection by hand can be challenging to get right. Alchemy Web3 automatically adds handling for these failures with no configuration necessary.

If you use your WebSocket URL when initializing, then when you create subscriptions using web3.eth.subscribe(), Alchemy Web3 will bring the following advantages over standard Web3 subscriptions:

  • Unlike standard Web3, you will not permanently miss events which arrive while the backing WebSocket is temporarily down. Instead, you will receive thees events as soon as the connection is reopened. Note that if the connection is down for more than 120 blocks (approximately 20 minutes), you may still miss some events that were not part of the most recent 120 blocks.

  • Compared to standard Web3, lowered rate of failure when sending requests over the WebSocket while the connection is down. Alchemy Web3 will attempt to send the requests once the connection is reopened. Note that it is still possible, with a lower likelihood, for outgoing requests to be lost, so you should still have error handling as with any network request.

Alchemy Higher Level API

The produced client also grants easy access to Alchemy's higher level API.

web3.alchemy.getTokenAllowance({contract, owner, spender})

Returns token balances for a specific address given a list of contracts.

Parameters:

An object with the following fields:

  • contract: The address of the token contract.
  • owner: The address of the token owner.
  • spender: The address of the token spender.

Returns:

The allowance amount, as a string representing a base-10 number.

web3.alchemy.getTokenBalances(address, contractAddresses)

Returns token balances for a specific address given a list of contracts.

Parameters:

  1. address: The address for which token balances will be checked.
  2. contractAddresses: An array of contract addresses.

Returns:

An object with the following fields:

  • address: The address for which token balances were checked.
  • tokenBalances: An array of token balance objects. Each object contains:
    • contractAddress: The address of the contract.
    • tokenBalance: The balance of the contract, as a string representing a base-10 number.
    • error: An error string. One of this or tokenBalance will be null.

web3.alchemy.getTokenMetadata(address)

Returns metadata (name, symbol, decimals, logo) for a given token contract address.

Parameters:

address: The address of the token contract.

Returns:

An object with the following fields:

  • name: The token's name. null if not defined in the contract and not available from other sources.
  • symbol: The token's symbol. null if not defined in the contract and not available from other sources.
  • decimals: The token's decimals. null if not defined in the contract and not available from other sources.
  • logo: URL of the token's logo image. null if not available.

Copyright © 2019 Alchemy Insights Inc.

alchemy-web3's People

Contributors

dphilipson avatar jaypaik avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.