Git Product home page Git Product logo

decentraland-connect's Introduction

Decentraland Connect

Connect to the Ethereum network with ease

Table of contents

API

The API surface is fairly small, you'll mainly be using the exported connection object, which is an instance of the also exported ConnectionManager using the default LocalStorage.

ConnectionManager

Handles the connection to the Ethereum network. It takes a Storage as the only argument, which will be used to store the last used connection.

.connect()

Connects to the supplied provider type and chain. It'll default to mainnet if no chain is supplied. After a successfull call the params will be stored using the supplied Storage, which will allow you to call tryPreviousConnection().

Definition

async connect(
  providerType: ProviderType,
  chainId: ChainId = ChainId.ETHEREUM_MAINNET
): Promise<ConnectionResponse>

Usage

const connection = new ConnectionManager(new Storage())
await connection.connect(ProviderType.INJECTED, ChainId.ETHEREUM_ROPSTEN)

.tryPreviousConnection()

Will try to connect to the provider and chain stored from the last successfull .connect(). It'll throw otherwise.

Definition

async tryPreviousConnection(): Promise<ConnectionResponse>

Usage

// Calls connect first
const connection = new ConnectionManager(new Storage())
await connection.connect(ProviderType.INJECTED, ChainId.ETHEREUM_ROPSTEN)

await connection.tryPreviousConnection() // Connects with ProviderType.INJECTED ChainId.ETHEREUM.ROPSTEN

.disconnect()

Disconnects the previous connection and clears the storage. It'll do nothing if no connection is found.

Definition

async disconnect()

Usage

const connection = new ConnectionManager(new Storage())
connection.connect(ProviderType.INJECTED, ChainId.ETHEREUM_ROPSTEN)

// (...)

connection.disconnect()

.getConnectionData()

Returns the data used for the last successfull .connect() call. It's used by .tryPreviousConnection to determine which connection to use. Check ConnectionData for more info on the returned type

Definition

getConnectionData(): ConnectionData | undefined

Usage

const connection = new ConnectionManager(new Storage())
connection.connect(ProviderType.INJECTED, ChainId.ETHEREUM_ROPSTEN)

// (...)

const connectionData = connection.getConnectionData() // => connectionData is ConnectionData

.getAvialableProviders()

Returns the providers available for connection. If for example no window object is found, ProviderType.INJECTED will not be returned on the list

Definition

getAvailableProviders(): ProviderType[]

Usage

connection.getAvailableProviders()

.getProvider()

Get's the currently connected provider. It'll throw if no connection was made, similar to calling .connect() without params the first time

Definition

async getProvider(): Promise<Provider>

Usage

const provider = await connection.getProvider()

.createProvider()

It creates a new provider using the supplied arguments. Similar to calling .connect() but without actually connecting.

Definition

async createProvider(
  providerType: ProviderType,
  chainId: ChainId = ChainId.ETHEREUM_MAINNET
): Promise<Provider> {

Usage

const provider = await connection.createProvider(
  Provider.FORTMATIC,
  ChainId.ETHEREUM_ROPSTEN
)

connection

Instance of ConnectionManager, using LocalStorage as it's internal storage engine, which translates to:

export const connection = new ConnectionMager(new LocalStorage())

Storage

Abstract class that defines the methods needed to create a new Storage engine. It only defines two methods:

abstract get(key: string): any | undefined
abstract set(key: string, value: any): void
abstract clear(): void

LocalStorage

An implementation of the Storage engine which uses window.localStorage to store data

Types

ProviderType

Represents the different types of connectors to the Ethereum Network

enum ProviderType {
  INJECTED = 'injected',
  FORTMATIC = 'formatic',
  NETWORK = 'network'
  WALLET_CONNECT = 'wallet_connect'
}

ChainId

Different Ethereum chains

enum ChainId {
  ETHEREUM_MAINNET = 1,
  ETHEREUM_ROPSTEN = 3,
  ETHEREUM_RINKEBY = 4,
  ETHEREUM_GOERLI = 5,
  ETHEREUM_KOVAN = 42,
  MATIC_MUMBAI = 13881,
  MATIC_MAINNET = 89
}

ConnectionResponse

type ConnectionResponse = {
  provider: Provider
  chainId: ChainId
  account: null | string
}

ConnectionData

type ConnectionData = {
  providerType: ProviderType
  chainId: ChainId
}

Example

import {
  connection,
  ConnectionResponse,
  ProviderType,
  ChainId
} from 'decentraland-connect'

async function connect() {
  let result: ConnectionResponse
  try {
    result = await connection.connect() // this will throw if no successful connect was called before
  } catch (error) {
    result = await connection.connect(ProviderType.FORTMATIC, ChainId.MAINNET)
  }
  return result
}

// If you're using something like React, you could do something like this (after trying a `.connect()`)
function showAvailableProviders() {
  const handleConect = useCallback((provider: ProviderType) =>
    connection.connect(provider, ChainId.MAINNET)
  )
  return connection
    .getAvailableProviders()
    .map(provider => (
      <div onClick={() => handleConnect(provider)}>{provider}</div>
    ))
}

Development

To run the project you simply need to

npm i
npm run test
npm run build

you can also check the test report using

npm run test:report

Copyright

This repository is protected with a standard Apache 2 license. See the terms and conditions in the LICENSE file.

decentraland-connect's People

Contributors

2fd avatar cazala avatar flobarreto avatar fzavalia avatar hprivakos avatar juanmahidalgo avatar kevinszuchet avatar lautaropetaccio avatar lauti7 avatar menduz avatar nachomazzara avatar nicosantangelo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

decentraland-connect's Issues

Decentraland RPC does not work with WalletConnectV2

// Request

curl --request POST \
  --url 'https://rpc.decentraland.org/mainnet?project=walletconnect_v2' \
  --header 'Content-Type: application/json' \
  --header 'accept: application/json' \
  --header 'accept-language: en-US,en;q=0.9' \
  --header 'authority: rpc.decentraland.org' \
  --header 'dnt: 1' \
  --header 'origin: http://localhost:3000' \
  --header 'referer: http://localhost:3000/' \
  --header 'sec-ch-ua: "Not:A-Brand";v="99", "Chromium";v="112"' \
  --header 'sec-ch-ua-mobile: ?0' \
  --header 'sec-ch-ua-platform: "macOS"' \
  --header 'sec-fetch-dest: empty' \
  --header 'sec-fetch-mode: cors' \
  --header 'sec-fetch-site: cross-site' \
  --header 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36' \
  --data '{
  "id": 1,
  "jsonrpc": "2.0",
  "method": "test",
  "params": []
}'
// Response

HTTP/1.1 503 Service Unavailable
Cf-Ray: 7ba73e39cb7bab1d-EZE
Connection: close
Content-Length: 33
Content-Type: text/plain;charset=UTF-8
Date: Wed, 19 Apr 2023 18:34:41 GMT
Server: cloudflare
Strict-Transport-Security: max-age=15552000; includeSubDomains; preload
X-Content-Type-Options: nosniff

No Provider available for mainnet

Checking logs, it seems that the test rpc method is being called which seems to be unsupported.

{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"The method test does not exist/is not available"}}

Using WallectConnect default rpcs seem to work fine

WalletConnect events do not trigger

When connected to a wallet connect enabled wallet, events do not trigger correctly. This creates the following scenarios:

  • Changing the chain does not trigger a refresh
  • Changing the account does not trigger a refresh
  • If you cancel a login attempt (canceling when the prompt asks to connect) decentraland-dapps's LoginModal keeps a perpetual Loading state (fixes itself on refresh)

The ethereumjs-abi library breaks the installation of several repositories

The following problem is recurrently found when installing our repositories:
Running npm install on some of our dapps like the builder breaks the CI changing the ethereumjs-abi resolved URL to ssh instead of https. Example of this happening
This is due to the version of @web3-react/walletconnect-connector that we're using. The ethereumjs-abi seems to have been removed in the upcoming versions of the library. Updating the library when the new version comes out seems to be the solution.

Unhandled PollingBlockTracker error crashes the explorer

There seems to be an error that is happening quite frequently in the Explorer that makes the explorer crash.
The error seems to be related to decentraland-connect not handling properly an error and is shown as:

Error:
PollingBlockTracker - encountered an error while attempting to update latest block:
undefined

Stacktrace

(Most recent call first)
File ../node_modules/eth-block-tracker/src/polling.js:51:24 in e/<
const newErr = new Error(`PollingBlockTracker - encountered an error while attempting to ...
File ../node_modules/regenerator-runtime/runtime.js:63:40 in l
return { type: "normal", arg: fn.call(obj, arg) };
File ../node_modules/regenerator-runtime/runtime.js:293:22 in c/a._invoke
var record = tryCatch(innerFn, self, context);
File ../node_modules/regenerator-runtime/runtime.js:118:21 in k/</<
return this._invoke(method, arg);
File ../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:20 in r
var info = gen[key](arg);
File ../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/asyncToGenerator.js:29:9 in u
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);

Check here for more info.

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.