API & SDK

Useful links and info for devs that want to integrate the Klever Blockchain to their projects

JavaScript SDK

To build a web or Node.js application that communicates with the Klever Blockchain, use the Klever JavaScript SDK. It provides a unified API for browser dApps (via Klever Extension or mobile wallet) and backend services.

Klever Blockchain API

If you need more info on the Klever Blockchain APIs to interact directly with the blockchain, you can access the swagger documentation for the API endpoints through the following URLs:

Proxy API endpoints

Proxy API endpoints Swagger UI

Node API endpoints

Node API endpoints Swagger UI

Multi-Signature API

Create and handle transactions with multiple signatures accounts: MultiSig API Reference

WebSocket

Receive blocks, addresses and transactions from WebSocket: Websocket Reference

Checking the status of the transaction

When you broadcast a transaction, you will receive it's unique hash.

Take the hash 7b066e58b650d4ea6ba61de087350ddf909cfee660cc9537c0167b38df6d4882 for example.

You can either see the transaction details using the Klever Explorer or by calling one of the api endpoint's.

Using the proxy api call, you will receive the parsed transaction as response.

Using the node api call, you will receive the transaction as it is in the blockchain.

Using the explorer or the proxy api, you can check the status code of the transaction, if it matches the expected format it will be "success".

If, for some reason, your transaction was broadcast but doesn't appear in the proxy api or in the explorer, you can check its status in the node api. It will help you identify if the node that you used to broadcast the transaction is faulty.

Sending a transaction to the Klever Blockchain

Sending a transaction involves three steps: building, signing, and broadcasting.

Using the JavaScript SDK

The Klever JavaScript SDK handles all three steps automatically:

import { KleverProvider } from '@klever/connect-provider'
import { BrowserWallet } from '@klever/connect-wallet' // or NodeWallet for backend
import { parseKLV } from '@klever/connect-core'

const provider = new KleverProvider('mainnet')
const wallet = new BrowserWallet(provider)
await wallet.connect()

const result = await wallet.transfer({
  receiver: 'klv1receiver...',
  amount: parseKLV('10'),
})
console.log('Transaction hash:', result.hash)

See the Web App guide or Node.js guide for more examples.

Using the raw API

If you need to interact with the blockchain endpoints directly:

1. Build — POST to the /transaction/send endpoint and receive an unsigned transaction as response.

2. Sign — Use the Go SDK or the Node.js SDK to sign without exposing your private key in the browser.

3. Broadcast — POST the signed transaction to the /transaction/broadcast endpoint to be processed and validated by the blockchain.

Checking the status of the transaction

When you broadcast a transaction, you will receive it's unique hash.

Take the hash 7b066e58b650d4ea6ba61de087350ddf909cfee660cc9537c0167b38df6d4882 for example.

You can either see the transaction details using the Klever Explorer or by calling one of the api endpoint's.

Using the proxy api call, you will receive the parsed transaction as response.

Using the node api call, you will receive the transaction as it is in the blockchain.

Using the explorer or the proxy api, you can check the status code of the transaction, if it matches the expected format it will be "success".

If, for some reason, your transaction was broadcast but doesn't appear in the proxy api or in the explorer, you can check its status in the node api. It will help you identify if the node that you used to broadcast the transaction is faulty.

Multisig API reference

The Multisig API stores a transaction while its cosigners collect signatures. It does not broadcast on its own: once the collected weight reaches the permission threshold, the client calls POST /broadcast/{hash}. It is available at https://multisign.mainnet.klever.org and https://multisign.testnet.klever.org.

1. Create a transaction

  • Build the transaction with the node (POST /transaction/send) or with an SDK, using the multisig account as sender and a valid permissionID.
  • Send it to POST /transaction together with its hash. The hash is the transaction hash the node returns: the hex encoding of the 32-byte Blake2b-256 digest of RawData. The API recomputes it from the raw.RawData you send and rejects the request when they differ, so the raw data and the signatures are always bound to the same hash. A 0x prefix is not accepted.
  • The transaction is stored under its lower-case hash, which the response returns: {"status": "OK", "hash": "<lower-case hash>"}. Upper-case hex is accepted on every endpoint and converted to lower case.
  • The first request may carry no signatures: it creates the pending transaction, stored with the permission addresses and weights.

2. Add signatures

  • Each cosigner signs the hash with their key and sends it to the same POST /transaction endpoint, with the same hash and raw.RawData and their signature in raw.Signature.
  • Once the transaction is stored, every request must bring at least one new signature. Sending the signatures already collected together with yours is fine: the known ones are ignored and the new one is merged. A request that brings nothing new, whether it repeats stored signatures or carries none, is rejected.
  • The request is read from hash and raw only. address, signers and threshold in the body are ignored; which signers are marked as signed is decided from the signatures themselves.
  • You can list the transactions, and signers by hash or address.

3. Broadcast

  • When the weight of the collected signatures reaches the permission threshold, call POST /broadcast/{hash}. Before that, the request is rejected with transaction is not fully signed yet.
  • The transaction joins a queue per sender account and is sent to the network in nonce order. A 200 means it was queued; a temporary failure to reach the network is retried by the API and is not reported to the caller.
  • A hash that is not stored also returns 200 and does nothing. Check it with GET /transaction/{hash} first.

Delete a pending transaction

  • Any signer listed on the pending transaction can remove it with DELETE /transaction/{hash}, whether or not they have signed it yet. Deleting drops every signature collected so far.
  • The request must carry a delete proof: an ed25519 signature, by one of those signers, over Blake2b-256("klever-multisign:delete:" || hash), where hash is the 32 raw bytes of the transaction hash (not its hex). Send it as hex in the body: {"signature": "<hex>"}.
  • Pending Tron transactions cannot be deleted through the API; they are removed when broadcast or when they expire.

Example in Go. A Klever private key is the 32-byte ed25519 seed. A Klever PEM file holds 64 bytes, the seed followed by the public key, so the seed is its first 32 bytes; the Go SDK's PrivateKey() already returns the seed. ed25519.Sign needs the expanded key, so derive it with ed25519.NewKeyFromSeed first:

txHash, _ := hex.DecodeString(hashHex) // 32 bytes
msg := blake2b.Sum256(append([]byte("klever-multisign:delete:"), txHash...))
key := ed25519.NewKeyFromSeed(seed) // seed: 32 bytes (the first 32 of a PEM key)
signature := hex.EncodeToString(ed25519.Sign(key, msg[:]))
// DELETE /transaction/{hashHex} with body {"signature": signature}

Errors

Errors are returned as {"error": "<reason>"} unless the table says the body is empty.

EndpointStatusReason
POST /transaction400json: Error marshalling json (the body is not valid JSON), invalid transaction data: missing raw data, sender or contract, invalid transaction hash: must be the 32-byte hash of the raw data, invalid signature, address has already signed this transaction, permission id not found on sender account
POST /broadcast/{hash}400failed to validate request, invalid transaction hash: must be the 32-byte hash of the raw data, transaction is not fully signed yet, transaction nonce is lower than account nonce, another pending transaction with the same nonce already exists
GET /transaction/{hash}400failed to validate request, invalid transaction hash: must be the 32-byte hash of the raw data
GET /transaction/{hash}404No transaction is stored under this hash. Empty body.
GET /transaction/by-address/{address}400json: Error marshalling json (the address does not pass validation)
GET /transaction/by-address/{address}204No transaction is stored for this address. Empty body.
DELETE /transaction/{hash}400failed to validate request, invalid transaction hash: must be the 32-byte hash of the raw data, missing signature: sign the delete proof of the transaction hash with a listed signer's key, invalid signature (malformed, or not a delete proof by a listed signer), deleting a Tron transaction requires a signature scheme that is not supported yet
DELETE /transaction/{hash}404transaction not found
POST /transaction, POST /broadcast/{hash}500cannot find account in database: the sender account does not exist on chain. Retrying does not help; the account must exist (receive a transfer) first.
Any500The API could not reach its storage or the blockchain. The body carries the underlying error.

API Reference

Create a new transaction or add a signature

POST
https://multisign.mainnet.klever.org/transaction

Body example, in the shape the GET endpoints return. A POST is read from hash and raw only; address, signers and threshold are ignored on input and filled by the API.

{ "hash": "bd51a21cb8c364f5b1cc20e44684fe1163bc0767a7051dcd34095d77d010bf5e", "address": "klv1kvl993g53ktvyg5675etu3c5hzyd7hxu75y8kathev6wazpe2tgqxu7xhv", "signers": [ { "address": "klv1kvl993g53ktvyg5675etu3c5hzyd7hxu75y8kathev6wazpe2tgqxu7xhv", "weight": 1, "signed": true }, { "address": "klv1nk2v6udpmv6v8hhp9eyp99v68zrgzd95c2u6zt799qm7de4vfnjqnngs8x", "weight": 1, "signed": true } ], "threshold": 2, "raw": { "RawData": { "Nonce": 4, "Sender": "sz5SxRSNlsIimvUyvkcUuIjfXNz1CHt1d8s07og5UtA=", "Contract": [ { "Parameter": { "type_url": "type.googleapis.com/proto.TransferContract", "value": "CiBSrsW33uMB+HZ7BFuEhcvcr79J5B5IhKVPhgmHPaaLQxIDS0xWGICt4gQ=" } } ], "KAppFee": 500000, "BandwidthFee": 1000000, "Version": 1, "ChainID": "MTAwNDIw" }, "Signature": [ "MjztYUmxAYJr6BQRLvlYj5NPkQKhbViXVgqJ31cBnfKV76B69ZZQ61lyMnGGS7Be1UJgm0BvI1wKdSHVT8roDw==", "i9AIua688ler+Cgs8E6uZALZds3Dtp4UZOO0nTxzSQH2XG0z/fXVHO4e+0N4LJyv/1j3utKAetmTekUSVX1/DQ==" ], "hash": "YmQ1MWEyMWNiOGMzNjRmNWIxY2MyMGU0NDY4NGZlMTE2M2JjMDc2N2E3MDUxZGNkMzQwOTVkNzdkMDEwYmY1ZQ==" } }

Broadcast the transaction if the threshold was reached

POST
https://multisign.mainnet.klever.org/broadcast/{hash}

List a transaction by hash

GET
https://multisign.mainnet.klever.org/transaction/{hash}

List all transactions for an address

GET
https://multisign.mainnet.klever.org/transaction/by-address/{address}

Delete a pending transaction (requires a delete proof from a listed signer)

DELETE
https://multisign.mainnet.klever.org/transaction/{hash}

Websocket Reference

Here you will find a guide on establishing a connection to the Blockchain WebSocket client. This guide will walk you through the step-by-step process of connecting and receiving messages.

Important: You need to set up and run your own Klever node with the indexer option enabled to use WebSocket subscriptions.

For detailed instructions on setting up your indexer, see: How to Set Up Your Own Indexer

How to receive messages:

To connect to the Blockchain WebSocket client, follow these steps.

  1. Connect to the WebSocket URL.
  2. Establish a connection to it using a WebSocket library or framework of your choice.
  3. After successfully connecting, it's important to send an initial message to subscribe to the desired topics or a specific address or hash. This message should contain the necessary information for the server to understand your subscription preferences.
  4. Once subscribed, you will start receiving messages related to the subscribed topics or a specific address or hash.
package main

import (
	"encoding/json"
	"log"
	"net/url"

	"github.com/gorilla/websocket"
)

type EventType string

const (
	ACCOUNTS    EventType = "accounts"    // receive all accounts changed or created
	BLOCKS      EventType = "blocks"      // receive all blocks
	TRANSACTION EventType = "transaction" // receive all transactions
)

type Data struct {
	Types     []EventType `json:"subcribed_types"`
	Addresses []string    `json:"addresses"`
}

type Event struct {
	Type    EventType `json:"type"`
	Address string    `json:"address"`
	Hash    string    `json:"hash"`
	Data    []byte    `json:"data"`
}

func main() {
	// your indexer node
	u := url.URL{Scheme: "ws", Host: "127.0.0.1:8080", Path: "/subscribe"}
	log.Printf("connecting to %s", u.String())

	c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("dial:", err)
	}
	defer c.Close()

	done := make(chan struct{})

	go func() {
		defer close(done)
		for {
			_, message, err := c.ReadMessage()
			if err != nil {
				log.Println("read:", err)
				return
			}

			// marshal the message to Event struct
			var event Event
			if err := json.Unmarshal(message, &event); err != nil {
				log.Println("unmarshal:", err)
				return
			}

			switch event.Type {
			case BLOCKS:
				log.Println("Received BLOCKS data:", string(event.Data))
			case ACCOUNTS:
				log.Println("Received ACCOUNTS data:", string(event.Data))
			case TRANSACTION:
				log.Println("Received TRANSACTION data:", string(event.Data))
			default:
				log.Println("Unknown data ", string(message))
			}

		}
	}()

	subMessage := Data{
		Types: []EventType{BLOCKS, TRANSACTION, ACCOUNTS},
	}

	// send the first message to subscribe
	if err := c.WriteJSON(subMessage); err != nil {
		log.Println("err: ", err)
		done <- struct{}{}
	}

	<-done
}

import useWebSocket from 'react-use-websocket'

export enum WSTopics {
  accounts = 'accounts', // receive all accounts changed or created
  blocks = 'blocks', // receive all blocks
  transaction = 'transaction', // receive all transactions
}

const socketUrl = "ws://127.0.0.1:8080" // your indexer node

const { sendJsonMessage, lastJsonMessage } = useWebSocket(socketUrl, {
    onOpen: () => {
      const payload = {
        addresses: ["klv1...."], // OPTIONAL field to listen a specific address
        subcribed_types: [WSTopics.blocks],
      }
      sendJsonMessage(payload)
    }
})

Topics

TopicValue
BLOCKSblocks
TRANSACTIONStransactions
ACCOUNTSaccounts

Was this page helpful?