Code Monkey home page Code Monkey logo

nkn-client-js's Introduction

Note: This repo is deprecated in favor of nkn-sdk-js.

CircleCI Status

nkn-client-js

EnglishРусский

JavaScript implementation of NKN client.

Send and receive data between any NKN clients without setting up a server.

Note: This is a client version of the NKN protocol, which can send and receive data but not relay data (mining). For node implementation which can mine NKN token by relaying data, please refer to nkn.

Usage

For npm:

npm install nkn-client

And then in your code:

const nkn = require('nkn-client');

For browser, use dist/nkn.js or dist/nkn.min.js.

Create a client with a generated key pair:

const client = nkn();

Or with an identifier (used to distinguish different clients sharing the same key pair):

const client = nkn({
  identifier: 'any string',
});

Get client key pair:

console.log(client.key.seed, client.key.privateKey, client.key.publicKey);

Create a client using an existing secret seed:

const client = nkn({
  identifier: 'any string',
  seed: '2bc5501d131696429264eb7286c44a29dd44dd66834d9471bd8b0eb875a1edb0',
});

Secret seed should be kept SECRET! Never put it in version control system like here.

By default the client will use bootstrap RPC server (for getting node address) provided by NKN. Any NKN full node can serve as a bootstrap RPC server. To create a client using customized bootstrap RPC server:

const client = nkn({
  identifier: 'any string',
  seedRpcServerAddr: 'https://ip:port',
});

Get client identifier:

console.log(client.identifier);

And client NKN address, which is used to receive data from other clients:

console.log(client.addr);

Listen for connection established:

client.on('connect', () => {
  console.log('Connection opened.');
});

Send text message to other clients:

client.send(
  'another client address',
  'hello world!',
);

You can also send byte array directly:

client.send(
  'another client address',
  Uint8Array.from([1,2,3,4,5]),
);

Or publish text message to a topic (subscribe is done through nkn-wallet-js):

client.publish(
  'topic',
  'hello world!',
);

Receive data from other clients:

// can also be async (src, payload, payloadType, encrypt) => {}
client.on('message', (src, payload, payloadType, encrypt) => {
  if (payloadType === nkn.PayloadType.TEXT) {
    console.log('Receive text message:', src, payload);
  } else if (payloadType === nkn.PayloadType.BINARY) {
    console.log('Receive binary message:', src, payload);
  }
  console.log('Message is', encrypt ? 'encrypted' : 'unencrypted');
});

If a valid data (string or Uint8Array) is returned at the end of the handler, the data will be sent back to sender as response:

client.on('message', (src, payload, payloadType, encrypt) => {
  return 'Well received!';
  // You can also return a byte array:
  // return Uint8Array.from([1,2,3,4,5]);
});

Note that if multiple onmessage handlers are added, the result returned by the first handler (in the order of being added) will be sent as response.

The send method will return a Promise that will be resolved when sender receives a response, or rejected if not receiving acknowledgement within timeout period. Similar to message, response can be either string or byte array:

client.send(
  'another client address',
  'hello world!',
).then((response) => {
  // The response here can be either string or Uint8Array
  console.log('Receive response:', response);
}).catch((e) => {
  // This will most likely to be timeout
  console.log('Catch:', e);
});

Client receiving data will automatically send an acknowledgement back to sender if no response is returned by any handler so that sender will be able to know if the packet has been delivered. From the sender's perspective, it's almost the same as receiving a response, except that the Promise is resolved without a value:

client.send(
  'another client address',
  'hello world!',
).then(() => {
  console.log('Receive ACK');
}).catch((e) => {
  // This will most likely to be timeout
  console.log('Catch:', e);
});

Timeout for receiving response or acknowledgement can be set when initializing client:

const client = nkn({
  responseTimeout: 5, // in seconds
});

or when sending a packet:

client.send(
  'another client address',
  'Hello world!',
  {
    responseTimeout: 5, // in seconds
  },
)

Check examples for full examples.

Contributing

Can I submit a bug, suggestion or feature request?

Yes. Please open an issue for that.

Can I contribute patches?

Yes, we appreciate your help! To make contributions, please fork the repo, push your changes to the forked repo with signed-off commits, and open a pull request here.

Please sign off your commit. This means adding a line "Signed-off-by: Name " at the end of each commit, indicating that you wrote the code and have the right to pass it on as an open source patch. This can be done automatically by adding -s when committing:

git commit -s

Community

nkn-client-js's People

Contributors

akacoder avatar dependabot[bot] avatar gdmmx avatar losnappas avatar realjohnsmith avatar trueinsider avatar turarabu avatar yilunzhang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nkn-client-js's Issues

Publish doesn't send messages

Hi,

I don't think the publish is working correctly.

const nknWallet = require('nkn-wallet')
const nkn = require('nkn-client')
const wallet = nknWallet.newWallet('pwd')
const client = nkn({
  privateKey: wallet.getPrivateKey(),
  indentifier: 'client'
})
const receivingClientWallet = nknWallet.newWallet('pwd')
receivingClientWallet.subscribe(
	'topic',
	0,
	10,
	'pwd',
	'identifier'
)
client.on('connect' , () => 
setTimeout(() => {
	client.publish(
	'topic',
	0,
	'hello world'
	)
}, 1000)
)

This makes a request where it gets a result like {"id":"1","jsonrpc":"2.0","result":{"identifier.02c988e6a672fd6b8cf42e68682362ee152a8afb5176b9206c558b4cb89daba47d":"","identifier.0352304707e0af0187b435ea5f3ec8f3a0fbac71e3e801dbc34b3cf8d4000d1128":"","identifier.03c7575885c10f141576d817fa5fbca5144e74e3fd85838530ec8a8027d587aa5a":""}}

But then nothing gets sent to them afterwards. My understanding was that it is a shortcut to send the message to all those addresses automatically.

NKN browser distribution is too big!

Hi,

The minified browser package for NKN is about 700KB. That's really hefty!
Could something be done to make it, like, 10 times smaller (70KB is still big for a minified js library).

Cheers,
Mark

Direct HTTP requests to the RPC node that is in use

Currently getSubscribers and some other requests are being directed to the seedRpcServerAddr that was used in initializing the client.

By default, how about directing those at the node that we are connected to, instead? Is that something we can do without problems?

If that is something that can be done, then in D-Chat I would also configure the wallet to send requests to the same node. It is better that way because you either have everything break down, or everything will work. Currently I see people not getting subscribed to chats, and while it's hard to pinpoint the cause, I think that this could be one of them.

Also, I think dropping "Origin" and "Referer" headers from requests is not a terrible idea if they aren't needed, since some will argue that those lower privacy.

Provide a default https seedRpcServerAddr instead of http

Hi,

I'm getting this error:

The page at '' was loaded over HTTPS, but requested an insecure resource 'http://mainnet-seed-0001.nkn.org:30003/'. This request has been blocked; the content must be served over HTTPS.

As my site works over https, i can't use the client library currently with the current seed nodes.
Is there an https seed node i can use?

I can proxy one of the seed nodes with nginx, but that only adds delays.
It would be highly preferred if NKN would provide a couple HTTPS nodes as well.

Cheers,
Mark

getSubscription from txPool

Hi,

Does client.getSubscription(topic, addr) have the capability of also fetching from the Tx pool, like getSubscribers does?

It isn't exposed as an option, and I thought asking was quicker than testing this time.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.