Connect to Mobile Wallet
EVM-Compatible Chains

EVM-Compatible Chains#

EVM-compatible chains refer to blockchain networks that use Ethereum Virtual Machine (EVM) technology.

These chains share the same smart contract execution environment as Ethereum, allowing developers to easily deploy Ethereum-based applications on these networks.

This compatibility enables developers to use existing Ethereum tools and libraries, such as Solidity, Web3.js, and Truffle, to build and deploy decentralized applications (DApps).

Common EVM-compatible chains include Polygon, Avalanche, and Fantom. The emergence of these networks has enriched the blockchain ecosystem, providing users with more options while promoting the development of cross-chain interoperability.

Installation and Initialization#

Make sure to update the OKX App to version 6.88.0 or later to start accessing it:

To integrate OKX Connect into your DApp, you can use npm:

npm install @okxconnect/universal-provider

Before connecting the wallet, you need to create an object for subsequent wallet connections, transaction submissions, and other operations.

OKXUniversalProvider.init({metaData: {name, icon}})

*Request Parameters

  • metaData - 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 better to pass a url pointing to a 180x180px PNG icon.

Return Value

  • OKXUniversalProvider

Example

import {OKXUniversalProvider} from "@okxconnect/universal-provider";

const okxUniversalProvider = await OKXUniversalProvider.init({
    dappMetaData: {
        name: "application name",
        icon: "application icon url"
    },
})

Connect to Wallet#

Connect the wallet to obtain the wallet address, which serves as an identifier and is necessary for signing transactions.

okxUniversalProvider.connect(connectParams: ConnectParams);

Request Parameters

  • connectParams - ConnectParams
    • namespaces - [namespace: string]: ConnectNamespace; Information required for connection. The key for EVM systems is "eip155". If any chain requested is not supported by the wallet, the wallet will reject the connection.
      • chains: string[]; Chain ID information,
      • rpcMap?: [chainId: string]: string; rpc information, configure the rpc url to request rpc information on the chain;
      • defaultChain?: string; default chain
    • optionalNamespaces - [namespace: string]: ConnectNamespace; optional information for connection request, the key of EVM system is “eip155”, if the corresponding chain information wallet is not available, the key will be “eip155”, if the corresponding chain information wallet is not available, the key will be “eip155”. If the corresponding chain information is not supported by the wallet, the connection can still be made;
      • chains: string[]; Chain id information, if the corresponding chain is not supported by the wallet, it can still be connected.
        • rpcMap?: [chainId: string]: string; rpc info;
        • defaultChain?: string; default chain
    • sessionConfig: object
      • redirect: string; Redirection parameter after a successful connection. If in a Telegram Mini App, set this to the Telegram deeplink: "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 under the current namespace;
      • rpcMap?: [chainId: string]: string; rpc info;
      • defaultChain?: string; 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 okxUniversalProvider.connect({
    namespaces: {
        eip155: {
            chains: ["eip155:1", "eip155:66", "eip155:56"],
            rpcMap: {
                1: "https://rpc" // set your own rpc url
            },
            defaultChain: "1"
        }
    },
    optionalNamespaces: {
        eip155: {
            chains: ["eip155:43114"]
        }
    },
    sessionConfig: {
        redirect: "tg://resolve"
    }
})

Sending Signature and Transactions#

This method allows sending messages to the wallet, supporting signatures, transactions, and RPC requests.

okxUniversalProvider.request(requestArguments, chain);

Request Parameters

  • requestArguments - object
    • method: string; the name of the requested method.
    • params?: unknown[] | Record<string, unknown> | object | undefined; Parameters corresponding to the requested method;
  • chain: string, the chain in which the requested method will be executed, it is recommended to pass this parameter, if not, it will be set to the current defaultChain;

Return Value.

Depending on the execution result of different methods, different parameters will be returned, refer to the following examples for specific parameters;

  • Personal Signature

    • Promise - string The signature result;
  • Promise - string Signature result

    • Promise - string Signature result
  • eth_sendTransaction

    • Promise - string hash
  • eth_accounts

    • Promise - string[] Returns the address of the default chainId;
  • eth_requestAccounts

    • Promise - string[] Returns the address of the default chainId;
  • eth_chainId

    • Promise - number Returns the default chainId;
  • wallet_switch ethereum_chain

    • Promise - empty
  • wallet_addEthereumChain

    • Promise - empty
  • wallet_watchAsset

    • Promise - Boolean Add Success

Example

let chain = 'eip155:1'
var data = {}

// Execute personalSign on the chain.
The first parameter in the // params array is mandatory for Challenge;
// The second parameter, hex encoded address, is optional.
data = {
    
    “params": [0x506c65617365207369676e2074686973206d65737361676520746f20636f6e6669726d20796f7572206964656e746974792e,0x4B0897b,0x4B0897b0x4B0897b0513FdBeEc7C469D9aF4fA6C0752aBea7]
}
var personalSignResult = await okxUniversalProvider.request(data, chain)
//personalSignResult: 0xe8d34297c33a61”

// Execute eth_signTypedData_v4 on chain chain
// params array, first parameter is Address is optional;
// The second parameter is TypedData, which must be passed.
data = {
    "method": "eth_signTypedData_v4",
    "params": [
        "0x00000",
        {
            "domain": {
                "name": "Ether Mail",
                "version": "1",
                "chainId": 1,
                "verifyingContract": "0xcccccccccccccccccccccccccccccccccccccccc"
            },
            "message": {
                "from": {"name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"},
                "to": {"name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"},
                "contents": "Hello, Bob!"
            },
            "primaryType": "Mail",
            "types": {
                "EIP712Domain": [{"name": "name", "type": "string"}, {
                    "name": "version",
                    "type": "string"
                }, {"name": "chainId", "type": "uint256"}, {"name": "verifyingContract", "type": "address"}],
                "Person": [{"name": "name", "type": "string"}, {"name": "wallet", "type": "address"}],
                "Mail": [{"name": "from", "type": "Person"}, {"name": "to", "type": "Person"}, {
                    "name": "contents",
                    "type": "string"
                }]
            }
        }
    ]
}
var signTypeV4Result = await okxUniversalProvider.request(data, chain)
//signTypeV4Result: "0xa8bb3c6b33a119d..."

// Execute sendTransaction on the chain,
data = {
    "method": "eth_sendTransaction",
    "params": [
        {
            to: "0x4B...",
            from: "0xDe...",
            gas: "0x76c0",
            value: "0x8ac7230489e80000",
            data: "0x",
            gasPrice: "0x4a817c800"
        }
    ]
}
var sendTransactionResult = await okxUniversalProvider.request(data, chain)
// "0x1ccf2c4a3d689067fc2ac..."

// Get address information for the default chain;
data = {"method": "eth_requestAccounts"}
var ethRequestAccountsResult = await okxUniversalProvider.request(data, chain)
//  ["0xf2f3e73b..."]

// Get the default chain information;
data = {"method": "eth_chainId"}
var chainIdResult = await okxUniversalProvider.request(data, chain)
//chainIdResult   1

// Switching chains;
data = {
    "method": "wallet_switchEthereumChain",
    "params": [
        {
            chainId: "0x1"
        }
    ]
}
var switchResult = await okxUniversalProvider.request(data, chain)
// switchResult null

// Add chain
data = {
    "method": "wallet_addEthereumChain",
    "params": [{
        "blockExplorerUrls": ["https://explorer.fuse.io"],
        "chainId": "0x7a",
        "chainName": "Fuse",
        "nativeCurrency": {"name": "Fuse", "symbol": "FUSE", "decimals": 18},
        "rpcUrls": ["https://rpc.fuse.io"]
    }]
}
var addEthereumChainResult = await okxUniversalProvider.request(data, chain)
//addEthereumChainResult   null

// add coins to the chain watchAsset
data = {
    "method": "wallet_watchAsset",
    "params": [{
        "type": "ERC20",
        "options": {
            "address": "0xeB51D9A39AD5EEF215dC0Bf39a8821ff804A0F01",
            "symbol": "LGNS",
            "image": "https://polygonscan.com/token/images/originlgns_32.png",
            "decimals": 9
        }
    }]
}
var watchAssetResult = await okxUniversalProvider.request(data, chain)
// watchAssetResult   
// true/false

// Execute requestRpc on the chain.
data = {"method": "eth_getBalance", "params": ["0x8D97689C9818892B700e27F316cc3E41e17fBeb9", "latest"]}
var getBalanceResult = await okxUniversalProvider.request(data, chain)
// getBalanceResult:  "0xba862b54effa"

Set Default Network#

In the case of multiple networks, if the developer does not specify the network where the current operation is performed, the interaction will be performed through the default network.

'setDefaultChain(chain, rpcUrl?)'

Example

okxUniversalProvider.setDefaultChain("eip155:1", "rpcurl")

Disconnect wallet#

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

okxUniversalProvider.disconnect();

Events#

// Generate universalLink  
okxUniversalProvider.on(“display_uri”, (uri) => {
    console.log(uri);
});

// Session information changes (e.g. adding a custom chain) will trigger this event;
okxUniversalProvider.on(“session_update”, (session) => {
    console.log(JSON.stringify(session));
}); 

// Disconnecting triggers this event;
okxUniversalProvider.on(“session_delete”, ({topic}) => {
    console.log(topic);
});

Error codes#

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

Exception

Error CodeDescription
OKX_CONNECT_ERROR_CODES.UNKNOWN_ERRORUnknown Exception
OKX_CONNECT_ERROR_CODES.ALREADY_CONNECTED_ERRORWallet 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
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,
}