Provider API#
什么是 Injected provider API?#
OKX Wallet Injected providers API 是一个 JavaScript API,OKX Wallet将其注入用户访问的网站。您的 DApp 可以使用此 API 请求用户帐户,从用户连接的区块链读取数据,帮助用户签署消息和交易。
特别说明#
OKX Wallet 的 WAX API 完全兼容 Scatter 协议,下面的 API 和示例都是基于该协议的,具体使用详情,开发者可以参考 Scatter 协议的文档。
连接钱包并获取账户信息#
import ScatterJS from '@scatterjs/core';
import ScatterEOS from '@scatterjs/eosjs2';
ScatterJS.plugins(new ScatterEOS());
ScatterJS.login().then(identity => {
    const account = identity.accounts[0]
    console.log(account)
})
是否已连接钱包#
确定钱包是否已连接。
import ScatterJS from '@scatterjs/core';
import ScatterEOS from '@scatterjs/eosjs2';
ScatterJS.plugins(new ScatterEOS());
const isConnected = ScatterJS.isConnected()
console.log(isConnected)
获取钱包信息#
获取当前连接的钱包信息,如果没有连接到钱包,则会返回 null 。
import ScatterJS from '@scatterjs/core';
import ScatterEOS from '@scatterjs/eosjs2';
ScatterJS.plugins(new ScatterEOS());
const isConnected = ScatterJS.isConnected()
if (isConnected) {
   const identity = ScatterJS.account()
   const account = identity.accounts[0]
   console.log(account)
}
签名交易#
签署交易时,需要用到 eosjs 这个库。
import ScatterJS from '@scatterjs/core';
import ScatterEOS from '@scatterjs/eosjs2';
import {JsonRpc, Api} from 'eosjs';
ScatterJS.plugins(new ScatterEOS());
const network = ScatterJS.Network.fromJson({
    blockchain:'wax',
    chainId:'1064487b3cd1a897ce03ae5b6a865651747e2e152090f99c1d19d44e01aea5a4',
    host:'nodes.get-scatter.com',
    port:443,
    protocol:'https'
});
const rpc = new JsonRpc(network.fullhost());
ScatterJS.connect('YourAppName', {network}).then(connected => {
    if(!connected) return console.error('no scatter');
    const eos = ScatterJS.eos(network, Api, {rpc});
    ScatterJS.login().then(identity => {
        if(!identity) return console.error('no identity');
        const account = identity.accounts[0]
        eos.transact({
            actions: []
        }).then(res => {
            console.log('sent: ', res);
        }).catch(err => {
            console.error('error: ', err);
        });
    });
});
添加/移除事件监听#
添加/移除事件监听,目前支持的事件有:
- connect: 钱包已连接的事件
- accountChanged:当用户切换账户时会触发该事件
- disconnect:当用户断开连接时会触发该事件
import ScatterJS from '@scatterjs/core';
const connect = () => {}
ScatterJS.on('connect', connect)
ScatterJS.off('connect', connect)
