Building the dApp with React
Copy npx create-react-app counter-dapp-frontend
cd counter-dapp-frontend
npm install ethers
Copy import React, { useEffect, useState } from 'react';
import { ethers } from 'ethers';
import './App.css';
// Replace with your deployed contract address
const CONTRACT_ADDRESS = "YOUR_DEPLOYED_CONTRACT_ADDRESS";
// ABI from your Counter contract
const CONTRACT_ABI = [
{
"inputs": [],
"name": "count",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "increment",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "getCount",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
}
];
function App() {
const [count, setCount] = useState(0);
const [provider, setProvider] = useState(null);
const [contract, setContract] = useState(null);
// Initialize provider and contract
useEffect(() => {
if (window.ethereum) {
const tempProvider = new ethers.providers.Web3Provider(window.ethereum);
setProvider(tempProvider);
const tempContract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, tempProvider.getSigner());
setContract(tempContract);
// Request account access if needed
window.ethereum.request({ method: 'eth_requestAccounts' });
} else {
alert("Please install MetaMask!");
}
}, []);
// Fetch count from contract
const fetchCount = async () => {
if (contract) {
const currentCount = await contract.getCount();
setCount(currentCount.toNumber());
}
};
// Call increment function
const incrementCount = async () => {
if (contract) {
const tx = await contract.increment();
await tx.wait();
fetchCount();
}
};
useEffect(() => {
fetchCount();
}, [contract]);
return (
<div className="App">
<header className="App-header">
<h2>Kite AI Counter DApp</h2>
<p>Current Count: {count}</p>
<button onClick={incrementCount}>Increment</button>
</header>
</div>
);
}
export default App;
Congratulations on building your basic counter dApp on the Kite AI blockchain testnet! You’ve successfully.