# NEXT SDK

The NEXT SDK allows you to integrate your dApps with the KUB Wallet, which provides native support for the KUB network. It offers various methods for managing user authentication, retrieving user information, and executing transactions on the blockchain. With the NEXT SDK, your dApps can integrate with the KUB Wallet authentication services and submit transactions directly on the network.

{% hint style="warning" %}
[Bitkub Blockchain Technology Co., Ltd.](https://bitkubblockchain.com/) is the sole party responsible for the operation and oversight of the NEXT SDK. Under no circumstances shall KUB Foundation be deemed to have any contractual or fiduciary obligation, nor any liability arising from the operation of the NEXT SDK.
{% endhint %}

## Prerequisites

Before installing or interacting with the NEXT SDK, we highly recommend generating the necessary keys, including the **Client ID** and **Project ID**.&#x20;

* For the KUB Testnet environment, visit the [KUB Playground](https://playground.kubchain.com/).&#x20;
* For the KUB Mainnet environment, enter your project details in this [form](https://forms.gle/paPJuF4JHZpKfRDj7), and we will contact you via email.

## Installation

To install the NEXT SDK, you can use npm, pnpm, or yarn.

{% tabs %}
{% tab title="npm" %}

```javascript
npm install @bitkub-chain/sdk.js
```

{% endtab %}

{% tab title="pnpm" %}

```javascript
pnpm install @bitkub-chain/sdk.js
```

{% endtab %}

{% tab title="yarn" %}

```javascript
yarn add @bitkub-chain/sdk.js
```

{% endtab %}
{% endtabs %}

## Initialization

To initialize the SDK, create `lib/bitkubchain-sdk/index.ts` at the root project with the `clientID` and `projectID`.

```javascript
import { initializeSDK, Network } from '@bitkub-chain/sdk.js';

const clientID = 'your-client-id';
const projectID = 'your-project-id';
const network = Network.BKC_TESTNET;
const initOpts = {
  loginRedirectPath: '/oauth/callback',
};

const sdk = initializeSDK(clientID, projectID, network, initOpts);
```

{% hint style="info" %}
Please declare your network as `Network.BKC_TESTNET` for KUB Testnet and `Network.BKC_MAINNET` for KUB Mainnet.
{% endhint %}

## Authentication

To begin with authentication, you must set up OAuth to allow your dApp to log in with KUB Wallet. The first step is to create `/oauth/callback` page, you can use the following code:

```javascript
import { useEffect } from 'react'
import { sdk } from '@lib/bitkubchain-sdk'

export default function Page() {
  useEffect(() => {
    const code = new URLSearchParams(window.location.search).get('code')
    if (code) {
      exchange(code)
    }
  }, [])

  const exchange = async (code: string) => {
    await sdk.exchangeAuthorizationCode(code)
    window.close()
  }

  return (
    <div>
      <h2>Callback Page</h2>
      <p>Exchanging code for tokens...</p>
    </div>
  )
}
```

### Redirect URI

You can visit the [KUB Playground](https://playground.kubchain.com/) to configure your redirect URI for your dApp.

If you have not specified a `loginRedirectPath`, the default redirect URI will be `/oauth/callback`. You should configure it as follows:

```url
http://your-application-domain.com/oauth/callback
```

If you have specified a custom `loginRedirectPath`, update your redirect UI as follows:

```url
http://your-application-domain.com/your-custom-loginRedirectPath
```

### Login

Opens a login window for KUB Wallet.

```javascript
await sdk.loginWithBitkubNext();
```

### **Logout**

Logs out the current user.

```javascript
await sdk.logout();
```

### Exchange Authorization Code

Exchanges the OAuth code for access and refresh tokens.

```javascript
const code = 'authorizationCode';
await sdk.exchangeAuthorizationCode(code);
```

## User Information

### Get User Information

Returns an object containing user details.

```javascript
const userInfo = await sdk.getUserInfo();
```

### **Get Wallet Address**

Fetches the user's wallet address.

```javascript
const walletAddress = await sdk.getUserWalletAddress();
```

### Get Phone Number

Fetches the user's phone number.

```javascript
const tel = await sdk.getUserTel();
```

### **Get Email**

Fetches the user's email address.

```javascript
const email = await sdk.getUserEmail();
```

### **Get User ID**

Fetches the user's unique ID.

```javascript
const userID = await sdk.getUserID();
```

## Balances

### Native Balance

Returns the user's native balance in *wei*.

```javascript
const balance = await sdk.getBalanceNative();
```

{% hint style="info" %}
If the network is `Network.BKC_MAINNET` or `Network.BKC_TESTNET`, KKUB balance will be returned. Otherwise, the native currency of the network will be returned.
{% endhint %}

### KAP-20 Token Balance

Returns the balance of a specific KAP-20 token in *wei*.

```javascript
const balance = await sdk.getBalance20(tokenAddress);
```

### **KAP-721 Token Balance**

Returns the number of KAP-721 tokens owned by the user.

```javascript
const balance = await sdk.getBalance721(tokenAddress);
```

### **KAP-1155 Token Balance**

Returns the quantity of a specific KAP-1155 token owned by the user.

```javascript
const balance = await sdk.getBalance1155(tokenAddress, tokenID);
```

## Token Approval and Transfers

Users must approve an allowance before transferring KAP-20 to ensure that only authorized smart contracts can spend their tokens, preventing unauthorized access and protecting their assets.

### Get Token Allowance

Gets the current token allowance for a given spender in *wei*.

```javascript
const allowanceAmount = await sdk.getAllowanceToken(tokenAddress, spenderAddress);
```

### Approve Token

Approves a spender to use a specified amount of tokens.

```javascript
const result = await sdk.approveToken(tokenAddress, amount, spenderAddress);
```

### **Transfer Native Token**

Transfers native KUB to a recipient.

```javascript
const result = await sdk.transferNative(toAddress, amount);
```

### **Transfer KAP-20 Token**

Transfers a specified KAP-20 token to a recipient.

```javascript
const result = await sdk.transfer20(tokenAddress, toAddress, amount);
```

## NFT Approval and Transfers

Users must approve before transferring NFTs to ensure that only authorized smart contracts can send their NFTs, preventing unauthorized access and protecting their assets.

### NFT Approval

Checks if a given operator is approved for the user's NFT.

```javascript
const isApprovedNFT = await sdk.getIsApprovedNFT(tokenAddress, operatorAddress);
```

### Approve NFT

Grants approval to an operator to manage the user's NFT.

```javascript
const result = await sdk.approveNFT(tokenAddress, operatorAddress);
```

### Transfer KAP-721 Token

Transfers a KAP-721 token to a recipient.

```javascript
const result = await sdk.transfer721(tokenAddress, toAddress, tokenID);
```

### **Transfer KAP-1155 Token**

Transfers a quantity of a KAP-1155 token to a recipient.

```javascript
const result = await sdk.transfer1155(tokenAddress, toAddress, tokenID, amount);
```

## Custom Transaction

Sends a custom smart contract transaction using human-readable ABI and parameters.

```javascript
const result = await sdk.sendCustomTx(toAddress, functionReadableABI, methodParams);
```

## Fetch Transaction Details

Returns the details of a submitted transaction using its queue ID.

```javascript
const details = await sdk.getTransactionDetails(queueId);
```

## Smart Contract Design for NEXT SDK

To allow KUB Wallet users to write data on a smart contract, you need to design the smart contract with additional functions. The additional functions are called through the **CallHelper** smart contract to execute commands on behalf of the KUB Wallet users. The function must also use an extra `address _bitkubNext` parameter at the end of the function.

### Example

This function for buying an NFT requires 2 parameters, which are `_recipeIndex` and `_amount`. MetaMask or other wallets can call this function to buy an NFT.

```solidity
function buyNft(uint256 _recipeIndex, uint256 _amount) external
```

The function must use an extra `address _bitkubNext` parameter at the end of the function to allow KUB Wallet users to call this function to buy an NFT.

```solidity
function buyNft(uint256 _recipeIndex, uint256 _amount, address _bitkubNext) external onlySdkCallHelperRouter
```

You can now apply the human-readable ABI when you are calling the NEXT SDK for your custom transaction.

```javascript
const functionReadableABI = "buyNft(uint256 _recipeIndex, uint256 _amount, address _bitkubNext)"
const methodParams = [1, 1]
```

### SDK CallHelper Router

When an end user invokes a function through the SDK library, the `msg.sender` interaction with your smart contract will be `sdkCallHelperRouter`. To ensure that only authorized calls are made to this function, you must include a modifier to check that `msg.sender` equals `sdkCallHelperRouter`.

### Example Modifier

```solidity
modifier onlySdkCallHelperRouter() {
   require(msg.sender == sdkCallHelperRouter, "Authorization: restricted only SDK CallHelper Router");
   _;
}
```

{% hint style="warning" %}
Confirm that the address of the `sdkCallHelperRouter` for `Network.BKC_TESTNET` is `0x96f4C25E4fEB02c8BCbAdb80d0088E0112F728Bc`.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.kubchain.com/build-on-kub/libraries-and-sdks/next-sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
