1.创建一个nkn客户端
import NKN from 'nkn-multiclient';
const nknClient = new NKN({
identifier: "any thing"
});
2.创建一个钱包
import nknWallet from 'nkn-wallet';
const seed = "64位字符串";
const wallet = nknWallet.restoreWalletBySeed(seed, 'password');
钱包和客户端建立联系
import rpcCall from 'nkn-client/lib/rpc';
nknWallet.configure({
rpcAddr: 'https://ip:port',
});
const client = nkn({
originalClient: true,
identifier: 'identifier',
seed: wallet.getSeed(),
seedRpcServerAddr: 'https://ip:port',
});
4.用钱包订阅一个主题
wallet.subscribe('topic', 5000, 'identifier')
.then(function(data) {
console.log('Subscribe success:', data, '');
}).catch(function(error) {
console.log('Subscribe fail:', error);
});
5.发送信息以及接收信息
client.on('connect', ()=>{
client.on('message', (src, payload, payloadType, encrypt) => {
console.log( payloadType + 'Receive', encrypt ? 'encrypted' : 'unencrypted', 'message', '"' + payload + '"','from', src, 'afterms');
return 'Well received!';
});
})
client.publish("topic", 'hello world', { txPool: true });
6.获取当前订阅主题的区块高度以及最近的区块高度
const latestBlockHeight = rpcCall(
'https://ip:port',
'getlatestblockheight',
);
const subinfo = client.defaultClient.getSubscription('topic', client.addr)
Promise.all([subinfo,latestBlockHeight]).then(([info, blockheight])=>{
if(info.expiresAt - blockheight > 5000){
return Promise.reject('Too soon.');
}else{
wallet.subscribe('topic', 5000, 'identifier');
}
})
7.获取订阅频道的人数
client.defaultClient.getSubscribers('tpoic', options);