Creating the Frontend with Web3.js

Building a Complete DApp

Chapter 4: Creating the Frontend with Web3.js

Build a frontend to interact with the marketplace.

  • Key Components:

    • Connect to Solana via Web3.js.

    • Send transactions for listing/buying.

    • Display listings.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Decentralized Marketplace</title>
    <script src="https://cdn.jsdelivr.net/npm/@solana/web3.js@1.66.0/lib/index.iife.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@coral-xyz/anchor@0.28.0/dist/browser/index.js"></script>
</head>
<body>
    <div id="app">
        <h1>Marketplace</h1>
        <div id="items"></div>
        <input id="price" type="number" placeholder="Price in SOL">
        <button onclick="listItem()">List Item</button>
    </div>
    <script>
        const { Connection, PublicKey, Keypair } = window.SolanaWeb3;
        const { Program, AnchorProvider } = window.Anchor;

        // Placeholder IDL and program ID (replace with your own)
        const idl = { /* Your program's IDL */ };
        const programId = new PublicKey("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");

        // Connect to localnet (replace with devnet/mainnet as needed)
        const connection = new Connection("http://localhost:8899", "confirmed");
        const wallet = { keypair: Keypair.generate() }; // Placeholder wallet
        const provider = new AnchorProvider(connection, wallet, {});
        const program = new Program(idl, programId, provider);

        async function listItem() {
            const price = parseInt(document.getElementById("price").value) * 1e9; // Convert to lamports
            try {
                const tx = await program.methods.listItem(price).accounts({
                    // Define accounts here
                }).rpc();
                console.log("Item listed:", tx);
                alert("Item listed successfully!");
            } catch (error) {
                console.error("Error listing item:", error);
                alert("Failed to list item.");
            }
        }

        // Placeholder: Load and display items (implement fetch logic as needed)
        document.getElementById("items").innerHTML = "Items will appear here.";
    </script>
</body>
</html>
  • Interactivity: Use a simulated UI to list items and see transaction results.

Note: The IDL and account structures are placeholders—replace them with your actual program’s details after deployment.

Last updated