Build a Web3 App with the Coinbase Wallet SDK

In 1977, the budding musician in me wanted to learn the piano after watching the movie “Star Wars.” My goal was to learn how to play the main theme from the movie everyone was talking about, so I bought the sheet music. We had a piano at home, a gift from my grandparents.

The 10-year-old version of me was quickly overwhelmed when I saw all the notes on the page:

I thought maybe I should start with something easier, so I started going through the papers inside the piano bench. Then I discovered this really cool note board template that fits perfectly behind the piano keys. I couldn’t find an exact match, but here’s an example:

It was a game changer for me. I threw all the other music on the piano bench and got to work, learning to play Star Wars. In no time, I learned to play this song (and the piano) without a single lesson.

It made me wonder why such “patterns” don’t exist in all aspects of life.

The Catch-22 for new technologies

New languages, platforms, frameworks, and design patterns all share a common requirement: developer acceptance and adoption. More often than not, most share another common challenge: steeper than desired learning curves.

For me, Web3 is currently in this state, although I worked on a Web3 example in my post “How to Go From a Full-Stack Developer to Web3 Pioneer in 2022”.

Top developers are already doing great things with Web3. But what about the next million developers, like me, who want to get started without feeling overwhelmed and frustrated? How can we find a way to integrate them with Web3?

I wanted to find a Web3 development help template, which I found when I started exploring the Coinbase SDKs.

The Coinbase SDK/API

According to Wikipedia, Coinbase is an American publicly listed company that has been operating a cryptocurrency exchange platform since June 2012. Similar to what I wrote with Marqeta, Coinbase provides a collection of programming interfaces for applications (APIs) and software development kits (SDKs) for use by developers who wish to create applications focused on digital currencies.

One such example is the Coinbase Wallet SDK.

For this publication, I wanted to accomplish the following tasks:

  • Create a Simple Web3 Application with React
  • Integrate my wallet browser extension with the Dapp
  • Allow users to donate using the Coinbase Wallet SDK

Build a Web3 App with the Coinbase Wallet SDK

To get started, we can create a React app called coinbase-wallet-example using the React CLI:

npx create-react-app coinbase-wallet-example

After creating the React app, I used the following command to navigate to the coinbase-wallet-example directory:

cd coinbase-wallet-example

Since newer versions of create-react-app no ​​longer include support for polyfills – a necessary requirement to use web3.js properly – this requires an older version of react-scripts:

npm install --save-exact [email protected]

Since we will be building a web3 example, the web3 framework has been installed using npm (other options can be found here):

npm install web3

Then the Coinbase Wallet SDK was installed using npm (other options can be found here):

npm install @coinbase/wallet-sdk

Using the Infura blockchain development suite, I created a new project called coinbase-wallet-example:

Next, I switched to the Ropsten testnet and noted down the project keys and URLs:

Now we just need to include the following code to initialize the Coinbase Wallet SDK and a Web3 object:

import CoinbaseWalletSDK from '@coinbase/wallet-sdk'
import Web3 from 'web3';

const APP_NAME = 'coinbase-wallet-example';
const APP_LOGO_URL = './coinbase-logo.png';
const DEFAULT_ETH_JSONRPC_URL = 'https://ropsten.infura.io/v3/56f … d69';
const DEFAULT_CHAIN_ID = 3; // 1=Ethereum (mainnet), 3=Ropsten, 5=Gorli

Inside of useEffect() method of my app, I’ve included the code needed to initialize the Coinbase and Web3 wallet:

   const coinbaseWallet = new CoinbaseWalletSDK({
      appName: APP_NAME,
      appLogoUrl: APP_LOGO_URL,
    });

    const walletSDKProvider = coinbaseWallet.makeWeb3Provider(
        DEFAULT_ETH_JSONRPC_URL,
        DEFAULT_CHAIN_ID
    );

   const web3 = new Web3(walletSDKProvider);

For this very simple example, we won’t use a smart contract, but instead provide a target address to send donations:

const DONATION_ADDRESS = '0x7 ... c94';

To reduce risk, the code will be updated to set DONATION_ADDRESS to the connected address of the wallet used.

DONATION_ADDRESS = account;

This basically means that the code will send funds to the sender, leaving only gas charges to be withdrawn from the user’s wallet. The React Dapp will allow users to connect their wallets, then provide a donation amount (using WEI units), then press the Donate button to send funds to DONATION_ADDRESS.

The complete source code of this simple Dapp is given below:

import React, { useEffect, useState } from 'react';
import './App.css';
import CoinbaseWalletSDK from '@coinbase/wallet-sdk'
import Web3 from 'web3';

const APP_NAME = 'coinbase-wallet-example';
const APP_LOGO_URL = './coinbase-logo.png';
const DEFAULT_ETH_JSONRPC_URL = 'https://ropsten.infura.io/v3/56f ... d69';
const DEFAULT_CHAIN_ID = 3; // 1=Ethereum (mainnet), 3=Ropsten, 5=Gorli
const DEFAULT_ETHEREUM_CHAIN_ID = '0x3'; // Should match DEFAULT_CHAIN_ID above, but with leading 0x

let DONATION_ADDRESS = '0x7 ... c94'; // Target donation address goes here, just as a simple example

const App = () => {
  const [isWalletConnected, setIsWalletConnected] = useState(false);
  const [account, setAccount] = useState();
  const [walletSDKProvider, setWalletSDKProvider] = useState();
  const [web3, setWeb3] = useState();
  const [responseMessage, setResponseMessage] = useState();

  useEffect(() => {
    const coinbaseWallet = new CoinbaseWalletSDK({
      appName: APP_NAME,
      appLogoUrl: APP_LOGO_URL,
    });

    const walletSDKProvider = coinbaseWallet.makeWeb3Provider(
        DEFAULT_ETH_JSONRPC_URL,
        DEFAULT_CHAIN_ID
    );

    setWalletSDKProvider(walletSDKProvider);

    const web3 = new Web3(walletSDKProvider);
    setWeb3(web3);
  }, []);

  const checkIfWalletIsConnected = () => {
    if (!window.ethereum) {
      console.log(
          'No ethereum object found. Please install Coinbase Wallet extension or similar.'
      );

      web3.setProvider(walletSDKProvider.enable());

      return;
    }

    console.log('Found the ethereum object:', window.ethereum);

    connectWallet();
  };

  const connectWallet = async () => {
    const accounts = await window.ethereum.request({
      method: 'eth_requestAccounts',
    });

    if (!accounts.length) {
      console.log('No authorized account found');
      return;
    }

    if (accounts.length) {
      const account = accounts[0];
      console.log('Found an authorized account:', account);
      setAccount(account);

      try {
        await window.ethereum.request({
          method: 'wallet_switchEthereumChain',
          params: [{ chainId: DEFAULT_ETHEREUM_CHAIN_ID }],
        });
        console.log('Successfully switched to Ropsten Network');
      } catch (error) {
        console.error(error);
      }
    }

    setIsWalletConnected(true);
  };

  const donate = async () => {
    if (!account || !window.ethereum) {
      console.log('Wallet is not connected');
      return;
    }

    // For this simple example, make the DONATION_ADDRESS the user's address (send to themselves)
    DONATION_ADDRESS = account;

    const donationAmount = document.querySelector('#donationAmount').value;

    web3.eth.sendTransaction({
      from: account,
      to: DONATION_ADDRESS,
      value: donationAmount
    }, function(err, transactionHash) {
      if (!err) {
        setResponseMessage(transactionHash + ' success');
        console.log(transactionHash + " success");
      } else {
        console.error(err);
      }
    });
  };

  return (
    
logo {isWalletConnected ? ( <>

Donate some funds to yourself

Connected Account: {account}

) : ( )}

{responseMessage}

); } export default App;

Running the React-based Dapp is as simple as using the following command:

npm start

Here is an example.

Conclusion

Since 2021, I have tried to live by the following mission statement, which I believe can be applied to any IT professional:

“Spend your time delivering features/functionality that extend the value of your IP. Leverage frameworks, products, and services for everything else.

– J. Vester

The grade chart template I referenced in my introduction turned out to be a turning point in my life. This hidden gem that was hidden inside our piano bench not only allowed me to play the Star Wars theme, it catapulted my ability to play music. This simple pattern and a desire to learn eventually paved the way for my admission to Berklee College of Music and the opportunity to participate in several musical productions.

The Coinbase APIs and SDKs – or developer tools – serve a similar purpose for developers looking to get started in the emerging world of Web3. Developers can include these modules in their applications and get started quickly, without getting bogged down in the details.

Either way, the Coinbase scoreboard template and developer tools adhere to my mission statement by allowing the individual to stay focused on their primary goal – either learning to play the piano for the first time, or making something cool with Web3.

If you are interested in the source code for this release, you can find it on GitLab at:

https://gitlab.com/johnjvester/coinbase-wallet-example

Have a very nice day !


Also posted here.

LOADING
. . . comments & After!