Connecting Your DApp to Blockchain with WalletConnect and GetBlock

This guide shows beginners how to connect their DApps to the blockchain using WalletConnect and GetBlock.io with a browser wallet like MetaMask. You’ll learn to set up your GetBlock Token Access, create a simple HTML page, and add JavaScript to enable wallet connections, listen for account changes, and display connection status. It’s all about getting your web DApp talking to the blockchain reliably.


This content originally appeared on HackerNoon and was authored by Kozmic Hash

Are you looking to connect your decentralized application (DApp) to the blockchain and allow users to interact with it using their browser wallets? This tutorial will guide you through integrating WalletConnect with GetBlock.io – a powerful combination for seamless and reliable blockchain interactions.

We'll focus on a browser-based setup, making it ideal for web applications where users typically use browser extensions like MetaMask.


What You'll Need

Before we dive into the code, make sure you have the following:

  • A GetBlock Account: GetBlock provides access to various blockchain nodes. You'll need an API key to connect. If you don't have one, sign up at https://getblock.io/.
  • A Browser-Based Wallet: We'll be using a common browser extension wallet like MetaMask for this tutorial. Make sure it's installed in your browser and connected to a testnet (e.g., Sepolia) for safe experimentation.
  • Basic JavaScript Knowledge: This tutorial involves some JavaScript code.
  • A Simple Web Project: A basic HTML file with a script tag is all you need to get started.

Step 1: Set Up Your GetBlock Access Token

  1. Log in to GetBlock: Once logged in, get a free endpoint for Sepolia.
  2. Get a New Endpoint (if needed): You'll find the Get button in your dashboard.
  3. Copy Your Access Token: Locate and copy your Access Token. We'll use this to connect to the blockchain nodes. For this tutorial, we'll assume you're connecting to an Ethereum testnet.

Step 2: Create Your HTML Structure

Let's create a simple HTML file (index.html) that will house our DApp and the JavaScript logic.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WalletConnect GetBlock Tutorial</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        button { padding: 10px 20px; margin-top: 10px; cursor: pointer; }
        #status { margin-top: 20px; font-weight: bold; }
        #account { margin-top: 10px; }
    </style>
</head>
<body>
    <h1>Connect Your Wallet</h1>
    <button id="connectButton">Connect Wallet</button>
    <button id="disconnectButton">Disconnect Wallet</button>
    <div id="status">Status: Disconnected</div>
    <div id="account">Account: N/A</div>

    <script src="./app.js"></script>
</body>
</html>

Step 3: Implement WalletConnect Logic (app.js)

Now, let's create our app.js file and add the JavaScript code to handle WalletConnect.

First, you'll need to install the WalletConnect Web3Modal library and the WalletConnectProvider. For a simple browser example, you can use a CDN. For a more robust project, you'd typically use npm.

Add these script tags to your index.html before your app.js script tag:

<script src="https://unpkg.com/web3@latest/dist/web3.min.js"></script>

<script src="https://unpkg.com/@walletconnect/web3-provider@1.8.0/dist/umd/index.min.js"></script>

<script src="https://unpkg.com/web3modal@1.9.12/dist/index.js"></script>

Now, create your app.js file:

// Replace with your actual GetBlock Access Token
const GETBLOCK_ACCESS_TOKEN = 'YOUR_GETBLOCK_ACCESS_TOKEN';
const GETBLOCK_NODE_URL = `https://go.getblock.io/${GETBLOCK_ACCESS_TOKEN}/`;

let web3Modal;
let provider;
let web3;
let selectedAccount;

const connectButton = document.getElementById('connectButton');
const statusDiv = document.getElementById('status');
const accountDiv = document.getElementById('account');

const init = async () => {
    // Configure Web3Modal
    const providerOptions = {
        // You can add more providers here, but for this tutorial, WalletConnect is the focus.
        walletconnect: {
            package: window.WalletConnectProvider.default, // required
            options: {
                rpc: {
                    // You can specify multiple chains and their GetBlock.io endpoints
                    11155111: GETBLOCK_NODE_URL // Sepolia Chain ID
                },
                infuraId: undefined, // Not needed if using GetBlock for RPC
                chainId: 11155111, // Default chain to connect to (Sepolia)
            }
        }
    };

    web3Modal = new Web3Modal.default({
        cacheProvider: true, // Optional: enables caching of provider for quicker reconnections
        providerOptions, // required
        disableInjectedProvider: false, // Optional: if you want to allow direct MetaMask connections too
    });

    console.log("Web3Modal initialized.", web3Modal);

    // If a provider is already cached, connect automatically
    if (web3Modal.cachedProvider) {
        await connectWallet();
    }
};

// Function to connect the wallet using WalletConnect
const connectWallet = async () => {
    try {
        statusDiv.textContent = 'Status: Connecting...';
        provider = await web3Modal.connect(); // This opens the WalletConnect modal

        // We plug the web3 provider into Web3.js
        web3 = new Web3(provider);

        // Get the connected accounts
        const accounts = await web3.eth.getAccounts();
        selectedAccount = accounts[0];

        statusDiv.textContent = 'Status: Connected!';
        accountDiv.textContent = `Account: ${selectedAccount}`;

        // Listen for accounts changed and disconnect events
        provider.on("accountsChanged", (accounts) => {
            console.log("Accounts changed:", accounts);
            selectedAccount = accounts[0];
            accountDiv.textContent = `Account: ${selectedAccount}`;
        });

        provider.on("chainChanged", (chainId) => {
            console.log("Chain changed:", chainId);
            // You might want to reload the page or update the UI based on the new chain
            statusDiv.textContent = `Status: Connected to Chain ID ${chainId}`;
        });

        provider.on("disconnect", (code, reason) => {
            console.log("Provider disconnected:", code, reason);
            resetApp();
        });

    } catch (e) {
        console.error("Could not connect wallet:", e);
        statusDiv.textContent = 'Status: Connection Failed';
        accountDiv.textContent = 'Account: N/A';
        selectedAccount = null;
    }
};

// This function will disconnect the wallet and reset the app state
async function disconnectWallet() {
    if (window.provider && window.provider.close) {
        await window.provider.close();
    }
    await web3Modal.clearCachedProvider();
    window.location.reload(); // Opcional: recarrega a página
}

const resetApp = () => {
    selectedAccount = null;
    statusDiv.textContent = 'Status: Disconnected';
    accountDiv.textContent = 'Account: N/A';
    web3Modal.clearCachedProvider();
    provider = null;
    web3 = null;
};

// Event listener for the connect button
connectButton.addEventListener('click', connectWallet);

// Event listener for the disconnect button
disconnectButton.addEventListener('click', disconnectWallet);

// Initialize the DApp when the DOM is loaded
window.addEventListener('load', init);

Important Notes:

  • Replace YOUR_GETBLOCK_ACCESS_TOKEN: Make sure to replace this placeholder with your actual GetBlock.io Access Token.
  • Chain ID: The chainId (11155111 for Sepolia) is crucial for WalletConnect to identify the correct network.
  • rpc Object: The rpc object within providerOptions.walletconnect.options is where you map chain IDs to your GetBlock.io node URLs. This tells WalletConnect which RPC endpoint to use for a specific network.
  • WalletConnectProvider: In a typical project using a bundler (like Webpack or Parcel), WalletConnectProvider would be imported from @walletconnect/web3-provider. For this simple browser example using a CDN, it's assumed to be globally available after the web3modal.min.js script.
  • Error Handling: The try...catch blocks are important for handling potential connection errors.
  • Event Listeners: We've added basic event listeners for accountsChanged, chainChanged, and disconnect to update the UI and handle changes in the user's wallet.

Step 4: Run Your Application

  1. Save your files: Make sure both index.html and app.js are in the same directory.

  2. Open index.html in your browser. Use a local server.

    If you open index.html directly in the browser (file://), some browsers will block cross-origin requests: You should see a "Connect Wallet" button.

  3. Click "Connect Wallet": The WalletConnect modal will pop up.

  4. Choose "WalletConnect": A QR code will appear.

  5. Scan with your Mobile Wallet (or use a desktop WalletConnect-compatible wallet): If you're using MetaMask's desktop extension, it should open a prompt for you to connect. For mobile wallets, scan the QR code using your wallet's built-in scanner.

  6. Approve the Connection: Confirm the connection request in your wallet.

Once connected, your DApp will display "Status: Connected!" and your connected account address.


Next Steps

Now that you have a basic connection established, you can expand your DApp to:

  • Read Contract Data: Use the web3 instance to interact with smart contracts (e.g., call view functions).
  • Send Transactions: Allow users to send transactions (e.g., call nonpayable functions on smart contracts, send ETH).
  • Sign Messages: Enable users to sign arbitrary messages.
  • Implement Disconnect: Add a button or mechanism for users to explicitly disconnect their wallet.

This tutorial provides a solid foundation for connecting your DApp to the blockchain using WalletConnect and GetBlock. By leveraging these tools, you can create a seamless and user-friendly experience for your decentralized applications!


This content originally appeared on HackerNoon and was authored by Kozmic Hash


Print Share Comment Cite Upload Translate Updates
APA

Kozmic Hash | Sciencx (2025-06-27T04:26:24+00:00) Connecting Your DApp to Blockchain with WalletConnect and GetBlock. Retrieved from https://www.scien.cx/2025/06/27/connecting-your-dapp-to-blockchain-with-walletconnect-and-getblock/

MLA
" » Connecting Your DApp to Blockchain with WalletConnect and GetBlock." Kozmic Hash | Sciencx - Friday June 27, 2025, https://www.scien.cx/2025/06/27/connecting-your-dapp-to-blockchain-with-walletconnect-and-getblock/
HARVARD
Kozmic Hash | Sciencx Friday June 27, 2025 » Connecting Your DApp to Blockchain with WalletConnect and GetBlock., viewed ,<https://www.scien.cx/2025/06/27/connecting-your-dapp-to-blockchain-with-walletconnect-and-getblock/>
VANCOUVER
Kozmic Hash | Sciencx - » Connecting Your DApp to Blockchain with WalletConnect and GetBlock. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/06/27/connecting-your-dapp-to-blockchain-with-walletconnect-and-getblock/
CHICAGO
" » Connecting Your DApp to Blockchain with WalletConnect and GetBlock." Kozmic Hash | Sciencx - Accessed . https://www.scien.cx/2025/06/27/connecting-your-dapp-to-blockchain-with-walletconnect-and-getblock/
IEEE
" » Connecting Your DApp to Blockchain with WalletConnect and GetBlock." Kozmic Hash | Sciencx [Online]. Available: https://www.scien.cx/2025/06/27/connecting-your-dapp-to-blockchain-with-walletconnect-and-getblock/. [Accessed: ]
rf:citation
» Connecting Your DApp to Blockchain with WalletConnect and GetBlock | Kozmic Hash | Sciencx | https://www.scien.cx/2025/06/27/connecting-your-dapp-to-blockchain-with-walletconnect-and-getblock/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.