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:


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/[email protected]/dist/umd/index.min.js"></script>

<script src="https://unpkg.com/[email protected]/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:


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:


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!