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
  • Connecting
  • Eagerly Connecting
  • Disconnecting
  • Changing Accounts

Was this helpful?

Edit on GitHub
  1. Connect To Software
  2. WebApp Connect OneKey
  3. SOLANA

Establishing a Connection

PreviousDetecting the ProviderNextSending a Transaction

Last updated 1 year ago

Was this helpful?

Once an application has , it can then request to connect to OneKey. This connection request will prompt the user for permission to share their public key, indicating that they are willing to interact further. Users must approve a connection request before the app can make additional requests such as or .

Once permission is established for the first time, the web application's domain will be whitelisted for future connection requests. After a connection is established, it is possible to terminate the connection from both the application and the user side.

Connecting

The recommended and easiest way to connect to OneKey is by calling window.$onekey.solana.connect(). However, the provider also exposes a request JSON RPC interface.

const provider = getProvider(); // see "Detecting the Provider"
try {
    const resp = await provider.connect();
    console.log(resp.publicKey.toString());
    // 26qv4GCcx98RihuK3c4T6ozB3J7L6VwCuFVc7Ta2A3Uo 
} catch (err) {
    // { code: 4001, message: 'User rejected the request.' }
}
const provider = getProvider(); // see "Detecting the Provider"
try {
    const resp = await provider.request({ method: "connect" });
    console.log(resp.publicKey.toString());
    // 26qv4GCcx98RihuK3c4T6ozB3J7L6VwCuFVc7Ta2A3Uo 
} catch (err) {
    // { code: 4001, message: 'User rejected the request.' }
}

The connect() call will return a that resolves when the user accepts the connection request, and reject (throw when awaited) when the user declines the request or closes the pop-up. See Errors for a breakdown of error messages OneKey may emit.

When the user accepts the request to connect, the provider will also emit a connect event.

provider.on("connect", () => console.log("connected!"));

Once the web application is connected to OneKey, it will be able to read the connected account's public key and prompt the user for additional transactions. It also exposes a convenience isConnected boolean.

console.log(provider.publicKey.toString()); 
console.log(provider.isConnected);
// true

Eagerly Connecting

After a web application connects to OneKey for the first time, it becomes trusted. Once trusted, it's possible for the application to automatically connect to OneKey on subsequent visits or page refreshes, without prompting the user for permission. This is referred to as "eagerly connecting".

To implement this, applications should pass an onlyIfTrusted option into the connect() call.

provider.connect({ onlyIfTrusted: true });
window.$onekey.solana.request({ method: "connect", params: { onlyIfTrusted: true }});

If this flag is present, OneKey will only eagerly connect and emit a connect event if the application is trusted. If the application is not trusted, OneKey will throw a 4001 error and remain disconnected until the user is prompted to connect without an onlyIfTrusted flag. In either case, OneKey will not open a pop-up window, making this convenient to use on all page loads.

The following is an example of how a React application can eagerly connect to OneKey.

import { useEffect } from "react";

useEffect(() => {
    // Will either automatically connect to OneKey, or do nothing.
    provider.connect({ onlyIfTrusted: true })
        .then(({ publicKey }) => {
            // Handle successful eager connection
        });
        .catch(() => {
            // Handle connection failure as usual
        })
}, []);

For a live demo, please refer to the handleConnect portion of our sandbox.

If a wallet disconnects from a trusted app and then attempts to reconnect at a later time, OneKey will still eagerly connect. Once an app is trusted, OneKey will only require the user to approve a connection request if the user revokes the app from within their Trusted Apps settings.

Disconnecting

Disconnecting mirrors the same process as connecting. However, it is also possible for the wallet to initiate the disconnection, rather than the application itself.

provider.disconnect();
provider.request({ method: "disconnect" });

The following is an example of how a React application can gracefully handle a disconnect event.

import { useState, useEffect } from "react";

const [pubKey, setPubKey] = useState(null);

useEffect(() => {
  // Store user's public key once they connect
  provider.on("connect", (publicKey) => {
    setPubKey(publicKey);
  });

  // Forget user's public key once they disconnect
  provider.on("disconnect", () => {
    setPubKey(null);
  });
}, [provider]);

Changing Accounts

provider.on('accountChanged', (publicKey) => {
    if (publicKey) {
        // Set new public key and continue as usual
        console.log(`Switched to account ${publicKey.toBase58()}`);
    } 
});

If OneKey does not pass the public key of the new account, an application can either do nothing or attempt to reconnect:

provider.on('accountChanged', (publicKey) => {
    if (publicKey) {
      // Set new public key and continue as usual
      console.log(`Switched to account ${publicKey.toBase58()}`);
    } else {
      // Attempt to reconnect to OneKey
      provider.connect().catch((error) => {
        // Handle connection failure
      });
    }
});

OneKey allows users to seamlessly manage multiple accounts (i.e. ) from within a single extension or mobile app. Whenever a user switches accounts, OneKey will emit an accountChanged event.

If a user changes accounts while already connected to an application, and the new account had already whitelisted that application, then the user will stay connected and OneKey will pass the of the new account:

🔮
detected the provider
signing a message
sending a transaction
Promise
Keypairs
PublicKey