Quantcast
Channel: Recent Questions - Solana Stack Exchange
Viewing all articles
Browse latest Browse all 7906

Getting Error- Buffer is not defined - For Wallet Integration

$
0
0

I am trying to build a simple web application that uses Solana Web3.js to facilitate token purchase on devnet through my phantom wallet.However, when I attempt to execute the buyTokens function, I encounter the following error in the browser console:

Uncaught ReferenceError: Buffer is not definedat buy-solana:9:29 (anonymous) @ buy-solana:9Understand this errorAI browser.js:48 Uncaught (in promise) ReferenceError: Buffer isnot defined

I have included the Solana Web3.js library using the following script tag:-

<script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.js"></script><script src="https://bundle.run/buffer@6.0.3"></script>

My relevent part of code-

async function buyTokens() {    const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('devnet'));    const transaction = new solanaWeb3.Transaction().add(        solanaWeb3.SystemProgram.transfer({            fromPubkey: new solanaWeb3.PublicKey(walletAddress),            toPubkey: new solanaWeb3.PublicKey(solanaPublicKey),            lamports: solanaWeb3.LAMPORTS_PER_SOL * solAmount,        })    );    try {        const signedTransaction = await window.solana.signTransaction(transaction);        const signature = await connection.sendRawTransaction(signedTransaction.serialize());        await connection.confirmTransaction(signature);        alert(`Transaction sent: ${signature}`);    } catch (error) {        alert('Transaction failed: '+ error.message);    }}

Full code for your reference-

<!DOCTYPE html><html><head><title>Buy AstroMatch Tokens - Solana</title><script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.js"></script><script src="https://bundle.run/buffer@6.0.3"></script><script>        if (!window.Buffer) {            window.Buffer = Buffer; // Define Buffer globally if not already defined        }</script><style>        body {            font-family: Arial, sans-serif;            margin: 0;            background: linear-gradient(to bottom, #f093fb, #f5576c);            display: flex;            justify-content: center;            align-items: center;            height: 100vh;        }        .card {            background-color: #ffffff;            padding: 30px;            border-radius: 15px;            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);            text-align: center;            width: 350px;        }        h2 {            margin-bottom: 20px;        }        button {            font-size: 16px;            padding: 10px 20px;            border: none;            cursor: pointer;            border-radius: 5px;            background-color: #4caf50;            color: white;            transition: background-color 0.3s;        }        button:hover {            background-color: #45a049;        }        #disconnect {            background-color: #f44336;            margin-top: 10px;        }        input {            width: 100%;            padding: 10px;            margin-top: 15px;            border-radius: 5px;            border: 1px solid #ccc;            font-size: 16px;        }        #status {            margin-top: 15px;            font-weight: bold;        }</style></head><body><div class="card"><h2>Buy AstroMatch Tokens</h2><button id="connect">Connect Wallet</button><button id="disconnect" style="display:none;">Disconnect Wallet</button><p id="status">Status: Not Connected</p><form id="buyForm" style="display:none;"><label for="tokenAmount">Amount of Tokens:</label><input type="number" id="tokenAmount" min="1" placeholder="Enter token amount"><p id="solanaInfo">1 SOL = 100,000 AMT</p><button type="button" id="buyButton">Buy Tokens</button></form><p id="balance" style="margin-top: 20px;">Your Token Balance: 0 asas</p></div><script>        const solanaPublicKey = 'KEYHERE'; // Your Solana wallet public key        const tokenRate = 100000; // 1 SOL = 100,000 AMT        let walletAddress = null;        let userBalance = 0;        async function connectWallet() {            if (window.solana && window.solana.isPhantom) {                try {                    const response = await window.solana.connect();                    walletAddress = response.publicKey.toString();                    document.getElementById('status').textContent = `Status: Connected (${walletAddress})`;                    document.getElementById('connect').style.display = 'none';                    document.getElementById('disconnect').style.display = 'block';                    document.getElementById('buyForm').style.display = 'block';                    updateBalance();                } catch (error) {                    alert('Connection failed: '+ error.message);                }            } else {                alert('Phantom wallet not detected. Please install it from https://phantom.app');            }        }        function disconnectWallet() {            walletAddress = null;            document.getElementById('status').textContent = 'Status: Not Connected';            document.getElementById('connect').style.display = 'block';            document.getElementById('disconnect').style.display = 'none';            document.getElementById('buyForm').style.display = 'none';        }        function updateBalance() {            document.getElementById('balance').textContent = `Your Token Balance: ${userBalance} AMT`;        }        async function buyTokens() {            const tokenAmount = parseInt(document.getElementById('tokenAmount').value);            if (isNaN(tokenAmount) || tokenAmount <= 0) {                alert('Please enter a valid number of tokens.');                return;            }            const solAmount = tokenAmount / tokenRate;            const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('devnet'));            const transaction = new solanaWeb3.Transaction().add(                solanaWeb3.SystemProgram.transfer({                    fromPubkey: new solanaWeb3.PublicKey(walletAddress),                    toPubkey: new solanaWeb3.PublicKey(solanaPublicKey),                    lamports: solanaWeb3.LAMPORTS_PER_SOL * solAmount,                })            );            try {                const signedTransaction = await window.solana.signTransaction(transaction);                const signature = await connection.sendRawTransaction(signedTransaction.serialize());                await connection.confirmTransaction(signature);                alert(`Transaction sent: ${signature}`);                userBalance += tokenAmount;                updateBalance();            } catch (error) {                alert('Transaction failed: '+ error.message);            }        }        document.getElementById('connect').addEventListener('click', connectWallet);        document.getElementById('disconnect').addEventListener('click', disconnectWallet);        document.getElementById('buyButton').addEventListener('click', buyTokens);</script></body></html>

Can you please help on this?


Viewing all articles
Browse latest Browse all 7906

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>