Connect to Extension Wallet
Provider API

Provider API#

What is injected provider API?#

The OKX injected provider API is a JavaScript API that OKX injects into websites visited by our users. Your DApp can use this API to request users' accounts, read data from blockchains users are connected to, and help users sign messages and transactions.

Obtaining the wallet object#

We use the wallet standard in Sui, which is slightly different from other heterogeneous chains. You can obtain the wallet object through event notifications:

const GlobalWallet = {
      register: (wallet) => {
          GlobalWallet[wallet.chainName] = wallet
      }
  }
  const event = new CustomEvent('wallet-standard:app-ready', { detail: GlobalWallet });
  window.dispatchEvent(event);

  const suiWallet = GlobalWallet.suiMainnet

Obtaining the account#

Using the suiWallet object obtained above, you can retrieve the account:

const suiAccounts = suiWallet.connectedAccounts

// Structure of suiAccounts:
[
    {
        "address": "0x7995ca23961fe06d8cea7da58ca751567ce820d7cba77b4a373249034eecca4a",
        "publicKey": "tUvCYrG22rHKR0c306MxgnhXOSf16Ot6H3GMO7btwDI=",
        "chains": [
            "sui:mainnet"
        ],
        "features": [
            "sui:signAndExecuteTransactionBlock",
            "sui:signTransactionBlock",
            "sui:signMessage"
        ]
    }
]

The first transaction#

suiWallet.features['sui:signAndExecuteTransactionBlock'].signAndExecuteTransactionBlock

Signing and sending transactions

The Sui wallet follows the wallet standard, which is slightly different from other heterogeneous chains. All methods are attached to the features[] array.

After creating a transaction, the web application may request you to sign and send the transaction using OKX Wallet. If accepted, OKX Wallet will sign the transaction with your private key and submit it through the SUI JSON RPC connection. Calling the signAndExecuteTransactionBlock method on suiWallet will return a Promise for the signed transaction.

const handleTransaction = async () => {
    const tx = new TransactionBlock()
    tx.moveCall({
      target: `${packageId}::${moduleName}::${functionName}`,
      arguments: [
        tx.pure(params1),
        tx.pure(params2),
      ],
      typeArguments: [],
    })
    const result = await suiWallet.features['sui:signAndExecuteTransactionBlock'].signAndExecuteTransactionBlock({
      transactionBlock: tx,
      options: { showEffects: true },
    })
    console.log('result', result)
    // You can retrieve the transaction status by accessing result?.effects?.status?.status. If the transaction is successful, the status will be 'success', and if it fails, the status will be 'failure'.
}

splitCoins

When sending a transaction, and the object used for paying gas fees is also included in the transaction, a technique called splitting coins is employed to handle this scenario.

const handleTransaction = async () => {
    const tx = new TransactionBlock()

    const value = '300000000'  // This is the desired value to split
    const [coins] = tx.splitCoins(tx.gas, [
      tx.pure(BigInt(value)),
    ])
    tx.moveCall({
      target: `${packageId}::${moduleName}::${functionName}`,
      arguments: [
        tx.pure(params1),
        tx.pure(params2),
        tx.makeMoveVec({ objects: [coins] }),
      ],
      typeArguments: [],
    })
    const result = await suiWallet.features['sui:signAndExecuteTransactionBlock'].signAndExecuteTransactionBlock({
      transactionBlock: tx,
      options: { showEffects: true },
    })
    console.log('result', result)
}

Signing a transaction block

You can sign a transaction block (a collection of multiple transactions) using the signTransactionBlock method on the provider.

const tx = new TransactionBlock();
tx.moveCall({
  target: 'xxx',
  arguments: [
    tx.pure('okx'),
    tx.pure('wallet'),
  ],
});
const input = {
  transactionBlockSerialized: tx.serialize(),
  options: {
    showEffects: true,
  }
}l
const transaction = await suiWallet.features['sui:signTransactionBlock'].signTransactionBlock(input);

Signing messages#

Signing a single transaction (without sending)

After creating a transaction, a web application may request your OKX Wallet to sign the transaction without submitting it to the network. Calling the signMessage method will return a Promise for the signed transaction.

import { ethers } from 'ethers';
// Here we utilize the ethers library to help us handle the message and convert it to Uint8Array type

const message = ethers.utils.toUtf8Bytes('okx')
const { signature, messageBytes } = await suiWallet.features['sui:signMessage'].signMessage({ message })

Error codes#

Code
Title
Description
4900DisconnectedOKX Wallet could not connect to the network
4100UnauthorizedThe requested method and/or account has not been authorized by the user
4001User rejected requestThe user rejected the request through OKX Wallet
-32000Invalid InputMissing or invalid parameters
-32002Resource unavailableThis error occurs when a DApp attempts to submit a new transaction while OKX Wallet's approval dialog is already open for a previous transaction. Only one approve window can be open at a time. Users should approve or reject their transaction before initiating a new one.
-32003Transaction rejectedOKX Wallet does not recognize a valid transaction
-32601Method not foundOKX Wallet does not recognize the method
-32603Internal errorSomething went wrong within OKX Wallet

Connect account#

suiWallet.features['standard:connect'].connect()

Description

Connecting to OKX Wallet can be done by calling suiWallet.features['standard:connect'].connect().

The connect call will return a Promise object that resolves if you accept the connection request, or rejects if you reject the request or closes the pop-up window. For more information on possible errors that may occur with OKX Wallet, refer to the error codes section. Once you accept the connection request, the suiWallet.features['standard:events'] will also trigger a connection event.

suiWallet.features['standard:events'].on("connect", () => console.log("connected!"));

Once the web application is connected to OKX Wallet, it'll be able to read the public key of the connected account and prompt you for further transactions.

Example

Open in codeopen

Events#

Connection successful

Connecting to OKX Wallet can be done by calling suiWallet.features['standard:events'].on. The connection event is triggered when you accept the connection request.

Usage

suiWallet.features['standard:events'].on("connect", () => console.log("connected!"));

Disconnect

Disconnecting is similar to the connecting process. However, disconnection can also be initiated by the wallet in addition to the application.

Usage

suiWallet.features['standard:events'].on("disconnect", () =>  {
  console.log("disconnected!")
});

Switching accounts

OKX Wallet allows you to seamlessly manage multiple accounts from a single extension or mobile application. Whenever you switch accounts, OKX Wallet will emit an accountChanged event.

If you switch accounts while already connected to an application, and the new account has allowlisted the application, you will remain connected and OKX Wallet will pass the public key of the new account.

Usage

suiWallet.features['standard:events'].on('accountChanged', (publicKey) => {
  if (publicKey) {
      console.log(`Switched to account ${publicKey.toBase58()}`);
  }
});