」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 將透過 Kalp API Gateway 產生的 API 端點與您的前端應用程式集成

將透過 Kalp API Gateway 產生的 API 端點與您的前端應用程式集成

發佈於2024-11-08
瀏覽:667

Introduction

Hello, readers; congratulations on making it to the final part of this tutorial series. Now that you have learnt how to create and connect a custodial wallet on Kalp Studio deploy the smart contract on Kalp Instant Deployer and generate the endpoints using the Kalp API Gateway. It’s time we interact and check how our deployed smart contract can connect to the front end. In this tutorial, we will create a basic airdrop machine that will help us check the balance of our wallet, airdrop tokens claimed etc.

Prerequisites

Before diving further into this tutorial, make sure that you have the following:

  • Kalp Studio Account. If you don’t have an account, sign up here.
  • Kalp Studio Wallet connected on Kalp Blockchain and on the Testnet network. If you haven’t connected the wallet yet, checkout the previous tutorial: Creating your Custodial Ethereum Wallet on Holsekey Network, using Kalp Studio and the official documentation.
  • A deployed smart contract on Kalp Instant Deployer. If you haven’t deployed you smart contract yet, check out our tutorial here Create Your First Smart Contract in Solidity and Upload it to Kalp Instant Deployer.
  • Generated API Endpoints, that will be used to interact the smart contract with the frontend. For more details, take a look at our tutorial.
  • Basic knowledge of React, Typescript, Javascript and Next.

Once we have the prerequisites ready, let’s jump into development.

Setting up the project

Before setting up the project, just ensure you have the following:

  • Installed go. Download Go and install version >=1.19 but
  • Install Node.js and npm. Ensure you have Node.js version >=14.x and npm version >=6.x.

Once, we have the required dependencies installed, navigate to the following GitHub repository: Code Structure. And follow the steps mentioned in check-point 0 of the GitHub repository.

After following the installation steps, our project folder structure should look like this.

airdrop-vending-machine
├── smart-contract
│   ├── vendor
│   ├── go.mod
│   ├── go.sum
│   ├── main.go
│   └── krc.go  (Your Airdrop Vending Machine contract file)
├── frontend
    ├── src
    │   ├── app
    │   │   ├── favicon.ico
    │   │   ├── globals.css
    │   │   └── page.tsx
    │   ├── hooks
    │   │   └── useKalpApi.ts   (Your API hook)
    │   ├── pages
    ├── public
    ├── package.json
    ├── tsconfig.json
    └── README.md

Smart Contract Development

Once, we have the folder structure ready, and have installed all the required dependencies, navigate to the smart-contract folder and take a look at the krc.go file. This is where our smart contract has been written.

Here’s the overview of what this smart contract does:

  • Initialization (Initialize):

    • Initializes the contract by setting the token's name, symbol, and decimals.
    • Once initialized, the token's name and symbol cannot be changed.
  • Minting (Claim):

    • Mints new tokens and assigns them to the minter's account balance (defined by address).
    • Updates the total token supply to reflect the newly minted tokens.
    • Emits a Transfer event with the minter as the recipient and "0x0" as the sender, indicating the creation of tokens.
  • Balance Retrieval (BalanceOf):

    • Retrieves the token balance of a specific account from the world state.
    • Returns 0 if the account does not exist.
  • Total Supply (TotalSupply):

    • Returns the total supply of tokens in existence by retrieving it from the world state.
  • Transfer (TransferFrom):

    • Allows the transfer of tokens between accounts. It subtracts the token amount from the sender's balance and adds it to the recipient’s balance.
    • Emits a Transfer event to record the transfer action.
  • Name and Symbol Retrieval (Name, Symbol):

    • Retrieves the name and symbol of the token set during initialization.

Helper Functions:

  • transferHelper: Ensures proper transfer logic by checking the sender’s balance, recipient’s balance, and handling the actual transfer.
  • add and sub: Safeguards against overflow during addition and subtraction of token balances.
  • checkInitialized: Ensures that the contract is initialized before certain functions are called.

In summary, this contract manages the minting and transfer of tokens, tracks balances, and ensures that only authorized users can mint or initialize the contract. It includes features such as querying balances and total supply, along with basic arithmetic and overflow checks for token management.

Deploying the Smart Contract and Generating the API Endpoints

To deploy our smart contract, we will be using the Kalp Instant Deployer. Deploying a smart contract on Kalp Studio is a streamlined process that involves a few simple steps.

To see how can we deploy the smart contract in detail, explore the tutorial here:
Create Your First Smart Contract in Solidity and Deploy it to Kalp Instant Deployer.

After deploying the smart contract, we would need to generate the API Endpoints and for that we will be using the Kalp API Gateway.

To follow the usage of Kalp API Gateway, refer to our detailed tutorial here:
Generating the API Endpoints of Your Smart Contract using the Kalp API Gateway.

Interacting with the Smart Contract

Now that we've deployed our token airdrop smart contract on the Kalp blockchain, it's time to interact with it. For this tutorial series, we will be using Postman.

Here are the steps that you need to follow:

  • Initialize the Contract
  • Claim Tokens
  • Check Balance
  • Transfer Tokens

To check more about how we can use Postman to interact with our deployed smart contract. Refer the tutorial: How to Send Transaction of Your Generated API Endpoints on Kalp Studio and the official documentation.

Integrating your Smart Contract with Frontend

Now comes the final piece of the puzzle. It’s time that we integrate our smart contract with our frontend via the API Endpoints that we have generated.

Let's open the file useKalpApi.ts located in the frontend/src/hooks folder and see how the frontend interacts with the Kalp blockchain.

1. Setting Up the API Hook

The useKalpApi hook encapsulates all the API calls to your smart contract. It manages loading states, errors, and provides functions to interact with the contract.

import { useState } from 'react';

export const useKalpApi = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const apiKey = process.env.NEXT_PUBLIC_API_KEY;

  // ... rest of the code
};

  • State Management:

    • loading: Indicates whether an API call is in progress.
    • error: Holds any error that occurs during API calls.
  • API Key:

    • apiKey: Your Kalp Studio API key stored in environment variables for security.

2. Making API Calls

The callApi function handles making HTTP requests to the Kalp blockchain API.

const callApi = async (endpoint: string, args: { [key: string]: any }) => {
  setError(null);
  setLoading(true);

  const params = {
    network: 'TESTNET',
    blockchain: 'KALP',
    walletAddress: 'your-wallet-address',
    args: args,
  };

  try {
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': apiKey!,
      },
      body: JSON.stringify(params),
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.message || 'Something went wrong');
    }

    setLoading(false);
    return data;
  } catch (err: any) {
    setError(err);
    setLoading(false);
    throw err;
  }
};

  • Parameters:

    • endpoint (string): The API endpoint URL.
    • args (object): The arguments to pass to the smart contract function.
  • API Request:

    • Sends a POST request with the required headers and body.
    • Handles the response and error states.

3. Interacting with Smart Contract Functions

a) Claim Tokens

const claim = async (address: string) => {
  const endpoint = 'https://your-api-endpoint/Claim';
  const args = {
    amount: 100,
    address: address,
  };
  return callApi(endpoint, args);
};

Purpose: Allows a user to claim tokens by calling the Claim function of your smart contract.

b) Check Balance

const balanceOf = async (account: string) => {
  const endpoint = 'https://your-api-endpoint/BalanceOf';
  const args = {
    account: account,
  };
  return callApi(endpoint, args);
};

Purpose: Retrieves the token balance of a specific account.

c) Get Total Supply

const totalSupply = async () => {
  const endpoint = 'https://your-api-endpoint/TotalSupply';
  const args = {};
  return callApi(endpoint, args);
};

Purpose: Gets the total supply of tokens from your smart contract.

d) Transfer Tokens

You need to add the Transfer functionality to your frontend.

const transferFrom = async (from: string, to: string, value: number) => {
  const endpoint = 'https://your-api-endpoint/TransferFrom';
  const args = {
    from: from,
    to: to,
    value: value,
  };
  return callApi(endpoint, args);
};

Purpose: Allows a user to transfer tokens from one account to another by calling the TransferFrom function of your smart contract.

4. Returning the API Functions

return { claim, balanceOf, totalSupply, transferFrom, loading, error };

Exports: The API functions and state variables for use in your components.

Configuring the Frontend with Your API Endpoints

Here are the steps that you can follow:

Update Environment Variables

Create a .env.local file in your project root:

touch .env.local

Add your API key to the .env.local file:

NEXT_PUBLIC_API_KEY=your-kalp-api-key

Note: Prefixing the variable with NEXT_PUBLIC_ makes it accessible in the browser.

Replace API Endpoints in useKalpApi.ts

Locate the endpoints in your code and replace them with your generated endpoints.

const claim = async (address: string) => {
  const endpoint = 'https://your-api-endpoint/Claim';
  const args = {
    amount: 100,
    address: address,
  };
  return callApi(endpoint, args);
};

const balanceOf = async (account: string) => {
  const endpoint = 'https://your-api-endpoint/BalanceOf';
  const args = {
    account: account,
  };
  return callApi(endpoint, args);
};

const totalSupply = async () => {
  const endpoint = 'https://your-api-endpoint/TotalSupply';
  const args = {};
  return callApi(endpoint, args);
};

const transferFrom = async (from: string, to: string, value: number) => {
  const endpoint = 'https://your-api-endpoint/TransferFrom';
  const args = {
    from: from,
    to: to,
    value: value,
  };
  return callApi(endpoint, args);
};

Replace 'https://your-api-endpoint/FunctionName' with the actual endpoints provided by Kalp Studio.

Update the Wallet Address

In the callApi function, update the walletAddress parameter:

const params = {
  network: 'TESTNET',
  blockchain: 'KALP',
  walletAddress: 'your-wallet-address',
  args: args,
};

Replace 'your-wallet-address' with the address you want to use for transactions.

Running the Frontend Application

Now that you've configured your API endpoints and API key, you're ready to run the application.

Follow the steps below:

  • Start the Development Server:

    • npm run dev
  • Open the Application in Your Browser:

    • Navigate to http://localhost:3000 in your web browser.

Interact with the Application:

  • Use the interface to claim tokens, check balances, transfer tokens, and view the total supply.
  • The application will communicate with your deployed smart contract via the configured API endpoints.

Here's how the final application will look like:

Integrating the API endpoints generated via Kalp API Gateway with your Frontend Application

Conclusion

Congratulations on reaching the end of this tutorial. By now you can now create a wallet of your choice on Kalp Studio, deploy smart contracts via Kalp Instant Deployer, generate API endpoints via Kalp API Gateway and integrate your smart contract with your frontend application.

Stay tuned for more advanced tutorials on using Kalp Studio to enhance your blockchain projects!

Check out our official documentation here to continue exploring what more Kalp Studio can do. If you have any queries, join our Discord server and let’s continue the discussion there.

版本聲明 本文轉載於:https://dev.to/kalpstudio/integrating-the-api-endpoints-generated-via-kalp-api-gateway-with-your-frontend-application-2me8?1如有侵犯,請聯絡study_golang @163.com刪除
最新教學 更多>
  • 關於 React useState Hook 你需要了解的一切 - 裡面的實際例子
    關於 React useState Hook 你需要了解的一切 - 裡面的實際例子
    ReactJS useState Hook:初学者指南 介绍 ReactJS 是一个用于构建用户界面的流行 JavaScript 库,引入了 hooks 来简化和增强组件逻辑。 React 中最常用的钩子之一是 useState 钩子,它管理组件的状态。了解其工作原...
    程式設計 發佈於2024-11-08
  • **何時在 JavaScript 中使用 Mouseover 與 Mouseenter?
    **何時在 JavaScript 中使用 Mouseover 與 Mouseenter?
    了解 Mouseover 和 Mouseenter 事件之間的差異mouseover 和 mouseenter 事件都回應滑鼠遊標在元素上的移動。然而,它們之間有一個微妙的區別。 Mouseover每次滑鼠遊標進入或在元素(包括後代)的邊界內移動時,都會觸發 mouseover 事件元素。這意味著,...
    程式設計 發佈於2024-11-08
  • 在 Gmail 中使用 PHPmailer 時如何解決「SMTP Connect() Failed」錯誤?
    在 Gmail 中使用 PHPmailer 時如何解決「SMTP Connect() Failed」錯誤?
    PHPmailer 中SMTP 連線失敗:解決問題透過PHPmailer 傳送電子郵件時,開發者可能會遇到錯誤:「Mailer Error : SMTP連線()失敗。 解決方案在於 Google 實施了新的授權機制 XOAUTH2。若要允許 PHPmailer 連線到 Gmail 的 SMTP,您必...
    程式設計 發佈於2024-11-08
  • 為什麼在發出跨域 AJAX 請求時會收到「jQuery XML 錯誤:\'Access-Control-Allow-Origin\' 標頭缺失」?
    為什麼在發出跨域 AJAX 請求時會收到「jQuery XML 錯誤:\'Access-Control-Allow-Origin\' 標頭缺失」?
    jQuery XML 錯誤:'Access-Control-Allow-Origin' 標頭遺失在這種情況下,根本問題是同源策略,基於安全性原因限制跨域請求。當向 HTML 頁面來源以外的網域發出 AJAX 請求時,瀏覽器會觸發 CORS(跨網域資源共用)請求。 具體錯誤訊息表明目標...
    程式設計 發佈於2024-11-08
  • 花了很多時間才編譯出一套完整的PHP資源。請喜歡它。
    花了很多時間才編譯出一套完整的PHP資源。請喜歡它。
    这里是我整理的PHP资源集合,可以帮助大家找到自己需要的东西,而不用浪费时间搜索。我会每周更新一次。如果觉得有用,请给个star吧❤️。如果您想分享或转载,请保留来源。谢谢你! ? PHP PSR 编码标准 官方网站:www.php-fig.org 原始文档:github.com/...
    程式設計 發佈於2024-11-08
  • Java 的 WatchService API 如何徹底改變文件更改監控?
    Java 的 WatchService API 如何徹底改變文件更改監控?
    在 Java 中監視文件變更檢測底層檔案系統中的檔案變更對於無數應用程式和實用程式至關重要。從歷史上看,採用的是次優輪詢方法,涉及重複查詢檔案的 LastModified 屬性。然而,這種方法效率低下,並且會帶來效能開銷。 Java 7 和WatchService APIJava 的進步帶來了專門為...
    程式設計 發佈於2024-11-08
  • Java 中連接字串的 asy 技巧
    Java 中連接字串的 asy 技巧
    1. 使用操作器 运算符是Java中连接字符串最简单也是最常用的方法。它直观且易于理解,使其成为初学者的热门选择。 1.1 基本示例 String firstName = "John"; String lastName = "Doe"; String fullNa...
    程式設計 發佈於2024-11-08
  • 如何透過相互頂級導入解決 Python 中的「AttributeError:『模組』物件沒有屬性」問題?
    如何透過相互頂級導入解決 Python 中的「AttributeError:『模組』物件沒有屬性」問題?
    AttributeError: 'module' object has no attributeAttributeError: 'module' object has no attribute當使用相互頂級導入運行Python 模組a.py 時,您會遇到錯誤“Attr...
    程式設計 發佈於2024-11-08
  • 用於建構生成式人工智慧應用程式的開源框架
    用於建構生成式人工智慧應用程式的開源框架
    有許多令人驚嘆的工具可以幫助建立生成式人工智慧應用程式。但開始使用新工具需要時間學習和練習。 因此,我創建了一個儲存庫,其中包含用於建立生成人工智慧應用程式的流行開源框架的範例。 這些範例也展示瞭如何將這些框架與 Amazon Bedrock 結合使用。 您可以在這裡找到存儲庫: https:...
    程式設計 發佈於2024-11-08
  • 如何在 C# 中從 MySQL 資料庫載入和顯示映像?
    如何在 C# 中從 MySQL 資料庫載入和顯示映像?
    如何從MySQL 資料庫擷取與顯示影像如何從MySQL 資料庫擷取與顯示影像從MySQL 資料庫擷取影像到PictureBox 控制項中需要採用具有正確位元組的特定方法數組處理。以下步驟示範了這個過程:將映像插入 MySQL 資料庫使用 MySql.Data.MySqlClient 庫進行 MySQ...
    程式設計 發佈於2024-11-08
  • 引用計數與追蹤垃圾收集
    引用計數與追蹤垃圾收集
    你好,Mentes Tech! 您知道記憶體釋放上下文中的引用計數和引用追蹤是什麼嗎? 引用追蹤(或追蹤垃圾收集)和引用計數(引用計數)之間的區別在於每種技術用於識別和釋放不存在的物件記憶體的方法。使用時間更長。 我將解釋每一個,然後強調主要差異。 引用計數(引用計數) 工作...
    程式設計 發佈於2024-11-08
  • 單行SQL查詢失敗時如何傳回預設值?
    單行SQL查詢失敗時如何傳回預設值?
    單行查詢失敗時傳回預設值在執行SQL查詢以取得特定資料時,常會遇到沒有對應行的情況存在。為了避免傳回空結果,您可能需要提供預設值。 考慮以下 SQL 語句,該語句檢索流的下一個計劃項目:SELECT `file` FROM `show`, `schedule` WHERE `channel` = ...
    程式設計 發佈於2024-11-08
  • Cypress 自動化可訪問性測試:綜合指南
    Cypress 自動化可訪問性測試:綜合指南
    介紹 輔助功能是 Web 開發的重要方面,確保所有使用者(包括殘障人士)都可以與您的 Web 應用程式有效互動。自動化可訪問性測試有助於在開發過程的早期識別和解決可訪問性問題。在這篇文章中,我們將探討如何使用 Cypress 實現自動化可訪問性測試,利用 cypress-axe 等...
    程式設計 發佈於2024-11-08
  • 為什麼 Javascript 和 jQuery 找不到 HTML 元素?
    為什麼 Javascript 和 jQuery 找不到 HTML 元素?
    Javascript 和jQuery 無法偵測HTML 元素當嘗試使用Javascript 和jQuery 操作HTML 元素時,您可能會遇到令人沮喪的問題未定義的元素。當腳本嘗試存取 HTML 文件中尚未定義的元素時,就會發生這種情況。 在提供的 HTML 和腳本中,「script.js」檔案在其...
    程式設計 發佈於2024-11-08
  • Polars 與 Pandas Python 資料幀的新時代?
    Polars 與 Pandas Python 資料幀的新時代?
    北極熊與熊貓:有什麼區別? 如果您一直在關注 Python 的最新發展,您可能聽說過 Polars,一個用於處理資料的新程式庫。雖然 pandas 長期以來一直是首選庫,但 Polars 正在掀起波瀾,尤其是在處理大型資料集方面。那麼,Polars 有什麼大不了的呢?它和熊貓有什麼...
    程式設計 發佈於2024-11-08

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3