0.7.1 • Published 1 month ago

@silk-wallet/silk-wallet-sdk v0.7.1

Weekly downloads
-
License
-
Repository
-
Last release
1 month ago

Silk Wallet SDK

npm link

Installation

npm install @silk-wallet/silk-wallet-sdk
# or
yarn add @silk-wallet/silk-wallet-sdk
# or
pnpm add @silk-wallet/silk-wallet-sdk

Usage

Basic Integration

import { initSilk } from '@silk-wallet/silk-wallet-sdk'

// Initialize Human Wallet. This will set window.silk with all necessary methods
initSilk()

// Request accounts (prompts user to connect)
const accounts = await window.silk.request({ method: 'eth_requestAccounts' })
console.log('Connected accounts:', accounts)

// Send a transaction
const txHash = await window.silk.request({
  method: 'eth_sendTransaction',
  params: [
    {
      from: accounts[0],
      to: '0xRecipientAddress',
      value: '0x123' // hex value in wei
    }
  ]
})

Configuration Options

The initSilk function accepts several configuration options:

initSilk({
  // Optional: Your WalletConnect project ID (REQUIRED for WalletConnect functionality)
  walletConnectProjectId: 'YOUR_WALLETCONNECT_PROJECT_ID',

  // Optional: Human Wallet points referral code
  referralCode: 'YOUR_REFERRAL_CODE',

  // Optional: Custom UI configuration
  config: {
    // See documentation or the Developer Portal for more style options
    authenticationMethods: [],
    allowedSocials: [],
    styles: {
      darkMode: true
    }
  },

  // Optional: Project configuration
  project: {
    name: 'Your App Name', // Project name used throughout the SDK
    entryTitle: 'Log in to Your App', // Optional: Custom entry title (defaults to "Log in to {name}")
    logo: 'Your app logo in base64 (see docs or portal)',
    projectId: '' // See documentation or the Developer Portal to learn how to set up a gastank for your users
  },

  // Optional: If you want to accept external wallets (by passing 'wallet' to the authenticationMethods array)
  walletConnectProjectId: ''
})

WalletConnect Support

To use WalletConnect functionality, you must provide a WalletConnect project ID. This ID can be obtained from WalletConnect Cloud.

You can provide the project ID in several ways (in order of precedence):

  1. Pass it directly when initializing (recommended):

    initSilk({
      walletConnectProjectId: 'YOUR_WALLETCONNECT_PROJECT_ID'
    })
  2. Set it programmatically:

    import { initSilk, SilkWalletConnect } from '@silk-wallet/silk-wallet-sdk'
    
    SilkWalletConnect.setProjectId('YOUR_WALLETCONNECT_PROJECT_ID')
    initSilk()
  3. Set it as an environment variable:

    • Set NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID in your .env.local file (Next.js)
    • Or set WALLET_CONNECT_PROJECT_ID for other environments

API Reference

The Silk SDK implements the standard Ethereum Provider API (EIP-1193) with some additional methods:

  • enable(): Alias for request({ method: 'eth_requestAccounts' })
  • isConnected(): Returns whether the provider is connected
  • login(): Prompt the user to connect an external wallet
  • logout(): Disconnect the current session
  • getLoginMethod(): Returns the current login method ('human', 'injected', 'walletconnect', or null)
  • requestEmail(): Request the user's email address
  • requestSBT(type): Request a Soulbound Token of the specified type
  • toggleDarkMode(): Toggle between light and dark mode

Auto-Connect Functionality

The Silk SDK automatically attempts to reconnect users when they refresh the page or return to your application. This works seamlessly in the background when you call eth_requestAccounts.

How Auto-Connect Works

  1. When a user successfully logs in via login(), their choice is remembered
  2. On subsequent page loads, calling eth_requestAccounts (before login()) will automatically attempt to reconnect using their previous method
  3. If the previous method is no longer available or connected, the auto-connect will fail gracefully

Checking the Current Login Method

You can check which login method is currently active without triggering a connection:

// Check the current login method
const loginMethod = window.silk.getLoginMethod()

if (loginMethod === 'human') {
  console.log('User is connected via Silk Human Wallet')
} else if (loginMethod === 'injected') {
  console.log('User is connected via injected wallet (e.g., MetaMask)')
} else if (loginMethod === 'walletconnect') {
  console.log('User is connected via WalletConnect')
} else {
  console.log('User is not connected')
}

Note: getLoginMethod() verifies that the connection is actually still valid. If the wallet extension is disabled, WalletConnect session expired, or any other connection issue exists, it will return null and automatically clean up the stored state.

Implementing Auto-Connect

import { initSilk } from '@silk-wallet/silk-wallet-sdk'

// Initialize Silk
initSilk()

// Attempt to auto-connect
try {
  const accounts = await window.silk.request({
    method: 'eth_requestAccounts'
  })
  console.log('Auto-connected with accounts:', accounts)

  // Auto connect failed, proceed with regular login
  if (accounts.length === 0) {
    await window.silk.login()
  }
} catch (error) {
  console.log('Auto-connect failed, user needs to login again')
}

Logout and Cleanup

When you call logout(), the stored login method is automatically cleared:

await window.silk.logout()
console.log(window.silk.getLoginMethod()) // Returns null

Error Handling

try {
  const accounts = await window.silk.request({ method: 'eth_requestAccounts' })
} catch (error) {
  console.error('Error connecting to Silk:', error)
}

Events

The Silk provider emits various events you can listen to:

// When the connection status changes
window.silk.on('connect', () => {
  console.log('Connected to Silk')
})

// When accounts change
window.silk.on('accountsChanged', (accounts) => {
  console.log('Active account changed:', accounts[0])
})

// When the chain changes
window.silk.on('chainChanged', (chainId) => {
  console.log('Chain changed to:', chainId)
})

TypeScript Support

The Silk SDK includes TypeScript definitions. You can import them like this:

import { initSilk, SilkProvider } from '@silk-wallet/silk-wallet-sdk'

// Now you can use type hints
const silk: SilkProvider = initSilk()

Support

If you encounter any issues or have questions, please reach out to our support team or file an issue in our GitHub repository.

Migrating from pre-v0.5.0

If you're migrating from a pre-v0.5.0 version, please note that event emitter fields like uiMessageManager have been removed from the SilkEthereumProviderInterface. For event handling, you should now use methods directly on the provider instance.

For example, if you were previously disconnecting with:

async disconnect(): Promise<void> {
  const provider = await this.getProvider();
  provider.uiMessageManager.removeListener('accountsChanged', this.onAccountsChanged);
  provider.uiMessageManager.removeListener('chainChanged', this.onChainChanged);
  provider.uiMessageManager.removeListener('disconnect', this.onDisconnect);
}

You should now use:

async disconnect(): Promise<void> {
  const provider = await this.getProvider();
  provider.removeListener('accountsChanged', this.onAccountsChanged);
  provider.removeListener('chainChanged', this.onChainChanged);
  provider.removeListener('disconnect', this.onDisconnect);
}

This follows the EIP-1193 standard for Ethereum providers.

0.3.0

3 months ago

0.2.1

3 months ago

0.2.0

5 months ago

0.7.1

1 month ago

0.5.0

2 months ago

0.4.0

3 months ago

0.3.1

3 months ago

0.7.0

1 month ago

0.6.0

2 months ago

0.5.1

2 months ago

0.1.3

9 months ago

0.1.0

10 months ago

0.1.2

9 months ago

0.1.1

10 months ago

0.0.25

1 year ago

0.0.26

1 year ago

0.0.23

1 year ago

0.0.24

1 year ago

0.0.22

1 year ago

0.0.20

2 years ago

0.0.21

2 years ago

0.0.12

2 years ago

0.0.13

2 years ago

0.0.17

2 years ago

0.0.18

2 years ago

0.0.19

2 years ago

0.0.11

2 years ago

0.0.10

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago