@bitkub-chain/sdk.js
v0.1.6
Published
**BitkubNextSDK** is a JavaScript library designed for developers to interact with the Bitkub Chain blockchain network. It offers various methods for managing user authentication, retrieving user information, and executing transactions on the blockchain.
Downloads
88
Readme
BitkubNextSDK
BitkubNextSDK is a JavaScript library designed for developers to interact with the Bitkub Chain blockchain network. It offers various methods for managing user authentication, retrieving user information, and executing transactions on the blockchain.
⚙️ Installation
To install the BitkubNextSDK, use npm, pnpm, or yarn:
npm install @bitkub-chain/sdk.js
or
pnpm install @bitkub-chain/sdk.js
or
yarn add @bitkub-chain/sdk.js
📝 Initialization
To initialize the SDK, use the initializeSDK function:
You can generate clientID
and projectID
in Bitkub Chain Playground
Create lib/bitkubchain-sdk/index.ts
at root project to initialze SDK
import { initializeSDK, Network } from '@bitkub-chain/sdk.js';
const clientID = 'your-client-id';
const projectID = 'your-project-id';
const network = Network.BKC_TESTNET; // or Network.BKC_MAINNET will comming soon
const initOpts = {
/**
* @default '/oauth/callback'
*/
loginRedirectPath: '/oauth/callback',
};
const sdk = initializeSDK(clientID, projectID, network, initOpts);
🔐 Authentication
First of all, to login with Bitkub NEXT, you have to set up Oauth first: It is the path on the client application’s URL where the authorization server will redirect the user after they have granted or denied access.
- Create
/oauth/callback
page
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>
)
}
- Navigate to the Bitkub Chain Playground and locate the Edit Client ID section to set up your redirect URIs.
Example:
- Default Redirect URI: If you haven’t specified a
loginRedirectPath
, the default redirect URI will be/oauth/callback.
You should configure it as follows:
http://localhost:3000/oauth/callback // For Development Purpose
https://your-application-domain-here.com/oauth/callback
- Custom Redirect URI: If you have specified a custom
loginRedirectPath
, update your redirect URI to match this path:
http://localhost:3000/your-custom-loginRedirectPath // For Development Purpose
https://your-application-domain-here.com/your-custom-loginRedirectPath
🎉 Now you should be able to login with BitkubNext. 🎉
Login
To open a BitkubNext login window:
await sdk.loginWithBitkubNext();
Logout
To log out the user:
await sdk.logout();
Exchange Authorization Code
To exchange the authorization code for access and refresh tokens:
const code = 'authorizationCode';
await sdk.exchangeAuthorizationCode(code);
User Information
Get User Info To fetch the user's information:
const userInfo = await sdk.getUserInfo();
Example Response
const userInfo = {
id: "64c30c0468b02b001c7629a4",
clientId: "65bc5c4560686a001bda94dc",
email: "[email protected]",
phone: "+66123456789",
status: "ACTIVE",
walletAddress: "0x1234567890abcdef1234567890abcdef12345678",
}
Get User Wallet Address
To fetch the user's wallet address:
const walletAddress = await sdk.getUserWalletAddress();
// 0x1234567890abcdef1234567890abcdef12345678
Get User Telephone Number
To fetch the user's telephone number:
const tel = await sdk.getUserTel();
// +661234567890
Get User Email
To fetch the user's email address:
const email = await sdk.getUserEmail();
// [email protected]
Get User ID
To fetch the user's ID:
const userID = await sdk.getUserID();
// 65c30c0469a02b001c7629b1
💰 Balances
| Property | Description | Type | Example |
| ------------ | ------------------------------------- | ------------ | -------------------------------------------- |
| tokenAddress | The address of the token contract | string | 0x67eBD850304c70d983B2d1b93ea79c7CD6c3F6b5
|
| tokenID | The ID of the specific token or asset | BigNumberish | 1 |
Get Native Balance
📌 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.
const balance = await sdk.getBalanceNative();
// 1000000000000000000
💡 How to get KKUB
- KKUB Contract Address in
Network.BKC_TESTNET
: 0x1BbE34CF9fd2E0669deEE34c68282ec1e6c44ab0- Request KUB Native coin from Faucet Here
- Wrap KUB Native coin using
deposit
method Here
Get ERC-20 Token Balance
To fetch an ERC-20 token's balance (in Wei):
const balance = await sdk.getBalance20(tokenAddress);
// 1000000000000000000
Get ERC-721 Token Balance
To fetch an ERC-721 token's balance:
const balance = await sdk.getBalance721(tokenAddress);
// 10
Get ERC-1155 Token Balance
To fetch an ERC-1155 token's balance:
const balance = await sdk.getBalance1155(tokenAddress, tokenID);
// 10
📤 Transactions
Property
| Property | Description | Type | Example |
| ------------------- | --------------------------------------------- | ------------ | -------------------------------------------------------------------- |
| tokenAddress | The address of the token contract | string | 0x67eBD850304c70d983B2d1b93ea79c7CD6c3F6b5
|
| toAddress | The address of the recipient | string | 0x1234567890abcdef1234567890abcdef12345678
|
| amount | The amount of tokens to be transferred in wei | BigNumberish | 1 Ether = 1000000000000000000
|
| tokenID | The ID of the specific token or asset | BigNumberish | 1 |
| functionReadableABI | The human-readable format of the function ABI | string | buyNft(uint256 _recipeIndex, uint256 _amount, address _bitkubNext)
|
| methodParams | The parameters used in the method call | Array | [1, 1]
|
SubmitTransactionResponse
The SubmitTransactionResponse
type represents the response structure for submitting a transaction. Here's a breakdown of its properties:
| Property | Type | Description |
| -------------------- | ------------------------- | ------------------------------------------------------------- |
| approvalExpireTime
| number
| The expiration time of the approval in Unix timestamp format. |
| approvalStatus
| 'pending' \| 'approved'
| The current status of the approval. |
| approvalUrl
| string
| The URL to approve the transaction. |
| queueId
| string
| The unique identifier for the transaction queue. |
Response
const result = {
approvalExpireTime: 1697740800,
approvalStatus: "pending",
approvalUrl: "https://example.com/approve",
queueId: "648abd81663ss"
}
Transfer Token
📌 Approval Token
Users must approve an allowance before transferring KAP20 to ensure that only authorized smart contracts can spend their tokens, preventing unauthorized access and protecting their assets.
Property
| Property | Description | Type | Example | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | --------------------------------------------- | | tokenAddress | The address of the token contract | string |
0x67eBD850304c70d983B2d1b93ea79c7CD6c3F6b5
| | amount | The allowance amount (in Wei) authorizes a smart contract to spend a specified number of your tokens on your behalf. | BigNumberish | 1 Ether =1000000000000000000
| | spenderAddress | (Optional) If transfer usingtransferNative
ortransfer20
, ignore this property. The address of a smart contract or user that has been granted permission to spend tokens on behalf of another address. | string |0x123eCF850304c70d983B2d1b93ea79c7CD6c3H6b7
|Get Approve Token Allowance
const allowanceAmount = await sdk.getAllowanceToken(tokenAddress, spenderAddress); // 1000000000000000000
Approve Token
const result = await sdk.approveToken(tokenAddress, amount, spenderAddress);
Now you should be able to transfer KAP20 (including Native)
Transfer Native Token
const result = await sdk.transferNative(toAddress, amount);
Transfer ERC-20 Token
const result = await sdk.transfer20(tokenAddress, toAddress, amount);
Transfer NFT
📌 Approval NFT
Users must approve before transferring NFT to ensure that only authorized smart contracts can send their NFT, preventing unauthorized access and protecting their assets.
Property
| Property | Description | Type | Example | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------ | --------------------------------------------- | | tokenAddress | The address of the token contract | string |
0x67eBD850304c70d983B2d1b93ea79c7CD6c3F6b5
| | operatorAddress | (Optional) If transfer usingtransfer721
ortransfer1155
, ignore this property. The address of a smart contract or user that has been granted permission to send NFT on behalf of another address. | string |0x123eCF850304c70d983B2d1b93ea79c7CD6c3H6b7
|Get Is Approved NFT
const isApprovedNFT = await sdk.getIsApprovedNFT(tokenAddress, operatorAddress); // true/false
Approve NFT
const result = await sdk.approveNFT(tokenAddress, operatorAddress);
Now you should be able to transfer NFT
Transfer ERC-721 Token
const result = await sdk.transfer721(tokenAddress, toAddress, tokenID);
Transfer ERC-1155 Token
const result = await sdk.transfer1155(tokenAddress, toAddress, tokenID, amount);
Send Custom Transaction
const result = await sdk.sendCustomTx(toAddress, functionReadableABI, methodParams);
To sendCustomTx via SDK
const functionReadableABI = "buyNft(uint256 _recipeIndex, uint256 _amount, address _bitkubNext)"
const methodParams = [1, 1]
const result = await sdk.sendCustomTx("0x1234567890abcdef1234567890abcdef12345678", functionReadableABI, methodParams);
💡 How to write Smart Contract for Bitkub Next
To allow the Bitkub NEXT user can writing the data on the Smart Contract. The developers need to design the Smart Contract with the additional functions. The additional functions is called through the CallHelper Smart Contract to execute commands on behalf of Bitkub NEXT users, and the function must take the bitkubnext address parameter at the end of the function
Here is an example demonstrating how to structure these functions:
// Function that can be called by any user ❌ function buyNft(uint256 _recipeIndex, uint256 _amount) external { // Metamask or other wallets call this function to buy an NFT } // Function that can only be called by BitkubNEXT ✅ function buyNft(uint256 _recipeIndex, uint256 _amount, address _bitkubNext) external onlySdkCallHelperRouter { // BtikubNEXT call this function to buy an NFT } // Usage const functionReadableABI = "buyNft(uint256 _recipeIndex, uint256 _amount, address _bitkubNext)" const methodParams = [1, 1] // Do not have to add `address _bitkubNext` param because SDK will automatically add for you
📌 Important Notes
- Authorization via sdkCallHelperRouter: When an end user invokes a function through the SDK library, the msg.sender interacting 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.
- The address of the sdkCallHelperRouter in
Network.BKC_TESTNET
:0x96f4C25E4fEB02c8BCbAdb80d0088E0112F728Bc
Here is an example demonstrating how to write a modifier:
modifier onlySdkCallHelperRouter() { require(msg.sender == sdkCallHelperRouter, "Authorization: restricted only sdk call helper router"); _; }
By enforcing this check, you protect your contract from unauthorized access and ensure that only calls made through the SDK are processed.
Fetch Transaction Details
const details = await sdk.getTransactionDetails(queueId);
TransactionDetailsResponse
The TransactionResponse
type represents the response structure for a transaction. Here's a breakdown of its properties:
| Property | Type | Description |
| -------------- | ------------------- | ---------------------------------------------------- |
| errorMessage
| string
| A message describing any error that occurred. |
| queueId
| string
| The unique identifier for the transaction queue. |
| signature
| string
| The signature associated with the transaction. |
| status
| TransactionStatus
| The current status of the transaction. |
| txHash
| string
| The transaction hash. |
| createdTime
| number
| The timestamp when the transaction was created. |
| updatedTime
| number
| The timestamp when the transaction was last updated. |
Example Response
const details = {
errorMessage: "",
queueId: "648abd81663ss",
signature: "0xabcdef1234567890",
status: "approved",
txHash: "0x5c5046e21aefb8db8f9eae3c5e5c8e4a0f9e4c6b77d4efc5b8a1e6e7e5a7b8a0d",
createdTime: 1697740800,
updatedTime: 1697827200
}
License
This project is licensed under the BBT License.