0.6.3 • Published 4 months ago

@wishknish/knishio-client-js v0.6.3

Weekly downloads
115
License
GPL-3.0-or-later
Repository
github
Last release
4 months ago

Knish.IO Javascript Client SDK

This is the official Javascript / NodeJS implementation of the Knish.IO client SDK. Its purpose is to expose class libraries for building and signing Knish.IO Molecules, composing Atoms, generating Wallets, and much more.

Installation

The SDK can be installed via either of the following:

  1. yarn add @wishknish/knishio-client-js

  2. npm install @wishknish/knishio-client-js --save

(Note: For installations in a Vite-based environment, you will need to install the https://www.npmjs.com/package/vite-plugin-node-polyfills plugin to ensure compatibility with Node.js libraries.)

Basic Usage

The purpose of the Knish.IO SDK is to expose various ledger functions to new or existing applications.

There are two ways to take advantage of these functions:

  1. The easy way: use the KnishIOClient wrapper class

  2. The granular way: build Atom and Molecule instances and broadcast GraphQL messages yourself

This document will explain both ways.

The Easy Way: KnishIOClient Wrapper

  1. Include the wrapper class in your application code:

    import { KnishIOClient } from '@wishknish/knishio-client-js'
  2. Instantiate the class with your node URI:

    const client = new KnishIOClient({
      uri: myNodeURI,
      cellSlug: myCellSlug,
      serverSdkVersion: 3, // Optional, defaults to 3
      logging: false // Optional, enables logging
    });
  3. Request authorization token from the node:

    await client.requestAuthToken({
      seed: 'myTopSecretCode',
      encrypt: true // Optional, enables encryption
    });

    (Note: The seed parameter can be a salted combination of username + password, a biometric hash, an existing user identifier from an external authentication process, for example)

  4. Begin using client to trigger commands described below...

KnishIOClient Methods

  • Query metadata for a Wallet Bundle. Omit the bundle parameter to query your own Wallet Bundle:

    const result = await client.queryBundle({
      bundle: 'c47e20f99df190e418f0cc5ddfa2791e9ccc4eb297cfa21bd317dc0f98313b1d',
    });
    
    console.log(result); // Raw Metadata
  • Query metadata for a Meta Asset:

    const result = await client.queryMeta({
      metaType: 'Vehicle',
      metaId: null, // Meta ID
      key: 'LicensePlate',
      value: '1H17P',
      latest: true, // Limit meta values to latest per key
      throughAtom: true // Optional, query through Atom (default: true)
    });
    
    console.log(result); // Raw Metadata
  • Writing new metadata for a Meta Asset:

    const result = await client.createMeta({
      metaType: 'Pokemon',
      metaId: 'Charizard',
      meta: {
        type: 'fire',
        weaknesses: [
          'rock',
          'water',
          'electric'
        ],
        immunities: [
          'ground',
        ],
        hp: 78,
        attack: 84,
      },
      policy: {} // Optional policy object
    });
    
    if (result.success()) {
      // Do things!
    }
    
    console.log(result.data()); // Raw response
  • Query Wallets associated with a Wallet Bundle:

    const result = await client.queryWallets({
      bundle: 'c47e20f99df190e418f0cc5ddfa2791e9ccc4eb297cfa21bd317dc0f98313b1d',
      token: 'FOO', // Optional, filter by token
      unspent: true // Optional, limit results to unspent wallets
    });
    
    console.log(result); // Raw response
  • Declaring new Wallets:

    (Note: If Tokens are sent to undeclared Wallets, Shadow Wallets will be used (placeholder Wallets that can receive, but cannot send) to store tokens until they are claimed.)

    const result = await client.createWallet({
      token: 'FOO' // Token Slug for the wallet we are declaring
    });
    
    if (result.success()) {
      // Do things!
    }
    
    console.log(result.data()); // Raw response
  • Issuing new Tokens:

    const result = await client.createToken({
      token: 'CRZY', // Token slug (ticker symbol)
      amount: '100000000', // Initial amount to issue
      meta: {
        name: 'CrazyCoin', // Public name for the token
        fungibility: 'fungible', // Fungibility style (fungible / nonfungible / stackable)
        supply: 'limited', // Supply style (limited / replenishable)
        decimals: '2' // Decimal places
      },
      units: [], // Optional, for stackable tokens
      batchId: null // Optional, for stackable tokens
    });
    
    if (result.success()) {
      // Do things!
    }
    
    console.log(result.data()); // Raw response
  • Transferring Tokens to other users:

    const result = await client.transferToken({
      bundleHash: '7bf38257401eb3b0f20cabf5e6cf3f14c76760386473b220d95fa1c38642b61d', // Recipient's bundle hash
      token: 'CRZY', // Token slug
      amount: '100',
      units: [], // Optional, for stackable tokens
      batchId: null // Optional, for stackable tokens
    });
    
    if (result.success()) {
      // Do things!
    }
    
    console.log(result.data()); // Raw response
  • Creating a new Rule:

    const result = await client.createRule({
      metaType: 'MyMetaType',
      metaId: 'MyMetaId',
      rule: [
        // Rule definition
      ],
      policy: {} // Optional policy object
    });
    
    if (result.success()) {
      // Do things!
    }
    
    console.log(result.data()); // Raw response
  • Querying Atoms:

    const result = await client.queryAtom({
      molecularHash: 'hash',
      bundleHash: 'bundle',
      isotope: 'V',
      tokenSlug: 'CRZY',
      latest: true,
      queryArgs: {
        limit: 15,
        offset: 1
      }
    });
    
    console.log(result.data()); // Raw response
  • Working with Buffer Tokens:

    // Deposit to buffer
    const depositResult = await client.depositBufferToken({
      tokenSlug: 'CRZY',
      amount: 100,
      tradeRates: {
        'OTHER_TOKEN': 0.5
      }
    });
    
    // Withdraw from buffer
    const withdrawResult = await client.withdrawBufferToken({
      tokenSlug: 'CRZY',
      amount: 50
    });
    
    console.log(depositResult.data(), withdrawResult.data()); // Raw responses
  • Getting client fingerprint:

    const fingerprint = await client.getFingerprint();
    console.log(fingerprint);
    
    const fingerprintData = await client.getFingerprintData();
    console.log(fingerprintData);

Advanced Usage: Working with Molecules

For more granular control, you can work directly with Molecules:

  • Create a new Molecule:

    const molecule = await client.createMolecule();
  • Create a custom Mutation:

    const mutation = await client.createMoleculeMutation({
      mutationClass: MyCustomMutationClass
    });
  • Sign and check a Molecule:

    molecule.sign();
    if (!molecule.check()) {
      // Handle error
    }
  • Execute a custom Query or Mutation:

    const result = await client.executeQuery(myQueryOrMutation, variables);

The Hard Way: DIY Everything

This method involves individually building Atoms and Molecules, triggering the signature and validation processes, and communicating the resulting signed Molecule mutation or Query to a Knish.IO node via your favorite GraphQL client.

  1. Include the relevant classes in your application code:

    import { Molecule, Wallet, Atom } from '@wishknish/knishio-client-js'
  2. Generate a 2048-symbol hexadecimal secret, either randomly, or via hashing login + password + salt, OAuth secret ID, biometric ID, or any other static value.

  3. (optional) Initialize a signing wallet with:

    const wallet = new Wallet({
      secret: mySecret,
      token: tokenSlug,
      position: myCustomPosition, // (optional) instantiate specific wallet instance vs. random
      characters: myCharacterSet // (optional) override the character set used by the wallet
    })

    WARNING 1: If ContinuID is enabled on the node, you will need to use a specific wallet, and therefore will first need to query the node to retrieve the position for that wallet.

    WARNING 2: The Knish.IO protocol mandates that all C and M transactions be signed with a USER token wallet.

  4. Build your molecule with:

    const molecule = new Molecule({
      secret: mySecret,
      sourceWallet: mySourceWallet, // (optional) wallet for signing
      remainderWallet: myRemainderWallet, // (optional) wallet to receive remainder tokens
      cellSlug: myCellSlug, // (optional) used to point a transaction to a specific branch of the ledger
      version: 4 // (optional) specify the molecule version
    });
  5. Either use one of the shortcut methods provided by the Molecule class (which will build Atom instances for you), or create Atom instances yourself.

    DIY example:

    // This example records a new Wallet on the ledger
    
    // Define metadata for our new wallet
    const newWalletMeta = {
      address: newWallet.address,
      token: newWallet.token,
      bundle: newWallet.bundle,
      position: newWallet.position,
      batchId: newWallet.batchId,
    }
    
    // Build the C isotope atom
    const walletCreationAtom = new Atom({
      position: sourceWallet.position,
      walletAddress: sourceWallet.address,
      isotope: 'C',
      token: sourceWallet.token,
      metaType: 'wallet',
      metaId: newWallet.address,
      meta: newWalletMeta,
      index: molecule.generateIndex()
    })
    
    // Add the atom to our molecule
    molecule.addAtom(walletCreationAtom)
    
    // Adding a ContinuID / remainder atom
    molecule.addContinuIdAtom();

    Molecule shortcut method example:

    // This example commits metadata to some Meta Asset
    
    // Defining our metadata
    const metadata = {
      foo: 'Foo',
      bar: 'Bar'
    }
    
    molecule.initMeta({
      meta: metadata,
      metaType: 'MyMetaType',
      metaId: 'MetaId123',
      policy: {} // Optional policy object
    });
  6. Sign the molecule with the stored user secret:

    molecule.sign()
  7. Make sure everything checks out by verifying the molecule:

    try {
      molecule.check();
      // If we're validating a V isotope transaction,
      // add the source wallet as a parameter
      molecule.check(sourceWallet);
    } catch (error) {
      console.error('Molecule check failed:', error);
      // Handle the error
    }
  8. Broadcast the molecule to a Knish.IO node:

    // Build our query object using the KnishIOClient wrapper
    const mutation = await client.createMoleculeMutation({
      mutationClass: MutationProposeMolecule,
      molecule: molecule
    });
    
    // Send the query to the node and get a response
    const response = await client.executeQuery(mutation);
  9. Inspect the response...

    // For basic queries, we look at the data property:
    console.log(response.data())
    
    // For mutations, check if the molecule was accepted by the ledger:
    console.log(response.success())
    
    // We can also check the reason for rejection
    console.log(response.reason())
    
    // Some queries may also produce a payload, with additional data:
    console.log(response.payload())

    Payloads are provided by responses to the following queries:

    1. QueryBalance and QueryContinuId -> returns a Wallet instance
    2. QueryWalletList -> returns a list of Wallet instances
    3. MutationProposeMolecule, MutationRequestAuthorization, MutationCreateIdentifier, MutationLinkIdentifier, MutationClaimShadowWallet, MutationCreateToken, MutationRequestTokens, and MutationTransferTokens -> returns molecule metadata

Getting Help

Knish.IO is under active development, and our team is ready to assist with integration questions. The best way to seek help is to stop by our Telegram Support Channel. You can also send us a contact request via our website.

0.6.3

4 months ago

0.6.2

4 months ago

0.6.1

4 months ago

0.6.0

5 months ago

0.4.42

3 years ago

0.4.43

3 years ago

0.4.48

3 years ago

0.4.46

3 years ago

0.4.47

3 years ago

0.4.44

3 years ago

0.4.45

3 years ago

0.5.0

3 years ago

0.5.2

3 years ago

0.5.1

3 years ago

0.4.40

3 years ago

0.4.41

3 years ago

0.4.31

4 years ago

0.4.32

4 years ago

0.4.30

4 years ago

0.4.39

3 years ago

0.4.37

3 years ago

0.4.38

3 years ago

0.4.35

4 years ago

0.4.36

3 years ago

0.4.33

4 years ago

0.4.34

4 years ago

0.4.28

4 years ago

0.4.29

4 years ago

0.4.27

4 years ago

0.4.26

4 years ago

0.4.25

4 years ago

0.4.24

4 years ago

0.4.22

4 years ago

0.4.23

4 years ago

0.4.21

4 years ago

0.4.20

4 years ago

0.4.19

4 years ago

0.4.17

4 years ago

0.4.18

4 years ago

0.4.15

4 years ago

0.4.16

4 years ago

0.4.14

4 years ago

0.4.13

4 years ago

0.4.11

4 years ago

0.4.12

4 years ago

0.4.10

4 years ago

0.4.9

4 years ago

0.4.8

4 years ago

0.4.7

4 years ago

0.4.6

4 years ago

0.4.5

4 years ago

0.4.4

4 years ago

0.4.3

4 years ago

0.4.2

4 years ago

0.3.34

4 years ago

0.3.33

4 years ago

0.3.32

4 years ago

0.3.31

4 years ago

0.3.30

4 years ago

0.4.1-staging

4 years ago

0.4.0-staging

4 years ago

0.3.29

4 years ago

0.3.28

4 years ago

0.3.27

4 years ago

0.3.26

5 years ago

0.3.25

5 years ago

0.3.24

5 years ago

0.3.23

5 years ago

0.3.22

5 years ago

0.3.21

5 years ago

0.3.20

5 years ago

0.3.19

5 years ago

0.3.18

5 years ago

0.3.17

5 years ago

0.3.16

5 years ago

0.3.15

5 years ago

0.3.14

5 years ago

0.3.13

5 years ago

0.3.12

5 years ago

0.3.11

5 years ago

0.3.10

5 years ago

0.3.8

5 years ago

0.3.9

5 years ago

0.3.7

5 years ago

0.3.6

5 years ago

0.3.5

5 years ago

0.3.4

5 years ago

0.3.3

5 years ago

0.3.2

5 years ago

0.3.1

5 years ago

0.3.0

5 years ago

0.2.0

5 years ago

0.1.64

5 years ago

0.1.63

5 years ago

0.1.62

5 years ago

0.1.61

5 years ago

0.1.56

6 years ago

0.1.55

6 years ago

0.1.54

6 years ago

0.1.53

6 years ago

0.1.52

6 years ago

0.1.51

6 years ago

0.1.50

6 years ago

0.1.29

6 years ago

0.1.28

6 years ago

0.1.27

6 years ago

0.1.26

6 years ago

0.1.25

6 years ago

0.1.24

6 years ago

0.1.23

6 years ago

0.1.22

6 years ago

0.1.21

6 years ago

0.1.20

6 years ago

0.1.19

6 years ago

0.1.18

6 years ago

0.1.17

6 years ago

0.1.16

6 years ago

0.1.15

6 years ago

0.1.14

6 years ago

0.1.13

6 years ago

0.1.12

6 years ago

0.1.11

6 years ago

0.1.10

6 years ago

0.1.9

6 years ago

0.1.8

6 years ago

0.1.7

6 years ago

0.1.6

6 years ago

0.1.5

6 years ago

0.1.4

6 years ago

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago