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 <1.20.
- 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.
- Mints new tokens and assigns them to the minter's account balance (defined by
-
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
andsub
: 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<any>(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.
- Navigate to
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:
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.
Top comments (0)