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 NeedBefore we dive into the code, make sure you have the following:
Let's create a simple HTML file (index.html) that will house our DApp and the JavaScript logic.
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:
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:
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.
Once connected, your DApp will display "Status: Connected!" and your connected account address.
Next StepsNow 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!
All Rights Reserved. Copyright , Central Coast Communications, Inc.