npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@okxconnect/walletsdk

v1.5.2

Published

OKX Connect Wallet SDK

Downloads

1,292

Readme

WalletSDK

安装及初始化

将 OKX Connect 集成到您的 Wallet WebApp 中,可以使用 npm:

npm install @okxconnect/walletsdk

接入钱包侧OKX Connect SDK需要初始化OKXConnectManager对象。

init接口

并调用init接口实现Connect功能初始化

请求参数

返回值

  • Promise<void>

可监听事件

  • OKXCONNECTOR_SESSION_PROPOSAL_EVENT 处理连接请求的监听事件
  • OKXCONNECTOR_REQUEST_EVENT 处理业务推送的监听事件

示例

import {OKXConnectManager} from "@okxconnect/walletsdk"
var connectManager = new OKXConnectManager()
//会话连接回调
const sessionProposalCallback = (sessionInfo: SessionInfo, connection: BridgeConnectionRequest) => {
    // 收到
    console.log('on connect manager called')
    console.log("callback:" + JSON.stringify(sessionInfo));
    ...
}
//收到请求回调
const requestCallback = (topic: string, rsp: DAppRequest) => {
    console.log('requestCallback' + rsp)
    // 模拟收到请求返回处理
    await connectManager.sendResponse(topic, successRsp)
    ...
}
//断开连接回调
const disconnectCallback = (sessionInfo: SessionInfo) => {
    console.log('disconnectCallback' , sessionInfo)
}
// 监听连接请求
connectManager.on(OKXCONNECTOR_SESSION_PROPOSAL_EVENT, sessionProposalCallback)

// 监听消息请求
connectManager.on(OKXCONNECTOR_REQUEST_EVENT, requestCallback)

// 监听消息请求
connectManager.on(OKXCONNECTOR_DISCONNECT_EVENT, disconnectCallback);

await connectManager.init()

on消息订阅接口

并调用on接口实现消息订阅

请求参数

  • eventName: string 目前支持session消息(OKXCONNECTOR_SESSION_PROPOSAL_EVENT) 和 请求消息(OKXCONNECTOR_REQUEST_EVENT)
  • callback: EventEmitter.EventListener<any, any>

返回值

可监听事件

  • OKXCONNECTOR_SESSION_PROPOSAL_EVENT 处理连接请求的监听事件
  • OKXCONNECTOR_REQUEST_EVENT 处理业务推送的监听事件
  • OKXCONNECTOR_DISCONNECT_EVENT 处理断开连接的监听事件

示例

connectManager.on(OKXCONNECTOR_SESSION_PROPOSAL_EVENT, sessionProposalCallback);
connectManager.on(OKXCONNECTOR_REQUEST_EVENT, requestCallback);
connectManager.on(OKXCONNECTOR_DISCONNECT_EVENT, disconnectCallback);

off解除消息订阅接口

并调用off接口实现消息解除订阅

请求参数

  • eventName: string 目前支持session消息(OKXCONNECTOR_SESSION_PROPOSAL_EVENT) 和 请求消息(OKXCONNECTOR_REQUEST_EVENT)
  • callback: EventEmitter.EventListener<any, any>

返回值

可监听事件

  • OKXCONNECTOR_SESSION_PROPOSAL_EVENT 处理连接请求的监听事件
  • OKXCONNECTOR_REQUEST_EVENT 处理业务推送的监听事件
  • OKXCONNECTOR_DISCONNECT_EVENT 处理断开连接的监听事件

示例

connectManager.off(OKXCONNECTOR_SESSION_PROPOSAL_EVENT, sessionProposalCallback);
connectManager.off(OKXCONNECTOR_REQUEST_EVENT, requestCallback);
connectManager.off(OKXCONNECTOR_DISCONNECT_EVENT, disconnectCallback);

Session连接场景

Session连接场景流程概述:

  • Session的连接由DApp通过url打开钱包页面,或其他形式的跳转为入口。 在钱包侧收到url参数后,可调用 await connectManager.pairingFromUrl() 来触发OKXCONNECTOR_SESSION_PROPOSAL_EVENT事件, 实践中携带两个数据,SessionInfo和BridgeConnectionRequest。

    • SessionInfo:当前连接信息
    • BridgeConnectionRequest
      • protocolVer:版本号;
      • topic:会话id;
      • clientId:客户端id;
      • requestId:请求id;
      • DAppInfo:DAppMetadata(DApp信息)
      • redirect:跳转URL;
      • requests:ConnectEngineRequest = (ConnectItem | ConnectEngineUniversalRequest)[] //详细请求数据
        • ConnectItem: 连接信息
        • ConnectEngineUniversalRequest:通用请求参数
  • 通过approveSession()接口或者rejectSession()方法返回DApp侧结果,并完成Session连接场景。

  • 监听OKXCONNECTOR_REQUEST_EVENT事件,在收到DApp消息后,在回调事件的返回DAppRequest。钱包侧解析DAppRequest内容,并根据实际场景处理返回的内容。

    • DAppRequest
      • requestId: 请求标识,
      • method: 请求方法,
      • params: 请求的业务数据,不同的链和方法,传递的params也会不同。 示例:personal_sign方法的请求体如下, { "requestId": String, "method": "personal_sign", "chainId": "eip155:1", // current chain "params": { "message": "签名体" }

ParingFromUrl方法

传入wallet页面的拉起参数,调用之后会触发OKXCONNECTOR_SESSION_PROPOSAL_EVENT事件

//?start_param=Base64(okxconnect: urlParamsString, extraParams: {})
async pairingFromUrl(urlParams: string): Promise<void>

请求参数

  • urlParams base64字符串

返回值

示例

// 普通页面跳转为例子,从param字段中获取base64入参
let searchParam = window.location.search;
let base64Param = searchParam.replace(/\?param=/g, "");
console.log("open url with params: ", base64Param)
if (base64Param) {
    // 触发pairingFromUrl
    connectManager.pairingFromUrl(base64Param)
} else {
    console.log("no connection")
}

ApproveSession方法

接受DApp连接

async approveSession(accountId: string, sessionInfo: SessionInfo, responses: (ConnectItemReply | UniversalResponse)[], walletInfo: DeviceALlInfo)

请求参数

  • accountId 钱包id
  • sessionInfo 回调中获取的SessionInfo
  • responses 处理连接request中的请求,并返回对应的responses, 类型为(ConnectItemReply | UniversalResponse)[]
    • ConnectItemReply = TonAddressItemReply | TonProofItemReply
      • TonAddressItemReply
        • name: 名称
        • address:TON address raw (0:<hex>)
        • network:网络
        • walletStateInit:初始化状态,Base64 (not url safe) encoded stateinit cell for the wallet contract
        • publicKey:HEX string without 0x
      • TonProofItemReply
        • name: 名称
        • proof:proof内容
          • timestamp:时间戳,64-bit unix epoch time of the signing operation (seconds)
          • domain:app域名
            • lengthBytes:域名长度
            • value:域名名称(as url part, without encoding)
        • payload:携带信息
        • signature:签名
    • UniversalResponse
      • name:名称
      • accounts[]:钱包信息
        • namespace: 协议和链信息
        • addresses: 地址
        • methods: 支持的方法
  • walletInfo 钱包信息
    • platform: 平台类型,'iphone' | 'ipad' | 'android' | 'windows' | 'mac' | 'linux' | 'browser'; appName: 钱包名称; appVersion: 钱包版本; maxProtocolVersion: 支持的最大协议版本;

示例

connectManager.approveSession(mockWalletId, currentSession, mockWalletConnectRspData, mockWalletInfoData).then(
            data => {
                console.log('Session approved:', data);
            },
            error => {
                console.error('Session approve error:', error);
            }
        )

RejectSession方法

拒绝DApp连接

async rejectSession(sessionInfo: SessionInfo, code: OKX_CONNECT_ERROR_CODES)

请求参数

  • sessionInfo 回调中获取的SessionInfo
  • code OKX_CONNECT_ERROR_CODES 中列举的拒绝理由

错误码说明

| 错误码 | 描述 | |-------------------------------------------------|-------| | OKX_CONNECT_ERROR_CODES.UNKNOWN_ERROR | 未知异常 | | OKX_CONNECT_ERROR_CODES.BAD_REQUEST_ERROR | 异常请求 | | OKX_CONNECT_ERROR_CODES.ALREADY_CONNECTED_ERROR | 已连接 | | OKX_CONNECT_ERROR_CODES.NOT_CONNECTED_ERROR | 钱包未连接 | | OKX_CONNECT_ERROR_CODES.UNKNOWN_APP_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 | 连接异常 |

示例

// 因用户操作而拒绝连接
connectManager.rejectSession(currentSession, OKX_CONNECT_ERROR_CODES.USER_REJECTS_ERROR)

DApp连接成功后通信方法

在session连接成功后发送信息

async sendResponse(topicId:string, response: WalletResponse)

请求参数

  • topicId sessionInfo中topicId字段
  • rsp 返回处理后的信息
    • WalletResponse = WalletResponseSuccess | WalletResponseError;
      • WalletResponseSuccess
        • reqeustId 对应request 请求中的id,标识该返回值是对应哪条请求
        • method 对应request 请求中的method,标识该返回值是对应哪条请求
        • result 结果,如签名时返回签名结果;合约交互时返回交易hash
      • WalletResponseError
        • reqeustId 对应request 请求中的id,标识该返回值是对应哪条请求
        • method 对应request 请求中的method,标识该返回值是对应哪条请求
        • error 错误信息
          • code:错误码
          • message:错误详情

返回值

示例

//成功
const testSuccessRsp: WalletResponseSuccess = {
    "requestId": rsp.requestId, // Corresponding DApp requestId
    "method": rsp.method, // Corresponding DApp request method
    "result": "xx" //签名结果
}
connectManager.sendResponse(topic, testSuccessRsp)
// 失败
const testFailRsp: WalletResponseError = {
        "requestId": rsp.requestId, // Corresponding DApp requestId
        "method": rsp.method, // Corresponding DApp request method
        "error": {
            "code": -1,
            "message": "签名失败" // Error message
        }
    }
connectManager.sendResponse(topic, testSuccessRsp)

DAppSession管理

DApp Session管理场景概述,提供用来绘制已连接DApp面板的api

  • 获取对应钱包ID下的全部session
  • 获取对应Topic下的session
  • 断开某个DAppSession
  • 断开指定钱包的所有DAppSession
  • 设置SessionList变化的监听
  • 移除SessionList变化的监听

获取对应钱包下的全部Session

getSessionsByAccountId(accountId: string): Array<SessionInfo>

请求参数

  • accountId 钱包id

返回值

  • session数组

示例

let sessions = connectManager.getSessionsByAccountId(mockWalletId)
...

获取对应Topic下的session

getSessionByTopic(topicId: string): SessionInfo | undefined

请求参数

  • topicId topicId

返回值

  • SessionInfo

示例

let session = connectManager.getSessionByTopic("topicId")
...

断开某个DAppSession

removeDAppSession(accountId: string, toppicId: string)

请求参数

  • accountId 钱包id
  • toppicId 会话id

返回值

示例

connectManager.removeDAppSession(mockWalletId, sessionInfo.topicId)

断开指定钱包的所有DAppSession

removeAllDAppSessions(accountId: string)

请求参数

  • accountId 钱包id

返回值

示例

connectManager.removeAllDAppSessions(mockWalletId)

设置SessionList变化的监听

setDAppSessionListListener(accountId: string, callback: (data: Array<SessionInfo> | undefined) => void)

请求参数

  • accountId 钱包id
  • callback 变化后sessionList回调
    • data Array

返回值

示例

connectManager.setDAppSessionListListener(mockWalletId, data => {
    console.log("sessionList changed", data)
    ...
})

移除SessionList变化的监听

removeDAppSessionListListener(accountId: string)

请求参数

  • accountId 钱包id

返回值

示例

connectManager.removeDAppSessionListListener(mockWalletId)