@okxconnect/universal-provider
v1.5.2
Published
OKX Connect Universal Provider
Downloads
14,292
Readme
SDK
Installation and Initialization
Make sure to update the OKX App to version 6.88.0 or later to start integration:
To integrate OKX Connect into your DApp, use npm:
npm install @okxconnect/universal-provider
Before connecting to the wallet, you need to create an object for subsequent wallet connection, transaction sending, and other operations.
OKXUniversalProvider.init({dappMetaData: {name, icon}})
Request Parameters
- dappMetaData - object
- name - string: Application name, not used as a unique identifier
- icon - string: URL of the application icon. Must be in PNG, ICO, or similar formats; SVG icons are not supported. Ideally, provide a URL for 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,
- 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 is not supported by the wallet, you can still connect to it; if you need to connect to a custom network, you can add the request for the custom network to this parameter, if there is already a custom network in the wallet, the information of the custom chain will be returned in the request session; if the wallet does not support it, there is no information of the custom chain in the request session, you can call the request method again, with the method set to wallet_addEthereumChain, to add the custom chain. If the wallet doesn't support it, there is no information about the custom chain in the request result session, so you can add the custom chain by calling the request method again with the method set to wallet_addEthereumChain.
- chains: string[]; Chain id information, if the corresponding chain is not supported by the wallet, it can still be connected.
- defaultChain?: string; default chain
- chains: string[]; Chain id information, if the corresponding chain is not supported by the wallet, it can still be connected.
- sessionConfig: object
- redirect: string; Redirection parameter after a successful connection. If in a Telegram Mini App, set this to the Telegram deeplink: "tg://resolve".
- 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.
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;
- 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;
- dappInfo: object DApp information;
Example
var session = await okxUniversalProvider.connect({
namespaces: {
eip155: {
// Please pass in as many chain ids as you need.
chains: ["eip155:1"],
defaultChain: "1"
}
},
optionalNamespaces: {
eip155: {
chains: ["eip155:43114"]
}
},
sessionConfig: {
redirect: "tg://resolve"
}
})
Determine if the wallet is connected
Gets whether the wallet is currently connected.
Return Value
- boolean
Example
okxUniversalProvider.connected();
Sending Signature and Transactions
This method allows sending messages to the wallet, supporting signatures, transactions.
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; - redirect -string 'none' |
${string}://${string}
; App wallet, the return policy of the deep link when the user signs or rejects the request, if it is a Mini App in Telegram, it can be configured with tg://resolve, if it's not configured here, it'll take the redirect passed by connect method, default is 'none'
- 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 Values
The results returned vary depending on the method executed. Refer to the examples below for specific parameters:
personal_sign
- Promise - string: Signature result
eth_signTypedData_v4
- Promise - string: Signature result
eth_sendTransaction
- Promise - string: Transaction hash
eth_accounts
- Promise - string[]: Returns addresses for the default chainId
eth_requestAccounts
- Promise - string[]: Returns addresses for the default chainId
eth_chainId
- Promise - number: Returns the default chain ID
wallet_switchEthereumChain
- Promise - null
wallet_addEthereumChain
- Promise - null
wallet_watchAsset
- Promise - boolean: Successfully added
Examples
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”,
“0x4B0897b0513FdBeEc7C469D9aF4fA6C0752aBea7”
]
}
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
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)'
Example
okxUniversalProvider.setDefaultChain("eip155:1")
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();
Event
// 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)); }); // Session information changes (e.g., adding a custom chain).
// 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 Code | Description | |----------------------------------------------|-------------------------| | OKX_CONNECT_ERROR_CODES.UNKNOWN_ERROR | Unknown Error | | OKX_CONNECT_ERROR_CODES.ALREADY_CONNECTED_ERROR | Wallet Already Connected | | OKX_CONNECT_ERROR_CODES.NOT_CONNECTED_ERROR | Wallet Not Connected | | OKX_CONNECT_ERROR_CODES.USER_REJECTS_ERROR | User Rejected | | OKX_CONNECT_ERROR_CODES.METHOD_NOT_SUPPORTED | Method Not Supported | | OKX_CONNECT_ERROR_CODES.CHAIN_NOT_SUPPORTED | Chain Not Supported | | OKX_CONNECT_ERROR_CODES.WALLET_NOT_SUPPORTED | Wallet Not Supported | | OKX_CONNECT_ERROR_CODES.CONNECTION_ERROR | Connection 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
}