”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 将通过 Kalp API Gateway 生成的 API 端点与您的前端应用程序集成

将通过 Kalp API Gateway 生成的 API 端点与您的前端应用程序集成

发布于2024-11-08
浏览:842

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如有侵犯,请联系[email protected]删除
最新教程 更多>
  • Bootstrap 4 Beta 中的列偏移发生了什么?
    Bootstrap 4 Beta 中的列偏移发生了什么?
    Bootstrap 4 Beta:列偏移的删除和恢复Bootstrap 4 在其 Beta 1 版本中引入了重大更改柱子偏移了。然而,随着 Beta 2 的后续发布,这些变化已经逆转。从 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    编程 发布于2024-12-28
  • HTML 格式标签
    HTML 格式标签
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    编程 发布于2024-12-28
  • 在 Go 中使用 WebSocket 进行实时通信
    在 Go 中使用 WebSocket 进行实时通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    编程 发布于2024-12-28
  • 插入数据时如何修复“常规错误:2006 MySQL 服务器已消失”?
    插入数据时如何修复“常规错误:2006 MySQL 服务器已消失”?
    插入记录时如何解决“一般错误:2006 MySQL 服务器已消失”介绍:将数据插入 MySQL 数据库有时会导致错误“一般错误:2006 MySQL 服务器已消失”。当与服务器的连接丢失时会出现此错误,通常是由于 MySQL 配置中的两个变量之一所致。解决方案:解决此错误的关键是调整wait_tim...
    编程 发布于2024-12-28
  • 大批
    大批
    方法是可以在对象上调用的 fns 数组是对象,因此它们在 JS 中也有方法。 slice(begin):将数组的一部分提取到新数组中,而不改变原始数组。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index p...
    编程 发布于2024-12-28
  • 如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    MySQL配置不正确:相对路径的问题在Django中运行python manage.py runserver时,可能会遇到以下错误:ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-...
    编程 发布于2024-12-28
  • 如何在 PHP 中组合两个关联数组,同时保留唯一 ID 并处理重复名称?
    如何在 PHP 中组合两个关联数组,同时保留唯一 ID 并处理重复名称?
    在 PHP 中组合关联数组在 PHP 中,将两个关联数组组合成一个数组是一项常见任务。考虑以下请求:问题描述:提供的代码定义了两个关联数组,$array1 和 $array2。目标是创建一个新数组 $array3,它合并两个数组中的所有键值对。 此外,提供的数组具有唯一的 ID,而名称可能重合。要求...
    编程 发布于2024-12-28
  • 除了“if”语句之外:还有哪些地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    除了“if”语句之外:还有哪些地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    无需强制转换即可上下文转换为 bool您的类定义了对 bool 的显式转换,使您能够在条件语句中直接使用其实例“t”。然而,这种显式转换提出了一个问题:“t”在哪里可以在不进行强制转换的情况下用作 bool?上下文转换场景C 标准指定了四种值可以根据上下文转换为的主要场景bool:语句:if、whi...
    编程 发布于2024-12-28
  • 如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 识别今天生日的用户使用 MySQL 确定今天是否是用户的生日涉及查找生日匹配的所有行今天的日期。这可以通过一个简单的 MySQL 查询来实现,该查询将存储为 UNIX 时间戳的生日与今天的日期进行比较。以下 SQL 查询将获取今天有生日的所有用户: FROM USERS ...
    编程 发布于2024-12-28
  • 尽管代码有效,为什么 POST 请求无法捕获 PHP 中的输入?
    尽管代码有效,为什么 POST 请求无法捕获 PHP 中的输入?
    解决 PHP 中的 POST 请求故障在提供的代码片段中:action=''而不是:action="<?php echo $_SERVER['PHP_SELF'];?>";?>"检查 $_POST数组:表单提交后使用 var_dump 检查 $_POST 数...
    编程 发布于2024-12-28
  • 如何准确地透视具有不同记录的数据以避免丢失信息?
    如何准确地透视具有不同记录的数据以避免丢失信息?
    有效地透视不同记录透视查询在将数据转换为表格格式、实现轻松数据分析方面发挥着至关重要的作用。但是,在处理不同记录时,数据透视查询的默认行为可能会出现问题。问题:忽略不同值考虑下表:------------------------------------------------------ | Id ...
    编程 发布于2024-12-27
  • 为什么 C 和 C++ 忽略函数签名中的数组长度?
    为什么 C 和 C++ 忽略函数签名中的数组长度?
    将数组传递给 C 和 C 中的函数 问题:为什么 C 和C 编译器允许在函数签名中声明数组长度,例如 int dis(char a[1])(当它们不允许时)强制执行?答案:C 和 C 中用于将数组传递给函数的语法是历史上的奇怪现象,它允许将指针传递给第一个元素详细说明:在 C 和 C 中,数组不是通...
    编程 发布于2024-12-26
  • 如何删除 MySQL 中的重音符号以改进自动完成搜索?
    如何删除 MySQL 中的重音符号以改进自动完成搜索?
    在 MySQL 中删除重音符号以实现高效的自动完成搜索管理大型地名数据库时,确保准确和高效至关重要数据检索。使用自动完成功能时,地名中的重音可能会带来挑战。为了解决这个问题,一个自然的问题出现了:如何在 MySQL 中删除重音符号以改进自动完成功能?解决方案在于为数据库列使用适当的排序规则设置。通过...
    编程 发布于2024-12-26
  • 如何在MySQL中实现复合外键?
    如何在MySQL中实现复合外键?
    在 SQL 中实现复合外键一种常见的数据库设计涉及使用复合键在表之间建立关系。复合键是多个列的组合,唯一标识表中的记录。在这个场景中,你有两个表,tutorial和group,你需要将tutorial中的复合唯一键链接到group中的字段。根据MySQL文档,MySQL支持外键映射到复合键。但是,要...
    编程 发布于2024-12-26
  • 为什么我的 JComponent 隐藏在 Java 的背景图像后面?
    为什么我的 JComponent 隐藏在 Java 的背景图像后面?
    调试背景图像隐藏的 JComponent在 Java 应用程序中使用 JComponent(例如 JLabels)时,必须确保正确的行为和可见度。如果遇到组件隐藏在背景图像后面的问题,请考虑以下方法:1。正确设置组件透明度:确保背景面板是透明的,以允许底层组件透过。使用setOpaque(false...
    编程 发布于2024-12-26

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3