Connect to App or Mini Wallet

UI#

Installation and Initialization#

Make sure to update the OKX App to version 6.94.0 or later to start integrating OKX Connect into your DApp can be done using npm:

npm install @okxconnect/ui
npm install @okxconnect/universal-provider

Before connecting to a wallet, you need to create an object that can provide a UI interface for subsequent operations such as connecting to the wallet and sending transactions.

OKXUniversalConnectUI.init(dappMetaData, actionsConfiguration, uiPreferences, language)

Request parameters

  • dappMetaData - object
    • name - string: The name of the application, will not be used as a unique representation.
    • icon - string: URL of the application icon, must be in PNG, ICO, etc. SVG icons are not supported. SVG icons are not supported. It is best to pass a url pointing to a 180x180px PNG icon.
  • actionsConfiguration - object
    • modals - (‘before’ | ‘success’ | ‘error’)[] | ‘all’ The modes of displaying alerts during transaction, defaults to ‘before’.
    • returnStrategy -string ‘none’ | ${string}://${string}; for app wallet, specify the return strategy for the deep link when the user signs/rejects the request, if it is in telegram, you can configure tg://resolve
    • tmaReturnUrl -string ‘back’ | ‘none’ | ${string}://${string}; For Telegram Mini Wallet, specify the return policy of deep link when user signs/rejects the request, if it's in telegram, you can configure tg://resolve none means no processing after signing; default is back;
  • uiPreferences -object
    • theme - Theme can be: THEME.DARK, THEME.LIGHT, ‘SYSTEM’.
  • language - ‘en_US’ | ‘ru_RU’ | ‘zh_CN’ | ‘ar_AE’ | ‘cs_CZ’ | ‘de_DE’ | ‘es_ES’ | ‘es_LAT’ | ‘fr_FR’ | ‘id_ID’ | ‘it_IT’ | ‘nl_NL’ | ‘pl_PL’ | ‘pt_BR’ | ‘pt_PT’ | ‘ro_RO’ | ‘tr_TR’ | ‘uk_UA’ | ‘vi_VN’. , defaults to en_US

Return value

  • OKXUniversalConnectUI

Example

import { OKXUniversalConnectUI } from "@okxconnect/ui";

const okxUniversalConnectUI = await OKXUniversalConnectUI.init({
    dappMetaData: {
        icon: "https://static.okx.com/cdn/assets/imgs/247/58E63FEA47A2B7D7.png",
        name: "OKX Connect Demo"
    },
    actionsConfiguration: {
        returnStrategy: 'tg://resolve',
        modals:"all",
        tmaReturnUrl:'back'
    },
    language: "en_US",
    uiPreferences: {
        theme: THEME.LIGHT
    },
});

Connect to a wallet#

Connect to the wallet to get the wallet address as an identifier and the necessary parameters for signing transactions.

okxUniversalConnectUI.connect(connectParams: ConnectParams);

Request Parameters

  • connectParams - ConnectParams

    • namespaces - [namespace: string]: ConnectNamespace ; Optional information about the requested connection, the key is ‘eip155’ for EVM, ‘cosmos’ for COSMOS, if any of the requested chain is not supported by the wallet, the wallet will reject the connection;
      • chains: string[]; chain id information, defaultChain?
      • defaultChain?: string; defaultChain
    • optionalNamespaces - [namespace: string]: ConnectNamespace; optional information of the requested connection, the key of EVM is ‘eip155’, the key of COSMOS is ‘cosmos’, if the corresponding chain information is not supported by the wallet, it can still be connected;
      • chains: string[]; chain id information, defaultChain?
        • defaultChain?: string; default chain
    • sessionConfig: object
      • redirect: string Jump parameter after successful connection, if it is a Mini App in Telegram, you can set it to deeplink of Telegram: ‘tg://resolve’. Return Value
  • Promise <SessionTypes.Struct | undefined>

    • topic: string; The session identifier;
    • namespaces: Record<string, Namespace>; namespace information for a successful connection;
      • chains: string[]; Chain information for the connection;
      • accounts: string[]; accounts information for the connection;
      • methods: string[]; Methods supported by the wallet in the current namespace;
      • defaultChain?: string; The default chain for the current session.
    • sessionConfig?: SessionConfig
      • dappInfo: object DApp information;
        • name: string
        • icon:string
      • redirect?: string, the redirect parameter after successful connection;

Example

var session = await okxUniversalConnectUI.connect({
    namespaces: {
        cosmos: {
            chains: [
                "cosmos:cosmoshub-4",
                 // "cosmos:osmosis-1"
            ],
        }
    },
    sessionConfig: {
        redirect: "tg://resolve"
    }
})

Connect to wallet and sign#

Connect to the wallet to get the wallet address and sign the data; the result will be called back in the event ‘connect_signResponse’;

await okxUniversalConnectUI.openModalAndSign(connectParams: ConnectParams, signRequest: RequestParams[]);

Request Parameters

  • connectParams - ConnectParams
    • namespaces - [namespace: string]: ConnectNamespace ; Optional information about the requested connection, the key of COSMOS system is ‘cosmos’, if any of the requested chain is not supported by the wallet, the wallet will reject the connection;
      • chains: string[]; chain id information, defaultChain?
      • defaultChain?: string; defaultChain
    • optionalNamespaces - [namespace: string]: ConnectNamespace; optional information of the requested connection, the key of COSMOS is ‘cosmos’, if the corresponding chain information is not supported by the wallet, it can still be connected;
      • chains: string[]; chain id information, defaultChain?
        • defaultChain?: string; default chain
    • sessionConfig: object
      • redirect: string The jump parameter after successful connection, if it is Mini App in Telegram, here can be set to Telegram's deeplink: ‘tg://resolve’
  • signRequest - RequestParams[]; the method to request the connection and sign the request, at most one method can be supported at the same time;
    • method: string; the name of the requested method, COSMOS supports the following methods: ‘cosmos_signArbitrary’;
    • chainId: string; the ID of the chain where the method is executed, the chainId must be included in the namespaces above;
    • params: unknown[] | Record<string, unknown> | object | undefined; Parameters corresponding to the requested method;

Return Value

  • Promise <SessionTypes.Struct | undefined>
    • topic: string; the session identifier;
    • namespaces: Record<string, Namespace>; namespace information for a successful connection;
      • chains: string[]; Chain information for the connection;
      • accounts: string[]; accounts information for the connection;
      • methods: string[]; Methods supported by the wallet in the current namespace;
      • defaultChain?: string; The default chain for the current session.
    • sessionConfig?: SessionConfig
      • dappInfo: object DApp information;
        • name: string
        • icon:string

Example

// Add the signature result minitor first
okxUniversalConnectUI.on("connect_signResponse", (signResponse) => {
  console.log(signResponse);
});
var session = await okxUniversalConnectUI.openModalAndSign({
        namespaces: {
            cosmos: {
                chains: [
                    "cosmos:cosmoshub-4",
                    // "cosmos:osmosis-1"
                ],
            }
        },
        sessionConfig: {
            redirect: "tg://resolve"
        }
    },
    [
        {
            chainId: "cosmos:cosmoshub-4",
            method: "cosmos_signArbitrary",
            params: {
                message: "Hello Cosmos"
            }
        }
])

Determine if the wallet is connected#

Gets whether the wallet is currently connected.

Return Value

  • boolean

Example

okxUniversalConnectUI.connected();

Prepare the transaction#

First create an OKXCosmosProvider object, with the constructor passing in OKXUniversalConnectUI

import { OKXCosmosProvider } from ‘@okxconnect/universal-provider’;
let okxCosmosProvider = new OKXCosmosProvider(okxUniversalConnectUI)

Get account information#

okxCosmosProvider.getAccount(chainId)

Request parameters

  • chainId: the requested chain, e.g. cosmos:cosmoshub-4, cosmos:osmosis-1

Return Value

  • Object
    • algo: ‘secp256k1’,
    • address: string wallet-address, bech32Address: string wallet-address, bech32Address
    • bech32Address: string walletAddress, pubKey: Uint8Address, pubKey: Uint8Address
    • pubKey: Uint8Array publicKey, pubKey: Uint8Array publicKey, pubKey: Uint8Array publicKey

Example

let result = okxCosmosProvider.getAccount("cosmos:cosmoshub-4")
//Return structure
{
    "algo": "secp256k1",
    "address": "cosmos1u6lts9ng4etxj0zdaxsada6zgl8dudpg3ygvjw",
    "bech32Address": "cosmos1u6lts9ng4etxj0zdaxsada6zgl8dudpg3ygvjw",
    "pubKey": Unit8Aray,
}

Sign the message#

okxCosmosProvider.signArbitrary(chain, signerAddress, message)

Request Parameters

  • chain - string, chain of requested execution methods
  • signerAddress - string The address of the signature wallet.
  • message - string The message to be signed.

Return Value

  • Promise - object
    • pub_key : object
      • type:string Public key type
      • value: string Public key
    • signature: string Signature result

Example

let chain = "cosmos:cosmoshub-4"
let signStr = "data need to sign ..."

let result = okxCosmosProvider.signArbitrary(chain, signStr)
//Return structure: {"pub_key":{"type":"tendermint/PubKeySecp256k1","value":"AkRuGelKwOg+qJbScSUHV36zn73S1q6fD8C5dZ8furqQ"},"signature":"YSyndEFlHYTWpSXsn28oolZpKim/BnmCVD0hZfvPQHQV3Bc0B0EU77CKE6LpV+PUJn19d1skAQy/bXyzppnuxw=="}

SignAmino#

okxCosmosProvider.signAmino(chainId: string, signerAddress: string, signDoc: StdSignDoc, signOptions?: object)

Request Parameters

  • chainId - string, the chain for which the signature execution is requested, mandatory parameter

  • signerAddress - string, the address of the wallet.

  • signDoc - object, the transaction information to be signed in a fixed format, similar to cosmjs OfflineSigner signAmino method, the parameter is the object, signDoc is a fixed format. ***signDoc is a fixed format.

  • Promise - Object

    • signed - object,transaction information
    • signature -object, the result of the signature.

Example

let signDoc = {
    "chain_id": "osmosis-1",
    "account_number": "630104",
    "sequence": "480",
    "fee": {"gas": "683300", "amount": [{"denom": "uosmo", "amount": "2818"}]},
    "msgs": [{
        "type": "osmosis/poolmanager/swap-exact-amount-in",
        "value": {
            "sender": "osmo1u6lts9ng4etxj0zdaxsada6zgl8dudpgelmuyu",
            "routes": [{
                "pool_id": "1096",
                "token_out_denom": "ibc/987C17B11ABC2B20019178ACE62929FE9840202CE79498E29FE8E5CB02B7C0A4"
            }, {
                "pool_id": "611",
                "token_out_denom": "ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2"
            }],
            "token_in": {"denom": "uosmo", "amount": "100"},
            "token_out_min_amount": "8"
        }
    }],
    "memo": "FE",
    "timeout_height": "23603788",
    "signOptions": {
        "useOneClickTrading": false,
        "preferNoSetFee": true,
        "fee": {"gas": "683300", "amount": [{"denom": "uosmo", "amount": "2818"}]}
    }
}
let res = await provider.signAmino("cosmos:osmosis-1", provider.getAccount("cosmos:osmosis-1").address, signDoc)


/**
    Return structure:
    {
    "signed": {
    "chain_id": "osmosis-1",
    "account_number": "630104",
    "sequence": "480",
    "fee": {
    "amount": [
    {
    "amount": "12500",
    "denom": "uosmo"
    }
    ],
    "gas": "500000"
    },
    "msgs": [
    {
    "type": "osmosis/poolmanager/swap-exact-amount-in",
    "value": {
    "sender": "osmo1u6lts9ng4etxj0zdaxsada6zgl8dudpgelmuyu",
    "routes": [
    {
    "pool_id": "1096",
    "token_out_denom": "ibc/987C17B11ABC2B20019178ACE62929FE9840202CE79498E29FE8E5CB02B7C0A4"
    },
    {
    "pool_id": "611",
    "token_out_denom": "ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2"
    }
    ],
    "token_in": {
    "denom": "uosmo",
    "amount": "100"
    },
    "token_out_min_amount": "8"
    }
    }
    ],
    "memo": "FE",
    "timeout_height": "23603788",
    "signOptions": {
    "useOneClickTrading": false,
    "preferNoSetFee": true,
    "fee": {
    "gas": "683300",
    "amount": [
    {
    "denom": "uosmo",
    "amount": "2818"
    }
    ]
    }
    }
    },
    "signature": {
    "pub_key": {
    "type": "tendermint/PubKeySecp256k1",
    "value": "AkRuGelKwOg+qJbScSUHV36zn73S1q6fD8C5dZ8furqQ"
    },
    "signature": "2Brt/w+1U3C+tIbsI//pv9zTYca9WlBd1eKm/Gde5MFaRagmxtsn6h2beP7+4R4MDav7r1G+0Nxd5arB0qVfUw=="
    }
    }
 */

SignDirect#

okxCosmosProvider.signDirect(chainId, signerAddress, signDoc, signOptions?)

Request Parameters

  • chainId - string, the chain where the signature execution is requested, mandatory parameter.
  • signerAddress - string, wallet address
  • signDoc - object transaction data
    • bodyBytes ,Uint8Array
    • authInfoBytes, Uint8Array
    • chainId, string
    • accountNumber, string

Return Value

  • Promise - Object
    • signed - object,transaction information
    • signature -object, the result of the signature.

Example

let signDoc = {
    "bodyBytes": Uint8Array,
    "authInfoBytes": Uint8Array,
    "chainId": "osmosis-1",
    "accountNumber": "630104",
}
let res = await provider.signDirect("cosmos:osmosis-1", provider.getAccount("cosmos:osmosis-1").address, signDoc)


/**
    {
    "signed": {
    "bodyBytes": Uint8Array,
    "authInfoBytes":Uint8Array ,
    "chainId": "osmosis-1",
    "accountNumber": "630104"
    },
    "signature": {
    "pub_key": {
    "type": "tendermint/PubKeySecp256k1",
    "value": "AkRuGelKwOg+qJbScSUHV36zn73S1q6fD8C5dZ8furqQ"
    },
    "signature": "YpX2kGmbZYVxUqK8y9OCweJNgZkS4WaS79nBDfOJaTgowPfY0gSbXSQeRLlif2SIkBqcwTNSItBqb5M7a6K30g=="
    }
    }
 */

Disconnect wallet#

Disconnect the connected wallet and delete the current session. If you want to switch the connected wallet, please disconnect the current wallet first.

okxUniversalConnectUI.disconnect();

Event#

// Generate universalLink
okxUniversalConnectUI.on("display_uri", (uri) => {
    console.log(uri);
}).
// Session information changes will trigger this event;
okxUniversalConnectUI.on("session_update", (session) => {
  console.log(JSON.stringify(session));
});
// Disconnecting triggers this event;
okxUniversalConnectUI.on("session_delete", ({topic}) => {
    console.log(topic);
});
// This event is triggered when a connection is made and the signature is signed.
okxUniversalConnectUI.on("connect_signResponse", (signResponse) => {
  console.log(signResponse);
});

Error codes#

Exceptions that may be thrown during connection, transaction, and disconnection.

Exception

Error CodeDescription
OKX_CONNECT_ERROR_CODES.UNKNOWN_ERRORUnknown Error
OKX_CONNECT_ERROR_CODES.ALREADY_CONNECTED_ERRORWallet Already Connected
OKX_CONNECT_ERROR_CODES.NOT_CONNECTED_ERRORWallet Not Connected
OKX_CONNECT_ERROR_CODES.USER_REJECTS_ERRORUser Rejected
OKX_CONNECT_ERROR_CODES.METHOD_NOT_SUPPORTEDMethod Not Supported
OKX_CONNECT_ERROR_CODES.CHAIN_NOT_SUPPORTEDChain Not Supported
OKX_CONNECT_ERROR_CODES.WALLET_NOT_SUPPORTEDWallet Not Supported
OKX_CONNECT_ERROR_CODES.CONNECTION_ERRORConnection Error
export enum OKX_CONNECT_ERROR_CODES {
    UNKNOWN_ERROR = 0,
    ALREADY_CONNECTED_ERROR = 11,
    NOT_CONNECTED_ERROR = 12,
    USER_REJECTS_ERROR = 300,
    METHOD_NOT_SUPPORTED = 400,
    CHAIN_NOT_SUPPORTED = 500,
    WALLET_NOT_SUPPORTED = 600,
    CONNECTION_ERROR = 700
}