npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

supra-starkey-connect

v1.0.11

Published

A unofficial typed, lightweight wrapper around the StarKey Supra wallet provider for the Supra Blockchain

Downloads

789

Readme

Supra Starkey Connect (Unofficial)

supra-starkey-connect is a TypeScript-based library that provides a robust and type-safe wrapper around the StarKey Supra wallet provider. It simplifies the integration of Supra Blockchain wallet functionalities into your web applications, enabling seamless interactions such as connecting wallets, sending transactions, signing messages, and handling network changes.

This version introduces improvements that resolve specific Server-Side Rendering (SSR) issues and adopts the getSupraStarkeyConnect method for enhanced functionality.

For an overview of the entire monorepo and example applications, please refer to the MONOREPO README.

Table of Contents

Features

  • Type Safety: Leveraging TypeScript to ensure type-safe interactions with the StarKey Supra provider.
  • Event Handling: Simplified event listeners for account changes, disconnections, and network changes.
  • Multiple Build Formats: Supports ESM, CJS, and Browser (IIFE) builds to cater to different environments.
  • Comprehensive Methods: Includes methods for connecting, disconnecting, sending transactions, signing messages, and more.
  • SSR Enhancements: Version 1.0.9 and up addresses specific SSR issues, ensuring better compatibility with server-rendered applications.
  • Utility Functions: Provides utilities like HexString, remove0xPrefix, and sleep for common tasks.
  • BuilderTypes: Exports BuilderTypes for constructing transaction payloads and other blockchain-related data structures.
  • Undocumented Methods Support: Exposes additional methods currently undocumented by StarKey, with plans for full support as documentation becomes available.

REACTJS supra-starkey-connect Features Demo: React Live Demo on Vercel REACT NEXTJS supra-starkey-connect Features Demo: React NextJS Live Demo on Vercel Vanilla JS supra-starkey-connect Features Demo: Vanilla JS Live Demo on Vercel

Installation

NPM

npm install supra-starkey-connect

PNPM

pnpm add supra-starkey-connect

For Browser (Vanilla JavaScript)

You can use the browser-friendly build provided by the library via a CDN:

<script src="https://unpkg.com/supra-starkey-connect/dist/browser.iife.js"></script>

Usage

Importing the Library

import { getSupraStarkeyConnect } from 'supra-starkey-connect'

// Initialize the connection
const ssc = getSupraStarkeyConnect()

// Connect to the wallet
const account = await ssc.connect()
console.log(`Connected Account: ${account}`)

Connecting to the Wallet

import { getSupraStarkeyConnect } from 'supra-starkey-connect'

const ssc = getSupraStarkeyConnect()

async function connectWallet() {
  try {
    const account = await ssc.connect()
    console.log(`Connected Account: ${account}`)
  } catch (error) {
    console.error(`Connection Failed: ${error.message}`)
  }
}

For detailed examples and integration guides, refer to the React Example App, React Next.js Example App, and the Vanilla Example App.

API

The supra-starkey-connect library exposes a comprehensive API to interact with the StarKey Supra wallet provider. Below is an overview of the available interfaces and methods, complete with examples for each function.

Interfaces

SendTransactionParams

Parameters for sending a transaction.

interface SendTransactionParams {
  from: string
  to: string
  value: string | number
  data?: string
  chainId?: string
}

Example:

const transaction = {
  from: '0xYourAccountAddress',
  to: '0xRecipientAddress',
  value: '100000000',
  data: '0x'
}

const txHash = await ssc.sendTransaction(transaction)
console.log(`Transaction Hash: ${txHash}`)

Balance

Represents the balance information.

interface Balance {
  balance: number
  formattedBalance: string
  decimal: number
  displayUnit: string
}

Example:

const balance = await ssc.getBalance()
console.log(`Balance: ${balance.formattedBalance} ${balance.displayUnit}`)

SignMessageParams

Parameters for signing a message.

interface SignMessageParams {
  message: string
  nonce?: string
}

SignMessageResponse

Represents the response from a signed message.

interface SignMessageResponse {
  publicKey: string
  signature: string
  address: string
}

RawTxPayload

Defines the structure of a raw transaction payload.

type RawTxPayload = [
  string, // sender address
  number, // sender sequence number
  string, // module address
  string, // module name
  string, // function name
  TypeTag[], // function type arguments
  Uint8Array[], // function arguments
  OptionalTransactionPayloadArgs? // optional transaction payload arguments
]

Methods

isStarKeyAvailable()

Checks if the Starkey Provider is available in the current environment.

isStarKeyAvailable(): boolean

Example:

if (ssc.isStarKeyAvailable()) {
  console.log('Supra Wallet is available.')
} else {
  console.log('Supra Wallet is not available.')
}

connect()

Connects to the Supra wallet and retrieves the first account.

async connect(): Promise<string>

Example:

const account = await ssc.connect()
console.log(`Connected Account: ${account}`)

disconnect()

Disconnects from the Supra wallet.

async disconnect(): Promise<void>

Example:

await ssc.disconnect()
console.log('Disconnected from Supra Wallet.')

isConnected()

Checks if there are any connected accounts.

async isConnected(): Promise<boolean>

Example:

const connected = await ssc.isConnected()
console.log(`Is Connected: ${connected}`)

getAllAccounts()

Retrieves all connected accounts.

async getAllAccounts(): Promise<string[] | null>

Example:

const accounts = await ssc.getAllAccounts()
console.log(`All Accounts: ${accounts?.join(', ')}`)

getCurrentAccount()

Retrieves the current connected account.

async getCurrentAccount(): Promise<string | null>

Example:

const currentAccount = await ssc.getCurrentAccount()
console.log(`Current Account: ${currentAccount}`)

getCurrentNetwork()

Retrieves the current network.

async getCurrentNetwork(): Promise<string | null>

Example:

const network = await ssc.getCurrentNetwork()
console.log(`Current Network: ${network || 'None'}`)

getChainId()

Retrieves the chain ID of the current network.

async getChainId(): Promise<{ chainId: string } | null>

Example:

const chainId = await ssc.getChainId()
console.log(`Chain ID: ${chainId?.chainId}`)

sendTransaction(tx: SendTransactionParams)

Sends a transaction.

async sendTransaction(tx: SendTransactionParams): Promise<string>

Example:

const transaction = {
  from: '0xYourAccountAddress',
  to: '0xRecipientAddress',
  value: '100000000'
}

const txHash = await ssc.sendTransaction(transaction)
console.log(`Transaction Hash: ${txHash}`)

getBalance()

Retrieves the balance of the connected account.

async getBalance(): Promise<Balance>

Example:

const balance = await ssc.getBalance()
console.log(`Balance: ${balance.formattedBalance} ${balance.displayUnit}`)

getVersion()

Retrieves the version of the Starkey Provider.

async getVersion(): Promise<string>

Example:

const version = await ssc.getVersion()
console.log(`Starkey Provider Version: ${version}`)

changeNetwork(chainId: string)

Changes the network chain.

async changeNetwork(chainId: string): Promise<{ chainId: string }>

Example:

const newChain = '6'
const result = await ssc.changeNetwork(newChain)
console.log(`Network changed to Chain ID: ${result.chainId}`)

promptInstall()

Prompts the user to install the StarKey Supra wallet.

promptInstall(): void

Example:

ssc.promptInstall()

signMessage(params: SignMessageParams)

Signs a message.

async signMessage(params: SignMessageParams): Promise<{ verified: boolean; response: SignMessageResponse }>

Example Usage:

try {
  const params = {
    message: 'Hello, Supra!'
  }
  const response = await ssc.signMessage(params)
  console.log(response) // Outputs: SignMessageResponse
} catch (error) {
  console.error(`Sign Message Error: ${error.message}`)
}

signAndSendTransaction(rawTxPayload: RawTxPayload, value?: string | number): Promise<string>

Signs and sends a raw transaction.

async signAndSendTransaction(
  rawTxPayload: RawTxPayload,
  value: string | number = ''
): Promise<string>

Example Usage:

import { HexString, BCS } from 'supra-starkey-connect'

// Define transaction parameters
const rawTxPayload: RawTxPayload = [
  '0xYourSenderAddress',
  0,
  '0xModuleAddress',
  'module_name',
  'function_name',
  [],
  [new HexString('0xabcdef').toUint8Array(), BCS.bcsSerializeUint64(100000000)]
]

try {
  const txHash = await ssc.signAndSendTransaction(rawTxPayload, '100000000')
  console.log(`Transaction sent successfully! Hash: ${txHash}`)
} catch (error) {
  console.error(`Transaction failed: ${error.message}`)
}

Undocumented Methods

The supra-starkey-connect library currently exposes some methods that are undocumented by StarKey. These methods are included based on existing functionality and observed behavior, with plans for full support once more comprehensive API documentation is available.

List of Undocumented Methods

Note: Use these methods with caution, as their behavior may change without notice.

waitForTransactionWithResult(txHash: string)

Waits for a transaction with a result.

async waitForTransactionWithResult(txHash: string): Promise<any>

Example:

try {
  const result = await ssc.waitForTransactionWithResult('0xTransactionHash')
  console.log(`Transaction Result:`, result)
} catch (error) {
  console.error(`Wait For Transaction Error: ${error.message}`)
}

waitForTransactionCompletion (Alternative to undocumented function)

Utility function that waits for a transaction to complete by polling its status at regular intervals (will be deprecated when waitForTransactionWithResult is documented)

async waitForTransactionCompletion(
  txHash: string,
  network?: string
): Promise<TransactionStatus>

Example:

import {
  waitForTransactionCompletion,
  TransactionStatus
} from 'supra-starkey-connect'

const txHash = '0xYourTransactionHashHere'

waitForTransactionCompletion(txHash, 'mainnet')
  .then((status) => {
    if (status === TransactionStatus.Success) {
      console.log('Transaction completed successfully!')
    } else if (status === TransactionStatus.Failed) {
      console.log('Transaction failed.')
    } else {
      console.log('Transaction is still pending after maximum retries.')
    }
  })
  .catch((error) => {
    console.error('Error while waiting for transaction completion:', error)
  })

Utilities

Utility Functions

The supra-starkey-connect library offers a set of utility functions to facilitate common tasks related to hexadecimal string manipulation and transaction payload validation.

HexString

A versatile class for managing hexadecimal strings and converting between hexadecimal strings and byte arrays.

Example Usage:

import { HexString } from 'supra-starkey-connect'

// Creating a HexString instance
const hex = new HexString('abcdef')

// Converting to Uint8Array
const bytes = hex.toUint8Array()
console.log(bytes) // Uint8Array(3) [ 171, 205, 239 ]

// Getting hex string with prefix
console.log(hex.hex()) // '0xabcdef'

// Getting hex string without prefix
console.log(hex.noPrefix()) // 'abcdef'

// Creating HexString from Uint8Array
const newHex = HexString.fromUint8Array(new Uint8Array([171, 205, 239]))
console.log(newHex.hex()) // '0xabcdef'

remove0xPrefix

Removes the 0x prefix from a hexadecimal string if it exists.

Example Usage:

import { remove0xPrefix } from 'supra-starkey-connect'

const cleanHex = remove0xPrefix('0xabcdef') // 'abcdef'
const sameHex = remove0xPrefix('abcdef') // 'abcdef'

console.log(cleanHex) // 'abcdef'
console.log(sameHex) // 'abcdef'

sleep

Delays execution for the specified time.

/**
 * Delays execution for a specified number of milliseconds.
 *
 * @param ms - The number of milliseconds to sleep.
 * @returns A promise that resolves after the specified delay.
 */

Example Usage:

import { sleep } from 'supra-starkey-connect'

async function delayedLog() {
  console.log('Wait for it...')
  await sleep(2000)
  console.log('Done!')
}

delayedLog()
// Output:
// Wait for it...
// (2 seconds later)
// Done!

BuilderTypes

Exports BuilderTypes for constructing transaction payloads and other blockchain-related data structures.

Example Usage:

import { TxnBuilderTypes } from 'supra-starkey-connect'

// Use TxnBuilderTypes to construct transaction payloads
const typeTag: TxnBuilderTypes.TypeTag = TxnBuilderTypes.TypeTagU64

Types

The library defines several TypeScript types and interfaces to ensure type safety and clarity in interactions.

TypeTag

Represents various type tags used in transactions.

export type TypeTag =
  | TypeTagBool
  | TypeTagU8
  | TypeTagU16
  | TypeTagU32
  | TypeTagU64
  | TypeTagU128
  | TypeTagU256
  | TypeTagAddress
  | TypeTagSigner
  | TypeTagVector
  | TypeTagStruct

TransactionStatus

Represents the status of a transaction.

export enum TransactionStatus {
  Success = 'Success',
  Failed = 'Failed',
  Pending = 'Pending'
}

Additional Types and Interfaces

  • OptionalTransactionPayloadArgs: Represents optional transaction options.
  • SendTransactionParams: Parameters for sending a transaction.
  • Balance: Represents balance information.
  • SignMessageParams: Parameters for signing a message.
  • SignMessageResponse: Represents the response from a signed message.
  • RawTxPayload: Defines the structure of a raw transaction payload.
  • StarkeyProvider & StarkeyProviderWithOff: Interfaces defining the Starkey wallet provider functionalities.
  • StarkeyObject: Represents the Starkey object attached to the window.
  • StructTag: Defines the structure of a blockchain struct.

For detailed type definitions, refer to the library's TypeScript Definitions.

Development

Building the Library

To build the library, run:

pnpm build

This command will compile the TypeScript code and generate the necessary build outputs in ESM, CJS, and IIFE formats.

Running Tests

To run tests for the supra-starkey-connect library:

pnpm run test

Ensure that all tests pass to maintain code quality and reliability.

Example Applications

This monorepo includes four example applications to demonstrate the integration and usage of supra-starkey-connect across different environments:

  1. React Example App (without Next.js)
  2. React Next.js Example App
  3. Vanilla JavaScript Example App

Each example app provides unique insights and showcases various features of the supra-starkey-connect library. Refer to their respective READMEs for detailed instructions and usage examples.

Contributing

Contributions are highly appreciated! Please ensure that your code adheres to the existing style and includes relevant tests. If you wish to add support for the undocumented methods, please coordinate with the StarKey team to ensure compatibility and stability.

License

This project is licensed under the MIT License.