Giter VIP home page Giter VIP logo

use-wallet-js's Introduction

⚠️ Notice

This repository's contents have been migrated to the v3 branch on the https://github.com/TxnLab/use-wallet repository. All further development will continue there.


UseWallet v3 Alpha - use-wallet-js

npm version License: MIT

use-wallet-js is a TypeScript library aimed at integrating Algorand wallets into decentralized applications (dApps). This vanilla JS version is a framework agnostic rewrite of the @txnlab/use-wallet React library: https://github.com/TxnLab/use-wallet

⚠️ This library is currently in its alpha stage and is not yet recommended for production use.

Overview

This version of UseWallet generally follows the same design principles as the React version, with a few key differences:

  1. Framework Agnostic: Unlike v2, which uses React Hooks, use-wallet-js employs TypeScript classes, making it usable in non-React dApps.

  2. Efficient: The core library has been optimized for speed and simplicity:

    • Framework-independent
    • Implements on-demand loading for wallet SDKs
  3. Dynamic SDK Initialization: Instead of initializing all wallet SDKs upfront, use-wallet-js dynamically imports the relevant SDK only when a "Connect" action has been triggered.

  4. Switching Networks: The library lets you configure and set the network(s) your application uses, exposing an algod client instance for the current active network. This pattern was inspired by solid-algo-wallets and allows for easy switching between public/local networks.

  5. State Updates: Each of the exported classes exposes a subscribe method for subscribing to state updates. In the absense of React, this provides a way for UI elements to re-render when the state changes.

Similar Structure to v2

At a high level, use-wallet-js retains a familiar structure and API for users of v2.x, principally through the WalletManager class. This class echoes the useWallet hook API from the previous version, aiming to make transitions between versions as seamless as possible.

While the library in its current form exports only classes, future updates will include framework-specific wrappers for React, Vue, Svelte, and Solid. These wrappers will be built on top of the core library, and will be published as separate packages [TBD].

Development Strategy

This repository will serve as the alpha stage for the @txnlab/use-wallet v3.0.0 release.

Once it reaches beta stage, the commit history will be patched to a branch on the TxnLab/use-wallet repository, with pre-releases published as @txnlab/[email protected].* on NPM.

Updates will be posted in the #use-wallet channel on the NFDomains Discord and from the @TxnLab Twitter.

Feedback and Issues

Feedback from the Algorand community during this stage will impact the quality and utility of the final release! Engage with the development, report bugs, and start discussions using the GitHub Issues.

Getting Started

Install the package using NPM:

npm install @txnlab/use-wallet-js

Install peer dependencies:

npm install @blockshake/defly-connect @perawallet/connect @walletconnect/modal @walletconnect/sign-client @walletconnect/types algosdk

Configuration

The WalletManager class is the main entry point for the library. It is responsible for initializing the wallet SDKs, managing the network, and handling wallet connections.

import { NetworkId, WalletId, WalletManager } from '@txnlab/use-wallet-js'

const walletManager = new WalletManager({
  wallets: [
    WalletId.DEFLY,
    WalletId.EXODUS,
    WalletId.PERA,
    {
      id: WalletId.WALLETCONNECT,
      options: { projectId: '<YOUR_PROJECT_ID>' }
    }
  ],
  network: NetworkId.TESTNET
})

wallets (required)

Each wallet you wish to support must be included in the wallets array.

To initialize wallets with default options, pass the wallet ID using the WalletId enum. To use custom options, pass an object with the id and options properties.

Note: WalletConnect's projectId option is required. You can get a project ID by registering your application at https://cloud.walletconnect.com/

network (optional)

The network property is used to set the default network for the application. It can be set to either BETANET, TESTNET, MAINNET, or LOCALNET. The default (if unset) is TESTNET.

The active network is persisted to local storage. If your application supports switching networks, when a user revisits your app or refreshes the page, the active network from the previous session will be restored.

algod (optional)

The WalletManager class exposes an algodClient property, which is an instance of the algosdk.Algodv2 class. This client is initialized with the default network, and can be used to make requests to an Algorand node.

const algodClient = walletManager.algodClient

If the active network changes, the algodClient instance will be updated to reflect the new network.

By default, the algodClient instance connects to AlgoNode's free (as in 🍺) API for public networks, and http://localhost for LOCALNET. You can override this behavior by passing an algod configuration object to the WalletManager constructor.

To configure the algodClient for the active network only, pass an object with token, baseServer and port properties:

const walletManager = new WalletManager({
  wallets: [...],
  network: NetworkId.TESTNET,
  algod: {
    token: '<YOUR_TOKEN>',
    baseServer: '<YOUR_SERVER_URL>',
    port: '<YOUR_PORT>', // string | number
  }
})

To configure the algodClient for specific networks, pass a mapped object of the network(s) you wish to configure, where each key is a NetworkId and each value is an algod configuration object:

const walletManager = new WalletManager({
  wallets: [...],
  network: NetworkId.TESTNET,
  algod: {
    [NetworkId.TESTNET]: {
      token: '<YOUR_TOKEN>',
      baseServer: '<YOUR_SERVER_URL>',
      port: '<YOUR_PORT>'
    },
    [NetworkId.MAINNET]: {
      token: '<YOUR_TOKEN>',
      baseServer: '<YOUR_SERVER_URL>',
      port: '<YOUR_PORT>'
    }
  }
})

WalletManager API

The WalletManager class manages wallets, networks, and states.

class WalletManager {
  constructor({
    wallets: Array<T | WalletIdConfig<T>>,
    network?: NetworkId,
    algod?: NetworkConfig
  }: WalletManagerConstructor)
}

Methods

subscribe(callback: (state: State) => void): (() => void)
  • Subscribes to state changes.

    • callback: The function to be executed when the state changes.
setActiveNetwork(network: NetworkId): void
  • Sets the active network.

    • network: The network to be set as active.
resumeSessions(): Promise<void>
  • Refreshes/resumes the sessions of all wallets.

Properties

wallets: BaseWallet[]
  • Returns all wallet instances.
activeNetwork: NetworkId
  • Returns the currently active network.
algodClient: algosdk.Algodv2
  • Returns the Algod client for the active network.
activeWallet: BaseWallet | null
  • Returns the currently active wallet instance.
activeWalletAccounts: WalletAccount[] | null
  • Returns accounts of the currently active wallet.
activeWalletAddresses: string[] | null
  • Returns addresses of the currently active wallet's accounts.
activeAccount: WalletAccount | null
  • Returns the currently active account.
activeAddress: string | null
  • Returns the address of the currently active account.
signTransactions
  • Throws an error if no active wallet, or returns the signTransactions method from the active wallet:
public signTransactions(
  txnGroup: algosdk.Transaction[] | algosdk.Transaction[][] | Uint8Array[] | Uint8Array[][],
  indexesToSign?: number[],
  returnGroup?: boolean // default: true
): Promise<Uint8Array[]>
transactionSigner: TransactionSigner
  • Throws an error if no active wallet, or returns a TransactionSigner function that signs with the active wallet.
public transactionSigner(
  txnGroup: algosdk.Transaction[],
  indexesToSign: number[]
): Promise<Uint8Array[]>
transactionSignerAccount: TransactionSignerAccount
  • Throws an error if no active account, or returns a TransactionSignerAccount object with addr set to the active address and signer set to this.transactionSigner (see above).
/** A wrapper around `TransactionSigner` that also has the sender address. */
interface TransactionSignerAccount {
  addr: Readonly<string>
  signer: TransactionSigner
}

Example UI

See the examples/vanilla-ts directory for a simple Vite app that demonstrates the library's functionality.

Switching Networks

Coming soon

Signing Transactions

Coming soon

License

MIT ©2024 TxnLab, Inc.

use-wallet-js's People

Contributors

drichar avatar gabrielkuettel avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

use-wallet-js's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): lock file maintenance

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v4
  • actions/setup-node v4
  • pnpm/action-setup v2
  • actions/cache v4
npm
package.json
  • @testing-library/jest-dom ^6.1.6
  • @testing-library/react ^14.1.2
  • @typescript-eslint/eslint-plugin ^6.7.2
  • @typescript-eslint/parser ^6.7.2
  • @vitejs/plugin-react ^4.2.1
  • @vitejs/plugin-vue ^5.0.2
  • @vitejs/plugin-vue-jsx ^3.1.0
  • @vue/test-utils ^2.4.3
  • eslint ^8.50.0
  • eslint-config-prettier ^9.0.0
  • eslint-plugin-prettier ^5.0.1
  • prettier 3.2.5
  • vite ^5.0.8
  • vitest ^1.1.1
  • vue-demi ^0.14.6
packages/use-wallet-js/package.json
  • @tanstack/store ^0.3.1
  • @walletconnect/utils ^2.10.2
  • algosdk ^2.7.0
  • buffer ^6.0.3
  • @blockshake/defly-connect ^1.1.6
  • @perawallet/connect ^1.3.3
  • @types/node ^20.6.5
  • @walletconnect/modal ^2.6.2
  • @walletconnect/modal-core ^2.6.2
  • @walletconnect/sign-client ^2.10.2
  • @walletconnect/types ^2.10.2
  • algo-msgpack-with-bigint ^2.1.1
  • lute-connect ^1.1.3
  • tsup ^8.0.0
  • typescript ^5.2.2
  • @blockshake/defly-connect ^1.1.6
  • @perawallet/connect ^1.3.3
  • @walletconnect/modal ^2.6.2
  • @walletconnect/sign-client ^2.10.2
  • lute-connect ^1.1.3
packages/use-wallet-react/package.json
  • @tanstack/react-store ^0.3.1
  • @types/react ^18.2.45
  • algosdk ^2.7.0
  • jsdom ^24.0.0
  • react ^18.2.0
  • react-dom ^18.2.0
  • tsup ^8.0.0
  • typescript ^5.2.2
  • @blockshake/defly-connect ^1.1.6
  • @perawallet/connect ^1.3.3
  • @walletconnect/modal ^2.6.2
  • @walletconnect/sign-client ^2.10.2
  • algosdk ^2.6.0
  • react ^18.2.0
packages/use-wallet-vue/package.json
  • @tanstack/vue-store ^0.3.1
  • algosdk ^2.7.0
  • tsup ^8.0.0
  • typescript ^5.2.2
  • vue ^3.3.13
  • @blockshake/defly-connect ^1.1.6
  • @perawallet/connect ^1.3.3
  • @walletconnect/modal ^2.6.2
  • @walletconnect/sign-client ^2.10.2
  • algosdk ^2.6.0
  • vue ^3.3.13

  • Check this box to trigger a request for Renovate to run again on this repository

vue `wallet.activeNetwork` stuck on `testnet`

Following the vue example, I set the network to NetworkId.MAINNET

app.use(WalletManagerPlugin, {
  wallets: [
    WalletId.PERA,
  ],
  network: NetworkId.MAINNET
})

but if i log the network it's always testnet

const wallet = useWallet()
cl(wallet.activeNetwork) // 'testnet'

The networks in wallet.wallets[].activeNetwork are correctly 'mainnet'

EDIT:

Hook data (walletState, walletManager) aren't reactive.

  1. For walletState, the issue is you can't reassign a reactive object

https://vuejs.org/guide/essentials/reactivity-fundamentals.html#limitations-of-reactive

  1. For walletManager, it's a bit more tricky, but you have to wrap it with a ref and somehow trigger a reactive update.

Wrong "this" for vue use-wallet

this value for signTransactions and transactionSigner is manager instead of the corresponding wallet.

return manager.signTransactions(txnGroup, indexesToSign, returnGroup)

Leads to this error:
image

My workaround:

        const fn = manager.signTransactions.bind(manager.activeWallet)
        return fn(txnGroup, indexesToSign, returnGroup)

Affects the react package as well. If this is a commonly used pattern (returning a function from a getter), you may want to go over them and confirm the this value is as expected.

Prevent server side (SSR) initialization

In the core library and/or framework adapters, prevent initialization if window and localStorage are not available.

It also might make sense to include SSR framework examples, e.g. Next, Nuxt, etc

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.