Git Product home page Git Product logo

solib's Introduction

Solib

Solana friendly API

Checkout the complete docs!

Current Capabilities

API

  • Connect Wallet:
    • Phantom
    • WalletConnect
  • Get balance
  • Sign Transaction
  • Send Transaction
  • Sign and send Transaction
  • Sign Message
  • Watch Transactions

Init

The init function needs to be called to prepare solib to be able to call all the functions in its API.

import { init } from 'solib'

init(
  {
    // The different connector methodologies that will be used.
    // PhantomConnector will interact with injected Phantom Wallet using browser
    // extension, while WalletConnectConnector can be used to interact with all
    // wallets that support the WalletConnect protocol.
    connectors: [
      new PhantomConnector(),
      new WalletConnectConnector({
        relayerRegion: 'wss://relay.walletconnect.com',
        metadata: {
          description: 'Test app for solib',
          name: 'Test Solib dApp',
          icons: ['https://avatars.githubusercontent.com/u/37784886'],
          url: 'http://localhost:3000'
        },
        autoconnect: true,
        qrcode: true
      })
    ],
    // Name of the connector to be used.
    // The connector needs to be registered in the connectors field above.
    // This can be switched later using `switchConnector` function.
    connectorName: WalletConnectConnector.connectorName,
    // The name of the cluster and network to use.
    // Here, `mainnetBeta` refers to the mainnetBeta Solana network, while
    // `WalletConnect` is the RPC server thhat will be used to do the communication
    chosenCluster: mainnetBetaWalletConnect()
  },
  WALLETCONNECT_PROJECT_ID
)

Connect Wallet

The connect function can be used to connect a wallet to a dApp. The wallet chosen needs to be configured in the init function above.

import { connect } from 'solib'

const address = await connect()

Watch Address

Instead of retrieving the address once on the connect function, one can globally watch address changes using the watchAddress API.

import { watchAddress, connect } from 'solib'

watchAddress(address => {
  console.log({ address })
})

connect()

Get Balance

import { getBalance } from 'solib'

const connectedWalletBalance: number = await getBalance()

Sign Message

import { signMessage } from 'solib'

const signature = await signMessage('Test')

Sign and Send Transaction

import { signAndSendTransaction } from 'solib'

const transactionHash = signAndSendTransaction('transfer', {
  to,
  amountInLamports,
  feePayer: 'from'
})

Watch Transaction

import { signAndSendTransaction, watchTransaction } from 'solib'

const transactionHash = signAndSendTransaction('transfer', {
  to,
  amountInLamports,
  feePayer: 'from'
})

watchTransaction(transactionHash, update => console.log({ update }))

Switch network

import { switchNetwork, mainnetBetaProjectSerum } from 'solib'

switchNetwork(mainnetBetaProjectSerum)

Switch Connector

import { switchConnector, PhantomConnector, connect } from 'solib'

switchConnector(PhantomConnector.connectorName)

const phantonWalletAddress = await connect()

Internals

  • Generic transaction construction
  • Using cluster sendTransaction to avoid depending on aa wallet's implementation, only having to use their signMessage function
  • Internal store maintaining state
  • Base connector to help with making future connectors (Eg: WalletConnect connector)
  • Generic typing
  • From scratch cluster websocket factory so we can listen to events and attach custom listeners in the future, in a generic manner.
  • Unsub functionality

Development

For now when developing, feel free to use the example/dev.sh to help with refreshing the cache and installing a fresh local solib package to test your changes. TODO: Will look into making this better.

Folders

Example

Example app written in react, for testing

Src

Actual source code.

  • actions: This where most of the developer public will live. Actions are what developers will use to fetch and manipulate data on the solana blockchain
  • connectors: This is where connectors will live. Connectors are basically adapters using wallet providers (Eg: Phantom). base.ts is a base class that has functionality for building connectors, as well as non-wallet-specific actions (eg: fetching wallet balance from the cluster)
  • defaults: This is where default things will live, like the clusters we have configured
  • store: A rudimentary store used for storing address, chosen cluster, etc
  • types: Self explanatory. Not all types need to live here, however.
  • utils: Self explanatory.

Resources:

solib's People

Contributors

arein avatar chadyj avatar devceline avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar

solib's Issues

How can I trigger Phantom browser extension connect?

My init function is as below:

init(
    () => ({
      // The different connector methodologies that will be used.
      // PhantomConnector will interact with injected Phantom Wallet using browser
      // extension, while WalletConnectConnector can be used to interact with all
      // wallets that support the WalletConnect protocol.
      connectors: [
        new PhantomConnector(),
        // new InjectedConnector("window.solib"),
        // new InjectedConnector("window.solflare"),
        new WalletConnectConnector({
          relayerRegion: "wss://relay.walletconnect.com",
          metadata: {
            description: "Test app for solib",
            name: "Test Solib dApp",
            icons: ["https://avatars.githubusercontent.com/u/37784886"],
            url: "https://app.staio.io",
          },
          autoconnect: true,
          qrcode: true,
        }),
      ],
      // Name of the connector to be used.
      // The connector needs to be registered in the connectors field above.
      // This can be switched later using `switchConnector` function.
      connectorName: WalletConnectConnector.connectorName,
      // The name of the cluster and network to use.
      // Here, `mainnetBeta` refers to the mainnetBeta Solana network, while
      // `WalletConnect` is the RPC server thhat will be used to do the communication
      chosenCluster: mainnetBetaWalletConnect(),
    }),
    walletConnectProjectId
  );

and when I call connect in @walletconnect/solib, it opens a modal, there is no phantom option

Reduce Solib's bundle size

Solib's bundle size is quiet big due to its dependency on @solana/web3js and our universal provider, among other factors.

We need to find ways to decrease the bundlesize. One option would be making @walletconnect/universal-provider and @solana/web3js peerDependencies instead of direct dependencies. This is similar to wagmi demanding an install of ethers alongside its main package.

However, with the way solib was written to not depend on the big utilities of @solana/web3js, we might be able to consider not using it all together. The biggest blocker of this is implementing PublicKey since it's the main struct we depend on.

This issue DOD is:

  • Make a plan on how to reduce bundle size
  • Implement it

Update dependencies

Deps

  • Update Universal Provider to ^2.9.1

Peer Deps

  • Update @solana/web3.js to ^1.78.0
  • Change @web3modal/core and @web3modal/ui to @walletconnect/modal

Add support for building and executing durable TXs

Following up on the discord server thread related to how to handle durable TXs when dApps connect to wallet-connect compatible wallet https://discord.com/channels/492410046307631105/1045008929450627113. Will reiterate the context on this issue for visibility:

  1. Some wallet-connect compatible wallets, e.g. Fireblocks, are MPC wallets that requires for some initiated TXs to be approved by a quorum of admins and shortly after signed by specific admins as well.
  2. The process from 1) is variable in length and can take from minutes to days.
  3. Given that Solana TXs can be executed in a window of roughly 2 mins after the recent blockhash of a TX (https://docs.solana.com/implemented-proposals/durable-tx-nonces#problem), the long process of approving and signing a TX requires the usage of durable TXs.
  4. Using durable TXs means creating a regular TX that has the AdvanceNonce IX prepended, which requires the existence of a NonceAccount with the authority set to one of the TX signers.
  5. To create durable TXs within the dApps each dApp must use a nonce account that has as authority one of the signers of the TXs, which most probably will be the user connected wallet.
  6. These NonceAccounts can be a) created by users and provided to the dApps, b) managed by the dApps to hide the complexity from end users or c) handled by the wallets by fetching the regular raw TXs from the dApps and change them to durable, besides the signing and broadcasting to the network. c) would be ideal for both dApps and users and it's something which scales better. From my understanding from discussing with Fireblocks on the subject, they already have business logic that support c). Solib provides the signAndSendTransaction primitive that shouldl kickstart the mutation of the raw TX to a durable one on Fireblocks side plus the TX approving, signing and broadcasting, but by looking at the implementation it seems that the method relies on the Solana validators sendTransaction RPC method, not on the wallet implementation of a solana_sendTransaction RPC method implemented on the relay server (please correct me if I am wrong). Also, Fireblocks is one of the many MPC wallets that might implement walletconnect v2 standard for Solana and the same assumptions around c) might not stand for all wallets.
  7. NonceAccounts are owned by SystemProgram so querying for them using Solana validator RPC methods (getProgramAccounts being the only option from my understanding) brings significant latencies given the number of accounts owned by the SystemProgram.
  8. dApps that want to take matters in their own hands must manage NonceAccounts creation/indexing for users wallet addresses, to enable the support for durable TXs that will be signed and broadcasted to the network on the wallets side.
  9. This is not something that scales very well (especially if all dApps will create nonce accounts for same users and index these nonce accounts in their backend to avoid 7.).
  10. Something which can improve 9) is if the querying for nonce accounts that have as authority the dApp connected user can be done in a more efficient manner (through some Solana primitive maybe?) or if the nonce account management will be deferred to the wallets.

I am curious to see how the reasoning process unfolds while progressing towards a decision and solution (one from 6. or others, not specified in this issue).

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.