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.
Before diving further into this tutorial, make sure that you have the following:
Once we have the prerequisites ready, let’s jump into development.
Before setting up the project, just ensure you have the following:
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
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):
Minting (Claim):
Balance Retrieval (BalanceOf):
Total Supply (TotalSupply):
Transfer (TransferFrom):
Name and Symbol Retrieval (Name, Symbol):
Helper Functions:
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.
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.
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:
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.
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.
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:
API Key:
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:
API Request:
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.
return { claim, balanceOf, totalSupply, transferFrom, loading, error };
Exports: The API functions and state variables for use in your components.
Here are the steps that you can follow:
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.
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.
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.
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:
Open the Application in Your Browser:
Interact with the Application:
Here's how the final application will look like:
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.
Отказ от ответственности: Все предоставленные ресурсы частично взяты из Интернета. В случае нарушения ваших авторских прав или других прав и интересов, пожалуйста, объясните подробные причины и предоставьте доказательства авторских прав или прав и интересов, а затем отправьте их по электронной почте: [email protected]. Мы сделаем это за вас как можно скорее.
Copyright© 2022 湘ICP备2022001581号-3