OneKey Docs
  • 👋GUIDE
    • Introduction
    • Web App Integration Developer
    • Hardware Integration Developer
    • External Contribution Guide
    • Common Terms
  • 🔮Connect To Software
    • Compatible with Metamask
      • detectEthereumProvider
    • Support Wallet Kit
      • Web3 Onboard
      • Rainbowkit
      • Aptos Wallet Adapter
      • Web3Modal
    • WebApp Connect OneKey
      • ETH
        • Provider API
        • RPC API
        • Accessing Accounts
        • Sending Transactions
        • Signing Data
      • BTC
        • Guide
        • API Reference
          • requestAccounts
          • getAccounts
          • getNetwork
          • switchNetwork
          • getPublicKey
          • getBalance
          • getInscriptions
          • sendBitcoin
          • sendInscription
          • signMessage
          • pushTx
          • signPsbt
          • signPsbts
          • pushPsbt
          • inscribeTransfer (Deprecated)
        • Event
      • Nostr
        • Guide
        • API Reference
          • getPublicKey
          • signEvent
          • signSchnorr
          • getRelays
          • nip04.encrypt
          • nip04.decrypt
        • Event
      • WebLN
        • Guide
        • API Reference
          • enable
          • getInfo
          • makeInvoice
          • sendPayment
          • signMessage
          • verifyMessage
          • lnurl
          • getBalance
        • Event
      • NEAR
        • Introduction
        • Integrating
          • Install the Provider SDK
          • Detecting the Provider
          • Establishing a Connection
          • Accessing Accounts
          • Detecting Provider Network
          • Watch Accounts & Network Status
          • Sending Transactions
            • Create Transaction
            • Sign and Send Transaction
            • Signing Transaction
          • Signing Messages
          • RPC API Calling
          • Debug Logging
          • Migrate from Near Web Wallet
        • Reference
          • API Reference
          • Trouble Shooting
        • Resources
          • Example & Demo
          • FAQ
      • SOLANA
        • Detecting the Provider
        • Establishing a Connection
        • Sending a Transaction
        • Signing a Message
    • Using WalletConnect
      • ETH
      • APTOS
        • Wallet Connect API
  • 📟Connect to Hardware
    • Hardware SDK
      • Started
      • Install SDK
      • Config Event
      • Common Params
      • Path Params
      • Error Code
      • API Reference
        • Basic API
          • Init SDK
          • Search Devices
          • Get Features
          • Get Passphrase State
          • Cancel Request
          • Response UI Event
        • Device API
          • deviceSupportFeatures
          • checkBridgeStatus
          • checkTransportRelease
          • checkFirmwareRelease
          • checkBLEFirmwareRelease
          • deviceChangePin
          • deviceReset
          • deviceSettings
          • deviceUpdateReboot
          • deviceVerify
          • deviceWipe
          • firmwareUpdate
        • Bitcoin & Bitcoin forks
          • btcGetAddress
          • btcGetPublicKey
          • btcSignMessage
          • btcSignTransaction
          • btcVerifyMessage
        • Ethereum & EVM
          • evmGetPublicKey
          • evmGetAddress
          • evmSignTransaction
          • evmSignTypedData
          • evmSignMessage
          • evmVerifyMessage
        • Algorand
          • algoGetAddress
          • algoSignTransaction
        • Aptos
          • aptosGetAddress
          • aptosGetPublicKey
          • aptosSignMessage
          • aptosSignTransaction
        • Alephium
          • alephiumGetAddress
          • alephiumSignMessage
          • alephiumSignTransaction
        • Cardano
          • cardanoGetAddress
          • cardanoGetPublicKey
          • cardanoSignMessage
          • cardanoSignTransaction
        • Conflux
          • confluxGetAddress
          • confluxSignMessage
          • confluxSignMessageCIP23
          • confluxSignTransaction
        • Cosmos
          • cosmosGetAddress
          • cosmosGetPublicKey
          • cosmosSignTransaction
        • Dynex
          • dnxGetAddress
          • dnxSignTransaction
        • FileCoin
          • filecoinGetAddress
          • filecoinSignTransaction
        • Kaspa
          • kaspaGetAddress
          • kaspaSignTransaction
        • Near
          • nearGetAddress
          • nearSignTransaction
        • Nervos
          • nervosGetAddress
          • nervosSignTransaction
        • Nostr
          • nostrGetPublicKey
          • nostrSignEvent
          • nostrSignSchnorr
          • nostrEncryptMessage
          • nostrDecryptMessage
        • NEM
          • nemGetAddress
          • nemSignTransaction
        • Nexa
          • nexaGetAddress
          • nexaSignTransaction
        • Polkadot
          • polkadotGetAddress
          • polkadotSignTransaction
        • Ripple
          • xrpGetAddress
          • xrpSignTransaction
        • Scdo
          • scdoGetAddress
          • scdoSignMessage
          • scdoSignTransaction
        • Solana
          • solGetAddress
          • solSignTransaction
        • Starcoin
          • startcoinGetAddress
          • starcoinGetPublicKey
          • starcoinSignMessage
          • starcoinSignTransaction
          • starcoinVerifyMessage
        • Stellar
          • stellarGetAddress
          • stellarSignTransaction
        • Sui
          • suiGetAddress
          • suiGetPublicKey
          • suiSignMessage
          • suiSignTransaction
        • Tron
          • tronGetAddress
          • tronSignMessage
          • tronSignTransaction
        • Ton
          • tonGetAddress
          • tonSignMessage
          • tonSignProof
      • Advanced
        • Passphrase
        • Common SDK Guide
        • Low-level transport plugin
        • OneKey Message Protocol
      • Tutorial: Get started with OneKey
    • Air Gap SDK
      • Started
      • Tutorial: Wallet Integration
      • API Reference
        • Basic API
          • CryptoHDkey
          • CryptoCoinInfo
          • CryptoKeypath
        • Ethereum & EVM
          • EthSignRequest
          • EthSignature
  • ⛳Best Practice
    • Registering Your Contract's Method Names
    • Registering Tokens with Users
    • Defining Your App's Icon
    • Migration from MetaMask
  • 🎨Logo Assets
  • 🧙Support
  • 🕹️Trouble Shooting
  • ❤️Contribute
Powered by GitBook
On this page
  • Installing and Initializing the SDK
  • Subscribe UI event
  • Get your Bitcoin address
  • Advanced: Passphrase

Was this helpful?

Edit on GitHub
  1. Connect to Hardware
  2. Hardware SDK

Tutorial: Get started with OneKey

PreviousOneKey Message ProtocolNextAir Gap SDK

Last updated 1 year ago

Was this helpful?

Installing and Initializing the SDK

Select the type of your project, and follow the installation instructions.

Web

  • Install @onekeyfe/hd-web-sdk package.

npm install --save @onekeyfe/hd-web-sdk
  • Initialize the SDK.

connectSrc: The official web page deployed by OneKey is used to create an iframe on the page to communicate with OneKey Bridge.

The complete link to the web page is .

Normally, the number after the URL should match the version number of the SDK you installed. For example, “0.3.30” in this case.

If encountering issues with the web page failing to load for the corresponding version number, please try using a different version of the SDK or submit an issue on for feedback. We will work quickly to resolve the problem.

import { HardwareWebSdk as HardwareSDK } from '@onekeyfe/hd-web-sdk';

HardwareSDK.init({
  debug: true,
  connectSrc: 'https://jssdk.onekey.so/0.3.30/',
  // Set to true if you need to use API related to firmware version checking, 
  // otherwise keep as false.
  fetchConfig: false,
})

React Native

  • Install @onekeyfe/hd-ble-sdk package.

npm install --save @onekeyfe/hd-ble-sdk
  • Initialize the SDK.

import HardwareSDK from '@onekeyfe/hd-ble-sdk';

HardwareSDK.init({
  debug: true
})

Node.js

  • Install @onekeyfe/hd-common-connect-sdk package.

npm install --save @onekeyfe/hd-common-connect-sdk
  • Initialize the SDK.

import HardwareSDK from '@onekeyfe/hd-common-connect-sdk';

HardwareSDK.init({
  debug: true,
  env: 'node'
})

iOS Native / Android Native / Flutter / Other platform

  • To enable communication with JavaScript, for example, iOS or Android can use methods such as WebView’s JSBridge or JSCore.

  • Install @onekey/hd-common-connect-sdk package at the JSBridge layer.

npm install --save @onekeyfe/hd-common-connect-sdk
  • Implement the low-level transport plugin to communicate with the native platform via JSBridge. Utilize native platform capabilities to manage device connections and send/receive data.

import HardwareSDK from '@onekeyfe/hd-common-connect-sdk'
import { createDeferred, isHeaderChunk, COMMON_HEADER_SIZE } from './utils'

function createLowlevelPlugin() {
  const plugin = {
    enumerate: () => {
      return new Promise((resolve) => {
        // Invoke the ‘enumerate’ method registered on the native side to retrieve the result of the device search.
        bridge.callHandler('enumerate', {}, (response) => {
	  resolve(response)
	})
      })
    },
    send: (uuid, data) => {
      return new Promise((resolve) => {
        // Invoke the ‘send’ method registered on the native side to send data to the device
        bridge.callHandler('send', {uuid, data}, (response) => {
	  resolve(response)
	})
      })
    },
    receive: () => {
      return new Promise((resolve) => {
        // Receive data from the device, 
        // verify and concatenate the data packets,
        // and only return the complete packets to the SDK.
        // You can refer to OneKey Message Protocol for this.
        // For more implementation details, please refer to the code 
        // https://github.com/originalix/Hardware-Lowlevel-Communicate/blob/main/web/index.js#L171
        runPromise = createDeferred()
        const response = runPromise.promise
        resolve(response)
      })
    },
    connect: (uuid) => {
      return new Promise((resolve) => {
        // Call the native connect method and pass in the UUID of the Bluetooth device.
        bridge.callHandler('connect', {uuid})
          // Since the connect method in the native end may be asynchronous, 
          // we also register a ‘connectFinished’ event to wait for the result returned by the native end
          bridge.registerHandler('connectFinished', () => {
             resolve()
          })
       })
    },
    disconnect: (uuid)  => {
      return new Promise((resolve) => {
        // Disconnect the device.
        bridge.callHandler('disconnect', {uuid}, (response) => {
          resolve(response)
        })
      })
    },
    init: () => {
      // Do something you want to handle during SDK initialization.
      return Promise.resolve()
    },
    version: 'OneKey-1.0'
  }
  return plugin
}

// This plugin object will be passed as a parameter during SDK initialization.
const plugin = createLowlevelPlugin()
  • Initialize the SDK.

import HardwareSDK from '@onekeyfe/hd-common-connect-sdk';

const settings = {
  env: 'lowlevel',
  debug: true
}

/**
 * Pass the previously written low-level plugin as the third parameter.
 */
HardwareSDK.init(settings, undefined, plugin)

Subscribe UI event

To improve the user experience when calling some methods such as getAddress and signTransaction, it is recommended to provide the user with some prompts at the UI layer for device unlocking and confirmation. This can be achieved through event passing.

It is recommended to register some common UI events before using the SDK.

import { UI_EVENT, UI_RESPONSE, CoreMessage } from '@onekeyfe/hd-core';

HardwareSDK.on(UI_EVENT, (message: CoreMessage) => {
  // Handle the PIN code input event
  if (message.type === UI_REQUEST.REQUEST_PIN) {
    // Enter the PIN code on the device
    HardwareSDK.uiResponse({
      type: UI_RESPONSE.RECEIVE_PIN,
      payload: '@@ONEKEY_INPUT_PIN_IN_DEVICE',
    });
  }
  
  // Handle the passphrase event
  if (message.type === UI_REQUEST.REQUEST_PASSPHRASE) {
    // Enter the passphrase on the device
    HardwareSDK.uiResponse({
      type: UI_RESPONSE.RECEIVE_PASSPHRASE,
      payload: {
        value: '',
        passphraseOnDevice: true,
        save: false,
      },
    });
  }
  
  if (message.type === UI_REQUEST.REQUEST_BUTTON) {
    // Confirmation is required on the device, a UI prompt can be displayed
  }
});

Get your Bitcoin address

After completing the steps of initializing the SDK and subscribe UI event listeners, we will now try to get the first Native Segwit Bitcoin address from the hardware wallet.

First, we need to search for the device and get its information.

const searchDeviceResponse = await HardwareSDK.searchDevices()
let device
if (searchDeviceResponse.success && searchDeviceResponse.payload.length > 0) {
  // Use the first device in the search results
  device = searchDeviceResponse.payload[0]
}

Next, we will get the first Native Segwit Bitcoin address.

During the execution of this method, the UI_REQUEST.REQUEST_PIN and UI_REQUEST.REQUEST_BUTTON events will be notified.

const params = {
  path: "m/84'/0'/0'/0/0"
  coin: 'btc',
  showOnOneKey: true,
}

const response = await HardwareSDK.btcGetAddress(device.connectId, device.deviceId, params)

if (response.success) {
  console.log('Your first native segwit bitcoin address: ', response.payload.address)
}

Now your Bitcoin address will be printed on the console.

Congratulations! You have mastered the usage of the SDK, as the calling method for all APIs is the same.

Advanced: Passphrase

Proceed to the .

Proceed to the .

Proceed to the .

For example, the code snippet below registers some events to communicate with native via library.

For more complete code, please refer to

Proceed to the .

Our wallet also supports hidden wallets. Once you have learned the basic API calling methods, it is easy for you to use the hidden wallet. You just need to add a parameter in Common Params. Please refer to the documentation related to for more information.

📟
https://jssdk.onekey.so/0.3.30/iframe.html
GitHub
WebViewJavascriptBridge
Hardware-Lowlevel-Communicate repo.
Passphrase
next step
next step
next step
next step