You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 7-8.RSVP
Socket
Socket
Sign inDemoInstall

@walletconnect/universal-provider

Package Overview
Dependencies
Maintainers
10
Versions
290
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@walletconnect/universal-provider

Universal Provider for WalletConnect Protocol


Version published
Weekly downloads
289K
increased by0.6%
Maintainers
10
Created
Weekly downloads
 

Package description

What is @walletconnect/universal-provider?

@walletconnect/universal-provider is a JavaScript library that allows developers to integrate WalletConnect functionality into their applications. WalletConnect is an open protocol for connecting decentralized applications (dApps) to mobile wallets with QR code scanning or deep linking. This package provides a universal provider that supports multiple blockchain networks and wallet types, making it easier to manage wallet connections and interactions.

What are @walletconnect/universal-provider's main functionalities?

Initialize WalletConnect Provider

This code initializes the WalletConnect Universal Provider with the necessary configuration, including project ID, relay URL, and metadata for the dApp.

const { UniversalProvider } = require('@walletconnect/universal-provider');

const provider = new UniversalProvider({
  projectId: 'your_project_id',
  relayUrl: 'wss://relay.walletconnect.org',
  metadata: {
    name: 'My DApp',
    description: 'My decentralized application',
    url: 'https://mydapp.com',
    icons: ['https://mydapp.com/icon.png']
  }
});

Connect to Wallet

This code demonstrates how to connect to a wallet using the Universal Provider. It specifies the required namespaces, methods, chains, and events, and then logs the connected session.

async function connectWallet() {
  const session = await provider.connect({
    requiredNamespaces: {
      eip155: {
        methods: ['eth_sendTransaction', 'personal_sign'],
        chains: ['eip155:1'],
        events: ['chainChanged', 'accountsChanged']
      }
    }
  });
  console.log('Connected session:', session);
}

connectWallet();

Send Transaction

This code demonstrates how to send a transaction using the Universal Provider. It constructs a transaction object and sends it using the 'eth_sendTransaction' method.

async function sendTransaction() {
  const tx = {
    from: '0xYourAddress',
    to: '0xRecipientAddress',
    value: '0xAmountInHex',
    gas: '0xGasLimitInHex'
  };
  const result = await provider.request({
    method: 'eth_sendTransaction',
    params: [tx]
  });
  console.log('Transaction result:', result);
}

sendTransaction();

Other packages similar to @walletconnect/universal-provider

Readme

Source

@walletconnect/universal-provider

Universal Provider for WalletConnect Protocol

Usage

import { ethers } from "ethers";
import UniversalProvider from "@walletconnect/universal-provider";

//  Initialize the provider
const provider = await UniversalProvider.init({
  logger: "info",
  relayUrl: "ws://<relay-url>",
  projectId: "12345678",
  metadata: {
    name: "React App",
    description: "React App for WalletConnect",
    url: "https://walletconnect.com/",
    icons: ["https://avatars.githubusercontent.com/u/37784886"],
  },
  client: undefined, // optional instance of @walletconnect/sign-client
});

//  create sub providers for each namespace/chain
await provider.connect({
  namespaces: {
    eip155: {
      methods: [
        "eth_sendTransaction",
        "eth_signTransaction",
        "eth_sign",
        "personal_sign",
        "eth_signTypedData",
      ],
      chains: ["eip155:80001"],
      events: ["chainChanged", "accountsChanged"],
      rpcMap: {
        80001: "https://rpc.walletconnect.com?chainId=eip155:80001&projectId=<your walletconnect project id>",
      },
    },
    pairingTopic: "<123...topic>", // optional topic to connect to
    skipPairing: false, // optional to skip pairing ( later it can be resumed by invoking .pair())
  },
});

//  Create Web3 Provider
const web3Provider = new ethers.providers.Web3Provider(provider);

Events

// Subscribe for pairing URI
provider.on("display_uri", (uri) => {
  console.log(uri);
});

// Subscribe to session ping
provider.on("session_ping", ({ id, topic }) => {
  console.log(id, topic);
});

// Subscribe to session event
provider.on("session_event", ({ event, chainId }) => {
  console.log(event, chainId);
});

// Subscribe to session update
provider.on("session_update", ({ topic, params }) => {
  console.log(topic, params);
});

// Subscribe to session delete
provider.on("session_delete", ({ id, topic }) => {
  console.log(id, topic);
});

Provider Methods

interface RequestArguments {
  method: string;
  params?: any[] | undefined;
}

// Send JSON RPC requests

/**
 * @param payload
 * @param chain - optionally specify which chain should handle this request
 * in the format `<namespace>:<chainId>` e.g. `eip155:1`
 */
const result = await provider.request(payload: RequestArguments, chain: string | undefined);

Multi-chain

const web3 = new Web3(provider);

// default chainId is the FIRST chain during setup
const chainId = await web3.eth.getChainId();

// set the default chain to 56
provider.setDefaultChain(`eip155:56`, rpcUrl?: string | undefined);

// get the updated default chainId
const updatedDefaultChainId = await web3.eth.getChainId();

Creating a provider file

  • Create a file under providers/universal-provider/src/providers/<NAMESPACE>.ts
  • Implement the IProvider interface
  • In the IProvider.request method, there should be a check for whether or not to run the request against the wallet or the blockchain. this.namespace.methods should only contain the methods supported by the wallet.
  • The rest of the methods of the class are very similar, mainly centering around httpProvider and for the most part will be 90% similar to other providers given similar structure of chainId. For example eip155:1 or solana:mainnetBeta.
  • Export provider under providers/universal-provider/src/providers/index.ts

Keywords

FAQs

Package last updated on 17 Aug 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc