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. WalletConnect GetBlock.io We'll focus on a browser-based setup, making it ideal for web applications where users typically use browser extensions like MetaMask. 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. 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 GetBlock Account: 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. A Browser-Based Wallet: MetaMask Basic JavaScript Knowledge: This tutorial involves some JavaScript code. Basic JavaScript Knowledge: A Simple Web Project: A basic HTML file with a script tag is all you need to get started. A Simple Web Project: Step 1: Set Up Your GetBlock Access Token Log in to GetBlock: Once logged in, get a free endpoint for Sepolia. Get a New Endpoint (if needed): You'll find the Get button in your dashboard. 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. Log in to GetBlock: Once logged in, get a free endpoint for Sepolia. Log in to GetBlock: Get a New Endpoint (if needed): You'll find the Get button in your dashboard. Get a New Endpoint (if needed): 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. Copy Your Access Token: Step 2: Create Your HTML Structure Let's create a simple HTML file (index.html) that will house our DApp and the JavaScript logic. index.html <!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> <!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) app.js Now, let's create our app.js file and add the JavaScript code to handle WalletConnect. app.js 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. WalletConnect Web3Modal WalletConnectProvider npm Add these script tags to your index.html before your app.js script tag: index.html before app.js <script src="https://unpkg.com/web3@latest/dist/web3.min.js"></script> <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/@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> <script src="https://unpkg.com/web3modal@1.9.12/dist/index.js"></script> Now, create your app.js file: app.js // 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); // 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: 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. Replace YOUR_GETBLOCK_ACCESS_TOKEN: Make sure to replace this placeholder with your actual GetBlock.io Access Token. Replace YOUR_GETBLOCK_ACCESS_TOKEN Chain ID: The chainId (11155111 for Sepolia) is crucial for WalletConnect to identify the correct network. Chain ID: chainId 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. rpc rpc providerOptions.walletconnect.options 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. WalletConnectProvider WalletConnectProvider @walletconnect/web3-provider web3modal.min.js Error Handling: The try...catch blocks are important for handling potential connection errors. Error Handling: try...catch 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. Event Listeners: accountsChanged chainChanged disconnect Step 4: Run Your Application Save your files: Make sure both index.html and app.js are in the same directory. 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. Click "Connect Wallet": The WalletConnect modal will pop up. Choose "WalletConnect": A QR code will appear. 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. Approve the Connection: Confirm the connection request in your wallet. Save your files: Make sure both index.html and app.js are in the same directory. Save your files: Make sure both index.html and app.js are in the same directory. Save your files: index.html app.js 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. Open index.html in your browser. Use a local server. Open index.html If you open index.html directly in the browser (file://), some browsers will block cross-origin requests: You should see a "Connect Wallet" button. Click "Connect Wallet": The WalletConnect modal will pop up. Click "Connect Wallet": The WalletConnect modal will pop up. Click "Connect Wallet": WalletConnect Choose "WalletConnect": A QR code will appear. Choose "WalletConnect": A QR code will appear. Choose "WalletConnect": 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. 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. Scan with your Mobile Wallet (or use a desktop WalletConnect-compatible wallet): Approve the Connection: Confirm the connection request in your wallet. Approve the Connection: Confirm the connection request in your wallet. Approve the Connection: 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. Read Contract Data: Use the web3 instance to interact with smart contracts (e.g., call view functions). Read Contract Data: web3 view Send Transactions: Allow users to send transactions (e.g., call nonpayable functions on smart contracts, send ETH). Send Transactions: nonpayable Sign Messages: Enable users to sign arbitrary messages. Sign Messages: Implement Disconnect: Add a button or mechanism for users to explicitly disconnect their wallet. Implement Disconnect: 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! WalletConnect GetBlock