连接App或Mini钱包

SDK#

安装及初始化#

请确保更新到 6.94.0或以后版本,即可开始接入:将 OKX Connect 集成到您的 DApp 中,可以使用 npm:

npm install @okxconnect/universal-provider

连接钱包之前,需要先创建一个对象,用于后续连接钱包、发送交易等操作。

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

请求参数

  • dappMetaData - object
    • name - string: 应用名称,不会作为唯一表示
    • icon - string: 应用图标的 URL。必须是 PNG、ICO 等格式,不支持 SVG 图标。最好传递指向 180x180px PNG 图标的 url。

返回值

  • OKXUniversalProvider

示例

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

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

连接钱包#

连接钱包去获取钱包地址,作为标识符和用于签名交易的必要参数;

okxUniversalProvider.connect(connectParams: ConnectParams);

请求参数

  • connectParams - ConnectParams
    • namespaces - [namespace: string]: ConnectNamespace ; 请求连接的可选信息, COSMOS系的key为"cosmos",如果请求的链中,有任何一个链钱包不支持的话,钱包会拒绝连接;
      • chains: string[]; 链id信息,
      • defaultChain?: string; 默认链
    • optionalNamespaces - [namespace: string]: ConnectNamespace; 请求连接的可选信息, COSMOS系的key为"cosmos",如果对应的链信息钱包不支持,依然可以连接;
      • chains: string[]; 链id信息,
        • defaultChain?: string; 默认链
    • sessionConfig: object
      • redirect: string 连接成功后的跳转参数,如果是Telegram中的Mini App,这里可以设置为Telegram的deeplink: "tg://resolve"

返回值

  • Promise<SessionTypes.Struct | undefined>
    • topic: string; 会话标识;
    • namespaces: Record<string, Namespace>; 成功连接的namespace 信息;
      • chains: string[]; 连接的链信息;
      • accounts: string[]; 连接的账户信息;
      • methods: string[]; 当前namespace下,钱包支持的方法;
      • defaultChain?: string; 当前会话的默认链
    • sessionConfig?: SessionConfig
      • dappInfo: object DApp 信息;
        • name:string
        • icon:string
      • redirect?:string, 连接成功后的跳转参数;

示例

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

判断钱包是否已连接#

获取当前是否有连接钱包;

返回值

  • boolean

示例

okxUniversalProvider.connected();

准备交易#

首先创建一个OKXCosmosProvider对象,构造函数传入OKXUniversalProvider

import { OKXCosmosProvider } from "@okxconnect/universal-provider";
let okxCosmosProvider = new OKXCosmosProvider(okxUniversalProvider)

获取账户信息#

okxCosmosProvider.getAccount(chainId);

请求参数

  • chainId: 请求的链,如cosmos:cosmoshub-4, cosmos:osmosis-1

返回值

  • Object
    • algo: "secp256k1",
    • address: string 钱包地址,
    • bech32Address: string 钱包地址,
    • pubKey: Uint8Array 公钥,

示例

let result = okxCosmosProvider.getAccount("cosmos:cosmoshub-4")
//返回结构
{
    "algo": "secp256k1",
    "address": "cosmos1u6lts9ng4etxj0zdaxsada6zgl8dudpg3ygvjw",
    "bech32Address": "cosmos1u6lts9ng4etxj0zdaxsada6zgl8dudpg3ygvjw",
    "pubKey": {
        "0": 2,
        "1": 68,
        "2": 110,
        ...
        "32": 144
     }
}

签署消息#

okxCosmosProvider.signArbitrary(chain, signerAddress, message);

请求参数

  • chain - string, 请求执行方法的链
  • signerAddress - string 签名钱包地址
  • message - string 需要签名的消息。

返回值

  • Promise - object
    • pub_key : object
      • type:string 公钥类型
      • value:string 公钥
    • signature: string 签名结果

示例

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

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

签署交易 signAmino#

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

请求参数

  • chainId - string, 请求签名执行的链,必传参数

  • signerAddress - string,钱包地址

  • signDoc - object,交易信息 按照固定格式签名,类似 cosmjs 的 OfflineSigner 的 signAmino 方法 参数就是对象,signDoc 就是一个固定格式 返回值

  • Promise - Object

    • signed - object,交易信息
    • signature -object,签名结果

示例

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)


/**
    返回结构:
    {
    "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?);

请求参数

  • chainId - string, 请求签名执行的链,必传参数,
  • signerAddress - string, 钱包地址
  • signDoc - object 交易数据
    • bodyBytes ,Uint8Array
    • authInfoBytes, Uint8Array
    • chainId, string
    • accountNumber, string

返回值

  • Promise - Object
    • signed - object,交易信息
    • signature -object,签名结果

示例

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": {
    "type": "Buffer",
    "data": [
    10, 193, 1, 10, 41, ...]
    },
    "authInfoBytes": {
    "0": 10,
    "1": 81,
    ...
    },
    "chainId": "osmosis-1",
    "accountNumber": "630104"
    },
    "signature": {
    "pub_key": {
    "type": "tendermint/PubKeySecp256k1",
    "value": "AkRuGelKwOg+qJbScSUHV36zn73S1q6fD8C5dZ8furqQ"
    },
    "signature": "YpX2kGmbZYVxUqK8y9OCweJNgZkS4WaS79nBDfOJaTgowPfY0gSbXSQeRLlif2SIkBqcwTNSItBqb5M7a6K30g=="
    }
    }
 */

断开钱包连接#

断开已连接钱包,并删除当前会话,如果要切换连接钱包,请先断开当前钱包。

okxUniversalProvider.disconnect();

Event事件#

// 生成 universalLink
okxUniversalProvider.on("display_uri", (uri) => {
    console.log(uri);
});
// session 信息变更会触发该事件;
okxUniversalProvider.on("session_update", (session) => {
    console.log(JSON.stringify(session));
});
// 断开连接会触发该事件;
okxUniversalProvider.on("session_delete", ({topic}) => {
    console.log(topic);
});

错误码#

在连接,交易,断开连接的过程中可能抛出的异常;

异常

错误码描述
OKX_CONNECT_ERROR_CODES.UNKNOWN_ERROR未知异常
OKX_CONNECT_ERROR_CODES.ALREADY_CONNECTED_ERROR钱包已连接
OKX_CONNECT_ERROR_CODES.NOT_CONNECTED_ERROR钱包未连接
OKX_CONNECT_ERROR_CODES.USER_REJECTS_ERROR用户拒绝
OKX_CONNECT_ERROR_CODES.METHOD_NOT_SUPPORTED方法不支持
OKX_CONNECT_ERROR_CODES.CHAIN_NOT_SUPPORTED链不支持
OKX_CONNECT_ERROR_CODES.WALLET_NOT_SUPPORTED钱包不支持
OKX_CONNECT_ERROR_CODES.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
}