"use client"; import { useEffect, useState } from "react"; import Web3 from "web3"; interface Config { API_URL: string; CONTRACT_ADDRESS: string; ABI: any[]; } export default function Home() { const [config, setConfig] = useState(null); const [web3, setWeb3] = useState(null); const [contract, setContract] = useState(null); const [message, setMessage] = useState(""); const [newMessage, setNewMessage] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const [account, setAccount] = useState(""); // Initialize Web3 and contract useEffect(() => { const loadConfig = async () => { try { const response = await fetch("/crypto_clash/config.json"); const data = await response.json(); setConfig(data); // Initialize Web3 const web3Instance = new Web3(data.API_URL); setWeb3(web3Instance); // Create contract instance const contractInstance = new web3Instance.eth.Contract( data.ABI, data.CONTRACT_ADDRESS ); setContract(contractInstance); // Try to get connected account (if MetaMask or similar is available) if (typeof window !== "undefined" && (window as any).ethereum) { try { const accounts = await (window as any).ethereum.request({ method: "eth_requestAccounts", }); setAccount(accounts[0]); // Get the network ID from the RPC endpoint const networkId = await web3Instance.eth.net.getId(); const currentChainId = await (window as any).ethereum.request({ method: "eth_chainId", }); // If on different network, notify user (they may need to switch networks manually) console.log( `RPC Network ID: ${networkId}, MetaMask Chain ID: ${currentChainId}` ); } catch (err) { console.log("MetaMask not available or user denied access"); } } // Load initial message await readMessage(contractInstance); } catch (err) { setError(`Failed to load config: ${err}`); console.error(err); } }; loadConfig(); }, []); // Read message from contract const readMessage = async (contractInstance: any) => { try { setLoading(true); setError(""); const result = await contractInstance.methods.message().call(); setMessage(result); } catch (err) { setError(`Failed to read message: ${err}`); console.error(err); } finally { setLoading(false); } }; // Update message on contract const updateMessage = async () => { if (!newMessage.trim()) { setError("Please enter a message"); return; } try { setLoading(true); setError(""); if (!web3 || !contract) { throw new Error("Web3 or contract not initialized"); } // Check if MetaMask is available if (!account && typeof window !== "undefined" && !(window as any).ethereum) { throw new Error( "MetaMask not available. Please install MetaMask to update the message." ); } // Create transaction const tx = contract.methods.update(newMessage); const gas = await tx.estimateGas({ from: account }); console.log(await web3.eth.net.getId()); // Send transaction via MetaMask const result = await (window as any).ethereum.request({ method: "eth_sendTransaction", params: [ { from: account, to: config?.CONTRACT_ADDRESS, data: tx.encodeABI(), gas: web3.utils.toHex(gas), chainId: web3.utils.toHex(await web3.eth.net.getId()), }, ], }); setError(`Transaction sent: ${result}`); setNewMessage(""); // Wait a bit and refresh message from the RPC endpoint setTimeout(() => { if (contract) { readMessage(contract); } }, 2000); } catch (err) { setError(`Failed to update message: ${err}`); console.error(err); } finally { setLoading(false); } }; return (

Smart Contract Interaction

Read and update messages on the blockchain

{/* Status Section */}

Connected Account:{" "} {account ? `${account.slice(0, 6)}...${account.slice(-4)}` : "Not connected"}

Contract Address:{" "} {config?.CONTRACT_ADDRESS}

{/* Current Message Display */}

Current Message:

{loading && !message ? (

Loading...

) : message ? (

{message}

) : (

No message yet

)}
{/* Refresh Button */} {/* Update Message Form */}

Update Message:

setNewMessage(e.target.value)} placeholder="Enter new message..." className="w-full px-4 py-3 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-white placeholder-slate-400 dark:placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500" />
{/* Error/Status Messages */} {error && (

{error}

)} {/* Info Section */}

ℹ️ Note:

  • To update messages, you need MetaMask or a compatible Web3 wallet
  • Make sure your MetaMask is connected to the correct test network
  • Reading messages is free and doesn't require a wallet
  • Updates are written to the blockchain and may take time to confirm
); }