kinecosystem / kin-node

DEPRECATED! Please use Kinetic: https://developer.kin.org/docs/kinetic
https://developer.kin.org/docs/kinetic
MIT License
16 stars 14 forks source link

Deprecation Warning

Kins's Agora powered SDKs have been deprecated and Agora replaced with Kinetic.

Kinetic

Kinetic is an open-source suite of tools that make it easy to build apps that integrate Solana.

It provides a consistent and clean abstraction over the Solana SDKs and enhances it with some commonly requested features like paying Solana fees on behalf of the user, tracking and timing the users transactions and sending out webhooks.

Kinetic is aimed at developers that want to build crypto-experiences for the users of their app, hiding a lot of the details about the blockchain out of sight for both the developer and the end user.

Learn more about Kinetic here.

See our new suite of Kinetic SDK's here.

Kin Node SDK

The Kin Node SDK enables developers use Kin inside their backend servers. It contains support for blockchain actions such as creating accounts and sending payments, as well a webhook handler class to assist with implementing Agora webhooks. It is recommended that developers read the website documentation prior to using this SDK.

Requirements

Installation

npm install @kinecosystem/kin-sdk-v2
yarn add @kinecosystem/kin-sdk-v2

Note: stellar-base uses tweetnacl and sodium-native as dependencies. If sodium-native cannot be built, or is absent, stellar-base falls back to the slower tweetnacl. There are certain cases where sodium-native may have issues. Notably:

  1. Browser environments
  2. Serverless functions with tight package sizing. For example, AWS Lambda has a 50 MiB limit, and sodium-native takes up a majority of this space. Developers may wish to delete the sodium_native directory in node_modules/ to save space.

Overview

The SDK contains two main components: the Client and webhook handlers. The Client is used for blockchain actions, such as creating accounts sending payments, while the web hook handlers are meant for developers who wish to make use of Agora Webhooks. For a high-level overview of using Agora, please refer to the website documentation.

Client

The main component of this library is the Client class, which facilitates access to the Kin blockchain.

Initialization

At a minimum, the client needs to be instantiated with an Environment.

import {Client, Environment} from "@kinecosystem/kin-sdk-v2";
const client = new Client(Environment.Test);

Apps with registered app indexes should initialize the client with their index:

import {Client, Environment} from "@kinecosystem/kin-sdk-v2";
const client = new Client(Environment.Test, {
    appIndex: 1
});

Additional options include:

Usage

Create an Account

The createAccount method creates an account with the provided private key.

const privateKey = PrivateKey.random();
await client.createAccount(privateKey);

In addition to the mandatory key parameter, createAccount has the following optional parameters:

Get a Transaction

The getTransaction method gets transaction data by transaction id.

// txId is either a 32-byte Stellar transaction hash or a 64-byte Solana transaction signature
const txId = bs58.decode('<base58-encoded transaction signature>');  // solana transaction signature
const transactionData = await client.getTransaction(txId);

In addition to the mandatory txId parameter, getTransaction has the following optional parameters:

Get an Account Balance

The getBalance method gets the balance of the provided account, in quarks

const publicKey = PublicKey.fromString("");
const balance = await client.getBalance(publicKey);

In addition to the mandatory account parameter, getBalance has the following optional parameters:

Submit a Payment

The submitPayment method submits the provided payment to Agora.

const sender: PrivateKey;
const dest: PublicKey;

let txId = await client.submitPayment({
    sender: sender,
    destination: dest,
    type: TransactionType.Earn,
    quarks: kinToQuarks("1"),
});

A Payment has the following required properties:

Additionally, it has the following optional properties:

submitPayment also has the following optional parameters:

Submit an Earn Batch

The submitEarnBatch method submits a batch of earns to Agora from a single account. It batches the earns into fewer transactions where possible and submits as many transactions as necessary to submit all the earns.

const earns: Earn[] = [
    {
        destination: PublicKey.fromString("xx"),
        quarks: kinToQuarks("1"),
    },
    {
        destination: PublicKey.fromString("yy"),
        quarks: kinToQuarks("1"),
    }
];
const result = await client.submitEarnBatch({
    sender: sender,
    earns: earns,
})

A single Earn has the following properties:

An EarnBatch has the following parameters:

submitEarnBatch also has the following optional parameters:

Examples

A few examples for creating an account and different ways of submitting payments and batched earns can be found in examples/client.

Webhook Handlers

The SDK offers handler functions to assist developers with implementing the Agora webhooks.

Only apps that have been assigned an app index can make use of Agora webhooks.

Prerequisites

The handlers assume usage of the express framework, as the default http library does not offer much support for body reading, and middleware.

Usage

There are currently two handlers:

When configuring a webhook, a webhook secret can be specified.

Events Webhook

To consume events from Agora:

import { express, json } from "express";
import { Event, EventsHandler } from "@kinecosystem/kin-sdk-v2/webhook";

// Note: if no secret is provided to the handler, all requests will be processed.
//       otherwise, the request signature will be validated to ensure it came from agora.
const secret = "WEBHOOK_SECRET";

const app = express();

// json() properly reads the entire response body and transforms it into a
// object suitable for use by the EventsHandler.
app.use("/events", json());
app.use("/events", EventsHandler(events: []Event) => {
    // processing logic
}, secret),

Sign Transaction Webhook

The sign transaction webhook is used to sign Kin 3 transactions with a whitelisted Kin 3 account to remove fees. On Kin 4, the webhook can be used to simply approve or reject transactions submitted by mobile clients.

To verify and sign transactions related to your app:

import { express, json } from "express";
import {
    SignTransactionRequest,
    SignTransactionResponse,
    SignTransactionHandler,
} from "@kinecosystem/kin-sdk-v2/webhook";

// Note: if no secret is provided to the handler, all requests will be processed.
//       otherwise, the request signature will be validated to ensure it came from agora.
const secret = "WEBHOOK_SECRET";

const app = express();

// json() properly reads the entire response body and transforms it into a
// object suitable for use by the EventsHandler.
app.use("/sign_transaction", json());
app.use("/sign_transaction", SignTransactionHandler(req: SignTransactionRequest, resp: SignTransactionResponse) => {
    // decide whether or not to sign() or reject() the request.
}, secret),

Example Code

A simple example Express server implementing both the Events and Sign Transaction webhooks can be found in examples/webhook/webhook.tx. To run it, first install all required dependencies:

$ npm i
or
$ yarn install

Next, run it as follows from the root directory (it will run on port 8080):

export WEBHOOK_SECRET=yoursecrethere
export WEBHOOK_SEED=SXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

npx ts-node examples/webhook/webhook.ts