How to use KleverChain SDK

Getting started with the KleverChain SDK

Basic usage

There are two ways to make a contract call: you can call only one method passing the user data plus the contract data or you can create an instance of an account.

Sender address and private key is required in all transactions.

With a simple call:

import { sendTransaction, TransactionType } from "@klever/sdk";

const transactionType = TransactionType.Transfer;
const transactionPayload = {
  sender: "address",
  privateKey: "privateKey",
  receiver: "receiver",
  amount: 100,
};

sendTransaction(transactionType, transactionPayload);

With an account instance:

import { Account } from "@klever/sdk";

const account = new Account("address", "privateKey");
const transactionPayload = {
  receiver: "receiver",
  amount: 100,
};

account.sendTransfer(transactionPayload);

Transactions

All available transactions:

IDType

0

Transfer

1

Create Asset

2

Create Validator

3

Validator Config

4

Freeze

5

Unfreeze

6

Delegate

7

Undelegate

8

Withdraw

9

Claim

10

Unjail

11

Asset Trigger

12

Set Account Name

13

Proposal

14

Vote

15

Config ITO Prices

16

Set ITO Prices

17

Buy

18

Sell

19

Cancel Market Order

20

Create Marketplace

21

Config Marketplace

22

Update Account Permission

Usage Inside a Context

If you want a global instance of your account to use throughout your app, you can create a custom hook to help you with that.

Using React as an example, you can create a MyCustomHook.tsx file and create your provider as follows:

import { useState, createContext, useContext } from 'react';
import { Account, core } from '@klever/sdk';

interface ISdkContext {
  isLoaded(): Promise<boolean>;
  getAccount(): Account | null;
  setAccount(account: Account): void;
}

const SdkContext = createContext({} as ISdkContext);

const SdkProvider: React.FC = ({ children }) => {
  const [acc, setAcc] = useState<Account | null>(null);

  const values: ISdkContext = {
    isLoaded: () => core.isSDKLoaded(),
    getAccount: () => acc,
    setAccount: account => setAcc(account),
  };
  return <SdkContext.Provider value={values}>{children}</SdkContext.Provider>;
};

const useSdk = () => useContext(SdkContext);

export { SdkContext, SdkProvider, useSdk };

And wrap your entire App.tsx in it:

import { SdkProvider } from './MyCustomHook';
...
  <SdkProvider>
    ...
  </SdkProvider>
...

With that, you can use it on any child component you want, without the need to instantiate an account every time:

import { useSdk } from './MyCustomHook';
...
const sdk = useSdk();
const account = sdk.getAccount();
...
await account.sendTransfer(payload)
...

The same pattern of global provider can be achieved in any framework you want, not only React.

Last updated